blob: 14dc3d73c7d2910e5f8b243c3900605035c96c80 [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]8d4bbdc2012-09-20 21:36:4932#include "chrome/browser/sessions/session_restore.h"
[email protected]d2912a22011-03-15 15:20:5033#include "chrome/browser/sessions/session_service.h"
[email protected]92371eb2011-04-28 11:50:1534#include "chrome/browser/sessions/session_service_factory.h"
[email protected]fbc947b2009-06-19 13:28:2435#include "chrome/browser/sessions/tab_restore_service.h"
[email protected]92371eb2011-04-28 11:50:1536#include "chrome/browser/sessions/tab_restore_service_factory.h"
[email protected]f9bc9b92009-11-24 00:55:3537#include "chrome/browser/sync/profile_sync_service.h"
[email protected]40f047972009-11-25 03:54:4038#include "chrome/browser/sync/sync_ui_util.h"
39#include "chrome/browser/sync/sync_ui_util_mac.h"
[email protected]ae04f592010-11-18 20:41:3540#include "chrome/browser/ui/browser.h"
[email protected]a37d4b02012-06-25 21:56:1041#include "chrome/browser/ui/browser_commands.h"
[email protected]d8748142012-05-16 21:13:4342#include "chrome/browser/ui/browser_finder.h"
[email protected]ae04f592010-11-18 20:41:3543#include "chrome/browser/ui/browser_list.h"
[email protected]a13b76f2012-06-20 15:36:2944#include "chrome/browser/ui/browser_mac.h"
[email protected]ae04f592010-11-18 20:41:3545#include "chrome/browser/ui/browser_window.h"
[email protected]5d9cace72012-06-21 16:07:1246#include "chrome/browser/ui/chrome_pages.h"
[email protected]7d791652010-12-01 16:34:4947#import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h"
48#import "chrome/browser/ui/cocoa/browser_window_cocoa.h"
49#import "chrome/browser/ui/cocoa/browser_window_controller.h"
[email protected]b6366ffa2012-02-29 17:12:2650#import "chrome/browser/ui/cocoa/confirm_quit.h"
[email protected]7d791652010-12-01 16:34:4951#import "chrome/browser/ui/cocoa/confirm_quit_panel_controller.h"
52#import "chrome/browser/ui/cocoa/encoding_menu_controller_delegate_mac.h"
53#import "chrome/browser/ui/cocoa/history_menu_bridge.h"
[email protected]4feb37d92012-07-01 20:22:1354#include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
[email protected]961a6932011-07-19 19:52:4655#import "chrome/browser/ui/cocoa/profile_menu_controller.h"
[email protected]cfe1d612011-01-19 20:06:4756#import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
57#import "chrome/browser/ui/cocoa/tabs/tab_window_controller.h"
[email protected]7d791652010-12-01 16:34:4958#include "chrome/browser/ui/cocoa/task_manager_mac.h"
[email protected]4feb37d92012-07-01 20:22:1359#include "chrome/browser/ui/startup/startup_browser_creator.h"
60#include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
[email protected]14fb7d32011-07-10 17:53:3261#include "chrome/common/chrome_notification_types.h"
[email protected]12dc3d42010-02-22 23:37:1262#include "chrome/common/chrome_paths_internal.h"
[email protected]f4acfae82009-09-11 00:33:3863#include "chrome/common/chrome_switches.h"
[email protected]13aec6c42011-10-27 21:22:0864#include "chrome/common/cloud_print/cloud_print_class_mac.h"
[email protected]6c583d32011-08-19 14:46:2265#include "chrome/common/mac/app_mode_common.h"
[email protected]a99fce0e2011-03-21 20:58:4866#include "chrome/common/pref_names.h"
[email protected]a529af52011-08-15 20:56:1767#include "chrome/common/service_messages.h"
[email protected]024617a2010-08-20 05:08:0568#include "chrome/common/url_constants.h"
[email protected]c38831a12011-10-28 12:44:4969#include "content/public/browser/browser_thread.h"
[email protected]e582fdd2011-12-20 16:48:1770#include "content/public/browser/download_manager.h"
[email protected]ad50def52011-10-19 23:17:0771#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:1672#include "content/public/browser/notification_types.h"
[email protected]5904cb42012-09-24 15:05:2073#include "content/public/browser/plugin_service.h"
[email protected]7f6f44c2011-12-14 13:23:3874#include "content/public/browser/user_metrics.h"
[email protected]9dcb59662009-09-23 01:15:5075#include "grit/chromium_strings.h"
[email protected]09729a552009-08-03 23:21:4176#include "grit/generated_resources.h"
[email protected]caadfca2010-01-22 21:51:2177#include "net/base/net_util.h"
[email protected]2b68f812011-11-25 15:02:1178#include "ui/base/accelerators/accelerator_cocoa.h"
[email protected]c051a1b2011-01-21 23:30:1779#include "ui/base/l10n/l10n_util.h"
80#include "ui/base/l10n/l10n_util_mac.h"
[email protected]88d74942009-01-21 22:04:4481
[email protected]b441a8492012-06-06 14:55:5782using content::BrowserContext;
[email protected]631bb742011-11-02 11:29:3983using content::BrowserThread;
[email protected]e582fdd2011-12-20 16:48:1784using content::DownloadManager;
[email protected]7f6f44c2011-12-14 13:23:3885using content::UserMetricsAction;
[email protected]631bb742011-11-02 11:29:3986
[email protected]d630d7d52010-02-21 00:55:1187namespace {
88
[email protected]ebbe94b2012-01-18 20:11:5689// Declare notification names from the 10.7 SDK.
90#if !defined(MAC_OS_X_VERSION_10_7) || \
91 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
92NSString* NSPopoverDidShowNotification = @"NSPopoverDidShowNotification";
93NSString* NSPopoverDidCloseNotification = @"NSPopoverDidCloseNotification";
94#endif
95
[email protected]a37d4b02012-06-25 21:56:1096// True while AppController is calling chrome::NewEmptyWindow(). We need a
[email protected]fe7c4872012-05-10 20:06:0397// global flag here, analogue to StartupBrowserCreator::InProcessStartup()
98// because otherwise the SessionService will try to restore sessions when we
99// make a new window while there are no other active windows.
[email protected]d630d7d52010-02-21 00:55:11100bool g_is_opening_new_window = false;
101
102// Activates a browser window having the given profile (the last one active) if
103// possible and returns a pointer to the activate |Browser| or NULL if this was
104// not possible. If the last active browser is minimized (in particular, if
105// there are only minimized windows), it will unminimize it.
106Browser* ActivateBrowser(Profile* profile) {
[email protected]d8748142012-05-16 21:13:43107 Browser* browser = browser::FindLastActiveWithProfile(profile);
[email protected]d630d7d52010-02-21 00:55:11108 if (browser)
109 browser->window()->Activate();
110 return browser;
111}
112
113// Creates an empty browser window with the given profile and returns a pointer
114// to the new |Browser|.
115Browser* CreateBrowser(Profile* profile) {
116 {
[email protected]0fbd70332010-06-01 19:28:34117 AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
[email protected]a37d4b02012-06-25 21:56:10118 chrome::NewEmptyWindow(profile);
[email protected]d630d7d52010-02-21 00:55:11119 }
120
[email protected]13858862012-05-24 03:22:51121 Browser* browser = browser::GetLastActiveBrowser();
[email protected]d630d7d52010-02-21 00:55:11122 CHECK(browser);
123 return browser;
124}
125
126// Activates a browser window having the given profile (the last one active) if
127// possible or creates an empty one if necessary. Returns a pointer to the
128// activated/new |Browser|.
129Browser* ActivateOrCreateBrowser(Profile* profile) {
130 if (Browser* browser = ActivateBrowser(profile))
131 return browser;
132 return CreateBrowser(profile);
133}
134
[email protected]151c4a62011-04-22 04:15:13135CFStringRef BaseBundleID_CFString() {
136 NSString* base_bundle_id =
137 [NSString stringWithUTF8String:base::mac::BaseBundleID()];
138 return base::mac::NSToCFCast(base_bundle_id);
139}
140
[email protected]0b8caad2011-11-28 23:33:27141// This callback synchronizes preferences (under "org.chromium.Chromium" or
[email protected]12dc3d42010-02-22 23:37:12142// "com.google.Chrome"), in particular, writes them out to disk.
[email protected]0b8caad2011-11-28 23:33:27143void PrefsSyncCallback() {
144 if (!CFPreferencesAppSynchronize(BaseBundleID_CFString()))
145 LOG(WARNING) << "Error recording application bundle path.";
146}
[email protected]12dc3d42010-02-22 23:37:12147
148// Record the location of the application bundle (containing the main framework)
149// from which Chromium was loaded. This is used by app mode shims to find
150// Chromium.
151void RecordLastRunAppBundlePath() {
152 // Going up three levels from |chrome::GetVersionedDirectory()| gives the
153 // real, user-visible app bundle directory. (The alternatives give either the
154 // framework's path or the initial app's path, which may be an app mode shim
155 // or a unit test.)
156 FilePath appBundlePath =
157 chrome::GetVersionedDirectory().DirName().DirName().DirName();
[email protected]b6b72222012-02-11 02:04:13158 CFPreferencesSetAppValue(
159 base::mac::NSToCFCast(app_mode::kLastRunAppBundlePathPrefsKey),
160 base::SysUTF8ToCFStringRef(appBundlePath.value()),
161 BaseBundleID_CFString());
[email protected]12dc3d42010-02-22 23:37:12162
163 // Sync after a delay avoid I/O contention on startup; 1500 ms is plenty.
[email protected]df32e89c2012-05-17 17:47:34164 BrowserThread::PostDelayedTask(
165 BrowserThread::FILE, FROM_HERE,
166 base::Bind(&PrefsSyncCallback),
167 base::TimeDelta::FromMilliseconds(1500));
[email protected]12dc3d42010-02-22 23:37:12168}
169
[email protected]d630d7d52010-02-21 00:55:11170} // anonymous namespace
171
[email protected]a529af52011-08-15 20:56:17172const AEEventClass kAECloudPrintInstallClass = 'GCPi';
173const AEEventClass kAECloudPrintUninstallClass = 'GCPu';
174
[email protected]a99fce0e2011-03-21 20:58:48175@interface AppController (Private)
[email protected]88d74942009-01-21 22:04:44176- (void)initMenuState;
[email protected]961a6932011-07-19 19:52:46177- (void)initProfileMenu;
[email protected]a99fce0e2011-03-21 20:58:48178- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
[email protected]eef99c22010-08-17 05:55:16179- (void)registerServicesMenuTypesTo:(NSApplication*)app;
[email protected]d630d7d52010-02-21 00:55:11180- (void)openUrls:(const std::vector<GURL>&)urls;
[email protected]57750f822009-04-21 21:43:09181- (void)getUrl:(NSAppleEventDescriptor*)event
182 withReply:(NSAppleEventDescriptor*)reply;
[email protected]a529af52011-08-15 20:56:17183- (void)submitCloudPrintJob:(NSAppleEventDescriptor*)event;
184- (void)installCloudPrint:(NSAppleEventDescriptor*)event;
185- (void)uninstallCloudPrint:(NSAppleEventDescriptor*)event;
[email protected]449dd2f2009-05-27 13:04:00186- (void)windowLayeringDidChange:(NSNotification*)inNotification;
[email protected]5c593702011-06-17 18:35:24187- (void)windowChangedToProfile:(Profile*)profile;
[email protected]dd6ab1282010-07-20 01:07:32188- (void)checkForAnyKeyWindows;
[email protected]73f5b362009-08-10 23:58:21189- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
[email protected]09729a552009-08-03 23:21:41190- (BOOL)shouldQuitWithInProgressDownloads;
[email protected]93b59fc2010-12-21 20:00:47191- (void)executeApplication:(id)sender;
[email protected]88d74942009-01-21 22:04:44192@end
[email protected]1bcdb532009-01-16 17:47:57193
194@implementation AppController
195
[email protected]caadfca2010-01-22 21:51:21196@synthesize startupComplete = startupComplete_;
197
[email protected]cd63ef62009-05-06 19:41:37198// This method is called very early in application startup (ie, before
199// the profile is loaded or any preferences have been registered). Defer any
200// user-data initialization until -applicationDidFinishLaunching:.
[email protected]88d74942009-01-21 22:04:44201- (void)awakeFromNib {
[email protected]136140c2009-05-19 13:58:25202 // We need to register the handlers early to catch events fired on launch.
[email protected]57750f822009-04-21 21:43:09203 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
204 [em setEventHandler:self
205 andSelector:@selector(getUrl:withReply:)
206 forEventClass:kInternetEventClass
207 andEventID:kAEGetURL];
208 [em setEventHandler:self
[email protected]a529af52011-08-15 20:56:17209 andSelector:@selector(submitCloudPrintJob:)
[email protected]13aec6c42011-10-27 21:22:08210 forEventClass:cloud_print::kAECloudPrintClass
211 andEventID:cloud_print::kAECloudPrintClass];
[email protected]a529af52011-08-15 20:56:17212 // Install and uninstall handlers for virtual drivers.
213 [em setEventHandler:self
214 andSelector:@selector(installCloudPrint:)
215 forEventClass:kAECloudPrintInstallClass
216 andEventID:kAECloudPrintInstallClass];
217 [em setEventHandler:self
218 andSelector:@selector(uninstallCloudPrint:)
219 forEventClass:kAECloudPrintUninstallClass
220 andEventID:kAECloudPrintUninstallClass];
221 [em setEventHandler:self
[email protected]57750f822009-04-21 21:43:09222 andSelector:@selector(getUrl:withReply:)
223 forEventClass:'WWW!' // A particularly ancient AppleEvent that dates
224 andEventID:'OURL']; // back to the Spyglass days.
[email protected]cd63ef62009-05-06 19:41:37225
[email protected]449dd2f2009-05-27 13:04:00226 // Register for various window layering changes. We use these to update
227 // various UI elements (command-key equivalents, etc) when the frontmost
228 // window changes.
229 NSNotificationCenter* notificationCenter =
230 [NSNotificationCenter defaultCenter];
[email protected]ce560f82009-06-03 09:39:44231 [notificationCenter
[email protected]449dd2f2009-05-27 13:04:00232 addObserver:self
233 selector:@selector(windowLayeringDidChange:)
234 name:NSWindowDidBecomeKeyNotification
235 object:nil];
236 [notificationCenter
237 addObserver:self
238 selector:@selector(windowLayeringDidChange:)
239 name:NSWindowDidResignKeyNotification
240 object:nil];
241 [notificationCenter
242 addObserver:self
243 selector:@selector(windowLayeringDidChange:)
244 name:NSWindowDidBecomeMainNotification
245 object:nil];
246 [notificationCenter
247 addObserver:self
248 selector:@selector(windowLayeringDidChange:)
249 name:NSWindowDidResignMainNotification
250 object:nil];
251
[email protected]ebbe94b2012-01-18 20:11:56252 if (base::mac::IsOSLionOrLater()) {
253 [notificationCenter
254 addObserver:self
255 selector:@selector(popoverDidShow:)
256 name:NSPopoverDidShowNotification
257 object:nil];
258 [notificationCenter
259 addObserver:self
260 selector:@selector(popoverDidClose:)
261 name:NSPopoverDidCloseNotification
262 object:nil];
263 }
264
[email protected]136140c2009-05-19 13:58:25265 // Set up the command updater for when there are no windows open
266 [self initMenuState];
[email protected]961a6932011-07-19 19:52:46267
268 // Initialize the Profile menu.
269 [self initProfileMenu];
[email protected]136140c2009-05-19 13:58:25270}
271
[email protected]71c0eb92012-01-03 17:57:30272- (void)unregisterEventHandlers {
273 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
274 [em removeEventHandlerForEventClass:kInternetEventClass
275 andEventID:kAEGetURL];
276 [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
277 andEventID:cloud_print::kAECloudPrintClass];
278 [em removeEventHandlerForEventClass:kAECloudPrintInstallClass
279 andEventID:kAECloudPrintInstallClass];
280 [em removeEventHandlerForEventClass:kAECloudPrintUninstallClass
281 andEventID:kAECloudPrintUninstallClass];
282 [em removeEventHandlerForEventClass:'WWW!'
283 andEventID:'OURL'];
284 [[NSNotificationCenter defaultCenter] removeObserver:self];
285}
286
[email protected]7dc8c6b2010-04-09 17:02:50287// (NSApplicationDelegate protocol) This is the Apple-approved place to override
288// the default handlers.
289- (void)applicationWillFinishLaunching:(NSNotification*)notification {
[email protected]58877932010-05-25 05:43:11290 // Nothing here right now.
[email protected]7dc8c6b2010-04-09 17:02:50291}
292
293- (BOOL)tryToTerminateApplication:(NSApplication*)app {
[email protected]3076fad2010-04-28 18:11:45294 // Check for in-process downloads, and prompt the user if they really want
295 // to quit (and thus cancel downloads). Only check if we're not already
296 // shutting down, else the user might be prompted multiple times if the
297 // download isn't stopped before terminate is called again.
298 if (!browser_shutdown::IsTryingToQuit() &&
299 ![self shouldQuitWithInProgressDownloads])
300 return NO;
301
[email protected]7dc8c6b2010-04-09 17:02:50302 // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
303 // them in, but I'm not sure about UX; we'd also want to disable other things
304 // though.) http://crbug.com/40861
305
[email protected]177aceb2010-11-03 16:17:41306 // Check if the user really wants to quit by employing the confirm-to-quit
307 // mechanism.
308 if (!browser_shutdown::IsTryingToQuit() &&
309 [self applicationShouldTerminate:app] != NSTerminateNow)
310 return NO;
311
[email protected]c984d9f2010-07-20 20:52:20312 size_t num_browsers = BrowserList::size();
[email protected]7dc8c6b2010-04-09 17:02:50313
[email protected]2e6389f2012-05-18 19:41:25314 // Initiate a shutdown (via browser::CloseAllBrowsers()) if we aren't
[email protected]c984d9f2010-07-20 20:52:20315 // already shutting down.
[email protected]ef61b8c2012-01-20 10:54:56316 if (!browser_shutdown::IsTryingToQuit()) {
317 content::NotificationService::current()->Notify(
[email protected]d53a08c2012-07-18 20:35:30318 chrome::NOTIFICATION_CLOSE_ALL_BROWSERS_REQUEST,
[email protected]ef61b8c2012-01-20 10:54:56319 content::NotificationService::AllSources(),
320 content::NotificationService::NoDetails());
[email protected]2e6389f2012-05-18 19:41:25321 browser::CloseAllBrowsers();
[email protected]ef61b8c2012-01-20 10:54:56322 }
[email protected]7dc8c6b2010-04-09 17:02:50323
[email protected]c984d9f2010-07-20 20:52:20324 return num_browsers == 0 ? YES : NO;
[email protected]7dc8c6b2010-04-09 17:02:50325}
326
327- (void)stopTryingToTerminateApplication:(NSApplication*)app {
328 if (browser_shutdown::IsTryingToQuit()) {
329 // Reset the "trying to quit" state, so that closing all browser windows
330 // will no longer lead to termination.
331 browser_shutdown::SetTryingToQuit(false);
332
333 // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
334 // would have to reinstall them here. http://crbug.com/40861
335 }
[email protected]a9e8afc2009-08-11 22:03:17336}
337
[email protected]177aceb2010-11-03 16:17:41338- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
[email protected]a99fce0e2011-03-21 20:58:48339 // Check if the preference is turned on.
[email protected]b6366ffa2012-02-29 17:12:26340 const PrefService* prefs = g_browser_process->local_state();
[email protected]1eaddf32011-04-05 15:09:23341 if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
342 confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
[email protected]177aceb2010-11-03 16:17:41343 return NSTerminateNow;
[email protected]1eaddf32011-04-05 15:09:23344 }
[email protected]177aceb2010-11-03 16:17:41345
346 // If the application is going to terminate as the result of a Cmd+Q
347 // invocation, use the special sauce to prevent accidental quitting.
348 // http://dev.chromium.org/developers/design-documents/confirm-to-quit-experiment
[email protected]177aceb2010-11-03 16:17:41349
[email protected]2020fd0b2010-12-10 01:16:50350 // This logic is only for keyboard-initiated quits.
[email protected]5df54fb2011-03-07 18:15:26351 if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
[email protected]2020fd0b2010-12-10 01:16:50352 return NSTerminateNow;
[email protected]177aceb2010-11-03 16:17:41353
[email protected]5df54fb2011-03-07 18:15:26354 return [[ConfirmQuitPanelController sharedController]
355 runModalLoopForApplication:app];
[email protected]177aceb2010-11-03 16:17:41356}
357
[email protected]449dd2f2009-05-27 13:04:00358// Called when the app is shutting down. Clean-up as appropriate.
[email protected]7dc8c6b2010-04-09 17:02:50359- (void)applicationWillTerminate:(NSNotification*)aNotification {
[email protected]7dc8c6b2010-04-09 17:02:50360 // There better be no browser windows left at this point.
[email protected]71c0eb92012-01-03 17:57:30361 CHECK_EQ(0u, BrowserList::size());
[email protected]3b6aa8b62009-09-15 21:36:11362
[email protected]c984d9f2010-07-20 20:52:20363 // Tell BrowserList not to keep the browser process alive. Once all the
364 // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
[email protected]2e6389f2012-05-18 19:41:25365 browser::EndKeepAlive();
[email protected]fbc947b2009-06-19 13:28:24366
[email protected]71c0eb92012-01-03 17:57:30367 [self unregisterEventHandlers];
[email protected]449dd2f2009-05-27 13:04:00368}
369
[email protected]3b6aa8b62009-09-15 21:36:11370- (void)didEndMainMessageLoop {
[email protected]d8748142012-05-16 21:13:43371 DCHECK_EQ(0u, browser::GetBrowserCount([self lastProfile]));
372 if (!browser::GetBrowserCount([self lastProfile])) {
[email protected]3b6aa8b62009-09-15 21:36:11373 // As we're shutting down, we need to nuke the TabRestoreService, which
374 // will start the shutdown of the NavigationControllers and allow for
375 // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
376 // and may end up crashing when some thread tries to use the IO thread (or
377 // another thread) that is no longer valid.
[email protected]a585a8db2011-06-20 18:58:35378 TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
[email protected]3b6aa8b62009-09-15 21:36:11379 }
380}
381
[email protected]8cfbdbd2011-06-16 04:17:17382// If the window has a tab controller, make "close window" be cmd-shift-w,
383// otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
[email protected]eddcf7502012-02-09 22:43:48384// affects whether the shift modifier is used.
[email protected]ebbe94b2012-01-18 20:11:56385- (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
386 [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
387 @"w")];
[email protected]8cfbdbd2011-06-16 04:17:17388 [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
389}
390
391// If the window has a tab controller, make "close tab" take over cmd-w,
392// otherwise it shouldn't have any key-equivalent because it should be disabled.
[email protected]ebbe94b2012-01-18 20:11:56393- (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
394 if (enableCloseTabShortcut) {
[email protected]8cfbdbd2011-06-16 04:17:17395 [closeTabMenuItem_ setKeyEquivalent:@"w"];
396 [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
397 } else {
398 [closeTabMenuItem_ setKeyEquivalent:@""];
399 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
400 }
401}
402
403// Explicitly remove any command-key equivalents from the close tab/window
404// menus so that nothing can go haywire if we get a user action during pending
405// updates.
406- (void)clearCloseMenuItemKeyEquivalents {
407 [closeTabMenuItem_ setKeyEquivalent:@""];
408 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
409 [closeWindowMenuItem_ setKeyEquivalent:@""];
410 [closeWindowMenuItem_ setKeyEquivalentModifierMask:0];
411}
412
[email protected]9f5f79b62011-10-28 00:43:45413// See if the focused window window has tabs, and adjust the key equivalents for
[email protected]8cfbdbd2011-06-16 04:17:17414// Close Tab/Close Window accordingly.
[email protected]9f5f79b62011-10-28 00:43:45415- (void)fixCloseMenuItemKeyEquivalents {
[email protected]8cfbdbd2011-06-16 04:17:17416 fileMenuUpdatePending_ = NO;
[email protected]8cfbdbd2011-06-16 04:17:17417
[email protected]9f5f79b62011-10-28 00:43:45418 NSWindow* window = [NSApp keyWindow];
419 NSWindow* mainWindow = [NSApp mainWindow];
420 if (!window || ([window parentWindow] == mainWindow)) {
421 // If the key window is a child of the main window (e.g. a bubble), the main
422 // window should be the one that handles the close menu item action.
423 // Also, there might be a small amount of time where there is no key window;
424 // in that case as well, just use our main browser window if there is one.
425 // You might think that we should just always use the main window, but the
426 // "About Chrome" window serves as a counterexample.
427 window = mainWindow;
428 }
429
430 BOOL hasTabs =
431 [[window windowController] isKindOfClass:[TabWindowController class]];
[email protected]ebbe94b2012-01-18 20:11:56432 BOOL enableCloseTabShortcut = hasTabs && !hasPopover_;
433 [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
434 [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
[email protected]8cfbdbd2011-06-16 04:17:17435}
436
437// Fix up the "close tab/close window" command-key equivalents. We do this
438// after a delay to ensure that window layer state has been set by the time
439// we do the enabling. This should only be called on the main thread, code that
440// calls this (even as a side-effect) from other threads needs to be fixed.
[email protected]9f5f79b62011-10-28 00:43:45441- (void)delayedFixCloseMenuItemKeyEquivalents {
[email protected]8cfbdbd2011-06-16 04:17:17442 DCHECK([NSThread isMainThread]);
443 if (!fileMenuUpdatePending_) {
444 // The OS prefers keypresses to timers, so it's possible that a cmd-w
445 // can sneak in before this timer fires. In order to prevent that from
446 // having any bad consequences, just clear the keys combos altogether. They
447 // will be reset when the timer eventually fires.
448 if ([NSThread isMainThread]) {
449 fileMenuUpdatePending_ = YES;
450 [self clearCloseMenuItemKeyEquivalents];
[email protected]9f5f79b62011-10-28 00:43:45451 [self performSelector:@selector(fixCloseMenuItemKeyEquivalents)
452 withObject:nil
[email protected]8cfbdbd2011-06-16 04:17:17453 afterDelay:0];
454 } else {
455 // This shouldn't be happening, but if it does, force it to the main
456 // thread to avoid dropping the update. Don't mess with
457 // |fileMenuUpdatePending_| as it's not expected to be threadsafe and
458 // there could be a race between the selector finishing and setting the
459 // flag.
460 [self
[email protected]9f5f79b62011-10-28 00:43:45461 performSelectorOnMainThread:@selector(fixCloseMenuItemKeyEquivalents)
462 withObject:nil
[email protected]8cfbdbd2011-06-16 04:17:17463 waitUntilDone:NO];
464 }
465 }
466}
467
[email protected]449dd2f2009-05-27 13:04:00468// Called when we get a notification about the window layering changing to
469// update the UI based on the new main window.
470- (void)windowLayeringDidChange:(NSNotification*)notify {
[email protected]9f5f79b62011-10-28 00:43:45471 [self delayedFixCloseMenuItemKeyEquivalents];
[email protected]8cfbdbd2011-06-16 04:17:17472
[email protected]dd6ab1282010-07-20 01:07:32473 if ([notify name] == NSWindowDidResignKeyNotification) {
474 // If a window is closed, this notification is fired but |[NSApp keyWindow]|
475 // returns nil regardless of whether any suitable candidates for the key
476 // window remain. It seems that the new key window for the app is not set
477 // until after this notification is fired, so a check is performed after the
478 // run loop is allowed to spin.
479 [self performSelector:@selector(checkForAnyKeyWindows)
480 withObject:nil
481 afterDelay:0.0];
482 }
[email protected]5c593702011-06-17 18:35:24483
484 // If the window changed to a new BrowserWindowController, update the profile.
485 id windowController = [[notify object] windowController];
[email protected]dc251482012-01-03 18:55:21486 if ([notify name] == NSWindowDidBecomeMainNotification &&
487 [windowController isKindOfClass:[BrowserWindowController class]]) {
[email protected]5c593702011-06-17 18:35:24488 // If the profile is incognito, use the original profile.
489 Profile* newProfile = [windowController profile]->GetOriginalProfile();
490 [self windowChangedToProfile:newProfile];
[email protected]cae68b3a2011-11-21 23:29:49491 } else if (BrowserList::empty()) {
492 [self windowChangedToProfile:
493 g_browser_process->profile_manager()->GetLastUsedProfile()];
[email protected]5c593702011-06-17 18:35:24494 }
495}
496
[email protected]ebbe94b2012-01-18 20:11:56497// Called on Lion and later when a popover (e.g. dictionary) is shown.
498- (void)popoverDidShow:(NSNotification*)notify {
499 hasPopover_ = YES;
500 [self fixCloseMenuItemKeyEquivalents];
501}
502
503// Called on Lion and later when a popover (e.g. dictionary) is closed.
504- (void)popoverDidClose:(NSNotification*)notify {
505 hasPopover_ = NO;
506 [self fixCloseMenuItemKeyEquivalents];
507}
508
[email protected]5c593702011-06-17 18:35:24509// Called when the user has changed browser windows, meaning the backing profile
510// may have changed. This can cause a rebuild of the user-data menus. This is a
511// no-op if the new profile is the same as the current one. This will always be
512// the original profile and never incognito.
513- (void)windowChangedToProfile:(Profile*)profile {
514 if (lastProfile_ == profile)
515 return;
516
517 // Before tearing down the menu controller bridges, return the Cocoa menus to
518 // their initial state.
519 if (bookmarkMenuBridge_.get())
520 bookmarkMenuBridge_->ResetMenu();
521 if (historyMenuBridge_.get())
522 historyMenuBridge_->ResetMenu();
523
524 // Rebuild the menus with the new profile.
525 lastProfile_ = profile;
526
[email protected]0c165cf2011-07-09 03:56:50527 bookmarkMenuBridge_.reset(new BookmarkMenuBridge(lastProfile_,
528 [[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] submenu]));
[email protected]dc251482012-01-03 18:55:21529 // No need to |BuildMenu| here. It is done lazily upon menu access.
[email protected]5c593702011-06-17 18:35:24530
531 historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
532 historyMenuBridge_->BuildMenu();
[email protected]dd6ab1282010-07-20 01:07:32533}
534
535- (void)checkForAnyKeyWindows {
536 if ([NSApp keyWindow])
537 return;
538
[email protected]ad50def52011-10-19 23:17:07539 content::NotificationService::current()->Notify(
[email protected]d53a08c2012-07-18 20:35:30540 chrome::NOTIFICATION_NO_KEY_WINDOW,
[email protected]ad50def52011-10-19 23:17:07541 content::NotificationService::AllSources(),
542 content::NotificationService::NoDetails());
[email protected]449dd2f2009-05-27 13:04:00543}
544
[email protected]414fde592009-05-21 16:14:43545// If the auto-update interval is not set, make it 5 hours.
546// This code is specific to Mac Chrome Dev Channel.
547// Placed here for 2 reasons:
548// 1) Same spot as other Pref stuff
549// 2) Try and be friendly by keeping this after app launch
550// TODO(jrg): remove once we go Beta.
551- (void)setUpdateCheckInterval {
552#if defined(GOOGLE_CHROME_BUILD)
553 CFStringRef app = (CFStringRef)@"com.google.Keystone.Agent";
554 CFStringRef checkInterval = (CFStringRef)@"checkInterval";
555 CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
556 if (!plist) {
557 const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
[email protected]7dc8c6b2010-04-09 17:02:50558 NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
[email protected]414fde592009-05-21 16:14:43559 CFPreferencesSetAppValue(checkInterval, value, app);
560 CFPreferencesAppSynchronize(app);
561 }
562#endif
563}
564
[email protected]136140c2009-05-19 13:58:25565// This is called after profiles have been loaded and preferences registered.
566// It is safe to access the default profile here.
567- (void)applicationDidFinishLaunching:(NSNotification*)notify {
[email protected]c984d9f2010-07-20 20:52:20568 // Notify BrowserList to keep the application running so it doesn't go away
569 // when all the browser windows get closed.
[email protected]2e6389f2012-05-18 19:41:25570 browser::StartKeepAlive();
[email protected]136140c2009-05-19 13:58:25571
[email protected]414fde592009-05-21 16:14:43572 [self setUpdateCheckInterval];
[email protected]2bcec612009-05-14 17:50:53573
574 // Build up the encoding menu, the order of the items differs based on the
575 // current locale (see http://crbug.com/7647 for details).
576 // We need a valid g_browser_process to get the profile which is why we can't
577 // call this from awakeFromNib.
[email protected]6f91e5ae2011-03-21 19:53:14578 NSMenu* viewMenu = [[[NSApp mainMenu] itemWithTag:IDC_VIEW_MENU] submenu];
579 NSMenuItem* encodingMenuItem = [viewMenu itemWithTag:IDC_ENCODING_MENU];
580 NSMenu* encodingMenu = [encodingMenuItem submenu];
[email protected]a585a8db2011-06-20 18:58:35581 EncodingMenuControllerDelegate::BuildEncodingMenu([self lastProfile],
[email protected]6f91e5ae2011-03-21 19:53:14582 encodingMenu);
[email protected]2bcec612009-05-14 17:50:53583
[email protected]f2c20fa2009-12-01 17:42:02584 // Since Chrome is localized to more languages than the OS, tell Cocoa which
585 // menu is the Help so it can add the search item to it.
[email protected]73980132012-07-26 20:09:28586 [NSApp setHelpMenu:helpMenu_];
[email protected]f2c20fa2009-12-01 17:42:02587
[email protected]12dc3d42010-02-22 23:37:12588 // Record the path to the (browser) app bundle; this is used by the app mode
589 // shim.
590 RecordLastRunAppBundlePath();
591
[email protected]eef99c22010-08-17 05:55:16592 // Makes "Services" menu items available.
593 [self registerServicesMenuTypesTo:[notify object]];
594
[email protected]caadfca2010-01-22 21:51:21595 startupComplete_ = YES;
596
597 // TODO(viettrungluu): This is very temporary, since this should be done "in"
598 // |BrowserMain()|, i.e., this list of startup URLs should be appended to the
599 // (probably-empty) list of URLs from the command line.
[email protected]d630d7d52010-02-21 00:55:11600 if (startupUrls_.size()) {
601 [self openUrls:startupUrls_];
602 [self clearStartupUrls];
[email protected]caadfca2010-01-22 21:51:21603 }
[email protected]aac169d2011-03-18 19:53:03604
605 const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
606 if (!parsed_command_line.HasSwitch(switches::kEnableExposeForTabs)) {
607 [tabposeMenuItem_ setHidden:YES];
608 }
[email protected]7c321082009-02-09 15:35:47609}
610
[email protected]a96ec6a2009-11-04 17:27:08611// This is called after profiles have been loaded and preferences registered.
612// It is safe to access the default profile here.
613- (void)applicationDidBecomeActive:(NSNotification*)notify {
[email protected]5904cb42012-09-24 15:05:20614 content::PluginService::GetInstance()->AppActivated();
[email protected]a96ec6a2009-11-04 17:27:08615}
616
[email protected]73f5b362009-08-10 23:58:21617// Helper function for populating and displaying the in progress downloads at
618// exit alert panel.
619- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
[email protected]83a9f652012-04-25 21:03:48620 NSString* titleText = nil;
[email protected]e8b5f7882009-09-14 20:59:13621 NSString* explanationText = nil;
[email protected]73f5b362009-08-10 23:58:21622 NSString* waitTitle = nil;
623 NSString* exitTitle = nil;
624
625 // Set the dialog text based on whether or not there are multiple downloads.
626 if (downloadCount == 1) {
[email protected]e8b5f7882009-09-14 20:59:13627 // Dialog text: warning and explanation.
[email protected]83a9f652012-04-25 21:03:48628 titleText = l10n_util::GetNSString(
629 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_TITLE);
[email protected]ab3b1c112012-01-13 22:04:16630 explanationText = l10n_util::GetNSString(
631 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION);
[email protected]73f5b362009-08-10 23:58:21632 } else {
[email protected]e8b5f7882009-09-14 20:59:13633 // Dialog text: warning and explanation.
[email protected]83a9f652012-04-25 21:03:48634 titleText = l10n_util::GetNSStringF(
635 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_TITLE,
[email protected]528c56d2010-07-30 19:28:44636 base::IntToString16(downloadCount));
[email protected]ab3b1c112012-01-13 22:04:16637 explanationText = l10n_util::GetNSString(
638 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_EXPLANATION);
[email protected]73f5b362009-08-10 23:58:21639 }
[email protected]83a9f652012-04-25 21:03:48640 // Cancel download and exit button text.
641 exitTitle = l10n_util::GetNSString(
642 IDS_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL);
643
644 // Wait for download button text.
645 waitTitle = l10n_util::GetNSString(
646 IDS_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL);
[email protected]73f5b362009-08-10 23:58:21647
648 // 'waitButton' is the default choice.
[email protected]83a9f652012-04-25 21:03:48649 int choice = NSRunAlertPanel(titleText, explanationText,
[email protected]e8b5f7882009-09-14 20:59:13650 waitTitle, exitTitle, nil);
[email protected]73f5b362009-08-10 23:58:21651 return choice == NSAlertDefaultReturn ? YES : NO;
652}
653
654// Check all profiles for in progress downloads, and if we find any, prompt the
[email protected]09729a552009-08-03 23:21:41655// user to see if we should continue to exit (and thus cancel the downloads), or
656// if we should wait.
657- (BOOL)shouldQuitWithInProgressDownloads {
[email protected]73f5b362009-08-10 23:58:21658 ProfileManager* profile_manager = g_browser_process->profile_manager();
659 if (!profile_manager)
660 return YES;
[email protected]09729a552009-08-03 23:21:41661
[email protected]844a1002011-04-19 11:37:21662 std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
663 for (size_t i = 0; i < profiles.size(); ++i) {
[email protected]9bb54ee2011-10-12 17:43:35664 DownloadService* download_service =
665 DownloadServiceFactory::GetForProfile(profiles[i]);
666 DownloadManager* download_manager =
667 (download_service->HasCreatedDownloadManager() ?
[email protected]b441a8492012-06-06 14:55:57668 BrowserContext::GetDownloadManager(profiles[i]) : NULL);
[email protected]5656f8a2011-11-17 16:12:58669 if (download_manager && download_manager->InProgressCount() > 0) {
670 int downloadCount = download_manager->InProgressCount();
[email protected]73f5b362009-08-10 23:58:21671 if ([self userWillWaitForInProgressDownloads:downloadCount]) {
672 // Create a new browser window (if necessary) and navigate to the
673 // downloads page if the user chooses to wait.
[email protected]323fd7122012-08-24 14:45:11674 Browser* browser = browser::FindBrowserWithProfile(
675 profiles[i], chrome::HOST_DESKTOP_TYPE_NATIVE);
[email protected]73f5b362009-08-10 23:58:21676 if (!browser) {
[email protected]a4fe67012012-07-25 20:14:29677 browser = new Browser(Browser::CreateParams(profiles[i]));
[email protected]73f5b362009-08-10 23:58:21678 browser->window()->Show();
679 }
680 DCHECK(browser);
[email protected]5d9cace72012-06-21 16:07:12681 chrome::ShowDownloads(browser);
[email protected]73f5b362009-08-10 23:58:21682 return NO;
683 }
[email protected]09729a552009-08-03 23:21:41684
[email protected]73f5b362009-08-10 23:58:21685 // User wants to exit.
686 return YES;
[email protected]09729a552009-08-03 23:21:41687 }
[email protected]09729a552009-08-03 23:21:41688 }
689
[email protected]73f5b362009-08-10 23:58:21690 // No profiles or active downloads found, okay to exit.
[email protected]09729a552009-08-03 23:21:41691 return YES;
692}
693
[email protected]fbc947b2009-06-19 13:28:24694// Called to determine if we should enable the "restore tab" menu item.
695// Checks with the TabRestoreService to see if there's anything there to
696// restore and returns YES if so.
697- (BOOL)canRestoreTab {
[email protected]92371eb2011-04-28 11:50:15698 TabRestoreService* service =
[email protected]a585a8db2011-06-20 18:58:35699 TabRestoreServiceFactory::GetForProfile([self lastProfile]);
[email protected]fbc947b2009-06-19 13:28:24700 return service && !service->entries().empty();
701}
702
[email protected]f6c15fa2010-06-04 20:08:21703// Returns true if there is not a modal window (either window- or application-
704// modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
705// sheets) will not count as blocking the browser. But things like open/save
706// dialogs that are window modal will block the browser.
707- (BOOL)keyWindowIsNotModal {
[email protected]13858862012-05-24 03:22:51708 Browser* browser = browser::GetLastActiveBrowser();
[email protected]dc76e8362010-06-11 16:29:52709 return [NSApp modalWindow] == nil && (!browser ||
[email protected]90556dd2012-06-07 20:26:18710 ![[browser->window()->GetNativeWindow() attachedSheet]
[email protected]f6c15fa2010-06-04 20:08:21711 isKindOfClass:[NSWindow class]]);
[email protected]6a281332009-10-13 17:41:06712}
713
[email protected]88d74942009-01-21 22:04:44714// Called to validate menu items when there are no key windows. All the
715// items we care about have been set with the |commandDispatch:| action and
716// a target of FirstResponder in IB. If it's not one of those, let it
717// continue up the responder chain to be handled elsewhere. We pull out the
718// tag as the cross-platform constant to differentiate and dispatch the
719// various commands.
720- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
721 SEL action = [item action];
722 BOOL enable = NO;
723 if (action == @selector(commandDispatch:)) {
724 NSInteger tag = [item tag];
[email protected]fbc947b2009-06-19 13:28:24725 if (menuState_->SupportsCommand(tag)) {
726 switch (tag) {
[email protected]419eb2a2009-11-11 16:26:26727 // The File Menu commands are not automatically disabled by Cocoa when a
728 // dialog sheet obscures the browser window, so we disable several of
729 // them here. We don't need to include IDC_CLOSE_WINDOW, because
730 // app_controller is only activated when there are no key windows (see
731 // function comment).
[email protected]fbc947b2009-06-19 13:28:24732 case IDC_RESTORE_TAB:
[email protected]f6c15fa2010-06-04 20:08:21733 enable = [self keyWindowIsNotModal] && [self canRestoreTab];
[email protected]6a281332009-10-13 17:41:06734 break;
[email protected]f6c15fa2010-06-04 20:08:21735 // Browser-level items that open in new tabs should not open if there's
736 // a window- or app-modal dialog.
[email protected]6a281332009-10-13 17:41:06737 case IDC_OPEN_FILE:
[email protected]6a281332009-10-13 17:41:06738 case IDC_NEW_TAB:
[email protected]f6c15fa2010-06-04 20:08:21739 case IDC_SHOW_HISTORY:
740 case IDC_SHOW_BOOKMARK_MANAGER:
741 enable = [self keyWindowIsNotModal];
742 break;
743 // Browser-level items that open in new windows.
744 case IDC_NEW_WINDOW:
745 case IDC_TASK_MANAGER:
746 // Allow the user to open a new window if there's a window-modal
747 // dialog.
748 enable = [self keyWindowIsNotModal] || ([NSApp modalWindow] == nil);
[email protected]fbc947b2009-06-19 13:28:24749 break;
[email protected]65549182012-02-25 00:45:40750 case IDC_SHOW_SYNC_SETUP: {
[email protected]a585a8db2011-06-20 18:58:35751 Profile* lastProfile = [self lastProfile];
[email protected]446e16a2010-05-03 21:23:58752 // The profile may be NULL during shutdown -- see
753 // http://code.google.com/p/chromium/issues/detail?id=43048 .
754 //
755 // TODO(akalin,viettrungluu): Figure out whether this method
[email protected]a585a8db2011-06-20 18:58:35756 // can be prevented from being called if lastProfile is
[email protected]446e16a2010-05-03 21:23:58757 // NULL.
[email protected]a585a8db2011-06-20 18:58:35758 if (!lastProfile) {
[email protected]446e16a2010-05-03 21:23:58759 LOG(WARNING)
[email protected]a585a8db2011-06-20 18:58:35760 << "NULL lastProfile detected -- not doing anything";
[email protected]446e16a2010-05-03 21:23:58761 break;
762 }
[email protected]a585a8db2011-06-20 18:58:35763 enable = lastProfile->IsSyncAccessible() &&
[email protected]d3b98c82010-07-14 07:45:59764 [self keyWindowIsNotModal];
[email protected]a585a8db2011-06-20 18:58:35765 sync_ui_util::UpdateSyncItem(item, enable, lastProfile);
[email protected]f9bc9b92009-11-24 00:55:35766 break;
[email protected]446e16a2010-05-03 21:23:58767 }
[email protected]acaa37b2011-08-31 07:19:11768 case IDC_FEEDBACK:
769 enable = NO;
770 break;
[email protected]fbc947b2009-06-19 13:28:24771 default:
[email protected]f6c15fa2010-06-04 20:08:21772 enable = menuState_->IsCommandEnabled(tag) ?
773 [self keyWindowIsNotModal] : NO;
[email protected]fbc947b2009-06-19 13:28:24774 }
775 }
[email protected]3b6aa8b62009-09-15 21:36:11776 } else if (action == @selector(terminate:)) {
[email protected]88d74942009-01-21 22:04:44777 enable = YES;
[email protected]3111f08b2009-04-30 16:01:52778 } else if (action == @selector(showPreferences:)) {
779 enable = YES;
[email protected]bde3dda2009-05-20 22:13:07780 } else if (action == @selector(orderFrontStandardAboutPanel:)) {
781 enable = YES;
[email protected]93b59fc2010-12-21 20:00:47782 } else if (action == @selector(commandFromDock:)) {
[email protected]3d4bd23f2009-10-06 03:58:38783 enable = YES;
[email protected]a99fce0e2011-03-21 20:58:48784 } else if (action == @selector(toggleConfirmToQuit:)) {
785 [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
786 enable = YES;
[email protected]88d74942009-01-21 22:04:44787 }
788 return enable;
789}
790
[email protected]947fc0d2010-01-14 22:33:05791// Called when the user picks a menu item when there are no key windows, or when
792// there is no foreground browser window. Calls through to the browser object to
793// execute the command. This assumes that the command is supported and doesn't
[email protected]d630d7d52010-02-21 00:55:11794// check, otherwise it should have been disabled in the UI in
795// |-validateUserInterfaceItem:|.
[email protected]88d74942009-01-21 22:04:44796- (void)commandDispatch:(id)sender {
[email protected]a585a8db2011-06-20 18:58:35797 Profile* lastProfile = [self lastProfile];
[email protected]f0a51fb52009-03-05 12:46:38798
[email protected]947fc0d2010-01-14 22:33:05799 // Handle the case where we're dispatching a command from a sender that's in a
800 // browser window. This means that the command came from a background window
801 // and is getting here because the foreground window is not a browser window.
802 if ([sender respondsToSelector:@selector(window)]) {
803 id delegate = [[sender window] windowController];
804 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
805 [delegate commandDispatch:sender];
806 return;
807 }
808 }
809
[email protected]8d4bbdc2012-09-20 21:36:49810 // Ignore commands during session restore's browser creation. It uses a
811 // nested message loop and commands dispatched during this operation cause
812 // havoc.
813 if (SessionRestore::IsRestoring(lastProfile) &&
814 MessageLoop::current()->IsNested())
815 return;
816
[email protected]88d74942009-01-21 22:04:44817 NSInteger tag = [sender tag];
818 switch (tag) {
[email protected]fbc947b2009-06-19 13:28:24819 case IDC_NEW_TAB:
[email protected]d630d7d52010-02-21 00:55:11820 // Create a new tab in an existing browser window (which we activate) if
821 // possible.
[email protected]a585a8db2011-06-20 18:58:35822 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d98294912012-06-27 22:57:40823 chrome::ExecuteCommand(browser, IDC_NEW_TAB);
[email protected]d630d7d52010-02-21 00:55:11824 break;
825 }
826 // Else fall through to create new window.
[email protected]88d74942009-01-21 22:04:44827 case IDC_NEW_WINDOW:
[email protected]a585a8db2011-06-20 18:58:35828 CreateBrowser(lastProfile);
[email protected]d630d7d52010-02-21 00:55:11829 break;
[email protected]91a5b3e2009-10-30 19:32:22830 case IDC_FOCUS_LOCATION:
[email protected]5d98294912012-06-27 22:57:40831 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
832 IDC_FOCUS_LOCATION);
[email protected]88d74942009-01-21 22:04:44833 break;
[email protected]cddc5242009-12-07 18:54:33834 case IDC_FOCUS_SEARCH:
[email protected]5d98294912012-06-27 22:57:40835 chrome::ExecuteCommand(ActivateOrCreateBrowser(lastProfile),
836 IDC_FOCUS_SEARCH);
[email protected]cddc5242009-12-07 18:54:33837 break;
[email protected]863ff662009-01-26 20:18:18838 case IDC_NEW_INCOGNITO_WINDOW:
[email protected]eddcf7502012-02-09 22:43:48839 CreateBrowser(lastProfile->GetOffTheRecordProfile());
[email protected]863ff662009-01-26 20:18:18840 break;
[email protected]fbc947b2009-06-19 13:28:24841 case IDC_RESTORE_TAB:
[email protected]a37d4b02012-06-25 21:56:10842 chrome::OpenWindowWithRestoredTabs(lastProfile);
[email protected]fbc947b2009-06-19 13:28:24843 break;
[email protected]e19516d2009-04-28 17:15:19844 case IDC_OPEN_FILE:
[email protected]5d98294912012-06-27 22:57:40845 chrome::ExecuteCommand(CreateBrowser(lastProfile), IDC_OPEN_FILE);
[email protected]e19516d2009-04-28 17:15:19846 break;
[email protected]1fdff702009-10-22 00:36:18847 case IDC_CLEAR_BROWSING_DATA: {
[email protected]93e181762009-05-29 14:30:38848 // There may not be a browser open, so use the default profile.
[email protected]a585a8db2011-06-20 18:58:35849 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:12850 chrome::ShowClearBrowsingDataDialog(browser);
[email protected]c8de64a2011-01-25 17:10:23851 } else {
[email protected]1f0b50b2012-06-22 20:37:16852 chrome::OpenClearBrowsingDataDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:23853 }
[email protected]93e181762009-05-29 14:30:38854 break;
[email protected]1fdff702009-10-22 00:36:18855 }
[email protected]4aee5652009-11-19 18:59:21856 case IDC_IMPORT_SETTINGS: {
[email protected]a585a8db2011-06-20 18:58:35857 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:12858 chrome::ShowImportDialog(browser);
[email protected]c8de64a2011-01-25 17:10:23859 } else {
[email protected]1f0b50b2012-06-22 20:37:16860 chrome::OpenImportSettingsDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:23861 }
[email protected]4aee5652009-11-19 18:59:21862 break;
863 }
[email protected]af7c25e2010-01-23 05:46:45864 case IDC_SHOW_BOOKMARK_MANAGER:
[email protected]7f6f44c2011-12-14 13:23:38865 content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
[email protected]a585a8db2011-06-20 18:58:35866 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]5d9cace72012-06-21 16:07:12867 chrome::ShowBookmarkManager(browser);
[email protected]90a8bf252010-03-12 00:09:47868 } else {
[email protected]47e532b2010-04-23 17:46:40869 // No browser window, so create one for the bookmark manager tab.
[email protected]1f0b50b2012-06-22 20:37:16870 chrome::OpenBookmarkManagerWindow(lastProfile);
[email protected]90a8bf252010-03-12 00:09:47871 }
[email protected]af7c25e2010-01-23 05:46:45872 break;
[email protected]91a5b3e2009-10-30 19:32:22873 case IDC_SHOW_HISTORY:
[email protected]a585a8db2011-06-20 18:58:35874 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:12875 chrome::ShowHistory(browser);
[email protected]d630d7d52010-02-21 00:55:11876 else
[email protected]1f0b50b2012-06-22 20:37:16877 chrome::OpenHistoryWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:22878 break;
879 case IDC_SHOW_DOWNLOADS:
[email protected]a585a8db2011-06-20 18:58:35880 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:12881 chrome::ShowDownloads(browser);
[email protected]d630d7d52010-02-21 00:55:11882 else
[email protected]1f0b50b2012-06-22 20:37:16883 chrome::OpenDownloadsWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:22884 break;
[email protected]bb37e6ec2009-11-18 17:59:36885 case IDC_MANAGE_EXTENSIONS:
[email protected]a585a8db2011-06-20 18:58:35886 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:12887 chrome::ShowExtensions(browser);
[email protected]d630d7d52010-02-21 00:55:11888 else
[email protected]1f0b50b2012-06-22 20:37:16889 chrome::OpenExtensionsWindow(lastProfile);
[email protected]bb37e6ec2009-11-18 17:59:36890 break;
[email protected]2ca35612012-06-12 03:49:48891 case IDC_HELP_PAGE_VIA_MENU:
[email protected]a585a8db2011-06-20 18:58:35892 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:12893 chrome::ShowHelp(browser, chrome::HELP_SOURCE_MENU);
[email protected]d630d7d52010-02-21 00:55:11894 else
[email protected]1f0b50b2012-06-22 20:37:16895 chrome::OpenHelpWindow(lastProfile, chrome::HELP_SOURCE_MENU);
[email protected]1fdff702009-10-22 00:36:18896 break;
[email protected]65549182012-02-25 00:45:40897 case IDC_SHOW_SYNC_SETUP:
898 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]5d9cace72012-06-21 16:07:12899 chrome::ShowSyncSetup(browser, SyncPromoUI::SOURCE_MENU);
[email protected]65549182012-02-25 00:45:40900 else
[email protected]1f0b50b2012-06-22 20:37:16901 chrome::OpenSyncSetupWindow(lastProfile, SyncPromoUI::SOURCE_MENU);
[email protected]f9bc9b92009-11-24 00:55:35902 break;
[email protected]ceaaf1812010-01-20 22:13:09903 case IDC_TASK_MANAGER:
[email protected]7f6f44c2011-12-14 13:23:38904 content::RecordAction(UserMetricsAction("TaskManager"));
[email protected]adb6a84d2011-02-07 16:58:40905 TaskManagerMac::Show(false);
[email protected]ceaaf1812010-01-20 22:13:09906 break;
[email protected]4a42d272010-06-18 01:29:42907 case IDC_OPTIONS:
908 [self showPreferences:sender];
909 break;
[email protected]93b59fc2010-12-21 20:00:47910 default:
911 // Background Applications use dynamic values that must be less than the
912 // smallest value among the predefined IDC_* labels.
913 if ([sender tag] < IDC_MinimumLabelValue)
914 [self executeApplication:sender];
915 break;
[email protected]d630d7d52010-02-21 00:55:11916 }
[email protected]88d74942009-01-21 22:04:44917}
918
[email protected]93b59fc2010-12-21 20:00:47919// Run a (background) application in a new tab.
920- (void)executeApplication:(id)sender {
921 NSInteger tag = [sender tag];
[email protected]a585a8db2011-06-20 18:58:35922 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:47923 DCHECK(profile);
924 BackgroundApplicationListModel applications(profile);
925 DCHECK(tag >= 0 &&
926 tag < static_cast<int>(applications.size()));
[email protected]1c321ee2012-05-21 03:02:34927 const extensions::Extension* extension = applications.GetExtension(tag);
[email protected]78d78a62011-09-29 18:24:33928 BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
[email protected]93b59fc2010-12-21 20:00:47929}
930
[email protected]947fc0d2010-01-14 22:33:05931// Same as |-commandDispatch:|, but executes commands using a disposition
932// determined by the key flags. This will get called in the case where the
933// frontmost window is not a browser window, and the user has command-clicked
934// a button in a background browser window whose action is
935// |-commandDispatchUsingKeyModifiers:|
936- (void)commandDispatchUsingKeyModifiers:(id)sender {
937 DCHECK(sender);
938 if ([sender respondsToSelector:@selector(window)]) {
939 id delegate = [[sender window] windowController];
940 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
941 [delegate commandDispatchUsingKeyModifiers:sender];
942 }
943 }
944}
945
[email protected]ff81e0a2009-04-13 14:58:54946// NSApplication delegate method called when someone clicks on the
947// dock icon and there are no open windows. To match standard mac
948// behavior, we should open a new window.
949- (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
950 hasVisibleWindows:(BOOL)flag {
[email protected]70631402010-04-26 20:16:54951 // If the browser is currently trying to quit, don't do anything and return NO
952 // to prevent AppKit from doing anything.
953 // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
954 if (browser_shutdown::IsTryingToQuit())
955 return NO;
956
[email protected]0236be22012-01-11 01:05:35957 // Don't do anything if there are visible tabbed or popup windows. This will
958 // cause AppKit to unminimize the most recently minimized window. If the
959 // visible windows are panels or notifications, we still need to open a new
960 // window.
961 if (flag) {
962 for (BrowserList::const_iterator iter = BrowserList::begin();
963 iter != BrowserList::end(); ++iter) {
964 Browser* browser = *iter;
965 if (browser->is_type_tabbed() || browser->is_type_popup())
966 return YES;
967 }
968 }
[email protected]ff81e0a2009-04-13 14:58:54969
[email protected]0d1210d62010-09-07 17:31:38970 // If launched as a hidden login item (due to installation of a persistent app
[email protected]eddcf7502012-02-09 22:43:48971 // or by the user, for example in System Preferences->Accounts->Login Items),
[email protected]0d1210d62010-09-07 17:31:38972 // allow session to be restored first time the user clicks on a Dock icon.
973 // Normally, it'd just open a new empty page.
974 {
[email protected]eddcf7502012-02-09 22:43:48975 static BOOL doneOnce = NO;
976 if (!doneOnce) {
977 doneOnce = YES;
978 if (base::mac::WasLaunchedAsHiddenLoginItem()) {
979 SessionService* sessionService =
980 SessionServiceFactory::GetForProfile([self lastProfile]);
981 if (sessionService &&
982 sessionService->RestoreIfNecessary(std::vector<GURL>()))
983 return NO;
[email protected]0d1210d62010-09-07 17:31:38984 }
[email protected]eddcf7502012-02-09 22:43:48985 }
[email protected]0d1210d62010-09-07 17:31:38986 }
[email protected]fc44f242012-02-14 16:54:39987
988 // Platform apps don't use browser windows so don't do anything if there are
989 // visible windows.
990 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
991 if (flag && command_line.HasSwitch(switches::kAppId))
992 return YES;
993
[email protected]ff81e0a2009-04-13 14:58:54994 // Otherwise open a new window.
[email protected]d630d7d52010-02-21 00:55:11995 {
[email protected]0fbd70332010-06-01 19:28:34996 AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
[email protected]fc44f242012-02-14 16:54:39997 int return_code;
[email protected]fe7c4872012-05-10 20:06:03998 StartupBrowserCreator browser_creator;
999 browser_creator.LaunchBrowser(
1000 command_line, [self lastProfile], FilePath(),
[email protected]4feb37d92012-07-01 20:22:131001 chrome::startup::IS_NOT_PROCESS_STARTUP,
1002 chrome::startup::IS_NOT_FIRST_RUN, &return_code);
[email protected]d630d7d52010-02-21 00:55:111003 }
[email protected]ff81e0a2009-04-13 14:58:541004
1005 // We've handled the reopen event, so return NO to tell AppKit not
1006 // to do anything.
1007 return NO;
1008}
1009
[email protected]88d74942009-01-21 22:04:441010- (void)initMenuState {
[email protected]3111f08b2009-04-30 16:01:521011 menuState_.reset(new CommandUpdater(NULL));
[email protected]fbc947b2009-06-19 13:28:241012 menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
[email protected]88d74942009-01-21 22:04:441013 menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
[email protected]863ff662009-01-26 20:18:181014 menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
[email protected]e19516d2009-04-28 17:15:191015 menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
[email protected]93e181762009-05-29 14:30:381016 menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
[email protected]fbc947b2009-06-19 13:28:241017 menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
[email protected]91a5b3e2009-10-30 19:32:221018 menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
[email protected]cddc5242009-12-07 18:54:331019 menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
[email protected]af7c25e2010-01-23 05:46:451020 menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
[email protected]91a5b3e2009-10-30 19:32:221021 menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1022 menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
[email protected]bb37e6ec2009-11-18 17:59:361023 menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
[email protected]2ca35612012-06-12 03:49:481024 menuState_->UpdateCommandEnabled(IDC_HELP_PAGE_VIA_MENU, true);
[email protected]4aee5652009-11-19 18:59:211025 menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
[email protected]1c41a932010-11-22 23:41:231026 menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
[email protected]65549182012-02-25 00:45:401027 menuState_->UpdateCommandEnabled(IDC_SHOW_SYNC_SETUP, true);
[email protected]ceaaf1812010-01-20 22:13:091028 menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
[email protected]88d74942009-01-21 22:04:441029}
[email protected]1bcdb532009-01-16 17:47:571030
[email protected]961a6932011-07-19 19:52:461031// Conditionally adds the Profile menu to the main menu bar.
1032- (void)initProfileMenu {
[email protected]961a6932011-07-19 19:52:461033 NSMenu* mainMenu = [NSApp mainMenu];
1034 NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
[email protected]e354ca42011-08-03 20:31:401035
[email protected]beee7a92012-08-09 20:27:261036 if (!ProfileManager::IsMultipleProfilesEnabled()) {
[email protected]e354ca42011-08-03 20:31:401037 [mainMenu removeItem:profileMenu];
1038 return;
1039 }
1040
[email protected]6b2d30bc2011-10-11 18:16:391041 // The controller will unhide the menu if necessary.
1042 [profileMenu setHidden:YES];
[email protected]961a6932011-07-19 19:52:461043
[email protected]6b2d30bc2011-10-11 18:16:391044 profileMenuController_.reset(
1045 [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
[email protected]961a6932011-07-19 19:52:461046}
1047
[email protected]a99fce0e2011-03-21 20:58:481048// The Confirm to Quit preference is atypical in that the preference lives in
1049// the app menu right above the Quit menu item. This method will refresh the
1050// display of that item depending on the preference state.
1051- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1052 // Format the string so that the correct key equivalent is displayed.
1053 NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1054 NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1055 base::SysNSStringToUTF16(acceleratorString));
1056 [item setTitle:title];
1057
[email protected]b6366ffa2012-02-29 17:12:261058 const PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481059 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1060 [item setState:enabled ? NSOnState : NSOffState];
1061}
1062
[email protected]eef99c22010-08-17 05:55:161063- (void)registerServicesMenuTypesTo:(NSApplication*)app {
[email protected]09ea24c2010-08-23 19:05:411064 // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1065 // handles requests from services.
1066 NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
1067 [app registerServicesMenuSendTypes:types returnTypes:types];
[email protected]eef99c22010-08-17 05:55:161068}
1069
[email protected]a585a8db2011-06-20 18:58:351070- (Profile*)lastProfile {
[email protected]7fd5a462011-06-19 16:57:231071 // Return the profile of the last-used BrowserWindowController, if available.
1072 if (lastProfile_)
1073 return lastProfile_;
1074
[email protected]056f8792011-07-20 15:40:151075 // On first launch, no profile will be stored, so use last from Local State.
[email protected]3f34599d2009-03-25 22:11:431076 if (g_browser_process->profile_manager())
[email protected]056f8792011-07-20 15:40:151077 return g_browser_process->profile_manager()->GetLastUsedProfile();
[email protected]3f34599d2009-03-25 22:11:431078
[email protected]f6314002009-04-23 01:18:131079 return NULL;
[email protected]3f34599d2009-03-25 22:11:431080}
1081
[email protected]57750f822009-04-21 21:43:091082// Various methods to open URLs that we get in a native fashion. We use
[email protected]fe7c4872012-05-10 20:06:031083// StartupBrowserCreator here because on the other platforms, URLs to open come
1084// through the ProcessSingleton, and it calls StartupBrowserCreator. It's best
1085// to bottleneck the openings through that for uniform handling.
[email protected]57750f822009-04-21 21:43:091086
[email protected]d630d7d52010-02-21 00:55:111087- (void)openUrls:(const std::vector<GURL>&)urls {
[email protected]caadfca2010-01-22 21:51:211088 // If the browser hasn't started yet, just queue up the URLs.
1089 if (!startupComplete_) {
[email protected]d630d7d52010-02-21 00:55:111090 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
[email protected]136140c2009-05-19 13:58:251091 return;
1092 }
[email protected]57750f822009-04-21 21:43:091093
[email protected]13858862012-05-24 03:22:511094 Browser* browser = browser::GetLastActiveBrowser();
[email protected]0e863512009-05-28 19:45:071095 // if no browser window exists then create one with no tabs to be filled in
1096 if (!browser) {
[email protected]a4fe67012012-07-25 20:14:291097 browser = new Browser(Browser::CreateParams([self lastProfile]));
[email protected]ce560f82009-06-03 09:39:441098 browser->window()->Show();
[email protected]0e863512009-05-28 19:45:071099 }
1100
[email protected]947446b2010-10-21 03:36:311101 CommandLine dummy(CommandLine::NO_PROGRAM);
[email protected]4feb37d92012-07-01 20:22:131102 chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
1103 chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
[email protected]cc2806852012-05-11 20:48:261104 StartupBrowserCreatorImpl launch(FilePath(), dummy, first_run);
[email protected]0e863512009-05-28 19:45:071105 launch.OpenURLsInBrowser(browser, false, urls);
[email protected]57750f822009-04-21 21:43:091106}
1107
[email protected]57750f822009-04-21 21:43:091108- (void)getUrl:(NSAppleEventDescriptor*)event
1109 withReply:(NSAppleEventDescriptor*)reply {
1110 NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1111 stringValue];
1112
1113 GURL gurl(base::SysNSStringToUTF8(urlStr));
1114 std::vector<GURL> gurlVector;
1115 gurlVector.push_back(gurl);
1116
[email protected]d630d7d52010-02-21 00:55:111117 [self openUrls:gurlVector];
[email protected]57750f822009-04-21 21:43:091118}
1119
[email protected]a529af52011-08-15 20:56:171120// Apple Event handler that receives print event from service
1121// process, gets the required data and launches Print dialog.
1122- (void)submitCloudPrintJob:(NSAppleEventDescriptor*)event {
1123 // Pull parameter list out of Apple Event.
[email protected]ebbe94b2012-01-18 20:11:561124 NSAppleEventDescriptor* paramList =
[email protected]13aec6c42011-10-27 21:22:081125 [event paramDescriptorForKeyword:cloud_print::kAECloudPrintClass];
[email protected]a529af52011-08-15 20:56:171126
1127 if (paramList != nil) {
1128 // Pull required fields out of parameter list.
1129 NSString* mime = [[paramList descriptorAtIndex:1] stringValue];
1130 NSString* inputPath = [[paramList descriptorAtIndex:2] stringValue];
1131 NSString* printTitle = [[paramList descriptorAtIndex:3] stringValue];
[email protected]e8368e92011-08-20 04:05:561132 NSString* printTicket = [[paramList descriptorAtIndex:4] stringValue];
[email protected]a529af52011-08-15 20:56:171133 // Convert the title to UTF 16 as required.
1134 string16 title16 = base::SysNSStringToUTF16(printTitle);
[email protected]e8368e92011-08-20 04:05:561135 string16 printTicket16 = base::SysNSStringToUTF16(printTicket);
[email protected]a529af52011-08-15 20:56:171136 print_dialog_cloud::CreatePrintDialogForFile(
[email protected]b5b79d72012-05-24 19:42:281137 ProfileManager::GetDefaultProfile(), NULL,
[email protected]a529af52011-08-15 20:56:171138 FilePath([inputPath UTF8String]), title16,
[email protected]b5b79d72012-05-24 19:42:281139 printTicket16, [mime UTF8String], /*delete_on_close=*/false);
[email protected]a529af52011-08-15 20:56:171140 }
1141}
1142
1143// Calls the helper class to install the virtual driver to the
1144// service process.
1145- (void)installCloudPrint:(NSAppleEventDescriptor*)event {
1146 cloud_print::VirtualDriverInstallHelper::SetUpInstall();
1147}
1148
1149// Calls the helper class to uninstall the virtual driver to the
1150// service process.
1151- (void)uninstallCloudPrint:(NSAppleEventDescriptor*)event {
1152 cloud_print::VirtualDriverInstallHelper::SetUpUninstall();
1153}
1154
[email protected]caadfca2010-01-22 21:51:211155- (void)application:(NSApplication*)sender
1156 openFiles:(NSArray*)filenames {
[email protected]57750f822009-04-21 21:43:091157 std::vector<GURL> gurlVector;
[email protected]caadfca2010-01-22 21:51:211158 for (NSString* file in filenames) {
1159 GURL gurl = net::FilePathToFileURL(FilePath(base::SysNSStringToUTF8(file)));
[email protected]57750f822009-04-21 21:43:091160 gurlVector.push_back(gurl);
1161 }
[email protected]caadfca2010-01-22 21:51:211162 if (!gurlVector.empty())
[email protected]d630d7d52010-02-21 00:55:111163 [self openUrls:gurlVector];
[email protected]caadfca2010-01-22 21:51:211164 else
1165 NOTREACHED() << "Nothing to open!";
[email protected]57750f822009-04-21 21:43:091166
[email protected]caadfca2010-01-22 21:51:211167 [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
[email protected]57750f822009-04-21 21:43:091168}
[email protected]3f34599d2009-03-25 22:11:431169
[email protected]3111f08b2009-04-30 16:01:521170// Show the preferences window, or bring it to the front if it's already
1171// visible.
1172- (IBAction)showPreferences:(id)sender {
[email protected]a585a8db2011-06-20 18:58:351173 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]445177652011-03-09 02:04:051174 // Show options tab in the active browser window.
[email protected]5d9cace72012-06-21 16:07:121175 chrome::ShowSettings(browser);
[email protected]4a42d272010-06-18 01:29:421176 } else {
[email protected]445177652011-03-09 02:04:051177 // No browser window, so create one for the options tab.
[email protected]1f0b50b2012-06-22 20:37:161178 chrome::OpenOptionsWindow([self lastProfile]);
[email protected]4a42d272010-06-18 01:29:421179 }
[email protected]d989f07c2009-11-14 00:35:461180}
1181
[email protected]bde3dda2009-05-20 22:13:071182- (IBAction)orderFrontStandardAboutPanel:(id)sender {
[email protected]a048ad22012-03-23 04:26:561183 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]5d9cace72012-06-21 16:07:121184 chrome::ShowAboutChrome(browser);
[email protected]a9fbb0962012-03-21 23:25:131185 } else {
[email protected]a048ad22012-03-23 04:26:561186 // No browser window, so create one for the about tab.
[email protected]1f0b50b2012-06-22 20:37:161187 chrome::OpenAboutWindow([self lastProfile]);
[email protected]bde3dda2009-05-20 22:13:071188 }
[email protected]bde3dda2009-05-20 22:13:071189}
1190
[email protected]a99fce0e2011-03-21 20:58:481191- (IBAction)toggleConfirmToQuit:(id)sender {
[email protected]b6366ffa2012-02-29 17:12:261192 PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481193 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1194 prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1195}
1196
[email protected]3d4bd23f2009-10-06 03:58:381197// Explicitly bring to the foreground when creating new windows from the dock.
[email protected]93b59fc2010-12-21 20:00:471198- (void)commandFromDock:(id)sender {
[email protected]3d4bd23f2009-10-06 03:58:381199 [NSApp activateIgnoringOtherApps:YES];
1200 [self commandDispatch:sender];
1201}
1202
[email protected]227fcee2010-06-11 19:19:371203- (NSMenu*)applicationDockMenu:(NSApplication*)sender {
[email protected]018a3962009-09-17 22:23:441204 NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
[email protected]a585a8db2011-06-20 18:58:351205 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:471206
[email protected]646fadbf2012-09-08 01:49:011207 BOOL profilesAdded = [profileMenuController_ insertItemsIntoMenu:dockMenu
1208 atOffset:0
1209 fromDock:YES];
1210 if (profilesAdded)
1211 [dockMenu addItem:[NSMenuItem separatorItem]];
[email protected]3d272f52012-08-23 19:00:331212
[email protected]646fadbf2012-09-08 01:49:011213 NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
[email protected]8c6b029d2011-01-21 22:39:511214 scoped_nsobject<NSMenuItem> item(
1215 [[NSMenuItem alloc] initWithTitle:titleStr
1216 action:@selector(commandFromDock:)
1217 keyEquivalent:@""]);
[email protected]288bfcd32009-09-14 18:14:461218 [item setTarget:self];
[email protected]646fadbf2012-09-08 01:49:011219 [item setTag:IDC_NEW_WINDOW];
1220 [dockMenu addItem:item];
1221
1222 titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
1223 item.reset(
1224 [[NSMenuItem alloc] initWithTitle:titleStr
1225 action:@selector(commandFromDock:)
1226 keyEquivalent:@""]);
1227 [item setTarget:self];
[email protected]288bfcd32009-09-14 18:14:461228 [item setTag:IDC_NEW_INCOGNITO_WINDOW];
[email protected]018a3962009-09-17 22:23:441229 [dockMenu addItem:item];
[email protected]288bfcd32009-09-14 18:14:461230
[email protected]8c6b029d2011-01-21 22:39:511231 // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1232 // tests which use the mock in place of the profile-initialized model.
1233
1234 // Avoid breaking unit tests which have no profile.
1235 if (profile) {
1236 BackgroundApplicationListModel applications(profile);
1237 if (applications.size()) {
1238 int position = 0;
1239 NSString* menuStr =
1240 l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
1241 scoped_nsobject<NSMenu> appMenu([[NSMenu alloc] initWithTitle:menuStr]);
[email protected]1c321ee2012-05-21 03:02:341242 for (extensions::ExtensionList::const_iterator cursor =
1243 applications.begin();
[email protected]8c6b029d2011-01-21 22:39:511244 cursor != applications.end();
1245 ++cursor, ++position) {
[email protected]2ce9c89752011-02-25 18:24:341246 DCHECK_EQ(applications.GetPosition(*cursor), position);
[email protected]8c6b029d2011-01-21 22:39:511247 NSString* itemStr =
1248 base::SysUTF16ToNSString(UTF8ToUTF16((*cursor)->name()));
1249 scoped_nsobject<NSMenuItem> appItem([[NSMenuItem alloc]
1250 initWithTitle:itemStr
1251 action:@selector(commandFromDock:)
1252 keyEquivalent:@""]);
1253 [appItem setTarget:self];
1254 [appItem setTag:position];
1255 [appMenu addItem:appItem];
1256 }
1257 scoped_nsobject<NSMenuItem> appMenuItem([[NSMenuItem alloc]
1258 initWithTitle:menuStr
1259 action:@selector(commandFromDock:)
1260 keyEquivalent:@""]);
1261 [appMenuItem setTarget:self];
1262 [appMenuItem setTag:position];
1263 [appMenuItem setSubmenu:appMenu];
1264 [dockMenu addItem:appMenuItem];
1265 }
1266 }
1267
[email protected]018a3962009-09-17 22:23:441268 return dockMenu;
[email protected]288bfcd32009-09-14 18:14:461269}
1270
[email protected]d630d7d52010-02-21 00:55:111271- (const std::vector<GURL>&)startupUrls {
1272 return startupUrls_;
[email protected]caadfca2010-01-22 21:51:211273}
1274
[email protected]d630d7d52010-02-21 00:55:111275- (void)clearStartupUrls {
1276 startupUrls_.clear();
[email protected]caadfca2010-01-22 21:51:211277}
1278
[email protected]7e4c69d02011-05-11 22:16:471279- (BookmarkMenuBridge*)bookmarkMenuBridge {
1280 return bookmarkMenuBridge_.get();
1281}
1282
[email protected]33190c82012-04-10 17:04:441283- (void)addObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1284 workAreaChangeObservers_.AddObserver(observer);
1285}
1286
1287- (void)removeObserverForWorkAreaChange:(ui::WorkAreaWatcherObserver*)observer {
1288 workAreaChangeObservers_.RemoveObserver(observer);
1289}
1290
[email protected]ebbe94b2012-01-18 20:11:561291- (void)applicationDidChangeScreenParameters:(NSNotification*)notification {
[email protected]6a455072011-11-02 01:32:281292 // During this callback the working area is not always already updated. Defer.
[email protected]33190c82012-04-10 17:04:441293 [self performSelector:@selector(delayedScreenParametersUpdate)
[email protected]6a455072011-11-02 01:32:281294 withObject:nil
1295 afterDelay:0];
1296}
1297
[email protected]33190c82012-04-10 17:04:441298- (void)delayedScreenParametersUpdate {
1299 FOR_EACH_OBSERVER(ui::WorkAreaWatcherObserver, workAreaChangeObservers_,
1300 WorkAreaChanged());
[email protected]6a455072011-11-02 01:32:281301}
1302
[email protected]d630d7d52010-02-21 00:55:111303@end // @implementation AppController
[email protected]60ad3e22009-09-18 21:07:191304
1305//---------------------------------------------------------------------------
1306
[email protected]216e9042009-10-29 17:05:231307namespace app_controller_mac {
1308
1309bool IsOpeningNewWindow() {
1310 return g_is_opening_new_window;
1311}
1312
1313} // namespace app_controller_mac