replace OVERRIDE and FINAL with override and final in ash/
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main_win.cc
blob97346ce3dd06e930be6e450f7595a9e63990b481
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/metrics/histogram.h"
18 #include "base/path_service.h"
19 #include "base/scoped_native_library.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/win/metro.h"
23 #include "base/win/win_util.h"
24 #include "base/win/windows_version.h"
25 #include "base/win/wrapped_window_proc.h"
26 #include "chrome/browser/browser_util_win.h"
27 #include "chrome/browser/chrome_elf_init_win.h"
28 #include "chrome/browser/first_run/first_run.h"
29 #include "chrome/browser/install_verification/win/install_verification.h"
30 #include "chrome/browser/prefs/incognito_mode_prefs.h"
31 #include "chrome/browser/profiles/profile_info_cache.h"
32 #include "chrome/browser/profiles/profile_shortcut_manager.h"
33 #include "chrome/browser/shell_integration.h"
34 #include "chrome/browser/ui/simple_message_box.h"
35 #include "chrome/browser/ui/uninstall_browser_prompt.h"
36 #include "chrome/common/chrome_constants.h"
37 #include "chrome/common/chrome_result_codes.h"
38 #include "chrome/common/chrome_switches.h"
39 #include "chrome/common/chrome_version_info.h"
40 #include "chrome/common/env_vars.h"
41 #include "chrome/common/terminate_on_heap_corruption_experiment_win.h"
42 #include "chrome/grit/chromium_strings.h"
43 #include "chrome/grit/generated_resources.h"
44 #include "chrome/installer/util/browser_distribution.h"
45 #include "chrome/installer/util/helper.h"
46 #include "chrome/installer/util/install_util.h"
47 #include "chrome/installer/util/l10n_string_util.h"
48 #include "chrome/installer/util/shell_util.h"
49 #include "content/public/browser/browser_thread.h"
50 #include "content/public/common/main_function_params.h"
51 #include "installer_util_strings/installer_util_strings.h"
52 #include "ui/base/cursor/cursor_loader_win.h"
53 #include "ui/base/l10n/l10n_util.h"
54 #include "ui/base/l10n/l10n_util_win.h"
55 #include "ui/base/ui_base_switches.h"
56 #include "ui/base/win/message_box_win.h"
57 #include "ui/gfx/platform_font_win.h"
58 #include "ui/gfx/switches.h"
59 #include "ui/strings/grit/app_locale_settings.h"
61 namespace {
63 typedef HRESULT (STDAPICALLTYPE* RegisterApplicationRestartProc)(
64 const wchar_t* command_line,
65 DWORD flags);
67 void InitializeWindowProcExceptions() {
68 // Get the breakpad pointer from chrome.exe
69 base::win::WinProcExceptionFilter exception_filter =
70 reinterpret_cast<base::win::WinProcExceptionFilter>(
71 ::GetProcAddress(::GetModuleHandle(
72 chrome::kBrowserProcessExecutableName),
73 "CrashForException"));
74 exception_filter = base::win::SetWinProcExceptionFilter(exception_filter);
75 DCHECK(!exception_filter);
78 // gfx::Font callbacks
79 void AdjustUIFont(LOGFONT* logfont) {
80 l10n_util::AdjustUIFont(logfont);
83 int GetMinimumFontSize() {
84 int min_font_size;
85 base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE),
86 &min_font_size);
87 return min_font_size;
90 class TranslationDelegate : public installer::TranslationDelegate {
91 public:
92 virtual base::string16 GetLocalizedString(int installer_string_id) OVERRIDE;
95 bool IsSafeModeStart() {
96 return ::GetEnvironmentVariableA(chrome::kSafeModeEnvVar, NULL, 0) != 0;
99 } // namespace
101 void ShowCloseBrowserFirstMessageBox() {
102 int message_id = IDS_UNINSTALL_CLOSE_APP;
103 if (base::win::GetVersion() >= base::win::VERSION_WIN8 &&
104 (ShellIntegration::GetDefaultBrowser() == ShellIntegration::IS_DEFAULT)) {
105 message_id = IDS_UNINSTALL_CLOSE_APP_IMMERSIVE;
107 chrome::ShowMessageBox(NULL,
108 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
109 l10n_util::GetStringUTF16(message_id),
110 chrome::MESSAGE_BOX_TYPE_WARNING);
113 int DoUninstallTasks(bool chrome_still_running) {
114 // We want to show a warning to user (and exit) if Chrome is already running
115 // *before* we show the uninstall confirmation dialog box. But while the
116 // uninstall confirmation dialog is up, user might start Chrome, so we
117 // check once again after user acknowledges Uninstall dialog.
118 if (chrome_still_running) {
119 ShowCloseBrowserFirstMessageBox();
120 return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE;
122 int result = chrome::ShowUninstallBrowserPrompt();
123 if (browser_util::IsBrowserAlreadyRunning()) {
124 ShowCloseBrowserFirstMessageBox();
125 return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE;
128 if (result != chrome::RESULT_CODE_UNINSTALL_USER_CANCEL) {
129 // The following actions are just best effort.
130 // TODO(gab): Look into removing this code which is now redundant with the
131 // work done by setup.exe on uninstall.
132 VLOG(1) << "Executing uninstall actions";
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 // ChromeBrowserMainPartsWin ---------------------------------------------------
158 ChromeBrowserMainPartsWin::ChromeBrowserMainPartsWin(
159 const content::MainFunctionParams& parameters)
160 : ChromeBrowserMainParts(parameters) {
161 if (base::win::IsMetroProcess()) {
162 typedef const wchar_t* (*GetMetroSwitches)(void);
163 GetMetroSwitches metro_switches_proc = reinterpret_cast<GetMetroSwitches>(
164 GetProcAddress(base::win::GetMetroModule(),
165 "GetMetroCommandLineSwitches"));
166 if (metro_switches_proc) {
167 base::string16 metro_switches = (*metro_switches_proc)();
168 if (!metro_switches.empty()) {
169 CommandLine extra_switches(CommandLine::NO_PROGRAM);
170 extra_switches.ParseFromString(metro_switches);
171 CommandLine::ForCurrentProcess()->AppendArguments(extra_switches,
172 false);
178 ChromeBrowserMainPartsWin::~ChromeBrowserMainPartsWin() {
181 void ChromeBrowserMainPartsWin::ToolkitInitialized() {
182 ChromeBrowserMainParts::ToolkitInitialized();
183 gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;
184 gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;
185 #if defined(USE_AURA)
186 ui::CursorLoaderWin::SetCursorResourceModule(chrome::kBrowserResourcesDll);
187 #endif
190 void ChromeBrowserMainPartsWin::PreMainMessageLoopStart() {
191 // installer_util references strings that are normally compiled into
192 // setup.exe. In Chrome, these strings are in the locale files.
193 SetupInstallerUtilStrings();
195 ChromeBrowserMainParts::PreMainMessageLoopStart();
196 if (!parameters().ui_task) {
197 // Make sure that we know how to handle exceptions from the message loop.
198 InitializeWindowProcExceptions();
201 IncognitoModePrefs::InitializePlatformParentalControls();
204 int ChromeBrowserMainPartsWin::PreCreateThreads() {
205 int rv = ChromeBrowserMainParts::PreCreateThreads();
207 if (IsSafeModeStart()) {
208 // TODO(cpu): disable other troublesome features for safe mode.
209 CommandLine::ForCurrentProcess()->AppendSwitch(
210 switches::kDisableGpu);
212 // TODO(viettrungluu): why don't we run this earlier?
213 if (!parsed_command_line().HasSwitch(switches::kNoErrorDialogs) &&
214 base::win::GetVersion() < base::win::VERSION_XP) {
215 chrome::ShowMessageBox(NULL,
216 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
217 l10n_util::GetStringUTF16(IDS_UNSUPPORTED_OS_PRE_WIN_XP),
218 chrome::MESSAGE_BOX_TYPE_WARNING);
221 return rv;
224 void ChromeBrowserMainPartsWin::ShowMissingLocaleMessageBox() {
225 ui::MessageBox(NULL,
226 base::ASCIIToUTF16(chrome_browser::kMissingLocaleDataMessage),
227 base::ASCIIToUTF16(chrome_browser::kMissingLocaleDataTitle),
228 MB_OK | MB_ICONERROR | MB_TOPMOST);
231 void ChromeBrowserMainPartsWin::PostBrowserStart() {
232 ChromeBrowserMainParts::PostBrowserStart();
234 UMA_HISTOGRAM_BOOLEAN("Windows.Tablet", base::win::IsTabletDevice());
236 // Set up a task to verify installed modules in the current process. Use a
237 // delay to reduce the impact on startup time.
238 content::BrowserThread::GetMessageLoopProxyForThread(
239 content::BrowserThread::UI)->PostDelayedTask(
240 FROM_HERE,
241 base::Bind(&VerifyInstallation),
242 base::TimeDelta::FromSeconds(45));
244 InitializeChromeElf();
246 // TODO(erikwright): Remove this and the implementation of the experiment by
247 // September 2014.
248 InitializeDisableTerminateOnHeapCorruptionExperiment();
251 // static
252 void ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
253 const CommandLine& parsed_command_line) {
254 // Clear this var so child processes don't show the dialog by default.
255 scoped_ptr<base::Environment> env(base::Environment::Create());
256 env->UnSetVar(env_vars::kShowRestart);
258 // For non-interactive tests we don't restart on crash.
259 if (env->HasVar(env_vars::kHeadless))
260 return;
262 // If the known command-line test options are used we don't create the
263 // environment block which means we don't get the restart dialog.
264 if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) ||
265 parsed_command_line.HasSwitch(switches::kBrowserAssertTest) ||
266 parsed_command_line.HasSwitch(switches::kNoErrorDialogs))
267 return;
269 // The encoding we use for the info is "title|context|direction" where
270 // direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
271 // on the current locale.
272 base::string16 dlg_strings(l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE));
273 dlg_strings.push_back('|');
274 base::string16 adjusted_string(
275 l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT));
276 base::i18n::AdjustStringForLocaleDirection(&adjusted_string);
277 dlg_strings.append(adjusted_string);
278 dlg_strings.push_back('|');
279 dlg_strings.append(base::ASCIIToUTF16(
280 base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale));
282 env->SetVar(env_vars::kRestartInfo, base::UTF16ToUTF8(dlg_strings));
285 // static
286 void ChromeBrowserMainPartsWin::RegisterApplicationRestart(
287 const CommandLine& parsed_command_line) {
288 DCHECK(base::win::GetVersion() >= base::win::VERSION_VISTA);
289 base::ScopedNativeLibrary library(base::FilePath(L"kernel32.dll"));
290 // Get the function pointer for RegisterApplicationRestart.
291 RegisterApplicationRestartProc register_application_restart =
292 reinterpret_cast<RegisterApplicationRestartProc>(
293 library.GetFunctionPointer("RegisterApplicationRestart"));
294 if (!register_application_restart) {
295 LOG(WARNING) << "Cannot find RegisterApplicationRestart in kernel32.dll";
296 return;
298 // The Windows Restart Manager expects a string of command line flags only,
299 // without the program.
300 CommandLine command_line(CommandLine::NO_PROGRAM);
301 command_line.AppendArguments(parsed_command_line, false);
302 if (!command_line.HasSwitch(switches::kRestoreLastSession))
303 command_line.AppendSwitch(switches::kRestoreLastSession);
305 // Restart Chrome if the computer is restarted as the result of an update.
306 // This could be extended to handle crashes, hangs, and patches.
307 HRESULT hr = register_application_restart(
308 command_line.GetCommandLineString().c_str(),
309 RESTART_NO_CRASH | RESTART_NO_HANG | RESTART_NO_PATCH);
310 if (FAILED(hr)) {
311 if (hr == E_INVALIDARG) {
312 LOG(WARNING) << "Command line too long for RegisterApplicationRestart";
313 } else {
314 NOTREACHED() << "RegisterApplicationRestart failed. hr: " << hr <<
315 ", command_line: " << command_line.GetCommandLineString();
320 // static
321 int ChromeBrowserMainPartsWin::HandleIconsCommands(
322 const CommandLine& parsed_command_line) {
323 if (parsed_command_line.HasSwitch(switches::kHideIcons)) {
324 base::string16 cp_applet;
325 base::win::Version version = base::win::GetVersion();
326 if (version >= base::win::VERSION_VISTA) {
327 cp_applet.assign(L"Programs and Features"); // Windows Vista and later.
328 } else if (version >= base::win::VERSION_XP) {
329 cp_applet.assign(L"Add/Remove Programs"); // Windows XP.
330 } else {
331 return chrome::RESULT_CODE_UNSUPPORTED_PARAM; // Not supported
334 const base::string16 msg =
335 l10n_util::GetStringFUTF16(IDS_HIDE_ICONS_NOT_SUPPORTED, cp_applet);
336 const base::string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
337 const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST;
338 if (IDOK == ui::MessageBox(NULL, msg, caption, flags))
339 ShellExecute(NULL, NULL, L"appwiz.cpl", NULL, NULL, SW_SHOWNORMAL);
341 // Exit as we are not launching the browser.
342 return content::RESULT_CODE_NORMAL_EXIT;
344 // We don't hide icons so we shouldn't do anything special to show them
345 return chrome::RESULT_CODE_UNSUPPORTED_PARAM;
348 // static
349 bool ChromeBrowserMainPartsWin::CheckMachineLevelInstall() {
350 // TODO(tommi): Check if using the default distribution is always the right
351 // thing to do.
352 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
353 Version version;
354 InstallUtil::GetChromeVersion(dist, true, &version);
355 if (version.IsValid()) {
356 base::FilePath exe_path;
357 PathService::Get(base::DIR_EXE, &exe_path);
358 std::wstring exe = exe_path.value();
359 base::FilePath user_exe_path(installer::GetChromeInstallPath(false, dist));
360 if (base::FilePath::CompareEqualIgnoreCase(exe, user_exe_path.value())) {
361 bool is_metro = base::win::IsMetroProcess();
362 if (!is_metro) {
363 // The dialog cannot be shown in Win8 Metro as doing so hangs Chrome on
364 // an invisible dialog.
365 // TODO (gab): Get rid of this dialog altogether and auto-launch
366 // system-level Chrome instead.
367 const base::string16 text =
368 l10n_util::GetStringUTF16(IDS_MACHINE_LEVEL_INSTALL_CONFLICT);
369 const base::string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
370 const UINT flags = MB_OK | MB_ICONERROR | MB_TOPMOST;
371 ui::MessageBox(NULL, text, caption, flags);
373 CommandLine uninstall_cmd(
374 InstallUtil::GetChromeUninstallCmd(false, dist->GetType()));
375 if (!uninstall_cmd.GetProgram().empty()) {
376 uninstall_cmd.AppendSwitch(installer::switches::kSelfDestruct);
377 uninstall_cmd.AppendSwitch(installer::switches::kForceUninstall);
378 uninstall_cmd.AppendSwitch(
379 installer::switches::kDoNotRemoveSharedItems);
381 // Trigger Active Setup for the system-level Chrome to make sure
382 // per-user shortcuts to the system-level Chrome are created. Skip this
383 // if the system-level Chrome will undergo first run anyway, as Active
384 // Setup is triggered on system-level Chrome's first run.
385 // TODO(gab): Instead of having callers of Active Setup think about
386 // other callers, have Active Setup itself register when it ran and
387 // no-op otherwise (http://crbug.com/346843).
388 if (!first_run::IsChromeFirstRun())
389 uninstall_cmd.AppendSwitch(installer::switches::kTriggerActiveSetup);
391 const base::FilePath setup_exe(uninstall_cmd.GetProgram());
392 const base::string16 params(uninstall_cmd.GetArgumentsString());
394 SHELLEXECUTEINFO sei = { sizeof(sei) };
395 sei.fMask = SEE_MASK_NOASYNC;
396 sei.nShow = SW_SHOWNORMAL;
397 sei.lpFile = setup_exe.value().c_str();
398 sei.lpParameters = params.c_str();
399 // On Windows 8 SEE_MASK_FLAG_LOG_USAGE is necessary to guarantee we
400 // flip to the Desktop when launching.
401 if (is_metro)
402 sei.fMask |= SEE_MASK_FLAG_LOG_USAGE;
404 if (!::ShellExecuteEx(&sei))
405 DPCHECK(false);
407 return true;
410 return false;
413 base::string16 TranslationDelegate::GetLocalizedString(
414 int installer_string_id) {
415 int resource_id = 0;
416 switch (installer_string_id) {
417 // HANDLE_STRING is used by the DO_INSTALLER_STRING_MAPPING macro which is in
418 // the generated header installer_util_strings.h.
419 #define HANDLE_STRING(base_id, chrome_id) \
420 case base_id: \
421 resource_id = chrome_id; \
422 break;
423 DO_INSTALLER_STRING_MAPPING
424 #undef HANDLE_STRING
425 default:
426 NOTREACHED();
428 if (resource_id)
429 return l10n_util::GetStringUTF16(resource_id);
430 return base::string16();
433 // static
434 void ChromeBrowserMainPartsWin::SetupInstallerUtilStrings() {
435 CR_DEFINE_STATIC_LOCAL(TranslationDelegate, delegate, ());
436 installer::SetTranslationDelegate(&delegate);