blob: 28064d97e63bcc041cd874c71769ccaa0732e63c [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]0934de82011-03-09 18:42:1626#include "chrome/browser/instant/instant_confirm_dialog.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]e7dd6d82010-10-07 23:21:1230#include "chrome/browser/printing/print_job_manager.h"
[email protected]8ecad5e2010-12-02 21:18:3331#include "chrome/browser/profiles/profile_manager.h"
[email protected]a529af52011-08-15 20:56:1732#include "chrome/browser/service/service_process_control.h"
[email protected]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]f7002802010-11-12 19:50:2841#include "chrome/browser/ui/browser_init.h"
[email protected]ae04f592010-11-18 20:41:3542#include "chrome/browser/ui/browser_list.h"
43#include "chrome/browser/ui/browser_window.h"
[email protected]7d791652010-12-01 16:34:4944#import "chrome/browser/ui/cocoa/about_window_controller.h"
45#import "chrome/browser/ui/cocoa/bookmarks/bookmark_menu_bridge.h"
46#import "chrome/browser/ui/cocoa/browser_window_cocoa.h"
47#import "chrome/browser/ui/cocoa/browser_window_controller.h"
[email protected]b6366ffa2012-02-29 17:12:2648#import "chrome/browser/ui/cocoa/confirm_quit.h"
[email protected]7d791652010-12-01 16:34:4949#import "chrome/browser/ui/cocoa/confirm_quit_panel_controller.h"
50#import "chrome/browser/ui/cocoa/encoding_menu_controller_delegate_mac.h"
51#import "chrome/browser/ui/cocoa/history_menu_bridge.h"
[email protected]961a6932011-07-19 19:52:4652#import "chrome/browser/ui/cocoa/profile_menu_controller.h"
[email protected]cfe1d612011-01-19 20:06:4753#import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
54#import "chrome/browser/ui/cocoa/tabs/tab_window_controller.h"
[email protected]7d791652010-12-01 16:34:4955#include "chrome/browser/ui/cocoa/task_manager_mac.h"
[email protected]6a455072011-11-02 01:32:2856#include "chrome/browser/ui/panels/panel_manager.h"
[email protected]14fb7d32011-07-10 17:53:3257#include "chrome/common/chrome_notification_types.h"
[email protected]12dc3d42010-02-22 23:37:1258#include "chrome/common/chrome_paths_internal.h"
[email protected]f4acfae82009-09-11 00:33:3859#include "chrome/common/chrome_switches.h"
[email protected]13aec6c42011-10-27 21:22:0860#include "chrome/common/cloud_print/cloud_print_class_mac.h"
[email protected]6c583d32011-08-19 14:46:2261#include "chrome/common/mac/app_mode_common.h"
[email protected]a99fce0e2011-03-21 20:58:4862#include "chrome/common/pref_names.h"
[email protected]a529af52011-08-15 20:56:1763#include "chrome/common/service_messages.h"
[email protected]024617a2010-08-20 05:08:0564#include "chrome/common/url_constants.h"
[email protected]c38831a12011-10-28 12:44:4965#include "content/public/browser/browser_thread.h"
[email protected]e582fdd2011-12-20 16:48:1766#include "content/public/browser/download_manager.h"
[email protected]ad50def52011-10-19 23:17:0767#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:1668#include "content/public/browser/notification_types.h"
[email protected]7f6f44c2011-12-14 13:23:3869#include "content/public/browser/user_metrics.h"
[email protected]9dcb59662009-09-23 01:15:5070#include "grit/chromium_strings.h"
[email protected]09729a552009-08-03 23:21:4171#include "grit/generated_resources.h"
[email protected]caadfca2010-01-22 21:51:2172#include "net/base/net_util.h"
[email protected]2b68f812011-11-25 15:02:1173#include "ui/base/accelerators/accelerator_cocoa.h"
[email protected]c051a1b2011-01-21 23:30:1774#include "ui/base/l10n/l10n_util.h"
75#include "ui/base/l10n/l10n_util_mac.h"
[email protected]88d74942009-01-21 22:04:4476
[email protected]631bb742011-11-02 11:29:3977using content::BrowserThread;
[email protected]e582fdd2011-12-20 16:48:1778using content::DownloadManager;
[email protected]7f6f44c2011-12-14 13:23:3879using content::UserMetricsAction;
[email protected]631bb742011-11-02 11:29:3980
[email protected]f2c20fa2009-12-01 17:42:0281// 10.6 adds a public API for the Spotlight-backed search menu item in the Help
82// menu. Provide the declaration so it can be called below when building with
83// the 10.5 SDK.
84#if !defined(MAC_OS_X_VERSION_10_6) || \
85 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
86@interface NSApplication (SnowLeopardSDKDeclarations)
[email protected]caadfca2010-01-22 21:51:2187- (void)setHelpMenu:(NSMenu*)helpMenu;
[email protected]f2c20fa2009-12-01 17:42:0288@end
89#endif
90
[email protected]d630d7d52010-02-21 00:55:1191namespace {
92
[email protected]ebbe94b2012-01-18 20:11:5693// Declare notification names from the 10.7 SDK.
94#if !defined(MAC_OS_X_VERSION_10_7) || \
95 MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7
96NSString* NSPopoverDidShowNotification = @"NSPopoverDidShowNotification";
97NSString* NSPopoverDidCloseNotification = @"NSPopoverDidCloseNotification";
98#endif
99
[email protected]eddcf7502012-02-09 22:43:48100// True while AppController is calling Browser::NewEmptyWindow(). We need a
[email protected]d630d7d52010-02-21 00:55:11101// global flag here, analogue to BrowserInit::InProcessStartup() because
102// otherwise the SessionService will try to restore sessions when we make a new
103// window while there are no other active windows.
104bool g_is_opening_new_window = false;
105
106// Activates a browser window having the given profile (the last one active) if
107// possible and returns a pointer to the activate |Browser| or NULL if this was
108// not possible. If the last active browser is minimized (in particular, if
109// there are only minimized windows), it will unminimize it.
110Browser* ActivateBrowser(Profile* profile) {
111 Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
112 if (browser)
113 browser->window()->Activate();
114 return browser;
115}
116
117// Creates an empty browser window with the given profile and returns a pointer
118// to the new |Browser|.
119Browser* CreateBrowser(Profile* profile) {
120 {
[email protected]0fbd70332010-06-01 19:28:34121 AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
[email protected]eddcf7502012-02-09 22:43:48122 Browser::NewEmptyWindow(profile);
[email protected]d630d7d52010-02-21 00:55:11123 }
124
125 Browser* browser = BrowserList::GetLastActive();
126 CHECK(browser);
127 return browser;
128}
129
130// Activates a browser window having the given profile (the last one active) if
131// possible or creates an empty one if necessary. Returns a pointer to the
132// activated/new |Browser|.
133Browser* ActivateOrCreateBrowser(Profile* profile) {
134 if (Browser* browser = ActivateBrowser(profile))
135 return browser;
136 return CreateBrowser(profile);
137}
138
[email protected]151c4a62011-04-22 04:15:13139CFStringRef BaseBundleID_CFString() {
140 NSString* base_bundle_id =
141 [NSString stringWithUTF8String:base::mac::BaseBundleID()];
142 return base::mac::NSToCFCast(base_bundle_id);
143}
144
[email protected]0b8caad2011-11-28 23:33:27145// This callback synchronizes preferences (under "org.chromium.Chromium" or
[email protected]12dc3d42010-02-22 23:37:12146// "com.google.Chrome"), in particular, writes them out to disk.
[email protected]0b8caad2011-11-28 23:33:27147void PrefsSyncCallback() {
148 if (!CFPreferencesAppSynchronize(BaseBundleID_CFString()))
149 LOG(WARNING) << "Error recording application bundle path.";
150}
[email protected]12dc3d42010-02-22 23:37:12151
152// Record the location of the application bundle (containing the main framework)
153// from which Chromium was loaded. This is used by app mode shims to find
154// Chromium.
155void RecordLastRunAppBundlePath() {
156 // Going up three levels from |chrome::GetVersionedDirectory()| gives the
157 // real, user-visible app bundle directory. (The alternatives give either the
158 // framework's path or the initial app's path, which may be an app mode shim
159 // or a unit test.)
160 FilePath appBundlePath =
161 chrome::GetVersionedDirectory().DirName().DirName().DirName();
[email protected]b6b72222012-02-11 02:04:13162 CFPreferencesSetAppValue(
163 base::mac::NSToCFCast(app_mode::kLastRunAppBundlePathPrefsKey),
164 base::SysUTF8ToCFStringRef(appBundlePath.value()),
165 BaseBundleID_CFString());
[email protected]12dc3d42010-02-22 23:37:12166
167 // Sync after a delay avoid I/O contention on startup; 1500 ms is plenty.
[email protected]d04e7662010-10-10 22:24:48168 BrowserThread::PostDelayedTask(BrowserThread::FILE, FROM_HERE,
[email protected]0b8caad2011-11-28 23:33:27169 base::Bind(&PrefsSyncCallback), 1500);
[email protected]12dc3d42010-02-22 23:37:12170}
171
[email protected]d630d7d52010-02-21 00:55:11172} // anonymous namespace
173
[email protected]a529af52011-08-15 20:56:17174const AEEventClass kAECloudPrintInstallClass = 'GCPi';
175const AEEventClass kAECloudPrintUninstallClass = 'GCPu';
176
[email protected]a99fce0e2011-03-21 20:58:48177@interface AppController (Private)
[email protected]88d74942009-01-21 22:04:44178- (void)initMenuState;
[email protected]961a6932011-07-19 19:52:46179- (void)initProfileMenu;
[email protected]a99fce0e2011-03-21 20:58:48180- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item;
[email protected]eef99c22010-08-17 05:55:16181- (void)registerServicesMenuTypesTo:(NSApplication*)app;
[email protected]d630d7d52010-02-21 00:55:11182- (void)openUrls:(const std::vector<GURL>&)urls;
[email protected]57750f822009-04-21 21:43:09183- (void)getUrl:(NSAppleEventDescriptor*)event
184 withReply:(NSAppleEventDescriptor*)reply;
[email protected]a529af52011-08-15 20:56:17185- (void)submitCloudPrintJob:(NSAppleEventDescriptor*)event;
186- (void)installCloudPrint:(NSAppleEventDescriptor*)event;
187- (void)uninstallCloudPrint:(NSAppleEventDescriptor*)event;
[email protected]449dd2f2009-05-27 13:04:00188- (void)windowLayeringDidChange:(NSNotification*)inNotification;
[email protected]5c593702011-06-17 18:35:24189- (void)windowChangedToProfile:(Profile*)profile;
[email protected]dd6ab1282010-07-20 01:07:32190- (void)checkForAnyKeyWindows;
[email protected]73f5b362009-08-10 23:58:21191- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount;
[email protected]09729a552009-08-03 23:21:41192- (BOOL)shouldQuitWithInProgressDownloads;
[email protected]93b59fc2010-12-21 20:00:47193- (void)executeApplication:(id)sender;
[email protected]88d74942009-01-21 22:04:44194@end
[email protected]1bcdb532009-01-16 17:47:57195
196@implementation AppController
197
[email protected]caadfca2010-01-22 21:51:21198@synthesize startupComplete = startupComplete_;
199
[email protected]cd63ef62009-05-06 19:41:37200// This method is called very early in application startup (ie, before
201// the profile is loaded or any preferences have been registered). Defer any
202// user-data initialization until -applicationDidFinishLaunching:.
[email protected]88d74942009-01-21 22:04:44203- (void)awakeFromNib {
[email protected]136140c2009-05-19 13:58:25204 // We need to register the handlers early to catch events fired on launch.
[email protected]57750f822009-04-21 21:43:09205 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
206 [em setEventHandler:self
207 andSelector:@selector(getUrl:withReply:)
208 forEventClass:kInternetEventClass
209 andEventID:kAEGetURL];
210 [em setEventHandler:self
[email protected]a529af52011-08-15 20:56:17211 andSelector:@selector(submitCloudPrintJob:)
[email protected]13aec6c42011-10-27 21:22:08212 forEventClass:cloud_print::kAECloudPrintClass
213 andEventID:cloud_print::kAECloudPrintClass];
[email protected]a529af52011-08-15 20:56:17214 // Install and uninstall handlers for virtual drivers.
215 [em setEventHandler:self
216 andSelector:@selector(installCloudPrint:)
217 forEventClass:kAECloudPrintInstallClass
218 andEventID:kAECloudPrintInstallClass];
219 [em setEventHandler:self
220 andSelector:@selector(uninstallCloudPrint:)
221 forEventClass:kAECloudPrintUninstallClass
222 andEventID:kAECloudPrintUninstallClass];
223 [em setEventHandler:self
[email protected]57750f822009-04-21 21:43:09224 andSelector:@selector(getUrl:withReply:)
225 forEventClass:'WWW!' // A particularly ancient AppleEvent that dates
226 andEventID:'OURL']; // back to the Spyglass days.
[email protected]cd63ef62009-05-06 19:41:37227
[email protected]449dd2f2009-05-27 13:04:00228 // Register for various window layering changes. We use these to update
229 // various UI elements (command-key equivalents, etc) when the frontmost
230 // window changes.
231 NSNotificationCenter* notificationCenter =
232 [NSNotificationCenter defaultCenter];
[email protected]ce560f82009-06-03 09:39:44233 [notificationCenter
[email protected]449dd2f2009-05-27 13:04:00234 addObserver:self
235 selector:@selector(windowLayeringDidChange:)
236 name:NSWindowDidBecomeKeyNotification
237 object:nil];
238 [notificationCenter
239 addObserver:self
240 selector:@selector(windowLayeringDidChange:)
241 name:NSWindowDidResignKeyNotification
242 object:nil];
243 [notificationCenter
244 addObserver:self
245 selector:@selector(windowLayeringDidChange:)
246 name:NSWindowDidBecomeMainNotification
247 object:nil];
248 [notificationCenter
249 addObserver:self
250 selector:@selector(windowLayeringDidChange:)
251 name:NSWindowDidResignMainNotification
252 object:nil];
253
[email protected]ebbe94b2012-01-18 20:11:56254 if (base::mac::IsOSLionOrLater()) {
255 [notificationCenter
256 addObserver:self
257 selector:@selector(popoverDidShow:)
258 name:NSPopoverDidShowNotification
259 object:nil];
260 [notificationCenter
261 addObserver:self
262 selector:@selector(popoverDidClose:)
263 name:NSPopoverDidCloseNotification
264 object:nil];
265 }
266
[email protected]136140c2009-05-19 13:58:25267 // Set up the command updater for when there are no windows open
268 [self initMenuState];
[email protected]961a6932011-07-19 19:52:46269
270 // Initialize the Profile menu.
271 [self initProfileMenu];
[email protected]136140c2009-05-19 13:58:25272}
273
[email protected]71c0eb92012-01-03 17:57:30274- (void)unregisterEventHandlers {
275 NSAppleEventManager* em = [NSAppleEventManager sharedAppleEventManager];
276 [em removeEventHandlerForEventClass:kInternetEventClass
277 andEventID:kAEGetURL];
278 [em removeEventHandlerForEventClass:cloud_print::kAECloudPrintClass
279 andEventID:cloud_print::kAECloudPrintClass];
280 [em removeEventHandlerForEventClass:kAECloudPrintInstallClass
281 andEventID:kAECloudPrintInstallClass];
282 [em removeEventHandlerForEventClass:kAECloudPrintUninstallClass
283 andEventID:kAECloudPrintUninstallClass];
284 [em removeEventHandlerForEventClass:'WWW!'
285 andEventID:'OURL'];
286 [[NSNotificationCenter defaultCenter] removeObserver:self];
287}
288
[email protected]7dc8c6b2010-04-09 17:02:50289// (NSApplicationDelegate protocol) This is the Apple-approved place to override
290// the default handlers.
291- (void)applicationWillFinishLaunching:(NSNotification*)notification {
[email protected]58877932010-05-25 05:43:11292 // Nothing here right now.
[email protected]7dc8c6b2010-04-09 17:02:50293}
294
295- (BOOL)tryToTerminateApplication:(NSApplication*)app {
[email protected]3076fad2010-04-28 18:11:45296 // Check for in-process downloads, and prompt the user if they really want
297 // to quit (and thus cancel downloads). Only check if we're not already
298 // shutting down, else the user might be prompted multiple times if the
299 // download isn't stopped before terminate is called again.
300 if (!browser_shutdown::IsTryingToQuit() &&
301 ![self shouldQuitWithInProgressDownloads])
302 return NO;
303
[email protected]7dc8c6b2010-04-09 17:02:50304 // TODO(viettrungluu): Remove Apple Event handlers here? (It's safe to leave
305 // them in, but I'm not sure about UX; we'd also want to disable other things
306 // though.) http://crbug.com/40861
307
[email protected]177aceb2010-11-03 16:17:41308 // Check if the user really wants to quit by employing the confirm-to-quit
309 // mechanism.
310 if (!browser_shutdown::IsTryingToQuit() &&
311 [self applicationShouldTerminate:app] != NSTerminateNow)
312 return NO;
313
[email protected]c984d9f2010-07-20 20:52:20314 size_t num_browsers = BrowserList::size();
[email protected]7dc8c6b2010-04-09 17:02:50315
[email protected]e7dd6d82010-10-07 23:21:12316 // Give any print jobs in progress time to finish.
317 if (!browser_shutdown::IsTryingToQuit())
318 g_browser_process->print_job_manager()->StopJobs(true);
319
[email protected]c984d9f2010-07-20 20:52:20320 // Initiate a shutdown (via BrowserList::CloseAllBrowsers()) if we aren't
321 // already shutting down.
[email protected]ef61b8c2012-01-20 10:54:56322 if (!browser_shutdown::IsTryingToQuit()) {
323 content::NotificationService::current()->Notify(
324 content::NOTIFICATION_APP_EXITING,
325 content::NotificationService::AllSources(),
326 content::NotificationService::NoDetails());
[email protected]c6032e82010-09-13 20:06:05327 BrowserList::CloseAllBrowsers();
[email protected]ef61b8c2012-01-20 10:54:56328 }
[email protected]7dc8c6b2010-04-09 17:02:50329
[email protected]c984d9f2010-07-20 20:52:20330 return num_browsers == 0 ? YES : NO;
[email protected]7dc8c6b2010-04-09 17:02:50331}
332
333- (void)stopTryingToTerminateApplication:(NSApplication*)app {
334 if (browser_shutdown::IsTryingToQuit()) {
335 // Reset the "trying to quit" state, so that closing all browser windows
336 // will no longer lead to termination.
337 browser_shutdown::SetTryingToQuit(false);
338
339 // TODO(viettrungluu): Were we to remove Apple Event handlers above, we
340 // would have to reinstall them here. http://crbug.com/40861
341 }
[email protected]a9e8afc2009-08-11 22:03:17342}
343
[email protected]177aceb2010-11-03 16:17:41344- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)app {
[email protected]a99fce0e2011-03-21 20:58:48345 // Check if the preference is turned on.
[email protected]b6366ffa2012-02-29 17:12:26346 const PrefService* prefs = g_browser_process->local_state();
[email protected]1eaddf32011-04-05 15:09:23347 if (!prefs->GetBoolean(prefs::kConfirmToQuitEnabled)) {
348 confirm_quit::RecordHistogram(confirm_quit::kNoConfirm);
[email protected]177aceb2010-11-03 16:17:41349 return NSTerminateNow;
[email protected]1eaddf32011-04-05 15:09:23350 }
[email protected]177aceb2010-11-03 16:17:41351
352 // If the application is going to terminate as the result of a Cmd+Q
353 // invocation, use the special sauce to prevent accidental quitting.
354 // http://dev.chromium.org/developers/design-documents/confirm-to-quit-experiment
[email protected]177aceb2010-11-03 16:17:41355
[email protected]2020fd0b2010-12-10 01:16:50356 // This logic is only for keyboard-initiated quits.
[email protected]5df54fb2011-03-07 18:15:26357 if (![ConfirmQuitPanelController eventTriggersFeature:[app currentEvent]])
[email protected]2020fd0b2010-12-10 01:16:50358 return NSTerminateNow;
[email protected]177aceb2010-11-03 16:17:41359
[email protected]5df54fb2011-03-07 18:15:26360 return [[ConfirmQuitPanelController sharedController]
361 runModalLoopForApplication:app];
[email protected]177aceb2010-11-03 16:17:41362}
363
[email protected]449dd2f2009-05-27 13:04:00364// Called when the app is shutting down. Clean-up as appropriate.
[email protected]7dc8c6b2010-04-09 17:02:50365- (void)applicationWillTerminate:(NSNotification*)aNotification {
[email protected]7dc8c6b2010-04-09 17:02:50366 // There better be no browser windows left at this point.
[email protected]71c0eb92012-01-03 17:57:30367 CHECK_EQ(0u, BrowserList::size());
[email protected]3b6aa8b62009-09-15 21:36:11368
[email protected]c984d9f2010-07-20 20:52:20369 // Tell BrowserList not to keep the browser process alive. Once all the
370 // browsers get dealloc'd, it will stop the RunLoop and fall back into main().
371 BrowserList::EndKeepAlive();
[email protected]fbc947b2009-06-19 13:28:24372
[email protected]d4e18652009-11-19 21:52:16373 // Close these off if they have open windows.
[email protected]d4e18652009-11-19 21:52:16374 [aboutController_ close];
375
[email protected]71c0eb92012-01-03 17:57:30376 [self unregisterEventHandlers];
[email protected]449dd2f2009-05-27 13:04:00377}
378
[email protected]3b6aa8b62009-09-15 21:36:11379- (void)didEndMainMessageLoop {
[email protected]a585a8db2011-06-20 18:58:35380 DCHECK(!BrowserList::HasBrowserWithProfile([self lastProfile]));
381 if (!BrowserList::HasBrowserWithProfile([self lastProfile])) {
[email protected]3b6aa8b62009-09-15 21:36:11382 // As we're shutting down, we need to nuke the TabRestoreService, which
383 // will start the shutdown of the NavigationControllers and allow for
384 // proper shutdown. If we don't do this, Chrome won't shut down cleanly,
385 // and may end up crashing when some thread tries to use the IO thread (or
386 // another thread) that is no longer valid.
[email protected]a585a8db2011-06-20 18:58:35387 TabRestoreServiceFactory::ResetForProfile([self lastProfile]);
[email protected]3b6aa8b62009-09-15 21:36:11388 }
389}
390
[email protected]8cfbdbd2011-06-16 04:17:17391// If the window has a tab controller, make "close window" be cmd-shift-w,
392// otherwise leave it as the normal cmd-w. Capitalization of the key equivalent
[email protected]eddcf7502012-02-09 22:43:48393// affects whether the shift modifier is used.
[email protected]ebbe94b2012-01-18 20:11:56394- (void)adjustCloseWindowMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
395 [closeWindowMenuItem_ setKeyEquivalent:(enableCloseTabShortcut ? @"W" :
396 @"w")];
[email protected]8cfbdbd2011-06-16 04:17:17397 [closeWindowMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
398}
399
400// If the window has a tab controller, make "close tab" take over cmd-w,
401// otherwise it shouldn't have any key-equivalent because it should be disabled.
[email protected]ebbe94b2012-01-18 20:11:56402- (void)adjustCloseTabMenuItemKeyEquivalent:(BOOL)enableCloseTabShortcut {
403 if (enableCloseTabShortcut) {
[email protected]8cfbdbd2011-06-16 04:17:17404 [closeTabMenuItem_ setKeyEquivalent:@"w"];
405 [closeTabMenuItem_ setKeyEquivalentModifierMask:NSCommandKeyMask];
406 } else {
407 [closeTabMenuItem_ setKeyEquivalent:@""];
408 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
409 }
410}
411
412// Explicitly remove any command-key equivalents from the close tab/window
413// menus so that nothing can go haywire if we get a user action during pending
414// updates.
415- (void)clearCloseMenuItemKeyEquivalents {
416 [closeTabMenuItem_ setKeyEquivalent:@""];
417 [closeTabMenuItem_ setKeyEquivalentModifierMask:0];
418 [closeWindowMenuItem_ setKeyEquivalent:@""];
419 [closeWindowMenuItem_ setKeyEquivalentModifierMask:0];
420}
421
[email protected]9f5f79b62011-10-28 00:43:45422// See if the focused window window has tabs, and adjust the key equivalents for
[email protected]8cfbdbd2011-06-16 04:17:17423// Close Tab/Close Window accordingly.
[email protected]9f5f79b62011-10-28 00:43:45424- (void)fixCloseMenuItemKeyEquivalents {
[email protected]8cfbdbd2011-06-16 04:17:17425 fileMenuUpdatePending_ = NO;
[email protected]8cfbdbd2011-06-16 04:17:17426
[email protected]9f5f79b62011-10-28 00:43:45427 NSWindow* window = [NSApp keyWindow];
428 NSWindow* mainWindow = [NSApp mainWindow];
429 if (!window || ([window parentWindow] == mainWindow)) {
430 // If the key window is a child of the main window (e.g. a bubble), the main
431 // window should be the one that handles the close menu item action.
432 // Also, there might be a small amount of time where there is no key window;
433 // in that case as well, just use our main browser window if there is one.
434 // You might think that we should just always use the main window, but the
435 // "About Chrome" window serves as a counterexample.
436 window = mainWindow;
437 }
438
439 BOOL hasTabs =
440 [[window windowController] isKindOfClass:[TabWindowController class]];
[email protected]ebbe94b2012-01-18 20:11:56441 BOOL enableCloseTabShortcut = hasTabs && !hasPopover_;
442 [self adjustCloseWindowMenuItemKeyEquivalent:enableCloseTabShortcut];
443 [self adjustCloseTabMenuItemKeyEquivalent:enableCloseTabShortcut];
[email protected]8cfbdbd2011-06-16 04:17:17444}
445
446// Fix up the "close tab/close window" command-key equivalents. We do this
447// after a delay to ensure that window layer state has been set by the time
448// we do the enabling. This should only be called on the main thread, code that
449// calls this (even as a side-effect) from other threads needs to be fixed.
[email protected]9f5f79b62011-10-28 00:43:45450- (void)delayedFixCloseMenuItemKeyEquivalents {
[email protected]8cfbdbd2011-06-16 04:17:17451 DCHECK([NSThread isMainThread]);
452 if (!fileMenuUpdatePending_) {
453 // The OS prefers keypresses to timers, so it's possible that a cmd-w
454 // can sneak in before this timer fires. In order to prevent that from
455 // having any bad consequences, just clear the keys combos altogether. They
456 // will be reset when the timer eventually fires.
457 if ([NSThread isMainThread]) {
458 fileMenuUpdatePending_ = YES;
459 [self clearCloseMenuItemKeyEquivalents];
[email protected]9f5f79b62011-10-28 00:43:45460 [self performSelector:@selector(fixCloseMenuItemKeyEquivalents)
461 withObject:nil
[email protected]8cfbdbd2011-06-16 04:17:17462 afterDelay:0];
463 } else {
464 // This shouldn't be happening, but if it does, force it to the main
465 // thread to avoid dropping the update. Don't mess with
466 // |fileMenuUpdatePending_| as it's not expected to be threadsafe and
467 // there could be a race between the selector finishing and setting the
468 // flag.
469 [self
[email protected]9f5f79b62011-10-28 00:43:45470 performSelectorOnMainThread:@selector(fixCloseMenuItemKeyEquivalents)
471 withObject:nil
[email protected]8cfbdbd2011-06-16 04:17:17472 waitUntilDone:NO];
473 }
474 }
475}
476
[email protected]449dd2f2009-05-27 13:04:00477// Called when we get a notification about the window layering changing to
478// update the UI based on the new main window.
479- (void)windowLayeringDidChange:(NSNotification*)notify {
[email protected]9f5f79b62011-10-28 00:43:45480 [self delayedFixCloseMenuItemKeyEquivalents];
[email protected]8cfbdbd2011-06-16 04:17:17481
[email protected]dd6ab1282010-07-20 01:07:32482 if ([notify name] == NSWindowDidResignKeyNotification) {
483 // If a window is closed, this notification is fired but |[NSApp keyWindow]|
484 // returns nil regardless of whether any suitable candidates for the key
485 // window remain. It seems that the new key window for the app is not set
486 // until after this notification is fired, so a check is performed after the
487 // run loop is allowed to spin.
488 [self performSelector:@selector(checkForAnyKeyWindows)
489 withObject:nil
490 afterDelay:0.0];
491 }
[email protected]5c593702011-06-17 18:35:24492
493 // If the window changed to a new BrowserWindowController, update the profile.
494 id windowController = [[notify object] windowController];
[email protected]dc251482012-01-03 18:55:21495 if ([notify name] == NSWindowDidBecomeMainNotification &&
496 [windowController isKindOfClass:[BrowserWindowController class]]) {
[email protected]5c593702011-06-17 18:35:24497 // If the profile is incognito, use the original profile.
498 Profile* newProfile = [windowController profile]->GetOriginalProfile();
499 [self windowChangedToProfile:newProfile];
[email protected]cae68b3a2011-11-21 23:29:49500 } else if (BrowserList::empty()) {
501 [self windowChangedToProfile:
502 g_browser_process->profile_manager()->GetLastUsedProfile()];
[email protected]5c593702011-06-17 18:35:24503 }
504}
505
[email protected]ebbe94b2012-01-18 20:11:56506// Called on Lion and later when a popover (e.g. dictionary) is shown.
507- (void)popoverDidShow:(NSNotification*)notify {
508 hasPopover_ = YES;
509 [self fixCloseMenuItemKeyEquivalents];
510}
511
512// Called on Lion and later when a popover (e.g. dictionary) is closed.
513- (void)popoverDidClose:(NSNotification*)notify {
514 hasPopover_ = NO;
515 [self fixCloseMenuItemKeyEquivalents];
516}
517
[email protected]5c593702011-06-17 18:35:24518// Called when the user has changed browser windows, meaning the backing profile
519// may have changed. This can cause a rebuild of the user-data menus. This is a
520// no-op if the new profile is the same as the current one. This will always be
521// the original profile and never incognito.
522- (void)windowChangedToProfile:(Profile*)profile {
523 if (lastProfile_ == profile)
524 return;
525
526 // Before tearing down the menu controller bridges, return the Cocoa menus to
527 // their initial state.
528 if (bookmarkMenuBridge_.get())
529 bookmarkMenuBridge_->ResetMenu();
530 if (historyMenuBridge_.get())
531 historyMenuBridge_->ResetMenu();
532
533 // Rebuild the menus with the new profile.
534 lastProfile_ = profile;
535
[email protected]0c165cf2011-07-09 03:56:50536 bookmarkMenuBridge_.reset(new BookmarkMenuBridge(lastProfile_,
537 [[[NSApp mainMenu] itemWithTag:IDC_BOOKMARKS_MENU] submenu]));
[email protected]dc251482012-01-03 18:55:21538 // No need to |BuildMenu| here. It is done lazily upon menu access.
[email protected]5c593702011-06-17 18:35:24539
540 historyMenuBridge_.reset(new HistoryMenuBridge(lastProfile_));
541 historyMenuBridge_->BuildMenu();
[email protected]dd6ab1282010-07-20 01:07:32542}
543
544- (void)checkForAnyKeyWindows {
545 if ([NSApp keyWindow])
546 return;
547
[email protected]ad50def52011-10-19 23:17:07548 content::NotificationService::current()->Notify(
[email protected]666641df2011-07-10 18:24:38549 content::NOTIFICATION_NO_KEY_WINDOW,
[email protected]ad50def52011-10-19 23:17:07550 content::NotificationService::AllSources(),
551 content::NotificationService::NoDetails());
[email protected]449dd2f2009-05-27 13:04:00552}
553
[email protected]414fde592009-05-21 16:14:43554// If the auto-update interval is not set, make it 5 hours.
555// This code is specific to Mac Chrome Dev Channel.
556// Placed here for 2 reasons:
557// 1) Same spot as other Pref stuff
558// 2) Try and be friendly by keeping this after app launch
559// TODO(jrg): remove once we go Beta.
560- (void)setUpdateCheckInterval {
561#if defined(GOOGLE_CHROME_BUILD)
562 CFStringRef app = (CFStringRef)@"com.google.Keystone.Agent";
563 CFStringRef checkInterval = (CFStringRef)@"checkInterval";
564 CFPropertyListRef plist = CFPreferencesCopyAppValue(checkInterval, app);
565 if (!plist) {
566 const float fiveHoursInSeconds = 5.0 * 60.0 * 60.0;
[email protected]7dc8c6b2010-04-09 17:02:50567 NSNumber* value = [NSNumber numberWithFloat:fiveHoursInSeconds];
[email protected]414fde592009-05-21 16:14:43568 CFPreferencesSetAppValue(checkInterval, value, app);
569 CFPreferencesAppSynchronize(app);
570 }
571#endif
572}
573
[email protected]136140c2009-05-19 13:58:25574// This is called after profiles have been loaded and preferences registered.
575// It is safe to access the default profile here.
576- (void)applicationDidFinishLaunching:(NSNotification*)notify {
[email protected]c984d9f2010-07-20 20:52:20577 // Notify BrowserList to keep the application running so it doesn't go away
578 // when all the browser windows get closed.
579 BrowserList::StartKeepAlive();
[email protected]136140c2009-05-19 13:58:25580
[email protected]414fde592009-05-21 16:14:43581 [self setUpdateCheckInterval];
[email protected]2bcec612009-05-14 17:50:53582
583 // Build up the encoding menu, the order of the items differs based on the
584 // current locale (see http://crbug.com/7647 for details).
585 // We need a valid g_browser_process to get the profile which is why we can't
586 // call this from awakeFromNib.
[email protected]6f91e5ae2011-03-21 19:53:14587 NSMenu* viewMenu = [[[NSApp mainMenu] itemWithTag:IDC_VIEW_MENU] submenu];
588 NSMenuItem* encodingMenuItem = [viewMenu itemWithTag:IDC_ENCODING_MENU];
589 NSMenu* encodingMenu = [encodingMenuItem submenu];
[email protected]a585a8db2011-06-20 18:58:35590 EncodingMenuControllerDelegate::BuildEncodingMenu([self lastProfile],
[email protected]6f91e5ae2011-03-21 19:53:14591 encodingMenu);
[email protected]2bcec612009-05-14 17:50:53592
[email protected]f2c20fa2009-12-01 17:42:02593 // Since Chrome is localized to more languages than the OS, tell Cocoa which
594 // menu is the Help so it can add the search item to it.
[email protected]caadfca2010-01-22 21:51:21595 if (helpMenu_ && [NSApp respondsToSelector:@selector(setHelpMenu:)])
[email protected]f2c20fa2009-12-01 17:42:02596 [NSApp setHelpMenu:helpMenu_];
[email protected]f2c20fa2009-12-01 17:42:02597
[email protected]12dc3d42010-02-22 23:37:12598 // Record the path to the (browser) app bundle; this is used by the app mode
599 // shim.
600 RecordLastRunAppBundlePath();
601
[email protected]eef99c22010-08-17 05:55:16602 // Makes "Services" menu items available.
603 [self registerServicesMenuTypesTo:[notify object]];
604
[email protected]caadfca2010-01-22 21:51:21605 startupComplete_ = YES;
606
607 // TODO(viettrungluu): This is very temporary, since this should be done "in"
608 // |BrowserMain()|, i.e., this list of startup URLs should be appended to the
609 // (probably-empty) list of URLs from the command line.
[email protected]d630d7d52010-02-21 00:55:11610 if (startupUrls_.size()) {
611 [self openUrls:startupUrls_];
612 [self clearStartupUrls];
[email protected]caadfca2010-01-22 21:51:21613 }
[email protected]aac169d2011-03-18 19:53:03614
615 const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
616 if (!parsed_command_line.HasSwitch(switches::kEnableExposeForTabs)) {
617 [tabposeMenuItem_ setHidden:YES];
618 }
[email protected]b6366ffa2012-02-29 17:12:26619
620 // TODO(rsesek): Remove from trunk when Mstone-20 goes to stable.
621 confirm_quit::MigratePrefToLocalState();
[email protected]7c321082009-02-09 15:35:47622}
623
[email protected]a96ec6a2009-11-04 17:27:08624// This is called after profiles have been loaded and preferences registered.
625// It is safe to access the default profile here.
626- (void)applicationDidBecomeActive:(NSNotification*)notify {
[email protected]ad50def52011-10-19 23:17:07627 content::NotificationService::current()->Notify(
628 content::NOTIFICATION_APP_ACTIVATED,
629 content::NotificationService::AllSources(),
630 content::NotificationService::NoDetails());
[email protected]a96ec6a2009-11-04 17:27:08631}
632
[email protected]73f5b362009-08-10 23:58:21633// Helper function for populating and displaying the in progress downloads at
634// exit alert panel.
635- (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount {
[email protected]e8b5f7882009-09-14 20:59:13636 NSString* warningText = nil;
637 NSString* explanationText = nil;
[email protected]73f5b362009-08-10 23:58:21638 NSString* waitTitle = nil;
639 NSString* exitTitle = nil;
640
641 // Set the dialog text based on whether or not there are multiple downloads.
642 if (downloadCount == 1) {
[email protected]e8b5f7882009-09-14 20:59:13643 // Dialog text: warning and explanation.
[email protected]ab3b1c112012-01-13 22:04:16644 warningText = l10n_util::GetNSString(
645 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_WARNING);
646 explanationText = l10n_util::GetNSString(
647 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_EXPLANATION);
[email protected]73f5b362009-08-10 23:58:21648
649 // Cancel download and exit button text.
[email protected]757127052010-04-27 14:42:26650 exitTitle = l10n_util::GetNSString(
651 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_OK_BUTTON_LABEL);
[email protected]73f5b362009-08-10 23:58:21652
653 // Wait for download button text.
[email protected]757127052010-04-27 14:42:26654 waitTitle = l10n_util::GetNSString(
655 IDS_SINGLE_DOWNLOAD_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL);
[email protected]73f5b362009-08-10 23:58:21656 } else {
[email protected]e8b5f7882009-09-14 20:59:13657 // Dialog text: warning and explanation.
[email protected]757127052010-04-27 14:42:26658 warningText = l10n_util::GetNSStringF(
[email protected]ab3b1c112012-01-13 22:04:16659 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_WARNING,
[email protected]528c56d2010-07-30 19:28:44660 base::IntToString16(downloadCount));
[email protected]ab3b1c112012-01-13 22:04:16661 explanationText = l10n_util::GetNSString(
662 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_EXPLANATION);
[email protected]73f5b362009-08-10 23:58:21663
664 // Cancel downloads and exit button text.
[email protected]757127052010-04-27 14:42:26665 exitTitle = l10n_util::GetNSString(
666 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_OK_BUTTON_LABEL);
[email protected]73f5b362009-08-10 23:58:21667
668 // Wait for downloads button text.
[email protected]757127052010-04-27 14:42:26669 waitTitle = l10n_util::GetNSString(
670 IDS_MULTIPLE_DOWNLOADS_REMOVE_CONFIRM_CANCEL_BUTTON_LABEL);
[email protected]73f5b362009-08-10 23:58:21671 }
672
673 // 'waitButton' is the default choice.
[email protected]e8b5f7882009-09-14 20:59:13674 int choice = NSRunAlertPanel(warningText, explanationText,
675 waitTitle, exitTitle, nil);
[email protected]73f5b362009-08-10 23:58:21676 return choice == NSAlertDefaultReturn ? YES : NO;
677}
678
679// Check all profiles for in progress downloads, and if we find any, prompt the
[email protected]09729a552009-08-03 23:21:41680// user to see if we should continue to exit (and thus cancel the downloads), or
681// if we should wait.
682- (BOOL)shouldQuitWithInProgressDownloads {
[email protected]73f5b362009-08-10 23:58:21683 ProfileManager* profile_manager = g_browser_process->profile_manager();
684 if (!profile_manager)
685 return YES;
[email protected]09729a552009-08-03 23:21:41686
[email protected]844a1002011-04-19 11:37:21687 std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
688 for (size_t i = 0; i < profiles.size(); ++i) {
[email protected]9bb54ee2011-10-12 17:43:35689 DownloadService* download_service =
690 DownloadServiceFactory::GetForProfile(profiles[i]);
691 DownloadManager* download_manager =
692 (download_service->HasCreatedDownloadManager() ?
693 download_service->GetDownloadManager() : NULL);
[email protected]5656f8a2011-11-17 16:12:58694 if (download_manager && download_manager->InProgressCount() > 0) {
695 int downloadCount = download_manager->InProgressCount();
[email protected]73f5b362009-08-10 23:58:21696 if ([self userWillWaitForInProgressDownloads:downloadCount]) {
697 // Create a new browser window (if necessary) and navigate to the
698 // downloads page if the user chooses to wait.
[email protected]844a1002011-04-19 11:37:21699 Browser* browser = BrowserList::FindBrowserWithProfile(profiles[i]);
[email protected]73f5b362009-08-10 23:58:21700 if (!browser) {
[email protected]844a1002011-04-19 11:37:21701 browser = Browser::Create(profiles[i]);
[email protected]73f5b362009-08-10 23:58:21702 browser->window()->Show();
703 }
704 DCHECK(browser);
705 browser->ShowDownloadsTab();
706 return NO;
707 }
[email protected]09729a552009-08-03 23:21:41708
[email protected]73f5b362009-08-10 23:58:21709 // User wants to exit.
710 return YES;
[email protected]09729a552009-08-03 23:21:41711 }
[email protected]09729a552009-08-03 23:21:41712 }
713
[email protected]73f5b362009-08-10 23:58:21714 // No profiles or active downloads found, okay to exit.
[email protected]09729a552009-08-03 23:21:41715 return YES;
716}
717
[email protected]fbc947b2009-06-19 13:28:24718// Called to determine if we should enable the "restore tab" menu item.
719// Checks with the TabRestoreService to see if there's anything there to
720// restore and returns YES if so.
721- (BOOL)canRestoreTab {
[email protected]92371eb2011-04-28 11:50:15722 TabRestoreService* service =
[email protected]a585a8db2011-06-20 18:58:35723 TabRestoreServiceFactory::GetForProfile([self lastProfile]);
[email protected]fbc947b2009-06-19 13:28:24724 return service && !service->entries().empty();
725}
726
[email protected]f6c15fa2010-06-04 20:08:21727// Returns true if there is not a modal window (either window- or application-
728// modal) blocking the active browser. Note that tab modal dialogs (HTTP auth
729// sheets) will not count as blocking the browser. But things like open/save
730// dialogs that are window modal will block the browser.
731- (BOOL)keyWindowIsNotModal {
[email protected]6a281332009-10-13 17:41:06732 Browser* browser = BrowserList::GetLastActive();
[email protected]dc76e8362010-06-11 16:29:52733 return [NSApp modalWindow] == nil && (!browser ||
[email protected]6a281332009-10-13 17:41:06734 ![[browser->window()->GetNativeHandle() attachedSheet]
[email protected]f6c15fa2010-06-04 20:08:21735 isKindOfClass:[NSWindow class]]);
[email protected]6a281332009-10-13 17:41:06736}
737
[email protected]88d74942009-01-21 22:04:44738// Called to validate menu items when there are no key windows. All the
739// items we care about have been set with the |commandDispatch:| action and
740// a target of FirstResponder in IB. If it's not one of those, let it
741// continue up the responder chain to be handled elsewhere. We pull out the
742// tag as the cross-platform constant to differentiate and dispatch the
743// various commands.
744- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
745 SEL action = [item action];
746 BOOL enable = NO;
747 if (action == @selector(commandDispatch:)) {
748 NSInteger tag = [item tag];
[email protected]fbc947b2009-06-19 13:28:24749 if (menuState_->SupportsCommand(tag)) {
750 switch (tag) {
[email protected]419eb2a2009-11-11 16:26:26751 // The File Menu commands are not automatically disabled by Cocoa when a
752 // dialog sheet obscures the browser window, so we disable several of
753 // them here. We don't need to include IDC_CLOSE_WINDOW, because
754 // app_controller is only activated when there are no key windows (see
755 // function comment).
[email protected]fbc947b2009-06-19 13:28:24756 case IDC_RESTORE_TAB:
[email protected]f6c15fa2010-06-04 20:08:21757 enable = [self keyWindowIsNotModal] && [self canRestoreTab];
[email protected]6a281332009-10-13 17:41:06758 break;
[email protected]f6c15fa2010-06-04 20:08:21759 // Browser-level items that open in new tabs should not open if there's
760 // a window- or app-modal dialog.
[email protected]6a281332009-10-13 17:41:06761 case IDC_OPEN_FILE:
[email protected]6a281332009-10-13 17:41:06762 case IDC_NEW_TAB:
[email protected]f6c15fa2010-06-04 20:08:21763 case IDC_SHOW_HISTORY:
764 case IDC_SHOW_BOOKMARK_MANAGER:
765 enable = [self keyWindowIsNotModal];
766 break;
767 // Browser-level items that open in new windows.
768 case IDC_NEW_WINDOW:
769 case IDC_TASK_MANAGER:
770 // Allow the user to open a new window if there's a window-modal
771 // dialog.
772 enable = [self keyWindowIsNotModal] || ([NSApp modalWindow] == nil);
[email protected]fbc947b2009-06-19 13:28:24773 break;
[email protected]65549182012-02-25 00:45:40774 case IDC_SHOW_SYNC_SETUP: {
[email protected]a585a8db2011-06-20 18:58:35775 Profile* lastProfile = [self lastProfile];
[email protected]446e16a2010-05-03 21:23:58776 // The profile may be NULL during shutdown -- see
777 // http://code.google.com/p/chromium/issues/detail?id=43048 .
778 //
779 // TODO(akalin,viettrungluu): Figure out whether this method
[email protected]a585a8db2011-06-20 18:58:35780 // can be prevented from being called if lastProfile is
[email protected]446e16a2010-05-03 21:23:58781 // NULL.
[email protected]a585a8db2011-06-20 18:58:35782 if (!lastProfile) {
[email protected]446e16a2010-05-03 21:23:58783 LOG(WARNING)
[email protected]a585a8db2011-06-20 18:58:35784 << "NULL lastProfile detected -- not doing anything";
[email protected]446e16a2010-05-03 21:23:58785 break;
786 }
[email protected]a585a8db2011-06-20 18:58:35787 enable = lastProfile->IsSyncAccessible() &&
[email protected]d3b98c82010-07-14 07:45:59788 [self keyWindowIsNotModal];
[email protected]a585a8db2011-06-20 18:58:35789 sync_ui_util::UpdateSyncItem(item, enable, lastProfile);
[email protected]f9bc9b92009-11-24 00:55:35790 break;
[email protected]446e16a2010-05-03 21:23:58791 }
[email protected]acaa37b2011-08-31 07:19:11792 case IDC_FEEDBACK:
793 enable = NO;
794 break;
[email protected]fbc947b2009-06-19 13:28:24795 default:
[email protected]f6c15fa2010-06-04 20:08:21796 enable = menuState_->IsCommandEnabled(tag) ?
797 [self keyWindowIsNotModal] : NO;
[email protected]fbc947b2009-06-19 13:28:24798 }
799 }
[email protected]3b6aa8b62009-09-15 21:36:11800 } else if (action == @selector(terminate:)) {
[email protected]88d74942009-01-21 22:04:44801 enable = YES;
[email protected]3111f08b2009-04-30 16:01:52802 } else if (action == @selector(showPreferences:)) {
803 enable = YES;
[email protected]bde3dda2009-05-20 22:13:07804 } else if (action == @selector(orderFrontStandardAboutPanel:)) {
805 enable = YES;
[email protected]93b59fc2010-12-21 20:00:47806 } else if (action == @selector(commandFromDock:)) {
[email protected]3d4bd23f2009-10-06 03:58:38807 enable = YES;
[email protected]a99fce0e2011-03-21 20:58:48808 } else if (action == @selector(toggleConfirmToQuit:)) {
809 [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)];
810 enable = YES;
[email protected]88d74942009-01-21 22:04:44811 }
812 return enable;
813}
814
[email protected]947fc0d2010-01-14 22:33:05815// Called when the user picks a menu item when there are no key windows, or when
816// there is no foreground browser window. Calls through to the browser object to
817// execute the command. This assumes that the command is supported and doesn't
[email protected]d630d7d52010-02-21 00:55:11818// check, otherwise it should have been disabled in the UI in
819// |-validateUserInterfaceItem:|.
[email protected]88d74942009-01-21 22:04:44820- (void)commandDispatch:(id)sender {
[email protected]a585a8db2011-06-20 18:58:35821 Profile* lastProfile = [self lastProfile];
[email protected]f0a51fb52009-03-05 12:46:38822
[email protected]947fc0d2010-01-14 22:33:05823 // Handle the case where we're dispatching a command from a sender that's in a
824 // browser window. This means that the command came from a background window
825 // and is getting here because the foreground window is not a browser window.
826 if ([sender respondsToSelector:@selector(window)]) {
827 id delegate = [[sender window] windowController];
828 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
829 [delegate commandDispatch:sender];
830 return;
831 }
832 }
833
[email protected]88d74942009-01-21 22:04:44834 NSInteger tag = [sender tag];
835 switch (tag) {
[email protected]fbc947b2009-06-19 13:28:24836 case IDC_NEW_TAB:
[email protected]d630d7d52010-02-21 00:55:11837 // Create a new tab in an existing browser window (which we activate) if
838 // possible.
[email protected]a585a8db2011-06-20 18:58:35839 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]d630d7d52010-02-21 00:55:11840 browser->ExecuteCommand(IDC_NEW_TAB);
841 break;
842 }
843 // Else fall through to create new window.
[email protected]88d74942009-01-21 22:04:44844 case IDC_NEW_WINDOW:
[email protected]a585a8db2011-06-20 18:58:35845 CreateBrowser(lastProfile);
[email protected]d630d7d52010-02-21 00:55:11846 break;
[email protected]91a5b3e2009-10-30 19:32:22847 case IDC_FOCUS_LOCATION:
[email protected]a585a8db2011-06-20 18:58:35848 ActivateOrCreateBrowser(lastProfile)->ExecuteCommand(IDC_FOCUS_LOCATION);
[email protected]88d74942009-01-21 22:04:44849 break;
[email protected]cddc5242009-12-07 18:54:33850 case IDC_FOCUS_SEARCH:
[email protected]a585a8db2011-06-20 18:58:35851 ActivateOrCreateBrowser(lastProfile)->ExecuteCommand(IDC_FOCUS_SEARCH);
[email protected]cddc5242009-12-07 18:54:33852 break;
[email protected]863ff662009-01-26 20:18:18853 case IDC_NEW_INCOGNITO_WINDOW:
[email protected]eddcf7502012-02-09 22:43:48854 CreateBrowser(lastProfile->GetOffTheRecordProfile());
[email protected]863ff662009-01-26 20:18:18855 break;
[email protected]fbc947b2009-06-19 13:28:24856 case IDC_RESTORE_TAB:
[email protected]a585a8db2011-06-20 18:58:35857 Browser::OpenWindowWithRestoredTabs(lastProfile);
[email protected]fbc947b2009-06-19 13:28:24858 break;
[email protected]e19516d2009-04-28 17:15:19859 case IDC_OPEN_FILE:
[email protected]a585a8db2011-06-20 18:58:35860 CreateBrowser(lastProfile)->ExecuteCommand(IDC_OPEN_FILE);
[email protected]e19516d2009-04-28 17:15:19861 break;
[email protected]1fdff702009-10-22 00:36:18862 case IDC_CLEAR_BROWSING_DATA: {
[email protected]93e181762009-05-29 14:30:38863 // There may not be a browser open, so use the default profile.
[email protected]a585a8db2011-06-20 18:58:35864 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]445177652011-03-09 02:04:05865 browser->OpenClearBrowsingDataDialog();
[email protected]c8de64a2011-01-25 17:10:23866 } else {
[email protected]ddddfda2011-07-14 23:19:39867 Browser::OpenClearBrowsingDataDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:23868 }
[email protected]93e181762009-05-29 14:30:38869 break;
[email protected]1fdff702009-10-22 00:36:18870 }
[email protected]4aee5652009-11-19 18:59:21871 case IDC_IMPORT_SETTINGS: {
[email protected]a585a8db2011-06-20 18:58:35872 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]445177652011-03-09 02:04:05873 browser->OpenImportSettingsDialog();
[email protected]c8de64a2011-01-25 17:10:23874 } else {
[email protected]a585a8db2011-06-20 18:58:35875 Browser::OpenImportSettingsDialogWindow(lastProfile);
[email protected]c8de64a2011-01-25 17:10:23876 }
[email protected]4aee5652009-11-19 18:59:21877 break;
878 }
[email protected]af7c25e2010-01-23 05:46:45879 case IDC_SHOW_BOOKMARK_MANAGER:
[email protected]7f6f44c2011-12-14 13:23:38880 content::RecordAction(UserMetricsAction("ShowBookmarkManager"));
[email protected]a585a8db2011-06-20 18:58:35881 if (Browser* browser = ActivateBrowser(lastProfile)) {
[email protected]47e532b2010-04-23 17:46:40882 // Open a bookmark manager tab.
[email protected]90a8bf252010-03-12 00:09:47883 browser->OpenBookmarkManager();
884 } else {
[email protected]47e532b2010-04-23 17:46:40885 // No browser window, so create one for the bookmark manager tab.
[email protected]a585a8db2011-06-20 18:58:35886 Browser::OpenBookmarkManagerWindow(lastProfile);
[email protected]90a8bf252010-03-12 00:09:47887 }
[email protected]af7c25e2010-01-23 05:46:45888 break;
[email protected]91a5b3e2009-10-30 19:32:22889 case IDC_SHOW_HISTORY:
[email protected]a585a8db2011-06-20 18:58:35890 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]d630d7d52010-02-21 00:55:11891 browser->ShowHistoryTab();
892 else
[email protected]a585a8db2011-06-20 18:58:35893 Browser::OpenHistoryWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:22894 break;
895 case IDC_SHOW_DOWNLOADS:
[email protected]a585a8db2011-06-20 18:58:35896 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]d630d7d52010-02-21 00:55:11897 browser->ShowDownloadsTab();
898 else
[email protected]a585a8db2011-06-20 18:58:35899 Browser::OpenDownloadsWindow(lastProfile);
[email protected]91a5b3e2009-10-30 19:32:22900 break;
[email protected]bb37e6ec2009-11-18 17:59:36901 case IDC_MANAGE_EXTENSIONS:
[email protected]a585a8db2011-06-20 18:58:35902 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]d630d7d52010-02-21 00:55:11903 browser->ShowExtensionsTab();
904 else
[email protected]a585a8db2011-06-20 18:58:35905 Browser::OpenExtensionsWindow(lastProfile);
[email protected]bb37e6ec2009-11-18 17:59:36906 break;
[email protected]1fdff702009-10-22 00:36:18907 case IDC_HELP_PAGE:
[email protected]a585a8db2011-06-20 18:58:35908 if (Browser* browser = ActivateBrowser(lastProfile))
[email protected]202802e42011-07-06 11:40:46909 browser->ShowHelpTab();
[email protected]d630d7d52010-02-21 00:55:11910 else
[email protected]a585a8db2011-06-20 18:58:35911 Browser::OpenHelpWindow(lastProfile);
[email protected]1fdff702009-10-22 00:36:18912 break;
[email protected]65549182012-02-25 00:45:40913 case IDC_SHOW_SYNC_SETUP:
914 if (Browser* browser = ActivateBrowser(lastProfile))
915 browser->ShowSyncSetup();
916 else
917 Browser::OpenSyncSetupWindow(lastProfile);
[email protected]f9bc9b92009-11-24 00:55:35918 break;
[email protected]ceaaf1812010-01-20 22:13:09919 case IDC_TASK_MANAGER:
[email protected]7f6f44c2011-12-14 13:23:38920 content::RecordAction(UserMetricsAction("TaskManager"));
[email protected]adb6a84d2011-02-07 16:58:40921 TaskManagerMac::Show(false);
[email protected]ceaaf1812010-01-20 22:13:09922 break;
[email protected]4a42d272010-06-18 01:29:42923 case IDC_OPTIONS:
924 [self showPreferences:sender];
925 break;
[email protected]93b59fc2010-12-21 20:00:47926 default:
927 // Background Applications use dynamic values that must be less than the
928 // smallest value among the predefined IDC_* labels.
929 if ([sender tag] < IDC_MinimumLabelValue)
930 [self executeApplication:sender];
931 break;
[email protected]d630d7d52010-02-21 00:55:11932 }
[email protected]88d74942009-01-21 22:04:44933}
934
[email protected]93b59fc2010-12-21 20:00:47935// Run a (background) application in a new tab.
936- (void)executeApplication:(id)sender {
937 NSInteger tag = [sender tag];
[email protected]a585a8db2011-06-20 18:58:35938 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:47939 DCHECK(profile);
940 BackgroundApplicationListModel applications(profile);
941 DCHECK(tag >= 0 &&
942 tag < static_cast<int>(applications.size()));
[email protected]93b59fc2010-12-21 20:00:47943 const Extension* extension = applications.GetExtension(tag);
[email protected]78d78a62011-09-29 18:24:33944 BackgroundModeManager::LaunchBackgroundApplication(profile, extension);
[email protected]93b59fc2010-12-21 20:00:47945}
946
[email protected]947fc0d2010-01-14 22:33:05947// Same as |-commandDispatch:|, but executes commands using a disposition
948// determined by the key flags. This will get called in the case where the
949// frontmost window is not a browser window, and the user has command-clicked
950// a button in a background browser window whose action is
951// |-commandDispatchUsingKeyModifiers:|
952- (void)commandDispatchUsingKeyModifiers:(id)sender {
953 DCHECK(sender);
954 if ([sender respondsToSelector:@selector(window)]) {
955 id delegate = [[sender window] windowController];
956 if ([delegate isKindOfClass:[BrowserWindowController class]]) {
957 [delegate commandDispatchUsingKeyModifiers:sender];
958 }
959 }
960}
961
[email protected]ff81e0a2009-04-13 14:58:54962// NSApplication delegate method called when someone clicks on the
963// dock icon and there are no open windows. To match standard mac
964// behavior, we should open a new window.
965- (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
966 hasVisibleWindows:(BOOL)flag {
[email protected]70631402010-04-26 20:16:54967 // If the browser is currently trying to quit, don't do anything and return NO
968 // to prevent AppKit from doing anything.
969 // TODO(rohitrao): Remove this code when http://crbug.com/40861 is resolved.
970 if (browser_shutdown::IsTryingToQuit())
971 return NO;
972
[email protected]0236be22012-01-11 01:05:35973 // Don't do anything if there are visible tabbed or popup windows. This will
974 // cause AppKit to unminimize the most recently minimized window. If the
975 // visible windows are panels or notifications, we still need to open a new
976 // window.
977 if (flag) {
978 for (BrowserList::const_iterator iter = BrowserList::begin();
979 iter != BrowserList::end(); ++iter) {
980 Browser* browser = *iter;
981 if (browser->is_type_tabbed() || browser->is_type_popup())
982 return YES;
983 }
984 }
[email protected]ff81e0a2009-04-13 14:58:54985
[email protected]0d1210d62010-09-07 17:31:38986 // If launched as a hidden login item (due to installation of a persistent app
[email protected]eddcf7502012-02-09 22:43:48987 // or by the user, for example in System Preferences->Accounts->Login Items),
[email protected]0d1210d62010-09-07 17:31:38988 // allow session to be restored first time the user clicks on a Dock icon.
989 // Normally, it'd just open a new empty page.
990 {
[email protected]eddcf7502012-02-09 22:43:48991 static BOOL doneOnce = NO;
992 if (!doneOnce) {
993 doneOnce = YES;
994 if (base::mac::WasLaunchedAsHiddenLoginItem()) {
995 SessionService* sessionService =
996 SessionServiceFactory::GetForProfile([self lastProfile]);
997 if (sessionService &&
998 sessionService->RestoreIfNecessary(std::vector<GURL>()))
999 return NO;
[email protected]0d1210d62010-09-07 17:31:381000 }
[email protected]eddcf7502012-02-09 22:43:481001 }
[email protected]0d1210d62010-09-07 17:31:381002 }
[email protected]fc44f242012-02-14 16:54:391003
1004 // Platform apps don't use browser windows so don't do anything if there are
1005 // visible windows.
1006 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1007 if (flag && command_line.HasSwitch(switches::kAppId))
1008 return YES;
1009
[email protected]ff81e0a2009-04-13 14:58:541010 // Otherwise open a new window.
[email protected]d630d7d52010-02-21 00:55:111011 {
[email protected]0fbd70332010-06-01 19:28:341012 AutoReset<bool> auto_reset_in_run(&g_is_opening_new_window, true);
[email protected]fc44f242012-02-14 16:54:391013 int return_code;
1014 BrowserInit browser_init;
1015 browser_init.LaunchBrowser(command_line, [self lastProfile], FilePath(),
1016 BrowserInit::IS_NOT_PROCESS_STARTUP,
1017 BrowserInit::IS_NOT_FIRST_RUN, &return_code);
[email protected]d630d7d52010-02-21 00:55:111018 }
[email protected]ff81e0a2009-04-13 14:58:541019
1020 // We've handled the reopen event, so return NO to tell AppKit not
1021 // to do anything.
1022 return NO;
1023}
1024
[email protected]88d74942009-01-21 22:04:441025- (void)initMenuState {
[email protected]3111f08b2009-04-30 16:01:521026 menuState_.reset(new CommandUpdater(NULL));
[email protected]fbc947b2009-06-19 13:28:241027 menuState_->UpdateCommandEnabled(IDC_NEW_TAB, true);
[email protected]88d74942009-01-21 22:04:441028 menuState_->UpdateCommandEnabled(IDC_NEW_WINDOW, true);
[email protected]863ff662009-01-26 20:18:181029 menuState_->UpdateCommandEnabled(IDC_NEW_INCOGNITO_WINDOW, true);
[email protected]e19516d2009-04-28 17:15:191030 menuState_->UpdateCommandEnabled(IDC_OPEN_FILE, true);
[email protected]93e181762009-05-29 14:30:381031 menuState_->UpdateCommandEnabled(IDC_CLEAR_BROWSING_DATA, true);
[email protected]fbc947b2009-06-19 13:28:241032 menuState_->UpdateCommandEnabled(IDC_RESTORE_TAB, false);
[email protected]91a5b3e2009-10-30 19:32:221033 menuState_->UpdateCommandEnabled(IDC_FOCUS_LOCATION, true);
[email protected]cddc5242009-12-07 18:54:331034 menuState_->UpdateCommandEnabled(IDC_FOCUS_SEARCH, true);
[email protected]af7c25e2010-01-23 05:46:451035 menuState_->UpdateCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER, true);
[email protected]91a5b3e2009-10-30 19:32:221036 menuState_->UpdateCommandEnabled(IDC_SHOW_HISTORY, true);
1037 menuState_->UpdateCommandEnabled(IDC_SHOW_DOWNLOADS, true);
[email protected]bb37e6ec2009-11-18 17:59:361038 menuState_->UpdateCommandEnabled(IDC_MANAGE_EXTENSIONS, true);
[email protected]1fdff702009-10-22 00:36:181039 menuState_->UpdateCommandEnabled(IDC_HELP_PAGE, true);
[email protected]4aee5652009-11-19 18:59:211040 menuState_->UpdateCommandEnabled(IDC_IMPORT_SETTINGS, true);
[email protected]1c41a932010-11-22 23:41:231041 menuState_->UpdateCommandEnabled(IDC_FEEDBACK, true);
[email protected]65549182012-02-25 00:45:401042 menuState_->UpdateCommandEnabled(IDC_SHOW_SYNC_SETUP, true);
[email protected]ceaaf1812010-01-20 22:13:091043 menuState_->UpdateCommandEnabled(IDC_TASK_MANAGER, true);
[email protected]88d74942009-01-21 22:04:441044}
[email protected]1bcdb532009-01-16 17:47:571045
[email protected]961a6932011-07-19 19:52:461046// Conditionally adds the Profile menu to the main menu bar.
1047- (void)initProfileMenu {
[email protected]961a6932011-07-19 19:52:461048 NSMenu* mainMenu = [NSApp mainMenu];
1049 NSMenuItem* profileMenu = [mainMenu itemWithTag:IDC_PROFILE_MAIN_MENU];
[email protected]e354ca42011-08-03 20:31:401050
1051 // On Leopard, hiding main menubar items does not work. This manifests itself
1052 // in Chromium as squished menu items <http://crbug.com/90753>. To prevent
1053 // this, remove the Profile menu on Leopard, regardless of the user's
1054 // multiprofile state.
[email protected]6b2d30bc2011-10-11 18:16:391055 if (!ProfileManager::IsMultipleProfilesEnabled() ||
1056 base::mac::IsOSLeopard()) {
[email protected]e354ca42011-08-03 20:31:401057 [mainMenu removeItem:profileMenu];
1058 return;
1059 }
1060
[email protected]6b2d30bc2011-10-11 18:16:391061 // The controller will unhide the menu if necessary.
1062 [profileMenu setHidden:YES];
[email protected]961a6932011-07-19 19:52:461063
[email protected]6b2d30bc2011-10-11 18:16:391064 profileMenuController_.reset(
1065 [[ProfileMenuController alloc] initWithMainMenuItem:profileMenu]);
[email protected]961a6932011-07-19 19:52:461066}
1067
[email protected]a99fce0e2011-03-21 20:58:481068// The Confirm to Quit preference is atypical in that the preference lives in
1069// the app menu right above the Quit menu item. This method will refresh the
1070// display of that item depending on the preference state.
1071- (void)updateConfirmToQuitPrefMenuItem:(NSMenuItem*)item {
1072 // Format the string so that the correct key equivalent is displayed.
1073 NSString* acceleratorString = [ConfirmQuitPanelController keyCommandString];
1074 NSString* title = l10n_util::GetNSStringF(IDS_CONFIRM_TO_QUIT_OPTION,
1075 base::SysNSStringToUTF16(acceleratorString));
1076 [item setTitle:title];
1077
[email protected]b6366ffa2012-02-29 17:12:261078 const PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481079 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1080 [item setState:enabled ? NSOnState : NSOffState];
1081}
1082
[email protected]eef99c22010-08-17 05:55:161083- (void)registerServicesMenuTypesTo:(NSApplication*)app {
[email protected]09ea24c2010-08-23 19:05:411084 // Note that RenderWidgetHostViewCocoa implements NSServicesRequests which
1085 // handles requests from services.
1086 NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, nil];
1087 [app registerServicesMenuSendTypes:types returnTypes:types];
[email protected]eef99c22010-08-17 05:55:161088}
1089
[email protected]a585a8db2011-06-20 18:58:351090- (Profile*)lastProfile {
[email protected]7fd5a462011-06-19 16:57:231091 // Return the profile of the last-used BrowserWindowController, if available.
1092 if (lastProfile_)
1093 return lastProfile_;
1094
[email protected]056f8792011-07-20 15:40:151095 // On first launch, no profile will be stored, so use last from Local State.
[email protected]3f34599d2009-03-25 22:11:431096 if (g_browser_process->profile_manager())
[email protected]056f8792011-07-20 15:40:151097 return g_browser_process->profile_manager()->GetLastUsedProfile();
[email protected]3f34599d2009-03-25 22:11:431098
[email protected]f6314002009-04-23 01:18:131099 return NULL;
[email protected]3f34599d2009-03-25 22:11:431100}
1101
[email protected]57750f822009-04-21 21:43:091102// Various methods to open URLs that we get in a native fashion. We use
1103// BrowserInit here because on the other platforms, URLs to open come through
1104// the ProcessSingleton, and it calls BrowserInit. It's best to bottleneck the
1105// openings through that for uniform handling.
1106
[email protected]d630d7d52010-02-21 00:55:111107- (void)openUrls:(const std::vector<GURL>&)urls {
[email protected]caadfca2010-01-22 21:51:211108 // If the browser hasn't started yet, just queue up the URLs.
1109 if (!startupComplete_) {
[email protected]d630d7d52010-02-21 00:55:111110 startupUrls_.insert(startupUrls_.end(), urls.begin(), urls.end());
[email protected]136140c2009-05-19 13:58:251111 return;
1112 }
[email protected]57750f822009-04-21 21:43:091113
[email protected]0e863512009-05-28 19:45:071114 Browser* browser = BrowserList::GetLastActive();
1115 // if no browser window exists then create one with no tabs to be filled in
1116 if (!browser) {
[email protected]a585a8db2011-06-20 18:58:351117 browser = Browser::Create([self lastProfile]);
[email protected]ce560f82009-06-03 09:39:441118 browser->window()->Show();
[email protected]0e863512009-05-28 19:45:071119 }
1120
[email protected]947446b2010-10-21 03:36:311121 CommandLine dummy(CommandLine::NO_PROGRAM);
[email protected]dfa08b042011-12-28 23:07:211122 BrowserInit::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
[email protected]e4a377cf2011-10-05 02:51:491123 BrowserInit::IS_FIRST_RUN : BrowserInit::IS_NOT_FIRST_RUN;
1124 BrowserInit::LaunchWithProfile launch(FilePath(), dummy, first_run);
[email protected]0e863512009-05-28 19:45:071125 launch.OpenURLsInBrowser(browser, false, urls);
[email protected]57750f822009-04-21 21:43:091126}
1127
[email protected]57750f822009-04-21 21:43:091128- (void)getUrl:(NSAppleEventDescriptor*)event
1129 withReply:(NSAppleEventDescriptor*)reply {
1130 NSString* urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
1131 stringValue];
1132
1133 GURL gurl(base::SysNSStringToUTF8(urlStr));
1134 std::vector<GURL> gurlVector;
1135 gurlVector.push_back(gurl);
1136
[email protected]d630d7d52010-02-21 00:55:111137 [self openUrls:gurlVector];
[email protected]57750f822009-04-21 21:43:091138}
1139
[email protected]a529af52011-08-15 20:56:171140// Apple Event handler that receives print event from service
1141// process, gets the required data and launches Print dialog.
1142- (void)submitCloudPrintJob:(NSAppleEventDescriptor*)event {
1143 // Pull parameter list out of Apple Event.
[email protected]ebbe94b2012-01-18 20:11:561144 NSAppleEventDescriptor* paramList =
[email protected]13aec6c42011-10-27 21:22:081145 [event paramDescriptorForKeyword:cloud_print::kAECloudPrintClass];
[email protected]a529af52011-08-15 20:56:171146
1147 if (paramList != nil) {
1148 // Pull required fields out of parameter list.
1149 NSString* mime = [[paramList descriptorAtIndex:1] stringValue];
1150 NSString* inputPath = [[paramList descriptorAtIndex:2] stringValue];
1151 NSString* printTitle = [[paramList descriptorAtIndex:3] stringValue];
[email protected]e8368e92011-08-20 04:05:561152 NSString* printTicket = [[paramList descriptorAtIndex:4] stringValue];
[email protected]a529af52011-08-15 20:56:171153 // Convert the title to UTF 16 as required.
1154 string16 title16 = base::SysNSStringToUTF16(printTitle);
[email protected]e8368e92011-08-20 04:05:561155 string16 printTicket16 = base::SysNSStringToUTF16(printTicket);
[email protected]a529af52011-08-15 20:56:171156 print_dialog_cloud::CreatePrintDialogForFile(
1157 FilePath([inputPath UTF8String]), title16,
[email protected]d955fc92011-09-19 20:49:031158 printTicket16, [mime UTF8String], /*modal=*/false,
1159 /*delete_on_close=*/false);
[email protected]a529af52011-08-15 20:56:171160 }
1161}
1162
1163// Calls the helper class to install the virtual driver to the
1164// service process.
1165- (void)installCloudPrint:(NSAppleEventDescriptor*)event {
1166 cloud_print::VirtualDriverInstallHelper::SetUpInstall();
1167}
1168
1169// Calls the helper class to uninstall the virtual driver to the
1170// service process.
1171- (void)uninstallCloudPrint:(NSAppleEventDescriptor*)event {
1172 cloud_print::VirtualDriverInstallHelper::SetUpUninstall();
1173}
1174
[email protected]caadfca2010-01-22 21:51:211175- (void)application:(NSApplication*)sender
1176 openFiles:(NSArray*)filenames {
[email protected]57750f822009-04-21 21:43:091177 std::vector<GURL> gurlVector;
[email protected]caadfca2010-01-22 21:51:211178 for (NSString* file in filenames) {
1179 GURL gurl = net::FilePathToFileURL(FilePath(base::SysNSStringToUTF8(file)));
[email protected]57750f822009-04-21 21:43:091180 gurlVector.push_back(gurl);
1181 }
[email protected]caadfca2010-01-22 21:51:211182 if (!gurlVector.empty())
[email protected]d630d7d52010-02-21 00:55:111183 [self openUrls:gurlVector];
[email protected]caadfca2010-01-22 21:51:211184 else
1185 NOTREACHED() << "Nothing to open!";
[email protected]57750f822009-04-21 21:43:091186
[email protected]caadfca2010-01-22 21:51:211187 [sender replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
[email protected]57750f822009-04-21 21:43:091188}
[email protected]3f34599d2009-03-25 22:11:431189
[email protected]3111f08b2009-04-30 16:01:521190// Show the preferences window, or bring it to the front if it's already
1191// visible.
1192- (IBAction)showPreferences:(id)sender {
[email protected]a585a8db2011-06-20 18:58:351193 if (Browser* browser = ActivateBrowser([self lastProfile])) {
[email protected]445177652011-03-09 02:04:051194 // Show options tab in the active browser window.
1195 browser->OpenOptionsDialog();
[email protected]4a42d272010-06-18 01:29:421196 } else {
[email protected]445177652011-03-09 02:04:051197 // No browser window, so create one for the options tab.
[email protected]a585a8db2011-06-20 18:58:351198 Browser::OpenOptionsWindow([self lastProfile]);
[email protected]4a42d272010-06-18 01:29:421199 }
[email protected]d989f07c2009-11-14 00:35:461200}
1201
[email protected]bde3dda2009-05-20 22:13:071202// Called when the about window is closed. We use this to release the
1203// window controller.
[email protected]d4e18652009-11-19 21:52:161204- (void)aboutWindowClosed:(NSNotification*)notification {
1205 NSWindow* window = [aboutController_ window];
[email protected]2ce9c89752011-02-25 18:24:341206 DCHECK_EQ([notification object], window);
[email protected]bde3dda2009-05-20 22:13:071207 [[NSNotificationCenter defaultCenter]
[email protected]49aeee52009-10-26 19:58:131208 removeObserver:self
[email protected]d4e18652009-11-19 21:52:161209 name:NSWindowWillCloseNotification
1210 object:window];
1211 // AboutWindowControllers are autoreleased in
1212 // -[AboutWindowController windowWillClose:].
1213 aboutController_ = nil;
[email protected]bde3dda2009-05-20 22:13:071214}
1215
1216- (IBAction)orderFrontStandardAboutPanel:(id)sender {
[email protected]a9fbb0962012-03-21 23:25:131217 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableUberPage)) {
1218 if (!aboutController_) {
1219 aboutController_ =
1220 [[AboutWindowController alloc] initWithProfile:[self lastProfile]];
[email protected]49aeee52009-10-26 19:58:131221
[email protected]a9fbb0962012-03-21 23:25:131222 // Watch for a notification of when it goes away so that we can destroy
1223 // the controller.
1224 [[NSNotificationCenter defaultCenter]
1225 addObserver:self
1226 selector:@selector(aboutWindowClosed:)
1227 name:NSWindowWillCloseNotification
1228 object:[aboutController_ window]];
1229 }
1230
1231 [aboutController_ showWindow:self];
1232 } else {
1233 if (Browser* browser = ActivateBrowser([self lastProfile])) {
1234 // Show about tab in the active browser window.
1235 browser->OpenAboutChromeDialog();
1236 } else {
1237 // No browser window, so create one for the about tab.
1238 Browser::OpenAboutWindow([self lastProfile]);
1239 }
[email protected]bde3dda2009-05-20 22:13:071240 }
[email protected]bde3dda2009-05-20 22:13:071241}
1242
[email protected]a99fce0e2011-03-21 20:58:481243- (IBAction)toggleConfirmToQuit:(id)sender {
[email protected]b6366ffa2012-02-29 17:12:261244 PrefService* prefService = g_browser_process->local_state();
[email protected]a99fce0e2011-03-21 20:58:481245 bool enabled = prefService->GetBoolean(prefs::kConfirmToQuitEnabled);
1246 prefService->SetBoolean(prefs::kConfirmToQuitEnabled, !enabled);
1247}
1248
[email protected]3d4bd23f2009-10-06 03:58:381249// Explicitly bring to the foreground when creating new windows from the dock.
[email protected]93b59fc2010-12-21 20:00:471250- (void)commandFromDock:(id)sender {
[email protected]3d4bd23f2009-10-06 03:58:381251 [NSApp activateIgnoringOtherApps:YES];
1252 [self commandDispatch:sender];
1253}
1254
[email protected]227fcee2010-06-11 19:19:371255- (NSMenu*)applicationDockMenu:(NSApplication*)sender {
[email protected]018a3962009-09-17 22:23:441256 NSMenu* dockMenu = [[[NSMenu alloc] initWithTitle: @""] autorelease];
[email protected]a585a8db2011-06-20 18:58:351257 Profile* profile = [self lastProfile];
[email protected]93b59fc2010-12-21 20:00:471258
[email protected]018a3962009-09-17 22:23:441259 NSString* titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_WINDOW_MAC);
[email protected]8c6b029d2011-01-21 22:39:511260 scoped_nsobject<NSMenuItem> item(
1261 [[NSMenuItem alloc] initWithTitle:titleStr
1262 action:@selector(commandFromDock:)
1263 keyEquivalent:@""]);
[email protected]288bfcd32009-09-14 18:14:461264 [item setTarget:self];
1265 [item setTag:IDC_NEW_WINDOW];
[email protected]018a3962009-09-17 22:23:441266 [dockMenu addItem:item];
[email protected]288bfcd32009-09-14 18:14:461267
1268 titleStr = l10n_util::GetNSStringWithFixup(IDS_NEW_INCOGNITO_WINDOW_MAC);
[email protected]018a3962009-09-17 22:23:441269 item.reset([[NSMenuItem alloc] initWithTitle:titleStr
[email protected]8c6b029d2011-01-21 22:39:511270 action:@selector(commandFromDock:)
[email protected]018a3962009-09-17 22:23:441271 keyEquivalent:@""]);
[email protected]288bfcd32009-09-14 18:14:461272 [item setTarget:self];
1273 [item setTag:IDC_NEW_INCOGNITO_WINDOW];
[email protected]018a3962009-09-17 22:23:441274 [dockMenu addItem:item];
[email protected]288bfcd32009-09-14 18:14:461275
[email protected]8c6b029d2011-01-21 22:39:511276 // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit
1277 // tests which use the mock in place of the profile-initialized model.
1278
1279 // Avoid breaking unit tests which have no profile.
1280 if (profile) {
1281 BackgroundApplicationListModel applications(profile);
1282 if (applications.size()) {
1283 int position = 0;
1284 NSString* menuStr =
1285 l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC);
1286 scoped_nsobject<NSMenu> appMenu([[NSMenu alloc] initWithTitle:menuStr]);
1287 for (ExtensionList::const_iterator cursor = applications.begin();
1288 cursor != applications.end();
1289 ++cursor, ++position) {
[email protected]2ce9c89752011-02-25 18:24:341290 DCHECK_EQ(applications.GetPosition(*cursor), position);
[email protected]8c6b029d2011-01-21 22:39:511291 NSString* itemStr =
1292 base::SysUTF16ToNSString(UTF8ToUTF16((*cursor)->name()));
1293 scoped_nsobject<NSMenuItem> appItem([[NSMenuItem alloc]
1294 initWithTitle:itemStr
1295 action:@selector(commandFromDock:)
1296 keyEquivalent:@""]);
1297 [appItem setTarget:self];
1298 [appItem setTag:position];
1299 [appMenu addItem:appItem];
1300 }
1301 scoped_nsobject<NSMenuItem> appMenuItem([[NSMenuItem alloc]
1302 initWithTitle:menuStr
1303 action:@selector(commandFromDock:)
1304 keyEquivalent:@""]);
1305 [appMenuItem setTarget:self];
1306 [appMenuItem setTag:position];
1307 [appMenuItem setSubmenu:appMenu];
1308 [dockMenu addItem:appMenuItem];
1309 }
1310 }
1311
[email protected]018a3962009-09-17 22:23:441312 return dockMenu;
[email protected]288bfcd32009-09-14 18:14:461313}
1314
[email protected]d630d7d52010-02-21 00:55:111315- (const std::vector<GURL>&)startupUrls {
1316 return startupUrls_;
[email protected]caadfca2010-01-22 21:51:211317}
1318
[email protected]d630d7d52010-02-21 00:55:111319- (void)clearStartupUrls {
1320 startupUrls_.clear();
[email protected]caadfca2010-01-22 21:51:211321}
1322
[email protected]7e4c69d02011-05-11 22:16:471323- (BookmarkMenuBridge*)bookmarkMenuBridge {
1324 return bookmarkMenuBridge_.get();
1325}
1326
[email protected]ebbe94b2012-01-18 20:11:561327- (void)applicationDidChangeScreenParameters:(NSNotification*)notification {
[email protected]6a455072011-11-02 01:32:281328 // During this callback the working area is not always already updated. Defer.
1329 [self performSelector:@selector(delayedPanelManagerScreenParametersUpdate)
1330 withObject:nil
1331 afterDelay:0];
1332}
1333
1334- (void)delayedPanelManagerScreenParametersUpdate {
1335 PanelManager::GetInstance()->OnDisplayChanged();
1336}
1337
[email protected]d630d7d52010-02-21 00:55:111338@end // @implementation AppController
[email protected]60ad3e22009-09-18 21:07:191339
1340//---------------------------------------------------------------------------
1341
[email protected]0934de82011-03-09 18:42:161342namespace browser {
1343
1344void ShowInstantConfirmDialog(gfx::NativeWindow parent, Profile* profile) {
1345 if (Browser* browser = ActivateBrowser(profile)) {
[email protected]b99081b2011-03-10 17:43:471346 browser->OpenInstantConfirmDialog();
[email protected]0934de82011-03-09 18:42:161347 } else {
[email protected]b99081b2011-03-10 17:43:471348 Browser::OpenInstantConfirmDialogWindow(profile);
[email protected]0934de82011-03-09 18:42:161349 }
1350}
1351
1352} // namespace browser
1353
[email protected]216e9042009-10-29 17:05:231354namespace app_controller_mac {
1355
1356bool IsOpeningNewWindow() {
1357 return g_is_opening_new_window;
1358}
1359
1360} // namespace app_controller_mac