Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main_win.cc
blob53745465ff7b49abf8042feb0c39bacb10f6a98d
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/chrome_browser_main_win.h"
7 #include <windows.h>
8 #include <shellapi.h>
10 #include <algorithm>
12 #include "base/command_line.h"
13 #include "base/environment.h"
14 #include "base/files/file_path.h"
15 #include "base/i18n/rtl.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/path_service.h"
18 #include "base/scoped_native_library.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/win/metro.h"
22 #include "base/win/windows_version.h"
23 #include "base/win/wrapped_window_proc.h"
24 #include "chrome/browser/browser_util_win.h"
25 #include "chrome/browser/chrome_elf_init_win.h"
26 #include "chrome/browser/install_verification/win/install_verification.h"
27 #include "chrome/browser/profiles/profile_info_cache.h"
28 #include "chrome/browser/profiles/profile_shortcut_manager.h"
29 #include "chrome/browser/shell_integration.h"
30 #include "chrome/browser/ui/simple_message_box.h"
31 #include "chrome/browser/ui/uninstall_browser_prompt.h"
32 #include "chrome/common/chrome_constants.h"
33 #include "chrome/common/chrome_result_codes.h"
34 #include "chrome/common/chrome_switches.h"
35 #include "chrome/common/chrome_version_info.h"
36 #include "chrome/common/env_vars.h"
37 #include "chrome/installer/launcher_support/chrome_launcher_support.h"
38 #include "chrome/installer/util/browser_distribution.h"
39 #include "chrome/installer/util/helper.h"
40 #include "chrome/installer/util/install_util.h"
41 #include "chrome/installer/util/l10n_string_util.h"
42 #include "chrome/installer/util/shell_util.h"
43 #include "content/public/browser/browser_thread.h"
44 #include "content/public/common/main_function_params.h"
45 #include "grit/app_locale_settings.h"
46 #include "grit/chromium_strings.h"
47 #include "grit/generated_resources.h"
48 #include "installer_util_strings/installer_util_strings.h"
49 #include "ui/base/cursor/cursor_loader_win.h"
50 #include "ui/base/l10n/l10n_util.h"
51 #include "ui/base/l10n/l10n_util_win.h"
52 #include "ui/base/ui_base_switches.h"
53 #include "ui/base/win/message_box_win.h"
54 #include "ui/gfx/platform_font_win.h"
55 #include "ui/gfx/switches.h"
57 namespace {
59 typedef HRESULT (STDAPICALLTYPE* RegisterApplicationRestartProc)(
60 const wchar_t* command_line,
61 DWORD flags);
63 void InitializeWindowProcExceptions() {
64 // Get the breakpad pointer from chrome.exe
65 base::win::WinProcExceptionFilter exception_filter =
66 reinterpret_cast<base::win::WinProcExceptionFilter>(
67 ::GetProcAddress(::GetModuleHandle(
68 chrome::kBrowserProcessExecutableName),
69 "CrashForException"));
70 exception_filter = base::win::SetWinProcExceptionFilter(exception_filter);
71 DCHECK(!exception_filter);
74 // gfx::Font callbacks
75 void AdjustUIFont(LOGFONT* logfont) {
76 l10n_util::AdjustUIFont(logfont);
79 int GetMinimumFontSize() {
80 int min_font_size;
81 base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE),
82 &min_font_size);
83 return min_font_size;
86 class TranslationDelegate : public installer::TranslationDelegate {
87 public:
88 virtual base::string16 GetLocalizedString(int installer_string_id) OVERRIDE;
91 bool IsSafeModeStart() {
92 return ::GetEnvironmentVariableA(chrome::kSafeModeEnvVar, NULL, 0) != 0;
95 } // namespace
97 void ShowCloseBrowserFirstMessageBox() {
98 int message_id = IDS_UNINSTALL_CLOSE_APP;
99 if (base::win::GetVersion() >= base::win::VERSION_WIN8 &&
100 (ShellIntegration::GetDefaultBrowser() == ShellIntegration::IS_DEFAULT)) {
101 message_id = IDS_UNINSTALL_CLOSE_APP_IMMERSIVE;
103 chrome::ShowMessageBox(NULL,
104 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
105 l10n_util::GetStringUTF16(message_id),
106 chrome::MESSAGE_BOX_TYPE_WARNING);
109 int DoUninstallTasks(bool chrome_still_running) {
110 // We want to show a warning to user (and exit) if Chrome is already running
111 // *before* we show the uninstall confirmation dialog box. But while the
112 // uninstall confirmation dialog is up, user might start Chrome, so we
113 // check once again after user acknowledges Uninstall dialog.
114 if (chrome_still_running) {
115 ShowCloseBrowserFirstMessageBox();
116 return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE;
118 int result = chrome::ShowUninstallBrowserPrompt(
119 !chrome_launcher_support::IsAppLauncherPresent());
120 // Don't offer to delete the profile if the App Launcher is also installed.
121 if (browser_util::IsBrowserAlreadyRunning()) {
122 ShowCloseBrowserFirstMessageBox();
123 return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE;
126 if (result != chrome::RESULT_CODE_UNINSTALL_USER_CANCEL) {
127 // The following actions are just best effort.
128 // TODO(gab): Look into removing this code which is now redundant with the
129 // work done by setup.exe on uninstall.
130 VLOG(1) << "Executing uninstall actions";
131 if (!first_run::RemoveSentinel())
132 VLOG(1) << "Failed to delete sentinel file.";
133 base::FilePath chrome_exe;
134 if (PathService::Get(base::FILE_EXE, &chrome_exe)) {
135 ShellUtil::ShortcutLocation user_shortcut_locations[] = {
136 ShellUtil::SHORTCUT_LOCATION_DESKTOP,
137 ShellUtil::SHORTCUT_LOCATION_QUICK_LAUNCH,
138 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_DIR,
139 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR,
141 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
142 for (size_t i = 0; i < arraysize(user_shortcut_locations); ++i) {
143 if (!ShellUtil::RemoveShortcuts(user_shortcut_locations[i], dist,
144 ShellUtil::CURRENT_USER, chrome_exe)) {
145 VLOG(1) << "Failed to delete shortcut at location "
146 << user_shortcut_locations[i];
149 } else {
150 NOTREACHED();
153 return result;
156 void MaybeEnableHighResolutionTimeEverywhere() {
157 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
158 bool user_enabled = CommandLine::ForCurrentProcess()->HasSwitch(
159 switches::kEnableHighResolutionTime);
160 if (user_enabled || channel == chrome::VersionInfo::CHANNEL_CANARY) {
161 bool is_enabled = base::TimeTicks::SetNowIsHighResNowIfSupported();
162 if (is_enabled && !user_enabled) {
163 // Ensure that all of the renderers will enable it too.
164 CommandLine::ForCurrentProcess()->AppendSwitch(
165 switches::kEnableHighResolutionTime);
170 // ChromeBrowserMainPartsWin ---------------------------------------------------
172 ChromeBrowserMainPartsWin::ChromeBrowserMainPartsWin(
173 const content::MainFunctionParams& parameters)
174 : ChromeBrowserMainParts(parameters) {
175 MaybeEnableHighResolutionTimeEverywhere();
176 if (base::win::IsMetroProcess()) {
177 typedef const wchar_t* (*GetMetroSwitches)(void);
178 GetMetroSwitches metro_switches_proc = reinterpret_cast<GetMetroSwitches>(
179 GetProcAddress(base::win::GetMetroModule(),
180 "GetMetroCommandLineSwitches"));
181 if (metro_switches_proc) {
182 base::string16 metro_switches = (*metro_switches_proc)();
183 if (!metro_switches.empty()) {
184 CommandLine extra_switches(CommandLine::NO_PROGRAM);
185 extra_switches.ParseFromString(metro_switches);
186 CommandLine::ForCurrentProcess()->AppendArguments(extra_switches,
187 false);
193 ChromeBrowserMainPartsWin::~ChromeBrowserMainPartsWin() {
196 void ChromeBrowserMainPartsWin::ToolkitInitialized() {
197 ChromeBrowserMainParts::ToolkitInitialized();
198 gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;
199 gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;
200 #if defined(USE_AURA)
201 ui::CursorLoaderWin::SetCursorResourceModule(chrome::kBrowserResourcesDll);
202 #endif
205 void ChromeBrowserMainPartsWin::PreMainMessageLoopStart() {
206 // installer_util references strings that are normally compiled into
207 // setup.exe. In Chrome, these strings are in the locale files.
208 SetupInstallerUtilStrings();
210 ChromeBrowserMainParts::PreMainMessageLoopStart();
211 if (!parameters().ui_task) {
212 // Make sure that we know how to handle exceptions from the message loop.
213 InitializeWindowProcExceptions();
217 int ChromeBrowserMainPartsWin::PreCreateThreads() {
218 int rv = ChromeBrowserMainParts::PreCreateThreads();
220 if (IsSafeModeStart()) {
221 // TODO(cpu): disable other troublesome features for safe mode.
222 CommandLine::ForCurrentProcess()->AppendSwitch(
223 switches::kDisableGpu);
224 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
225 switches::kHighDPISupport, "0");
227 // TODO(viettrungluu): why don't we run this earlier?
228 if (!parsed_command_line().HasSwitch(switches::kNoErrorDialogs) &&
229 base::win::GetVersion() < base::win::VERSION_XP) {
230 chrome::ShowMessageBox(NULL,
231 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
232 l10n_util::GetStringUTF16(IDS_UNSUPPORTED_OS_PRE_WIN_XP),
233 chrome::MESSAGE_BOX_TYPE_WARNING);
236 return rv;
239 void ChromeBrowserMainPartsWin::ShowMissingLocaleMessageBox() {
240 ui::MessageBox(NULL,
241 base::ASCIIToUTF16(chrome_browser::kMissingLocaleDataMessage),
242 base::ASCIIToUTF16(chrome_browser::kMissingLocaleDataTitle),
243 MB_OK | MB_ICONERROR | MB_TOPMOST);
246 void ChromeBrowserMainPartsWin::PostBrowserStart() {
247 ChromeBrowserMainParts::PostBrowserStart();
249 // Set up a task to verify installed modules in the current process. Use a
250 // delay to reduce the impact on startup time.
251 content::BrowserThread::GetMessageLoopProxyForThread(
252 content::BrowserThread::UI)->PostDelayedTask(
253 FROM_HERE,
254 base::Bind(&VerifyInstallation),
255 base::TimeDelta::FromSeconds(45));
257 InitializeChromeElf();
260 // static
261 void ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
262 const CommandLine& parsed_command_line) {
263 // Clear this var so child processes don't show the dialog by default.
264 scoped_ptr<base::Environment> env(base::Environment::Create());
265 env->UnSetVar(env_vars::kShowRestart);
267 // For non-interactive tests we don't restart on crash.
268 if (env->HasVar(env_vars::kHeadless))
269 return;
271 // If the known command-line test options are used we don't create the
272 // environment block which means we don't get the restart dialog.
273 if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) ||
274 parsed_command_line.HasSwitch(switches::kBrowserAssertTest) ||
275 parsed_command_line.HasSwitch(switches::kNoErrorDialogs))
276 return;
278 // The encoding we use for the info is "title|context|direction" where
279 // direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
280 // on the current locale.
281 base::string16 dlg_strings(l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE));
282 dlg_strings.push_back('|');
283 base::string16 adjusted_string(
284 l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT));
285 base::i18n::AdjustStringForLocaleDirection(&adjusted_string);
286 dlg_strings.append(adjusted_string);
287 dlg_strings.push_back('|');
288 dlg_strings.append(base::ASCIIToUTF16(
289 base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale));
291 env->SetVar(env_vars::kRestartInfo, base::UTF16ToUTF8(dlg_strings));
294 // static
295 void ChromeBrowserMainPartsWin::RegisterApplicationRestart(
296 const CommandLine& parsed_command_line) {
297 DCHECK(base::win::GetVersion() >= base::win::VERSION_VISTA);
298 base::ScopedNativeLibrary library(base::FilePath(L"kernel32.dll"));
299 // Get the function pointer for RegisterApplicationRestart.
300 RegisterApplicationRestartProc register_application_restart =
301 reinterpret_cast<RegisterApplicationRestartProc>(
302 library.GetFunctionPointer("RegisterApplicationRestart"));
303 if (!register_application_restart) {
304 LOG(WARNING) << "Cannot find RegisterApplicationRestart in kernel32.dll";
305 return;
307 // The Windows Restart Manager expects a string of command line flags only,
308 // without the program.
309 CommandLine command_line(CommandLine::NO_PROGRAM);
310 command_line.AppendArguments(parsed_command_line, false);
311 if (!command_line.HasSwitch(switches::kRestoreLastSession))
312 command_line.AppendSwitch(switches::kRestoreLastSession);
314 // Restart Chrome if the computer is restarted as the result of an update.
315 // This could be extended to handle crashes, hangs, and patches.
316 HRESULT hr = register_application_restart(
317 command_line.GetCommandLineString().c_str(),
318 RESTART_NO_CRASH | RESTART_NO_HANG | RESTART_NO_PATCH);
319 if (FAILED(hr)) {
320 if (hr == E_INVALIDARG) {
321 LOG(WARNING) << "Command line too long for RegisterApplicationRestart";
322 } else {
323 NOTREACHED() << "RegisterApplicationRestart failed. hr: " << hr <<
324 ", command_line: " << command_line.GetCommandLineString();
329 // static
330 int ChromeBrowserMainPartsWin::HandleIconsCommands(
331 const CommandLine& parsed_command_line) {
332 if (parsed_command_line.HasSwitch(switches::kHideIcons)) {
333 base::string16 cp_applet;
334 base::win::Version version = base::win::GetVersion();
335 if (version >= base::win::VERSION_VISTA) {
336 cp_applet.assign(L"Programs and Features"); // Windows Vista and later.
337 } else if (version >= base::win::VERSION_XP) {
338 cp_applet.assign(L"Add/Remove Programs"); // Windows XP.
339 } else {
340 return chrome::RESULT_CODE_UNSUPPORTED_PARAM; // Not supported
343 const base::string16 msg =
344 l10n_util::GetStringFUTF16(IDS_HIDE_ICONS_NOT_SUPPORTED, cp_applet);
345 const base::string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
346 const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST;
347 if (IDOK == ui::MessageBox(NULL, msg, caption, flags))
348 ShellExecute(NULL, NULL, L"appwiz.cpl", NULL, NULL, SW_SHOWNORMAL);
350 // Exit as we are not launching the browser.
351 return content::RESULT_CODE_NORMAL_EXIT;
353 // We don't hide icons so we shouldn't do anything special to show them
354 return chrome::RESULT_CODE_UNSUPPORTED_PARAM;
357 // static
358 bool ChromeBrowserMainPartsWin::CheckMachineLevelInstall() {
359 // TODO(tommi): Check if using the default distribution is always the right
360 // thing to do.
361 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
362 Version version;
363 InstallUtil::GetChromeVersion(dist, true, &version);
364 if (version.IsValid()) {
365 base::FilePath exe_path;
366 PathService::Get(base::DIR_EXE, &exe_path);
367 std::wstring exe = exe_path.value();
368 base::FilePath user_exe_path(installer::GetChromeInstallPath(false, dist));
369 if (base::FilePath::CompareEqualIgnoreCase(exe, user_exe_path.value())) {
370 bool is_metro = base::win::IsMetroProcess();
371 if (!is_metro) {
372 // The dialog cannot be shown in Win8 Metro as doing so hangs Chrome on
373 // an invisible dialog.
374 // TODO (gab): Get rid of this dialog altogether and auto-launch
375 // system-level Chrome instead.
376 const base::string16 text =
377 l10n_util::GetStringUTF16(IDS_MACHINE_LEVEL_INSTALL_CONFLICT);
378 const base::string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
379 const UINT flags = MB_OK | MB_ICONERROR | MB_TOPMOST;
380 ui::MessageBox(NULL, text, caption, flags);
382 CommandLine uninstall_cmd(
383 InstallUtil::GetChromeUninstallCmd(false, dist->GetType()));
384 if (!uninstall_cmd.GetProgram().empty()) {
385 uninstall_cmd.AppendSwitch(installer::switches::kSelfDestruct);
386 uninstall_cmd.AppendSwitch(installer::switches::kForceUninstall);
387 uninstall_cmd.AppendSwitch(
388 installer::switches::kDoNotRemoveSharedItems);
390 const base::FilePath setup_exe(uninstall_cmd.GetProgram());
391 const base::string16 params(uninstall_cmd.GetArgumentsString());
393 SHELLEXECUTEINFO sei = { sizeof(sei) };
394 sei.fMask = SEE_MASK_NOASYNC;
395 sei.nShow = SW_SHOWNORMAL;
396 sei.lpFile = setup_exe.value().c_str();
397 sei.lpParameters = params.c_str();
398 // On Windows 8 SEE_MASK_FLAG_LOG_USAGE is necessary to guarantee we
399 // flip to the Desktop when launching.
400 if (is_metro)
401 sei.fMask |= SEE_MASK_FLAG_LOG_USAGE;
403 if (!::ShellExecuteEx(&sei))
404 DPCHECK(false);
406 return true;
409 return false;
412 base::string16 TranslationDelegate::GetLocalizedString(
413 int installer_string_id) {
414 int resource_id = 0;
415 switch (installer_string_id) {
416 // HANDLE_STRING is used by the DO_INSTALLER_STRING_MAPPING macro which is in
417 // the generated header installer_util_strings.h.
418 #define HANDLE_STRING(base_id, chrome_id) \
419 case base_id: \
420 resource_id = chrome_id; \
421 break;
422 DO_INSTALLER_STRING_MAPPING
423 #undef HANDLE_STRING
424 default:
425 NOTREACHED();
427 if (resource_id)
428 return l10n_util::GetStringUTF16(resource_id);
429 return base::string16();
432 // static
433 void ChromeBrowserMainPartsWin::SetupInstallerUtilStrings() {
434 CR_DEFINE_STATIC_LOCAL(TranslationDelegate, delegate, ());
435 installer::SetTranslationDelegate(&delegate);