blob: 9d89ead14ce0e825d788b144d7532b5681bd1d1b [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]f805fe82010-08-03 22:47:1010#include "base/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]528c56d2010-07-30 19:28:4414#include "base/string_number_conversions.h"
[email protected]57750f822009-04-21 21:43:0915#include "base/sys_string_conversions.h"
[email protected]061a5ea82011-08-03 10:11:5016#include "base/utf_string_conversions.h"
[email protected]1a3aba82010-11-08 23:52:5417#include "chrome/app/chrome_command_ids.h"
[email protected]a07676b22011-06-17 16:36:5318#include "chrome/browser/background/background_application_list_model.h"
[email protected]78d78a62011-09-29 18:24:3319#include "chrome/browser/background/background_mode_manager.h"
[email protected]5c238752009-06-13 10:29:0720#include "chrome/browser/browser_process.h"
[email protected]41741a962009-02-18 21:51:3921#include "chrome/browser/browser_shutdown.h"
[email protected]2c47bc12009-04-10 20:14:0022#include "chrome/browser/command_updater.h"
[email protected]9bb54ee2011-10-12 17:43:3523#include "chrome/browser/download/download_service.h"
24#include "chrome/browser/download/download_service_factory.h"
[email protected]e4a377cf2011-10-05 02:51:4925#include "chrome/browser/first_run/first_run.h"
[email protected]2e6389f2012-05-18 19:41:2526#include "chrome/browser/lifetime/application_lifetime.h"
[email protected]a99fce0e2011-03-21 20:58:4827#include "chrome/browser/prefs/pref_service.h"
[email protected]a529af52011-08-15 20:56:1728#include "chrome/browser/printing/cloud_print/virtual_driver_install_helper.h"
29#include "chrome/browser/printing/print_dialog_cloud.h"
[email protected]8ecad5e2010-12-02 21:18:3330#include "chrome/browser/profiles/profile_manager.h"
[email protected]a529af52011-08-15 20:56:1731#include "chrome/browser/service/service_process_control.h"
[email protected]d2912a22011-03-15 15:20:5032#include "chrome/browser/sessions/session_service.h"
[email protected]92371eb2011-04-28 11:50:1533#include "chrome/browser/sessions/session_service_factory.h"
[email protected]fbc947b2009-06-19 13:28:2434#include "chrome/browser/sessions/tab_restore_service.h"
[email protected]92371eb2011-04-28 11:50:1535#include "chrome/browser/sessions/tab_restore_service_factory.h"
[email protected]f9bc9b92009-11-24 00:55:3536#include "chrome/browser/sync/profile_sync_service.h"
[email protected]40f047972009-11-25 03:54:4037#include "chrome/browser/sync/sync_ui_util.h"
38#include "chrome/browser/sync/sync_ui_util_mac.h"
[email protected]ae04f592010-11-18 20:41:3539#include "chrome/browser/ui/browser.h"
[email protected]a37d4b02012-06-25 21:56:1040#include "chrome/browser/ui/browser_commands.h"
[email protected]d8748142012-05-16 21:13:4341#include "chrome/browser/ui/browser_finder.h"
[email protected]ae04f592010-11-18 20:41:3542#include "chrome/browser/ui/browser_list.h"
[email protected]a13b76f2012-06-20 15:36:2943#include "chrome/browser/ui/browser_mac.h"
[email protected]ae04f592010-11-18 20:41:3544#include "chrome/browser/ui/browser_window.h"
[email protected]5d9cace72012-06-21 16:07:1245#include "chrome/browser/ui/chrome_pages.h"
[email protected]7d791652010-12-01 16:34:4946#import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h"
47#import "chrome/browser/ui/cocoa/browser_window_cocoa.h"
48#import "chrome/browser/ui/cocoa/browser_window_controller.h"
[email protected]b6366ffa2012-02-29 17:12:2649#import "chrome/browser/ui/cocoa/confirm_quit.h"
[email protected]7d791652010-12-01 16:34:4950#import "chrome/browser/ui/cocoa/confirm_quit_panel_controller.h"
51#import "chrome/browser/ui/cocoa/encoding_menu_controller_delegate_mac.h"
52#import "chrome/browser/ui/cocoa/history_menu_bridge.h"
[email protected]4feb37d92012-07-01 20:22:1353#include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
[email protected]961a6932011-07-19 19:52:4654#import "chrome/browser/ui/cocoa/profile_menu_controller.h"
[email protected]cfe1d612011-01-19 20:06:4755#import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
56#import "chrome/browser/ui/cocoa/tabs/tab_window_controller.h"
[email protected]7d791652010-12-01 16:34:4957#include "chrome/browser/ui/cocoa/task_manager_mac.h"
[email protected]4feb37d92012-07-01 20:22:1358#include "chrome/browser/ui/startup/startup_browser_creator.h"
59#include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
[email protected]14fb7d32011-07-10 17:53:3260#include "chrome/common/chrome_notification_types.h"
[email protected]12dc3d42010-02-22 23:37:1261#include "chrome/common/chrome_paths_internal.h"
[email protected]f4acfae82009-09-11 00:33:3862#include "chrome/common/chrome_switches.h"
[email protected]13aec6c42011-10-27 21:22:0863#include "chrome/common/cloud_print/cloud_print_class_mac.h"
[email protected]6c583d32011-08-19 14:46:2264#include "chrome/common/mac/app_mode_common.h"
[email protected]a99fce0e2011-03-21 20:58:4865#include "chrome/common/pref_names.h"
[email protected]a529af52011-08-15 20:56:1766#include "chrome/common/service_messages.h"
[email protected]024617a2010-08-20 05:08:0567#include "chrome/common/url_constants.h"
[email protected]c38831a12011-10-28 12:44:4968#include "content/public/browser/browser_thread.h"
[email protected]e582fdd2011-12-20 16:48:1769#include "content/public/browser/download_manager.h"
[email protected]ad50def52011-10-19 23:17:0770#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:1671#include "content/public/browser/notification_types.h"
[email protected]7f6f44c2011-12-14 13:23:3872#include "content/public/browser/user_metrics.h"
[email protected]9dcb59662009-09-23 01:15:5073#include "grit/chromium_strings.h"
[email protected]09729a552009-08-03 23:21:4174#include "grit/generated_resources.h"
[email protected]caadfca2010-01-22 21:51:2175#include "net/base/net_util.h"
[email protected]2b68f812011-11-25 15:02:1176#include "ui/base/accelerators/accelerator_cocoa.h"
[email protected]c051a1b2011-01-21 23:30:1777#include "ui/base/l10n/l10n_util.h"
78#include "ui/base/l10n/l10n_util_mac.h"
[email protected]88d74942009-01-21 22:04:4479
[email protected]b441a8492012-06-06 14:55:5780using content::BrowserContext;
[email protected]631bb742011-11-02 11:29:3981using content::BrowserThread;
[email protected]e582fdd2011-12-20 16:48:1782using content::DownloadManager;
[email protected]7f6f44c2011-12-14 13:23:3883using content::UserMetricsAction;
[email protected]631bb742011-11-02 11:29:3984
[email protected]f2c20fa2009-12-01 17:42:0285// 10.6 adds a public API for the Spotlight-backed search menu item in the Help
86// menu. Provide the declaration so it can be called below when building with
87// the 10.5 SDK.
88#if !defined(MAC_OS_X_VERSION_10_6) || \
89 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
90@interface NSApplication (SnowLeopardSDKDeclarations)
[email protected]caadfca2010-01-22 21:51:2191- (void)setHelpMenu:(NSMenu*)helpMenu;
[email protected]f2c20fa2009-12-01 17:42:0292@end
93#endif
94
[email protected]d630d7d52010-02-21 00:55:1195namespace {
96
[email protected]ebbe94b2012-01-18 20:11:5697// Declare notification names from the 10.7 SDK.
98#if !defined(MAC_OS_X_VERSION_10_7) || \
99 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
100NSString* NSPopoverDidShowNotification = @"NSPopoverDidShowNotification";
101NSString* NSPopoverDidCloseNotification = @"NSPopoverDidCloseNotification";
102#endif
103
[email protected]a37d4b02012-06-25 21:56:10104// True while AppController is calling chrome::NewEmptyWindow(). We need a
[email protected]fe7c4872012-05-10 20:06:03105// global flag here, analogue to StartupBrowserCreator::InProcessStartup()
106// because otherwise the SessionService will try to restore sessions when we
107// make a new window while there are no other active windows.
[email protected]d630d7d52010-02-21 00:55:11108bool g_is_opening_new_window = false;
109
110// Activates a browser window having the given profile (the last one active) if
111// possible and returns a pointer to the activate |Browser| or NULL if this was
112// not possible. If the last active browser is minimized (in particular, if
113// there are only minimized windows), it will unminimize it.
114Browser* ActivateBrowser(Profile* profile) {
[email protected]d8748142012-05-16 21:13:43115 Browser* browser = browser::FindLastActiveWithProfile(profile);
[email protected]d630d7d52010-02-21 00:55:11116 if (browser)
117 browser->window()->Activate();
118 return browser;
119}
120
121// Creates an empty browser window with the given profile and returns a pointer
122// to the new |Browser|.
123Browser* CreateBrowser(Profile* profile) {
124 {
[email protected]0fbd70332010-06-01 19:28:34125 AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
[email protected]a37d4b02012-06-25 21:56:10126 chrome::NewEmptyWindow(profile);
[email protected]d630d7d52010-02-21 00:55:11127 }
128
[email protected]13858862012-05-24 03:22:51129 Browser* browser = browser::GetLastActiveBrowser();
[email protected]d630d7d52010-02-21 00:55:11130 CHECK(browser);
131 return browser;
132}
133
134// Activates a browser window having the given profile (the last one active) if
135// possible or creates an empty one if necessary. Returns a pointer to the
136// activated/new |Browser|.
137Browser* ActivateOrCreateBrowser(Profile* profile) {
138 if (Browser* browser = ActivateBrowser(profile))
139 return browser;
140 return CreateBrowser(profile);
141}
142
[email protected]151c4a62011-04-22 04:15:13143CFStringRef BaseBundleID_CFString() {
144 NSString* base_bundle_id =
145 [NSString stringWithUTF8String:base::mac::BaseBundleID()];
146 return base::mac::NSToCFCast(base_bundle_id);
147}
148
[email protected]0b8caad2011-11-28 23:33:27149// This callback synchronizes preferences (under "org.chromium.Chromium" or
[email protected]12dc3d42010-02-22 23:37:12150// "com.google.Chrome"), in particular, writes them out to disk.
[email protected]0b8caad2011-11-28 23:33:27151void PrefsSyncCallback() {
152 if (!CFPreferencesAppSynchronize(BaseBundleID_CFString()))
153 LOG(WARNING) << "Error recording application bundle path.";
154}
[email protected]12dc3d42010-02-22 23:37:12155
156// Record the location of the application bundle (containing the main framework)
157// from which Chromium was loaded. This is used by app mode shims to find
158// Chromium.
159void RecordLastRunAppBundlePath() {
160 // Going up three levels from |chrome::GetVersionedDirectory()| gives the
161 // real, user-visible app bundle directory. (The alternatives give either the
162 // framework's path or the initial app's path, which may be an app mode shim
163 // or a unit test.)
164 FilePath appBundlePath =
165 chrome::GetVersionedDirectory().DirName().DirName().DirName();
[email protected]b6b72222012-02-11 02:04:13166 CFPreferencesSetAppValue(
167 base::mac::NSToCFCast(app_mode::kLastRunAppBundlePathPrefsKey),
168 base::SysUTF8ToCFStringRef(appBundlePath.value()),
169 BaseBundleID_CFString());
[email protected]12dc3d42010-02-22 23:37:12170
171 // Sync after a delay avoid I/O contention on startup; 1500 ms is plenty.
[email protected]df32e89c2012-05-17 17:47:34172 BrowserThread::PostDelayedTask(
173 BrowserThread::FILE, FROM_HERE,
174 base::Bind(&PrefsSyncCallback),
175 base::TimeDelta::FromMilliseconds(1500));
[email protected]12dc3d42010-02-22 23:37:12176}
177
[email protected]d630d7d52010-02-21 00:55:11178} // anonymous namespace
179
[email protected]a529af52011-08-15 20:56:17180const AEEventClass kAECloudPrintInstallClass = 'GCPi';
181const AEEventClass kAECloudPrintUninstallClass = 'GCPu';
182
[email protected]a99fce0e2011-03-21 20:58:48183@interface AppController (Private)
[email protected]88d74942009-01-21 22:04:44184- (void)initMenuState;
[email protected]961a6932011-07-19 19:52:46185- (void)initProfileMenu;
[email protected]a99fce0e2011-03-21 20:58:48186- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
[email protected]eef99c22010-08-17 05:55:16187- (void)registerServicesMenuTypesTo:(NSApplication*)app;
[email protected]d630d7d52010-02-21 00:55:11188- (void)openUrls:(const std::vector<GURL>&)urls;
[email protected]57750f822009-04-21 21:43:09189- (void)getUrl:(NSAppleEventDescriptor*)event
190 withReply:(NSAppleEventDescriptor*)reply;
[email protected]a529af52011-08-15 20:56:17191- (void)submitCloudPrintJob:(NSAppleEventDescriptor*)event;
192- (void)installCloudPrint:(NSAppleEventDescriptor*)event;
193- (void)uninstallCloudPrint:(NSAppleEventDescriptor*)event;
[email protected]449dd2f2009-05-27 13:04:00194- (void)windowLayeringDidChange:(NSNotification*)inNotification;
[email protected]5c593702011-06-17 18:35:24195- (void)windowChangedToProfile:(Profile*)profile;
[email protected]dd6ab1282010-07-20 01:07:32196- (void)checkForAnyKeyWindows;
[email protected]73f5b362009-08-10 23:58:21197- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
[email protected]09729a552009-08-03 23:21:41198- (BOOL)shouldQuitWithInProgressDownloads;
[email protected]93b59fc2010-12-21 20:00:47199- (void)executeApplication:(id)sender;
[email protected]88d74942009-01-21 22:04:44200@end
[email protected]1bcdb532009-01-16 17:47:57201
202@implementation AppController
203
[email protected]caadfca2010-01-22 21:51:21204@synthesize startupComplete = startupComplete_;
205
[email protected]cd63ef62009-05-06 19:41:37206// This method is called very early in application startup (ie, before
207// the profile is loaded or any preferences have been registered). Defer any
208// user-data initialization until -applicationDidFinishLaunching:.
[email protected]88d74942009-01-21 22:04:44209- (void)awakeFromNib {
[email protected]136140c2009-05-19 13:58:25210 // We need to register the handlers early to catch events fired on launch.
[email protected]57750f822009-04-21 21:43:09211 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
212 [em setEventHandler:self
213 andSelector:@selector(getUrl:withReply:)
214 forEventClass:kInternetEventClass
215 andEventID:kAEGetURL];
216 [em setEventHandler:self
[email protected]a529af52011-08-15 20:56:17217 andSelector:@selector(submitCloudPrintJob:)
[email protected]13aec6c42011-10-27 21:22:08218 forEventClass:cloud_print::kAECloudPrintClass
219 andEventID:cloud_print::kAECloudPrintClass];
[email protected]a529af52011-08-15 20:56:17220 // Install and uninstall handlers for virtual drivers.
221 [em setEventHandler:self
222 andSelector:@selector(installCloudPrint:)
223 forEventClass:kAECloudPrintInstallClass
224 andEventID:kAECloudPrintInstallClass];
225 [em setEventHandler:self
226 andSelector:@selector(uninstallCloudPrint:)
227 forEventClass:kAECloudPrintUninstallClass
228 andEventID:kAECloudPrintUninstallClass];
229 [em setEventHandler:self
[email protected]57750f822009-04-21 21:43:09230 andSelector:@selector(getUrl:withReply:)
231 forEventClass:'WWW!' // A particularly ancient AppleEvent that dates
232 andEventID:'OURL']; // back to the Spyglass days.
[email protected]cd63ef62009-05-06 19:41:37233
[email protected]449dd2f2009-05-27 13:04:00234 // Register for various window layering changes. We use these to update
235 // various UI elements (command-key equivalents, etc) when the frontmost
236 // window changes.
237 NSNotificationCenter* notificationCenter =
238 [NSNotificationCenter defaultCenter];
[email protected]ce560f82009-06-03 09:39:44239 [notificationCenter
[email protected]449dd2f2009-05-27 13:04:00240 addObserver:self
241 selector:@selector(windowLayeringDidChange:)
242 name:NSWindowDidBecomeKeyNotification
243 object:nil];
244 [notificationCenter
245 addObserver:self
246 selector:@selector(windowLayeringDidChange:)
247 name:NSWindowDidResignKeyNotification
248 object:nil];
249 [notificationCenter
250 addObserver:self
251 selector:@selector(windowLayeringDidChange:)
252 name:NSWindowDidBecomeMainNotification
253 object:nil];
254 [notificationCenter
255 addObserver:self
256 selector:@selector(windowLayeringDidChange:)
257 name:NSWindowDidResignMainNotification
258 object:nil];
259
[email protected]ebbe94b2012-01-18 20:11:56260 if (base::mac::IsOSLionOrLater()) {
261 [notificationCenter
262 addObserver:self
263 selector:@selector(popoverDidShow:)
264 name:NSPopoverDidShowNotification
265 object:nil];
266 [notificationCenter
267 addObserver:self
268 selector:@selector(popoverDidClose:)
269 name:NSPopoverDidCloseNotification
270 object:nil];
271 }
272
[email protected]136140c2009-05-19 13:58:25273 // Set up the command updater for when there are no windows open
274 [self initMenuState];
[email protected]961a6932011-07-19 19:52:46275
276 // Initialize the Profile menu.
277 [self initProfileMenu];
[email protected]136140c2009-05-19 13:58:25278}
279
[email protected]71c0eb92012-01-03 17:57:30280- (void)unregisterEventHandlers {
281 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
282 [em removeEventHandlerForEventClass:kInternetEventClass
283 andEventID:kAEGetURL];
284 [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
285 andEventID:cloud_print::kAECloudPrintClass];
286 [em removeEventHandlerForEventClass:kAECloudPrintInstallClass
287 andEventID:kAECloudPrintInstallClass];
288 [em removeEventHandlerForEventClass:kAECloudPrintUninstallClass
289 andEventID:kAECloudPrintUninstallClass];
290 [em removeEventHandlerForEventClass:'WWW!'
291 andEventID:'OURL'];
292 [[NSNotificationCenter defaultCenter] removeObserver:self];
293}
294
[email protected]7dc8c6b2010-04-09 17:02:50295// (NSApplicationDelegate protocol) This is the Apple-approved place to override
296// the default handlers.
297- (void)applicationWillFinishLaunching:(NSNotification*)notification {
[email protected]58877932010-05-25 05:43:11298 // Nothing here right now.
[email protected]7dc8c6b2010-04-09 17:02:50299}
300
301- (BOOL)tryToTerminateApplication:(NSApplication*)app {
[email protected]3076fad2010-04-28 18:11:45302 // Check for in-process downloads, and prompt the user if they really want
303 // to quit (and thus cancel downloads). Only check if we're not already
304 // shutting down, else the user might be prompted multiple times if the
305 // download isn't stopped before terminate is called again.
306 if (!browser_shutdown::IsTryingToQuit() &&
307 ![self shouldQuitWithInProgressDownloads])
308 return NO;
309
[email protected]7dc8c6b2010-04-09 17:02:50310 // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
311 // them in, but I'm not sure about UX; we'd also want to disable other things
312 // though.) http://crbug.com/40861
313
[email protected]177aceb2010-11-03 16:17:41314 // Check if the user really wants to quit by employing the confirm-to-quit
315 // mechanism.
316 if (!browser_shutdown::IsTryingToQuit() &&
317 [self applicationShouldTerminate:app] != NSTerminateNow)
318 return NO;
319
[email protected]c984d9f2010-07-20 20:52:20320 size_t num_browsers = BrowserList::size();
[email protected]7dc8c6b2010-04-09 17:02:50321
[email protected]2e6389f2012-05-18 19:41:25322 // Initiate a shutdown (via browser::CloseAllBrowsers()) if we aren't
[email protected]c984d9f2010-07-20 20:52:20323 // already shutting down.
[email protected]ef61b8c2012-01-20 10:54:56324 if (!browser_shutdown::IsTryingToQuit()) {
325 content::NotificationService::current()->Notify(
[email protected]d53a08c2012-07-18 20:35:30326 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
[email protected]ef61b8c2012-01-20 10:54:56327 content::NotificationService::AllSources(),
328 content::NotificationService::NoDetails());
[email protected]2e6389f2012-05-18 19:41:25329 browser::CloseAllBrowsers();
[email protected]ef61b8c2012-01-20 10:54:56330 }
[email protected]7dc8c6b2010-04-09 17:02:50331
[email protected]c984d9f2010-07-20 20:52:20332 return num_browsers == 0 ? YES : NO;
[email protected]7dc8c6b2010-04-09 17:02:50333}
334
335- (void)stopTryingToTerminateApplication:(NSApplication*)app {
336 if (browser_shutdown::IsTryingToQuit()) {
337 // Reset the "trying to quit" state, so that closing all browser windows
338 // will no longer lead to termination.
339 browser_shutdown::SetTryingToQuit(false);
340
341 // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
342 // would have to reinstall them here. http://crbug.com/40861
343 }
[email protected]a9e8afc2009-08-11 22:03:17344}
345
[email protected]177aceb2010-11-03 16:17:41346- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
[email protected]a99fce0e2011-03-21 20:58:48347 // Check if the preference is turned on.
[email protected]b6366ffa2012-02-29 17:12:26348 const PrefService* prefs = g_browser_process->local_state();
[email protected]1eaddf32011-04-05 15:09:23349 if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
350 confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
[email protected]177aceb2010-11-03 16:17:41351 return NSTerminateNow;
[email protected]1eaddf32011-04-05 15:09:23352 }
[email protected]177aceb2010-11-03 16:17:41353
354 // If the application is going to terminate as the result of a Cmd+Q
355 // invocation, use the special sauce to prevent accidental quitting.
356 // http://dev.chromium.org/developers/design-documents/confirm-to-quit-experiment
[email protected]177aceb2010-11-03 16:17:41357
[email protected]2020fd0b2010-12-10 01:16:50358 // This logic is only for keyboard-initiated quits.
[email protected]5df54fb2011-03-07 18:15:26359 if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
[email protected]2020fd0b2010-12-10 01:16:50360 return NSTerminateNow;
[email protected]177aceb2010-11-03 16:17:41361
[email protected]5df54fb2011-03-07 18:15:26362 return [[ConfirmQuitPanelController sharedController]
363 runModalLoopForApplication:app];
[email protected]177aceb2010-11-03 16:17:41364}
365
[email protected]449dd2f2009-05-27 13:04:00366// Called when the app is shutting down. Clean-up as appropriate.
[email protected]7dc8c6b2010-04-09 17:02:50367- (void)applicationWillTerminate:(NSNotification*)aNotification {
[email protected]7dc8c6b2010-04-09 17:02:50368 // There better be no browser windows left at this point.
[email protected]71c0eb92012-01-03 17:57:30369 CHECK_EQ(0u, BrowserList::size());
[email protected]3b6aa8b62009-09-15 21:36:11370
[email protected]c984d9f2010-07-20 20:52:20371 // Tell BrowserList not to keep the browser process alive. Once all the
372 // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
[email protected]2e6389f2012-05-18 19:41:25373 browser::EndKeepAlive();
[email protected]fbc947b2009-06-19 13:28:24374
[email protected]71c0eb92012-01-03 17:57:30375 [self unregisterEventHandlers];
[email protected]449dd2f2009-05-27 13:04:00376}
377
[email protected]3b6aa8b62009-09-15 21:36:11378- (void)didEndMainMessageLoop {
[email protected]d8748142012-05-16 21:13:43379 DCHECK_EQ(0u, browser::GetBrowserCount([self lastProfile]));
380 if (!browser::GetBrowserCount([self lastProfile])) {
[email protected]3b6aa8b62009-09-15 21:36:11381 // As we're shutting down, we need to nuke the TabRestoreService, which
382 // will start the shutdown of the NavigationControllers and allow for
383 // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
384 // and may end up crashing when some thread tries to use the IO thread (or
385 // another thread) that is no longer valid.
[email protected]a585a8db2011-06-20 18:58:35386 TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
[email protected]3b6aa8b62009-09-15 21:36:11387 }
388}
389
[email protected]8cfbdbd2011-06-16 04:17:17390// If the window has a tab controller, make "close window" be cmd-shift-w,
391// otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
[email protected]eddcf7502012-02-09 22:43:48392// affects whether the shift modifier is used.
[email protected]ebbe94b2012-01-18 20:11:56393- (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
394 [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
395 @"w")];
[email protected]8cfbdbd2011-06-16 04:17:17396 [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
397}
398
399// If the window has a tab controller, make "close tab" take over cmd-w,
400// otherwise it shouldn't have any key-equivalent because it should be disabled.
[email protected]ebbe94b2012-01-18 20:11:56401- (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
402 if (enableCloseTabShortcut) {
[email protected]8cfbdbd2011-06-16 04:17:17403 [closeTabMenuItem_ setKeyEquivalent:@"w"];
404 [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
405 } else {
406 [closeTabMenuItem_ setKeyEquivalent:@""];
407 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
408 }
409}
410
411// Explicitly remove any command-key equivalents from the close tab/window
412// menus so that nothing can go haywire if we get a user action during pending
413// updates.
414- (void)clearCloseMenuItemKeyEquivalents {
415 [closeTabMenuItem_ setKeyEquivalent:@""];
416 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
417 [closeWindowMenuItem_ setKeyEquivalent:@""];
418 [closeWindowMenuItem_ setKeyEquivalentModifierMask:0];
419}
420
[email protected]9f5f79b62011-10-28 00:43:45421// See if the focused window window has tabs, and adjust the key equivalents for
[email protected]8cfbdbd2011-06-16 04:17:17422// Close Tab/Close Window accordingly.
[email protected]9f5f79b62011-10-28 00:43:45423- (void)fixCloseMenuItemKeyEquivalents {
[email protected]8cfbdbd2011-06-16 04:17:17424 fileMenuUpdatePending_ = NO;
[email protected]8cfbdbd2011-06-16 04:17:17425
[email protected]9f5f79b62011-10-28 00:43:45426 NSWindow* window = [NSApp keyWindow];
427 NSWindow* mainWindow = [NSApp mainWindow];
428 if (!window || ([window parentWindow] == mainWindow)) {
429 // If the key window is a child of the main window (e.g. a bubble), the main
430 // window should be the one that handles the close menu item action.
431 // Also, there might be a small amount of time where there is no key window;
432 // in that case as well, just use our main browser window if there is one.
433 // You might think that we should just always use the main window, but the
434 // "About Chrome" window serves as a counterexample.
435 window = mainWindow;
436 }
437
438 BOOL hasTabs =
439 [[window windowController] isKindOfClass:[TabWindowController class]];
[email protected]ebbe94b2012-01-18 20:11:56440 BOOL enableCloseTabShortcut = hasTabs && !hasPopover_;
441 [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
442 [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
[email protected]8cfbdbd2011-06-16 04:17:17443}
444
445// Fix up the "close tab/close window" command-key equivalents. We do this
446// after a delay to ensure that window layer state has been set by the time
447// we do the enabling. This should only be called on the main thread, code that
448// calls this (even as a side-effect) from other threads needs to be fixed.
[email protected]9f5f79b62011-10-28 00:43:45449- (void)delayedFixCloseMenuItemKeyEquivalents {
[email protected]8cfbdbd2011-06-16 04:17:17450 DCHECK([NSThread isMainThread]);
451 if (!fileMenuUpdatePending_) {
452 // The OS prefers keypresses to timers, so it's possible that a cmd-w
453 // can sneak in before this timer fires. In order to prevent that from
454 // having any bad consequences, just clear the keys combos altogether. They
455 // will be reset when the timer eventually fires.
456 if ([NSThread isMainThread]) {
457 fileMenuUpdatePending_ = YES;
458 [self clearCloseMenuItemKeyEquivalents];
[email protected]9f5f79b62011-10-28 00:43:45459 [self performSelector:@selector(fixCloseMenuItemKeyEquivalents)
460 withObject:nil
[email protected]8cfbdbd2011-06-16 04:17:17461 afterDelay:0];
462 } else {
463 // This shouldn't be happening, but if it does, force it to the main
464 // thread to avoid dropping the update. Don't mess with
465 // |fileMenuUpdatePending_| as it's not expected to be threadsafe and
466 // there could be a race between the selector finishing and setting the
467 // flag.
468 [self
[email protected]9f5f79b62011-10-28 00:43:45469 performSelectorOnMainThread:@selector(fixCloseMenuItemKeyEquivalents)
470 withObject:nil
[email protected]8cfbdbd2011-06-16 04:17:17471 waitUntilDone:NO];
472 }
473 }
474}
475
[email protected]449dd2f2009-05-27 13:04:00476// Called when we get a notification about the window layering changing to
477// update the UI based on the new main window.
478- (void)windowLayeringDidChange:(NSNotification*)notify {
[email protected]9f5f79b62011-10-28 00:43:45479 [self delayedFixCloseMenuItemKeyEquivalents];
[email protected]8cfbdbd2011-06-16 04:17:17480
[email protected]dd6ab1282010-07-20 01:07:32481 if ([notify name] == NSWindowDidResignKeyNotification) {
482 // If a window is closed, this notification is fired but |[NSApp keyWindow]|
483 // returns nil regardless of whether any suitable candidates for the key
484 // window remain. It seems that the new key window for the app is not set
485 // until after this notification is fired, so a check is performed after the
486 // run loop is allowed to spin.
487 [self performSelector:@selector(checkForAnyKeyWindows)
488 withObject:nil
489 afterDelay:0.0];
490 }
[email protected]5c593702011-06-17 18:35:24491
492 // If the window changed to a new BrowserWindowController, update the profile.
493 id windowController = [[notify object] windowController];
[email protected]dc251482012-01-03 18:55:21494 if ([notify name] == NSWindowDidBecomeMainNotification &&
495 [windowController isKindOfClass:[BrowserWindowController class]]) {
[email protected]5c593702011-06-17 18:35:24496 // If the profile is incognito, use the original profile.
497 Profile* newProfile = [windowController profile]->GetOriginalProfile();
498 [self windowChangedToProfile:newProfile];
[email protected]cae68b3a2011-11-21 23:29:49499 } else if (BrowserList::empty()) {
500 [self windowChangedToProfile:
501 g_browser_process->profile_manager()->GetLastUsedProfile()];
[email protected]5c593702011-06-17 18:35:24502 }
503}
504
[email protected]ebbe94b2012-01-18 20:11:56505// Called on Lion and later when a popover (e.g. dictionary) is shown.
506- (void)popoverDidShow:(NSNotification*)notify {
507 hasPopover_ = YES;
508 [self fixCloseMenuItemKeyEquivalents];
509}
510
511// Called on Lion and later when a popover (e.g. dictionary) is closed.
512- (void)popoverDidClose:(NSNotification*)notify {
513 hasPopover_ = NO;
514 [self fixCloseMenuItemKeyEquivalents];
515}
516
[email protected]5c593702011-06-17 18:35:24517// Called when the user has changed browser windows, meaning the backing profile
518// may have changed. This can cause a rebuild of the user-data menus. This is a
519// no-op if the new profile is the same as the current one. This will always be
520// the original profile and never incognito.
521- (void)windowChangedToProfile:(Profile*)profile {
522 if (lastProfile_ == profile)
523 return;
524
525 // Before tearing down the menu controller bridges, return the Cocoa menus to
526 // their initial state.
527 if (bookmarkMenuBridge_.get())
528 bookmarkMenuBridge_->ResetMenu();
529 if (historyMenuBridge_.get())
530 historyMenuBridge_->ResetMenu();
531
532 // Rebuild the menus with the new profile.
533 lastProfile_ = profile;
534
[email protected]0c165cf2011-07-09 03:56:50535 bookmarkMenuBridge_.reset(new BookmarkMenuBridge(lastProfile_,
536 [[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] submenu]));
[email protected]dc251482012-01-03 18:55:21537 // No need to |BuildMenu| here. It is done lazily upon menu access.
[email protected]5c593702011-06-17 18:35:24538
539 historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
540 historyMenuBridge_->BuildMenu();
[email protected]dd6ab1282010-07-20 01:07:32541}
542
543- (void)checkForAnyKeyWindows {
544 if ([NSApp keyWindow])
545 return;
546
[email protected]ad50def52011-10-19 23:17:07547 content::NotificationService::current()->Notify(
[email protected]d53a08c2012-07-18 20:35:30548 chrome::NOTIFICATION_NO_KEY_WINDOW,
[email protected]ad50def52011-10-19 23:17:07549 content::NotificationService::AllSources(),
550 content::NotificationService::NoDetails());
[email protected]449dd2f2009-05-27 13:04:00551}
552
[email protected]414fde592009-05-21 16:14:43553// If the auto-update interval is not set, make it 5 hours.
554// This code is specific to Mac Chrome Dev Channel.
555// Placed here for 2 reasons:
556// 1) Same spot as other Pref stuff
557// 2) Try and be friendly by keeping this after app launch
558// TODO(jrg): remove once we go Beta.
559- (void)setUpdateCheckInterval {
560#if defined(GOOGLE_CHROME_BUILD)
561 CFStringRef app = (CFStringRef)@"com.google.Keystone.Agent";
562 CFStringRef checkInterval = (CFStringRef)@"checkInterval";
563 CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
564 if (!plist) {
565 const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
[email protected]7dc8c6b2010-04-09 17:02:50566 NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
[email protected]414fde592009-05-21 16:14:43567 CFPreferencesSetAppValue(checkInterval, value, app);
568 CFPreferencesAppSynchronize(app);
569 }
570#endif
571}
572
[email protected]136140c2009-05-19 13:58:25573// This is called after profiles have been loaded and preferences registered.
574// It is safe to access the default profile here.
575- (void)applicationDidFinishLaunching:(NSNotification*)notify {
[email protected]c984d9f2010-07-20 20:52:20576 // Notify BrowserList to keep the application running so it doesn't go away
577 // when all the browser windows get closed.
[email protected]2e6389f2012-05-18 19:41:25578 browser::StartKeepAlive();
[email protected]136140c2009-05-19 13:58:25579
[email protected]414fde592009-05-21 16:14:43580 [self setUpdateCheckInterval];
[email protected]2bcec612009-05-14 17:50:53581
582 // Build up the encoding menu, the order of the items differs based on the
583 // current locale (see http://crbug.com/7647 for details).
584 // We need a valid g_browser_process to get the profile which is why we can't
585 // call this from awakeFromNib.
[email protected]6f91e5ae2011-03-21 19:53:14586 NSMenu* viewMenu = [[[NSApp mainMenu] itemWithTag:IDC_VIEW_MENU] submenu];
587 NSMenuItem* encodingMenuItem = [viewMenu itemWithTag:IDC_ENCODING_MENU];
588 NSMenu* encodingMenu = [encodingMenuItem submenu];
[email protected]a585a8db2011-06-20 18:58:35589 EncodingMenuControllerDelegate::BuildEncodingMenu([self lastProfile],
[email protected]6f91e5ae2011-03-21 19:53:14590 encodingMenu);
[email protected]2bcec612009-05-14 17:50:53591
[email protected]f2c20fa2009-12-01 17:42:02592 // Since Chrome is localized to more languages than the OS, tell Cocoa which
593 // menu is the Help so it can add the search item to it.
[email protected]caadfca2010-01-22 21:51:21594 if (helpMenu_ && [NSApp respondsToSelector:@selector(setHelpMenu:)])
[email protected]f2c20fa2009-12-01 17:42:02595 [NSApp setHelpMenu:helpMenu_];
[email protected]f2c20fa2009-12-01 17:42:02596
[email protected]12dc3d42010-02-22 23:37:12597 // Record the path to the (browser) app bundle; this is used by the app mode
598 // shim.
599 RecordLastRunAppBundlePath();
600
[email protected]eef99c22010-08-17 05:55:16601 // Makes "Services" menu items available.
602 [self registerServicesMenuTypesTo:[notify object]];
603
[email protected]caadfca2010-01-22 21:51:21604 startupComplete_ = YES;
605
606 // TODO(viettrungluu): This is very temporary, since this should be done "in"
607 // |BrowserMain()|, i.e., this list of startup URLs should be appended to the
608 // (probably-empty) list of URLs from the command line.
[email protected]d630d7d52010-02-21 00:55:11609 if (startupUrls_.size()) {
610 [self openUrls:startupUrls_];
611 [self clearStartupUrls];
[email protected]caadfca2010-01-22 21:51:21612 }
[email protected]aac169d2011-03-18 19:53:03613
614 const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
615 if (!parsed_command_line.HasSwitch(switches::kEnableExposeForTabs)) {
616 [tabposeMenuItem_ setHidden:YES];
617 }
[email protected]7c321082009-02-09 15:35:47618}
619
[email protected]a96ec6a2009-11-04 17:27:08620// This is called after profiles have been loaded and preferences registered.
621// It is safe to access the default profile here.
622- (void)applicationDidBecomeActive:(NSNotification*)notify {
[email protected]ad50def52011-10-19 23:17:07623 content::NotificationService::current()->Notify(
624 content::NOTIFICATION_APP_ACTIVATED,
625 content::NotificationService::AllSources(),
626 content::NotificationService::NoDetails());
[email protected]a96ec6a2009-11-04 17:27:08627}
628
[email protected]73f5b362009-08-10 23:58:21629// Helper function for populating and displaying the in progress downloads at
630// exit alert panel.
631- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
[email protected]83a9f652012-04-25 21:03:48632 NSString* titleText = nil;
[email protected]e8b5f7882009-09-14 20:59:13633 NSString* explanationText = nil;
[email protected]73f5b362009-08-10 23:58:21634 NSString* waitTitle = nil;
635 NSString* exitTitle = nil;
636
637 // Set the dialog text based on whether or not there are multiple downloads.
638 if (downloadCount == 1) {
[email protected]e8b5f7882009-09-14 20:59:13639 // Dialog text: warning and explanation.
[email protected]83a9f652012-04-25 21:03:48640 titleText = l10n_util::GetNSString(
641 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_TITLE);
[email protected]ab3b1c112012-01-13 22:04:16642 explanationText = l10n_util::GetNSString(
643 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION);
[email protected]73f5b362009-08-10 23:58:21644 } else {
[email protected]e8b5f7882009-09-14 20:59:13645 // Dialog text: warning and explanation.
[email protected]83a9f652012-04-25 21:03:48646 titleText = l10n_util::GetNSStringF(
647 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_TITLE,
[email protected]528c56d2010-07-30 19:28:44648 base::IntToString16(downloadCount));
[email protected]ab3b1c112012-01-13 22:04:16649 explanationText = l10n_util::GetNSString(
650 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_EXPLANATION);
[email protected]73f5b362009-08-10 23:58:21651 }
[email protected]83a9f652012-04-25 21:03:48652 // Cancel download and exit button text.
653 exitTitle = l10n_util::GetNSString(
654 IDS_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL);
655
656 // Wait for download button text.
657 waitTitle = l10n_util::GetNSString(
658 IDS_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL);
[email protected]73f5b362009-08-10 23:58:21659
660 // 'waitButton' is the default choice.
[email protected]83a9f652012-04-25 21:03:48661 int choice = NSRunAlertPanel(titleText, explanationText,
[email protected]e8b5f7882009-09-14 20:59:13662 waitTitle, exitTitle, nil);
[email protected]73f5b362009-08-10 23:58:21663 return choice == NSAlertDefaultReturn ? YES : NO;
664}
665
666// Check all profiles for in progress downloads, and if we find any, prompt the
[email protected]09729a552009-08-03 23:21:41667// user to see if we should continue to exit (and thus cancel the downloads), or
668// if we should wait.
669- (BOOL)shouldQuitWithInProgressDownloads {
[email protected]73f5b362009-08-10 23:58:21670 ProfileManager* profile_manager = g_browser_process->profile_manager();
671 if (!profile_manager)
672 return YES;
[email protected]09729a552009-08-03 23:21:41673
[email protected]844a1002011-04-19 11:37:21674 std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
675 for (size_t i = 0; i < profiles.size(); ++i) {
[email protected]9bb54ee2011-10-12 17:43:35676 DownloadService* download_service =
677 DownloadServiceFactory::GetForProfile(profiles[i]);
678 DownloadManager* download_manager =
679 (download_service->HasCreatedDownloadManager() ?
[email protected]b441a8492012-06-06 14:55:57680 BrowserContext::GetDownloadManager(profiles[i]) : NULL);
[email protected]5656f8a2011-11-17 16:12:58681 if (download_manager && download_manager->InProgressCount() > 0) {
682 int downloadCount = download_manager->InProgressCount();
[email protected]73f5b362009-08-10 23:58:21683 if ([self userWillWaitForInProgressDownloads:downloadCount]) {
684 // Create a new browser window (if necessary) and navigate to the
685 // downloads page if the user chooses to wait.
[email protected]d8748142012-05-16 21:13:43686 Browser* browser = browser::FindBrowserWithProfile(profiles[i]);
[email protected]73f5b362009-08-10 23:58:21687 if (!browser) {
[email protected]844a1002011-04-19 11:37:21688 browser = Browser::Create(profiles[i]);
[email protected]73f5b362009-08-10 23:58:21689 browser->window()->Show();
690 }
691 DCHECK(browser);
[email protected]5d9cace72012-06-21 16:07:12692 chrome::ShowDownloads(browser);
[email protected]73f5b362009-08-10 23:58:21693 return NO;
694 }
[email protected]09729a552009-08-03 23:21:41695
[email protected]73f5b362009-08-10 23:58:21696 // User wants to exit.
697 return YES;
[email protected]09729a552009-08-03 23:21:41698 }
[email protected]09729a552009-08-03 23:21:41699 }
700
[email protected]73f5b362009-08-10 23:58:21701 // No profiles or active downloads found, okay to exit.
[email protected]09729a552009-08-03 23:21:41702 return YES;
703}
704
[email protected]fbc947b2009-06-19 13:28:24705// Called to determine if we should enable the "restore tab" menu item.
706// Checks with the TabRestoreService to see if there's anything there to
707// restore and returns YES if so.
708- (BOOL)canRestoreTab {
[email protected]92371eb2011-04-28 11:50:15709 TabRestoreService* service =
[email protected]a585a8db2011-06-20 18:58:35710 TabRestoreServiceFactory::GetForProfile([self lastProfile]);
[email protected]fbc947b2009-06-19 13:28:24711 return service && !service->entries().empty();
712}
713
[email protected]f6c15fa2010-06-04 20:08:21714// Returns true if there is not a modal window (either window- or application-
715// modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
716// sheets) will not count as blocking the browser. But things like open/save
717// dialogs that are window modal will block the browser.
718- (BOOL)keyWindowIsNotModal {
[email protected]13858862012-05-24 03:22:51719 Browser* browser = browser::GetLastActiveBrowser();
[email protected]dc76e8362010-06-11 16:29:52720 return [NSApp modalWindow] == nil && (!browser ||
[email protected]90556dd2012-06-07 20:26:18721 ![[browser->window()->GetNativeWindow() attachedSheet]
[email protected]f6c15fa2010-06-04 20:08:21722 isKindOfClass:[NSWindow class]]);
[email protected]6a281332009-10-13 17:41:06723}
724
[email protected]88d74942009-01-21 22:04:44725// Called to validate menu items when there are no key windows. All the
726// items we care about have been set with the |commandDispatch:| action and
727// a target of FirstResponder in IB. If it's not one of those, let it
728// continue up the responder chain to be handled elsewhere. We pull out the
729// tag as the cross-platform constant to differentiate and dispatch the
730// various commands.
731- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
732 SEL action = [item action];
733 BOOL enable = NO;
734 if (action == @selector(commandDispatch:)) {
735 NSInteger tag = [item tag];
[email protected]fbc947b2009-06-19 13:28:24736 if (menuState_->SupportsCommand(tag)) {
737 switch (tag) {
[email protected]419eb2a2009-11-11 16:26:26738 // The File Menu commands are not automatically disabled by Cocoa when a
739 // dialog sheet obscures the browser window, so we disable several of
740 // them here. We don't need to include IDC_CLOSE_WINDOW, because
741 // app_controller is only activated when there are no key windows (see
742 // function comment).
[email protected]fbc947b2009-06-19 13:28:24743 case IDC_RESTORE_TAB:
[email protected]f6c15fa2010-06-04 20:08:21744 enable = [self keyWindowIsNotModal] && [self canRestoreTab];
[email protected]6a281332009-10-13 17:41:06745 break;
[email protected]f6c15fa2010-06-04 20:08:21746 // Browser-level items that open in new tabs should not open if there's
747 // a window- or app-modal dialog.
[email protected]6a281332009-10-13 17:41:06748 case IDC_OPEN_FILE:
[email protected]6a281332009-10-13 17:41:06749 case IDC_NEW_TAB:
[email protected]f6c15fa2010-06-04 20:08:21750 case IDC_SHOW_HISTORY:
751 case IDC_SHOW_BOOKMARK_MANAGER:
752 enable = [self keyWindowIsNotModal];
753 break;
754 // Browser-level items that open in new windows.
755 case IDC_NEW_WINDOW:
756 case IDC_TASK_MANAGER:
757 // Allow the user to open a new window if there's a window-modal
758 // dialog.
759 enable = [self keyWindowIsNotModal] || ([NSApp modalWindow] == nil);
[email protected]fbc947b2009-06-19 13:28:24760 break;
[email protected]65549182012-02-25 00:45:40761 case IDC_SHOW_SYNC_SETUP: {
[email protected]a585a8db2011-06-20 18:58:35762 Profile* lastProfile = [self lastProfile];
[email protected]446e16a2010-05-03 21:23:58763 // The profile may be NULL during shutdown -- see
764 // http://code.google.com/p/chromium/issues/detail?id=43048 .
765 //
766 // TODO(akalin,viettrungluu): Figure out whether this method
[email protected]a585a8db2011-06-20 18:58:35767 // can be prevented from being called if lastProfile is
[email protected]446e16a2010-05-03 21:23:58768 // NULL.
[email protected]a585a8db2011-06-20 18:58:35769 if (!lastProfile) {
[email protected]446e16a2010-05-03 21:23:58770 LOG(WARNING)
[email protected]a585a8db2011-06-20 18:58:35771 << "NULL lastProfile detected -- not doing anything";
[email protected]446e16a2010-05-03 21:23:58772 break;
773 }
[email protected]a585a8db2011-06-20 18:58:35774 enable = lastProfile->IsSyncAccessible() &&
[email protected]d3b98c82010-07-14 07:45:59775 [self keyWindowIsNotModal];
[email protected]a585a8db2011-06-20 18:58:35776 sync_ui_util::UpdateSyncItem(item, enable, lastProfile);
[email protected]f9bc9b92009-11-24 00:55:35777 break;
[email protected]446e16a2010-05-03 21:23:58778 }
[email protected]acaa37b2011-08-31 07:19:11779 case IDC_FEEDBACK:
780 enable = NO;
781 break;
[email protected]fbc947b2009-06-19 13:28:24782 default:
[email protected]f6c15fa2010-06-04 20:08:21783 enable = menuState_->IsCommandEnabled(tag) ?
784 [self keyWindowIsNotModal] : NO;
[email protected]fbc947b2009-06-19 13:28:24785 }
786 }
[email protected]3b6aa8b62009-09-15 21:36:11787 } else if (action == @selector(terminate:)) {
[email protected]88d74942009-01-21 22:04:44788 enable = YES;
[email protected]3111f08b2009-04-30 16:01:52789 } else if (action == @selector(showPreferences:)) {
790 enable = YES;
[email protected]bde3dda2009-05-20 22:13:07791 } else if (action == @selector(orderFrontStandardAboutPanel:)) {
792 enable = YES;
[email protected]93b59fc2010-12-21 20:00:47793 } else if (action == @selector(commandFromDock:)) {
[email protected]3d4bd23f2009-10-06 03:58:38794 enable = YES;
[email protected]a99fce0e2011-03-21 20:58:48795 } else if (action == @selector(toggleConfirmToQuit:)) {
796 [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
797 enable = YES;
[email protected]88d74942009-01-21 22:04:44798 }
799 return enable;
800}
801
[email protected]947fc0d2010-01-14 22:33:05802// Called when the user picks a menu item when there are no key windows, or when
803// there is no foreground browser window. Calls through to the browser object to
804// execute the command. This assumes that the command is supported and doesn't
[email protected]d630d7d52010-02-21 00:55:11805// check, otherwise it should have been disabled in the UI in
806// |-validateUserInterfaceItem:|.
[email protected]88d74942009-01-21 22:04:44807- (void)commandDispatch:(id)sender {
[email protected]a585a8db2011-06-20 18:58:35808 Profile* lastProfile = [self lastProfile];
[email protected]f0a51fb52009-03-05 12:46:38809
[email protected]947fc0d2010-01-14 22:33:05810 // Handle the case where we're dispatching a command from a sender that's in a
811 // browser window. This means that the command came from a background window
812 // and is getting here because the foreground window is not a browser window.
813 if ([sender respondsToSelector:@selector(window)]) {
814 id delegate = [[sender window] windowController];
815 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
816 [delegate commandDispatch:sender];
817 return;
818 }
819 }
820
[email protected]88d74942009-01-21 22:04:44821 NSInteger tag = [sender tag];
822 switch (tag) {
[email protected]fbc947b2009-06-19 13:28:24823 case IDC_NEW_TAB:
[email protected]d630d7d52010-02-21 00:55:11824 // Create a new tab in an existing browser window (which we activate) if
825 // possible.
[email protected]a585a8db2011-06-20 18:58:35826 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d98294912012-06-27 22:57:40827 chrome::ExecuteCommand(browser, IDC_NEW_TAB);
[email protected]d630d7d52010-02-21 00:55:11828 break;
829 }
830 // Else fall through to create new window.
[email protected]88d74942009-01-21 22:04:44831 case IDC_NEW_WINDOW:
[email protected]a585a8db2011-06-20 18:58:35832 CreateBrowser(lastProfile);
[email protected]d630d7d52010-02-21 00:55:11833 break;
[email protected]91a5b3e2009-10-30 19:32:22834 case IDC_FOCUS_LOCATION:
[email protected]5d98294912012-06-27 22:57:40835 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
836 IDC_FOCUS_LOCATION);
[email protected]88d74942009-01-21 22:04:44837 break;
[email protected]cddc5242009-12-07 18:54:33838 case IDC_FOCUS_SEARCH:
[email protected]5d98294912012-06-27 22:57:40839 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
840 IDC_FOCUS_SEARCH);
[email protected]cddc5242009-12-07 18:54:33841 break;
[email protected]863ff662009-01-26 20:18:18842 case IDC_NEW_INCOGNITO_WINDOW:
[email protected]eddcf7502012-02-09 22:43:48843 CreateBrowser(lastProfile->GetOffTheRecordProfile());
[email protected]863ff662009-01-26 20:18:18844 break;
[email protected]fbc947b2009-06-19 13:28:24845 case IDC_RESTORE_TAB:
[email protected]a37d4b02012-06-25 21:56:10846 chrome::OpenWindowWithRestoredTabs(lastProfile);
[email protected]fbc947b2009-06-19 13:28:24847 break;
[email protected]e19516d2009-04-28 17:15:19848 case IDC_OPEN_FILE:
[email protected]5d98294912012-06-27 22:57:40849 chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
[email protected]e19516d2009-04-28 17:15:19850 break;
[email protected]1fdff702009-10-22 00:36:18851 case IDC_CLEAR_BROWSING_DATA: {
[email protected]93e181762009-05-29 14:30:38852 // There may not be a browser open, so use the default profile.
[email protected]a585a8db2011-06-20 18:58:35853 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:12854 chrome::ShowClearBrowsingDataDialog(browser);
[email protected]c8de64a2011-01-25 17:10:23855 } else {
[email protected]1f0b50b2012-06-22 20:37:16856 chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:23857 }
[email protected]93e181762009-05-29 14:30:38858 break;
[email protected]1fdff702009-10-22 00:36:18859 }
[email protected]4aee5652009-11-19 18:59:21860 case IDC_IMPORT_SETTINGS: {
[email protected]a585a8db2011-06-20 18:58:35861 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:12862 chrome::ShowImportDialog(browser);
[email protected]c8de64a2011-01-25 17:10:23863 } else {
[email protected]1f0b50b2012-06-22 20:37:16864 chrome::OpenImportSettingsDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:23865 }
[email protected]4aee5652009-11-19 18:59:21866 break;
867 }
[email protected]af7c25e2010-01-23 05:46:45868 case IDC_SHOW_BOOKMARK_MANAGER:
[email protected]7f6f44c2011-12-14 13:23:38869 content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
[email protected]a585a8db2011-06-20 18:58:35870 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:12871 chrome::ShowBookmarkManager(browser);
[email protected]90a8bf252010-03-12 00:09:47872 } else {
[email protected]47e532b2010-04-23 17:46:40873 // No browser window, so create one for the bookmark manager tab.
[email protected]1f0b50b2012-06-22 20:37:16874 chrome::OpenBookmarkManagerWindow(lastProfile);
[email protected]90a8bf252010-03-12 00:09:47875 }
[email protected]af7c25e2010-01-23 05:46:45876 break;
[email protected]91a5b3e2009-10-30 19:32:22877 case IDC_SHOW_HISTORY:
[email protected]a585a8db2011-06-20 18:58:35878 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:12879 chrome::ShowHistory(browser);
[email protected]d630d7d52010-02-21 00:55:11880 else
[email protected]1f0b50b2012-06-22 20:37:16881 chrome::OpenHistoryWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:22882 break;
883 case IDC_SHOW_DOWNLOADS:
[email protected]a585a8db2011-06-20 18:58:35884 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:12885 chrome::ShowDownloads(browser);
[email protected]d630d7d52010-02-21 00:55:11886 else
[email protected]1f0b50b2012-06-22 20:37:16887 chrome::OpenDownloadsWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:22888 break;
[email protected]bb37e6ec2009-11-18 17:59:36889 case IDC_MANAGE_EXTENSIONS:
[email protected]a585a8db2011-06-20 18:58:35890 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:12891 chrome::ShowExtensions(browser);
[email protected]d630d7d52010-02-21 00:55:11892 else
[email protected]1f0b50b2012-06-22 20:37:16893 chrome::OpenExtensionsWindow(lastProfile);
[email protected]bb37e6ec2009-11-18 17:59:36894 break;
[email protected]2ca35612012-06-12 03:49:48895 case IDC_HELP_PAGE_VIA_MENU:
[email protected]a585a8db2011-06-20 18:58:35896 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:12897 chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
[email protected]d630d7d52010-02-21 00:55:11898 else
[email protected]1f0b50b2012-06-22 20:37:16899 chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
[email protected]1fdff702009-10-22 00:36:18900 break;
[email protected]65549182012-02-25 00:45:40901 case IDC_SHOW_SYNC_SETUP:
902 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:12903 chrome::ShowSyncSetup(browser, SyncPromoUI::SOURCE_MENU);
[email protected]65549182012-02-25 00:45:40904 else
[email protected]1f0b50b2012-06-22 20:37:16905 chrome::OpenSyncSetupWindow(lastProfile, SyncPromoUI::SOURCE_MENU);
[email protected]f9bc9b92009-11-24 00:55:35906 break;
[email protected]ceaaf1812010-01-20 22:13:09907 case IDC_TASK_MANAGER:
[email protected]7f6f44c2011-12-14 13:23:38908 content::RecordAction(UserMetricsAction("TaskManager"));
[email protected]adb6a84d2011-02-07 16:58:40909 TaskManagerMac::Show(false);
[email protected]ceaaf1812010-01-20 22:13:09910 break;
[email protected]4a42d272010-06-18 01:29:42911 case IDC_OPTIONS:
912 [self showPreferences:sender];
913 break;
[email protected]93b59fc2010-12-21 20:00:47914 default:
915 // Background Applications use dynamic values that must be less than the
916 // smallest value among the predefined IDC_* labels.
917 if ([sender tag] < IDC_MinimumLabelValue)
918 [self executeApplication:sender];
919 break;
[email protected]d630d7d52010-02-21 00:55:11920 }
[email protected]88d74942009-01-21 22:04:44921}
922
[email protected]93b59fc2010-12-21 20:00:47923// Run a (background) application in a new tab.
924- (void)executeApplication:(id)sender {
925 NSInteger tag = [sender tag];
[email protected]a585a8db2011-06-20 18:58:35926 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:47927 DCHECK(profile);
928 BackgroundApplicationListModel applications(profile);
929 DCHECK(tag >= 0 &&
930 tag < static_cast<int>(applications.size()));
[email protected]1c321ee2012-05-21 03:02:34931 const extensions::Extension* extension = applications.GetExtension(tag);
[email protected]78d78a62011-09-29 18:24:33932 BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
[email protected]93b59fc2010-12-21 20:00:47933}
934
[email protected]947fc0d2010-01-14 22:33:05935// Same as |-commandDispatch:|, but executes commands using a disposition
936// determined by the key flags. This will get called in the case where the
937// frontmost window is not a browser window, and the user has command-clicked
938// a button in a background browser window whose action is
939// |-commandDispatchUsingKeyModifiers:|
940- (void)commandDispatchUsingKeyModifiers:(id)sender {
941 DCHECK(sender);
942 if ([sender respondsToSelector:@selector(window)]) {
943 id delegate = [[sender window] windowController];
944 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
945 [delegate commandDispatchUsingKeyModifiers:sender];
946 }
947 }
948}
949
[email protected]ff81e0a2009-04-13 14:58:54950// NSApplication delegate method called when someone clicks on the
951// dock icon and there are no open windows. To match standard mac
952// behavior, we should open a new window.
953- (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
954 hasVisibleWindows:(BOOL)flag {
[email protected]70631402010-04-26 20:16:54955 // If the browser is currently trying to quit, don't do anything and return NO
956 // to prevent AppKit from doing anything.
957 // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
958 if (browser_shutdown::IsTryingToQuit())
959 return NO;
960
[email protected]0236be22012-01-11 01:05:35961 // Don't do anything if there are visible tabbed or popup windows. This will
962 // cause AppKit to unminimize the most recently minimized window. If the
963 // visible windows are panels or notifications, we still need to open a new
964 // window.
965 if (flag) {
966 for (BrowserList::const_iterator iter = BrowserList::begin();
967 iter != BrowserList::end(); ++iter) {
968 Browser* browser = *iter;
969 if (browser->is_type_tabbed() || browser->is_type_popup())
970 return YES;
971 }
972 }
[email protected]ff81e0a2009-04-13 14:58:54973
[email protected]0d1210d62010-09-07 17:31:38974 // If launched as a hidden login item (due to installation of a persistent app
[email protected]eddcf7502012-02-09 22:43:48975 // or by the user, for example in System Preferences->Accounts->Login Items),
[email protected]0d1210d62010-09-07 17:31:38976 // allow session to be restored first time the user clicks on a Dock icon.
977 // Normally, it'd just open a new empty page.
978 {
[email protected]eddcf7502012-02-09 22:43:48979 static BOOL doneOnce = NO;
980 if (!doneOnce) {
981 doneOnce = YES;
982 if (base::mac::WasLaunchedAsHiddenLoginItem()) {
983 SessionService* sessionService =
984 SessionServiceFactory::GetForProfile([self lastProfile]);
985 if (sessionService &&
986 sessionService->RestoreIfNecessary(std::vector<GURL>()))
987 return NO;
[email protected]0d1210d62010-09-07 17:31:38988 }
[email protected]eddcf7502012-02-09 22:43:48989 }
[email protected]0d1210d62010-09-07 17:31:38990 }
[email protected]fc44f242012-02-14 16:54:39991
992 // Platform apps don't use browser windows so don't do anything if there are
993 // visible windows.
994 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
995 if (flag && command_line.HasSwitch(switches::kAppId))
996 return YES;
997
[email protected]ff81e0a2009-04-13 14:58:54998 // Otherwise open a new window.
[email protected]d630d7d52010-02-21 00:55:11999 {
[email protected]0fbd70332010-06-01 19:28:341000 AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
[email protected]fc44f242012-02-14 16:54:391001 int return_code;
[email protected]fe7c4872012-05-10 20:06:031002 StartupBrowserCreator browser_creator;
1003 browser_creator.LaunchBrowser(
1004 command_line, [self lastProfile], FilePath(),
[email protected]4feb37d92012-07-01 20:22:131005 chrome::startup::IS_NOT_PROCESS_STARTUP,
1006 chrome::startup::IS_NOT_FIRST_RUN, &return_code);
[email protected]d630d7d52010-02-21 00:55:111007 }
[email protected]ff81e0a2009-04-13 14:58:541008
1009 // We've handled the reopen event, so return NO to tell AppKit not
1010 // to do anything.
1011 return NO;
1012}
1013
[email protected]88d74942009-01-21 22:04:441014- (void)initMenuState {
[email protected]3111f08b2009-04-30 16:01:521015 menuState_.reset(new CommandUpdater(NULL));
[email protected]fbc947b2009-06-19 13:28:241016 menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
[email protected]88d74942009-01-21 22:04:441017 menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
[email protected]863ff662009-01-26 20:18:181018 menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
[email protected]e19516d2009-04-28 17:15:191019 menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
[email protected]93e181762009-05-29 14:30:381020 menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
[email protected]fbc947b2009-06-19 13:28:241021 menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
[email protected]91a5b3e2009-10-30 19:32:221022 menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
[email protected]cddc5242009-12-07 18:54:331023 menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
[email protected]af7c25e2010-01-23 05:46:451024 menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
[email protected]91a5b3e2009-10-30 19:32:221025 menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1026 menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
[email protected]bb37e6ec2009-11-18 17:59:361027 menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
[email protected]2ca35612012-06-12 03:49:481028 menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
[email protected]4aee5652009-11-19 18:59:211029 menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
[email protected]1c41a932010-11-22 23:41:231030 menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
[email protected]65549182012-02-25 00:45:401031 menuState_->UpdateCommandEnabled(IDC_SHOW_SYNC_SETUP, true);
[email protected]ceaaf1812010-01-20 22:13:091032 menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
[email protected]88d74942009-01-21 22:04:441033}
[email protected]1bcdb532009-01-16 17:47:571034
[email protected]961a6932011-07-19 19:52:461035// Conditionally adds the Profile menu to the main menu bar.
1036- (void)initProfileMenu {
[email protected]961a6932011-07-19 19:52:461037 NSMenu* mainMenu = [NSApp mainMenu];
1038 NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
[email protected]e354ca42011-08-03 20:31:401039
1040 // On Leopard, hiding main menubar items does not work. This manifests itself
1041 // in Chromium as squished menu items <http://crbug.com/90753>. To prevent
1042 // this, remove the Profile menu on Leopard, regardless of the user's
1043 // multiprofile state.
[email protected]6b2d30bc2011-10-11 18:16:391044 if (!ProfileManager::IsMultipleProfilesEnabled() ||
1045 base::mac::IsOSLeopard()) {
[email protected]e354ca42011-08-03 20:31:401046 [mainMenu removeItem:profileMenu];
1047 return;
1048 }
1049
[email protected]6b2d30bc2011-10-11 18:16:391050 // The controller will unhide the menu if necessary.
1051 [profileMenu setHidden:YES];
[email protected]961a6932011-07-19 19:52:461052
[email protected]6b2d30bc2011-10-11 18:16:391053 profileMenuController_.reset(
1054 [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
[email protected]961a6932011-07-19 19:52:461055}
1056
[email protected]a99fce0e2011-03-21 20:58:481057// The Confirm to Quit preference is atypical in that the preference lives in
1058// the app menu right above the Quit menu item. This method will refresh the
1059// display of that item depending on the preference state.
1060- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1061 // Format the string so that the correct key equivalent is displayed.
1062 NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1063 NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1064 base::SysNSStringToUTF16(acceleratorString));
1065 [item setTitle:title];
1066
[email protected]b6366ffa2012-02-29 17:12:261067 const PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481068 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1069 [item setState:enabled ? NSOnState : NSOffState];
1070}
1071
[email protected]eef99c22010-08-17 05:55:161072- (void)registerServicesMenuTypesTo:(NSApplication*)app {
[email protected]09ea24c2010-08-23 19:05:411073 // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1074 // handles requests from services.
1075 NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
1076 [app registerServicesMenuSendTypes:types returnTypes:types];
[email protected]eef99c22010-08-17 05:55:161077}
1078
[email protected]a585a8db2011-06-20 18:58:351079- (Profile*)lastProfile {
[email protected]7fd5a462011-06-19 16:57:231080 // Return the profile of the last-used BrowserWindowController, if available.
1081 if (lastProfile_)
1082 return lastProfile_;
1083
[email protected]056f8792011-07-20 15:40:151084 // On first launch, no profile will be stored, so use last from Local State.
[email protected]3f34599d2009-03-25 22:11:431085 if (g_browser_process->profile_manager())
[email protected]056f8792011-07-20 15:40:151086 return g_browser_process->profile_manager()->GetLastUsedProfile();
[email protected]3f34599d2009-03-25 22:11:431087
[email protected]f6314002009-04-23 01:18:131088 return NULL;
[email protected]3f34599d2009-03-25 22:11:431089}
1090
[email protected]57750f822009-04-21 21:43:091091// Various methods to open URLs that we get in a native fashion. We use
[email protected]fe7c4872012-05-10 20:06:031092// StartupBrowserCreator here because on the other platforms, URLs to open come
1093// through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
1094// to bottleneck the openings through that for uniform handling.
[email protected]57750f822009-04-21 21:43:091095
[email protected]d630d7d52010-02-21 00:55:111096- (void)openUrls:(const std::vector<GURL>&)urls {
[email protected]caadfca2010-01-22 21:51:211097 // If the browser hasn't started yet, just queue up the URLs.
1098 if (!startupComplete_) {
[email protected]d630d7d52010-02-21 00:55:111099 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
[email protected]136140c2009-05-19 13:58:251100 return;
1101 }
[email protected]57750f822009-04-21 21:43:091102
[email protected]13858862012-05-24 03:22:511103 Browser* browser = browser::GetLastActiveBrowser();
[email protected]0e863512009-05-28 19:45:071104 // if no browser window exists then create one with no tabs to be filled in
1105 if (!browser) {
[email protected]a585a8db2011-06-20 18:58:351106 browser = Browser::Create([self lastProfile]);
[email protected]ce560f82009-06-03 09:39:441107 browser->window()->Show();
[email protected]0e863512009-05-28 19:45:071108 }
1109
[email protected]947446b2010-10-21 03:36:311110 CommandLine dummy(CommandLine::NO_PROGRAM);
[email protected]4feb37d92012-07-01 20:22:131111 chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
1112 chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
[email protected]cc2806852012-05-11 20:48:261113 StartupBrowserCreatorImpl launch(FilePath(), dummy, first_run);
[email protected]0e863512009-05-28 19:45:071114 launch.OpenURLsInBrowser(browser, false, urls);
[email protected]57750f822009-04-21 21:43:091115}
1116
[email protected]57750f822009-04-21 21:43:091117- (void)getUrl:(NSAppleEventDescriptor*)event
1118 withReply:(NSAppleEventDescriptor*)reply {
1119 NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1120 stringValue];
1121
1122 GURL gurl(base::SysNSStringToUTF8(urlStr));
1123 std::vector<GURL> gurlVector;
1124 gurlVector.push_back(gurl);
1125
[email protected]d630d7d52010-02-21 00:55:111126 [self openUrls:gurlVector];
[email protected]57750f822009-04-21 21:43:091127}
1128
[email protected]a529af52011-08-15 20:56:171129// Apple Event handler that receives print event from service
1130// process, gets the required data and launches Print dialog.
1131- (void)submitCloudPrintJob:(NSAppleEventDescriptor*)event {
1132 // Pull parameter list out of Apple Event.
[email protected]ebbe94b2012-01-18 20:11:561133 NSAppleEventDescriptor* paramList =
[email protected]13aec6c42011-10-27 21:22:081134 [event paramDescriptorForKeyword:cloud_print::kAECloudPrintClass];
[email protected]a529af52011-08-15 20:56:171135
1136 if (paramList != nil) {
1137 // Pull required fields out of parameter list.
1138 NSString* mime = [[paramList descriptorAtIndex:1] stringValue];
1139 NSString* inputPath = [[paramList descriptorAtIndex:2] stringValue];
1140 NSString* printTitle = [[paramList descriptorAtIndex:3] stringValue];
[email protected]e8368e92011-08-20 04:05:561141 NSString* printTicket = [[paramList descriptorAtIndex:4] stringValue];
[email protected]a529af52011-08-15 20:56:171142 // Convert the title to UTF 16 as required.
1143 string16 title16 = base::SysNSStringToUTF16(printTitle);
[email protected]e8368e92011-08-20 04:05:561144 string16 printTicket16 = base::SysNSStringToUTF16(printTicket);
[email protected]a529af52011-08-15 20:56:171145 print_dialog_cloud::CreatePrintDialogForFile(
[email protected]b5b79d72012-05-24 19:42:281146 ProfileManager::GetDefaultProfile(), NULL,
[email protected]a529af52011-08-15 20:56:171147 FilePath([inputPath UTF8String]), title16,
[email protected]b5b79d72012-05-24 19:42:281148 printTicket16, [mime UTF8String], /*delete_on_close=*/false);
[email protected]a529af52011-08-15 20:56:171149 }
1150}
1151
1152// Calls the helper class to install the virtual driver to the
1153// service process.
1154- (void)installCloudPrint:(NSAppleEventDescriptor*)event {
1155 cloud_print::VirtualDriverInstallHelper::SetUpInstall();
1156}
1157
1158// Calls the helper class to uninstall the virtual driver to the
1159// service process.
1160- (void)uninstallCloudPrint:(NSAppleEventDescriptor*)event {
1161 cloud_print::VirtualDriverInstallHelper::SetUpUninstall();
1162}
1163
[email protected]caadfca2010-01-22 21:51:211164- (void)application:(NSApplication*)sender
1165 openFiles:(NSArray*)filenames {
[email protected]57750f822009-04-21 21:43:091166 std::vector<GURL> gurlVector;
[email protected]caadfca2010-01-22 21:51:211167 for (NSString* file in filenames) {
1168 GURL gurl = net::FilePathToFileURL(FilePath(base::SysNSStringToUTF8(file)));
[email protected]57750f822009-04-21 21:43:091169 gurlVector.push_back(gurl);
1170 }
[email protected]caadfca2010-01-22 21:51:211171 if (!gurlVector.empty())
[email protected]d630d7d52010-02-21 00:55:111172 [self openUrls:gurlVector];
[email protected]caadfca2010-01-22 21:51:211173 else
1174 NOTREACHED() << "Nothing to open!";
[email protected]57750f822009-04-21 21:43:091175
[email protected]caadfca2010-01-22 21:51:211176 [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
[email protected]57750f822009-04-21 21:43:091177}
[email protected]3f34599d2009-03-25 22:11:431178
[email protected]3111f08b2009-04-30 16:01:521179// Show the preferences window, or bring it to the front if it's already
1180// visible.
1181- (IBAction)showPreferences:(id)sender {
[email protected]a585a8db2011-06-20 18:58:351182 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]445177652011-03-09 02:04:051183 // Show options tab in the active browser window.
[email protected]5d9cace72012-06-21 16:07:121184 chrome::ShowSettings(browser);
[email protected]4a42d272010-06-18 01:29:421185 } else {
[email protected]445177652011-03-09 02:04:051186 // No browser window, so create one for the options tab.
[email protected]1f0b50b2012-06-22 20:37:161187 chrome::OpenOptionsWindow([self lastProfile]);
[email protected]4a42d272010-06-18 01:29:421188 }
[email protected]d989f07c2009-11-14 00:35:461189}
1190
[email protected]bde3dda2009-05-20 22:13:071191- (IBAction)orderFrontStandardAboutPanel:(id)sender {
[email protected]a048ad22012-03-23 04:26:561192 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]5d9cace72012-06-21 16:07:121193 chrome::ShowAboutChrome(browser);
[email protected]a9fbb0962012-03-21 23:25:131194 } else {
[email protected]a048ad22012-03-23 04:26:561195 // No browser window, so create one for the about tab.
[email protected]1f0b50b2012-06-22 20:37:161196 chrome::OpenAboutWindow([self lastProfile]);
[email protected]bde3dda2009-05-20 22:13:071197 }
[email protected]bde3dda2009-05-20 22:13:071198}
1199
[email protected]a99fce0e2011-03-21 20:58:481200- (IBAction)toggleConfirmToQuit:(id)sender {
[email protected]b6366ffa2012-02-29 17:12:261201 PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481202 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1203 prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1204}
1205
[email protected]3d4bd23f2009-10-06 03:58:381206// Explicitly bring to the foreground when creating new windows from the dock.
[email protected]93b59fc2010-12-21 20:00:471207- (void)commandFromDock:(id)sender {
[email protected]3d4bd23f2009-10-06 03:58:381208 [NSApp activateIgnoringOtherApps:YES];
1209 [self commandDispatch:sender];
1210}
1211
[email protected]227fcee2010-06-11 19:19:371212- (NSMenu*)applicationDockMenu:(NSApplication*)sender {
[email protected]018a3962009-09-17 22:23:441213 NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
[email protected]a585a8db2011-06-20 18:58:351214 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:471215
[email protected]018a3962009-09-17 22:23:441216 NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
[email protected]8c6b029d2011-01-21 22:39:511217 scoped_nsobject<NSMenuItem> item(
1218 [[NSMenuItem alloc] initWithTitle:titleStr
1219 action:@selector(commandFromDock:)
1220 keyEquivalent:@""]);
[email protected]288bfcd32009-09-14 18:14:461221 [item setTarget:self];
1222 [item setTag:IDC_NEW_WINDOW];
[email protected]018a3962009-09-17 22:23:441223 [dockMenu addItem:item];
[email protected]288bfcd32009-09-14 18:14:461224
1225 titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
[email protected]018a3962009-09-17 22:23:441226 item.reset([[NSMenuItem alloc] initWithTitle:titleStr
[email protected]8c6b029d2011-01-21 22:39:511227 action:@selector(commandFromDock:)
[email protected]018a3962009-09-17 22:23:441228 keyEquivalent:@""]);
[email protected]288bfcd32009-09-14 18:14:461229 [item setTarget:self];
1230 [item setTag:IDC_NEW_INCOGNITO_WINDOW];
[email protected]018a3962009-09-17 22:23:441231 [dockMenu addItem:item];
[email protected]288bfcd32009-09-14 18:14:461232
[email protected]8c6b029d2011-01-21 22:39:511233 // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1234 // tests which use the mock in place of the profile-initialized model.
1235
1236 // Avoid breaking unit tests which have no profile.
1237 if (profile) {
1238 BackgroundApplicationListModel applications(profile);
1239 if (applications.size()) {
1240 int position = 0;
1241 NSString* menuStr =
1242 l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
1243 scoped_nsobject<NSMenu> appMenu([[NSMenu alloc] initWithTitle:menuStr]);
[email protected]1c321ee2012-05-21 03:02:341244 for (extensions::ExtensionList::const_iterator cursor =
1245 applications.begin();
[email protected]8c6b029d2011-01-21 22:39:511246 cursor != applications.end();
1247 ++cursor, ++position) {
[email protected]2ce9c89752011-02-25 18:24:341248 DCHECK_EQ(applications.GetPosition(*cursor), position);
[email protected]8c6b029d2011-01-21 22:39:511249 NSString* itemStr =
1250 base::SysUTF16ToNSString(UTF8ToUTF16((*cursor)->name()));
1251 scoped_nsobject<NSMenuItem> appItem([[NSMenuItem alloc]
1252 initWithTitle:itemStr
1253 action:@selector(commandFromDock:)
1254 keyEquivalent:@""]);
1255 [appItem setTarget:self];
1256 [appItem setTag:position];
1257 [appMenu addItem:appItem];
1258 }
1259 scoped_nsobject<NSMenuItem> appMenuItem([[NSMenuItem alloc]
1260 initWithTitle:menuStr
1261 action:@selector(commandFromDock:)
1262 keyEquivalent:@""]);
1263 [appMenuItem setTarget:self];
1264 [appMenuItem setTag:position];
1265 [appMenuItem setSubmenu:appMenu];
1266 [dockMenu addItem:appMenuItem];
1267 }
1268 }
1269
[email protected]018a3962009-09-17 22:23:441270 return dockMenu;
[email protected]288bfcd32009-09-14 18:14:461271}
1272
[email protected]d630d7d52010-02-21 00:55:111273- (const std::vector<GURL>&)startupUrls {
1274 return startupUrls_;
[email protected]caadfca2010-01-22 21:51:211275}
1276
[email protected]d630d7d52010-02-21 00:55:111277- (void)clearStartupUrls {
1278 startupUrls_.clear();
[email protected]caadfca2010-01-22 21:51:211279}
1280
[email protected]7e4c69d02011-05-11 22:16:471281- (BookmarkMenuBridge*)bookmarkMenuBridge {
1282 return bookmarkMenuBridge_.get();
1283}
1284
[email protected]33190c82012-04-10 17:04:441285- (void)addObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1286 workAreaChangeObservers_.AddObserver(observer);
1287}
1288
1289- (void)removeObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1290 workAreaChangeObservers_.RemoveObserver(observer);
1291}
1292
[email protected]ebbe94b2012-01-18 20:11:561293- (void)applicationDidChangeScreenParameters:(NSNotification*)notification {
[email protected]6a455072011-11-02 01:32:281294 // During this callback the working area is not always already updated. Defer.
[email protected]33190c82012-04-10 17:04:441295 [self performSelector:@selector(delayedScreenParametersUpdate)
[email protected]6a455072011-11-02 01:32:281296 withObject:nil
1297 afterDelay:0];
1298}
1299
[email protected]33190c82012-04-10 17:04:441300- (void)delayedScreenParametersUpdate {
1301 FOR_EACH_OBSERVER(ui::WorkAreaWatcherObserver, workAreaChangeObservers_,
1302 WorkAreaChanged());
[email protected]6a455072011-11-02 01:32:281303}
1304
[email protected]d630d7d52010-02-21 00:55:111305@end // @implementation AppController
[email protected]60ad3e22009-09-18 21:07:191306
1307//---------------------------------------------------------------------------
1308
[email protected]0934de82011-03-09 18:42:161309namespace browser {
1310
1311void ShowInstantConfirmDialog(gfx::NativeWindow parent, Profile* profile) {
1312 if (Browser* browser = ActivateBrowser(profile)) {
[email protected]5d9cace72012-06-21 16:07:121313 chrome::ShowInstantConfirmDialog(browser);
[email protected]0934de82011-03-09 18:42:161314 } else {
[email protected]1f0b50b2012-06-22 20:37:161315 chrome::OpenInstantConfirmDialogWindow(profile);
[email protected]0934de82011-03-09 18:42:161316 }
1317}
1318
1319} // namespace browser
1320
[email protected]216e9042009-10-29 17:05:231321namespace app_controller_mac {
1322
1323bool IsOpeningNewWindow() {
1324 return g_is_opening_new_window;
1325}
1326
1327} // namespace app_controller_mac