Update mojo surfaces bindings and mojo/cc/ glue
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main_win.cc
blobfb517eecf08be7342a6a0a3aecd40c78c4043ab8
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 "grit/app_locale_settings.h"
52 #include "installer_util_strings/installer_util_strings.h"
53 #include "ui/base/cursor/cursor_loader_win.h"
54 #include "ui/base/l10n/l10n_util.h"
55 #include "ui/base/l10n/l10n_util_win.h"
56 #include "ui/base/ui_base_switches.h"
57 #include "ui/base/win/message_box_win.h"
58 #include "ui/gfx/platform_font_win.h"
59 #include "ui/gfx/switches.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 base::TimeTicks::SetNowIsHighResNowIfSupported();
162 if (base::win::IsMetroProcess()) {
163 typedef const wchar_t* (*GetMetroSwitches)(void);
164 GetMetroSwitches metro_switches_proc = reinterpret_cast<GetMetroSwitches>(
165 GetProcAddress(base::win::GetMetroModule(),
166 "GetMetroCommandLineSwitches"));
167 if (metro_switches_proc) {
168 base::string16 metro_switches = (*metro_switches_proc)();
169 if (!metro_switches.empty()) {
170 CommandLine extra_switches(CommandLine::NO_PROGRAM);
171 extra_switches.ParseFromString(metro_switches);
172 CommandLine::ForCurrentProcess()->AppendArguments(extra_switches,
173 false);
179 ChromeBrowserMainPartsWin::~ChromeBrowserMainPartsWin() {
182 void ChromeBrowserMainPartsWin::ToolkitInitialized() {
183 ChromeBrowserMainParts::ToolkitInitialized();
184 gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;
185 gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;
186 #if defined(USE_AURA)
187 ui::CursorLoaderWin::SetCursorResourceModule(chrome::kBrowserResourcesDll);
188 #endif
191 void ChromeBrowserMainPartsWin::PreMainMessageLoopStart() {
192 // installer_util references strings that are normally compiled into
193 // setup.exe. In Chrome, these strings are in the locale files.
194 SetupInstallerUtilStrings();
196 ChromeBrowserMainParts::PreMainMessageLoopStart();
197 if (!parameters().ui_task) {
198 // Make sure that we know how to handle exceptions from the message loop.
199 InitializeWindowProcExceptions();
202 IncognitoModePrefs::InitializePlatformParentalControls();
205 int ChromeBrowserMainPartsWin::PreCreateThreads() {
206 int rv = ChromeBrowserMainParts::PreCreateThreads();
208 if (IsSafeModeStart()) {
209 // TODO(cpu): disable other troublesome features for safe mode.
210 CommandLine::ForCurrentProcess()->AppendSwitch(
211 switches::kDisableGpu);
213 // TODO(viettrungluu): why don't we run this earlier?
214 if (!parsed_command_line().HasSwitch(switches::kNoErrorDialogs) &&
215 base::win::GetVersion() < base::win::VERSION_XP) {
216 chrome::ShowMessageBox(NULL,
217 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
218 l10n_util::GetStringUTF16(IDS_UNSUPPORTED_OS_PRE_WIN_XP),
219 chrome::MESSAGE_BOX_TYPE_WARNING);
222 return rv;
225 void ChromeBrowserMainPartsWin::ShowMissingLocaleMessageBox() {
226 ui::MessageBox(NULL,
227 base::ASCIIToUTF16(chrome_browser::kMissingLocaleDataMessage),
228 base::ASCIIToUTF16(chrome_browser::kMissingLocaleDataTitle),
229 MB_OK | MB_ICONERROR | MB_TOPMOST);
232 void ChromeBrowserMainPartsWin::PostBrowserStart() {
233 ChromeBrowserMainParts::PostBrowserStart();
235 UMA_HISTOGRAM_BOOLEAN("Windows.Tablet", base::win::IsTabletDevice());
237 // Set up a task to verify installed modules in the current process. Use a
238 // delay to reduce the impact on startup time.
239 content::BrowserThread::GetMessageLoopProxyForThread(
240 content::BrowserThread::UI)->PostDelayedTask(
241 FROM_HERE,
242 base::Bind(&VerifyInstallation),
243 base::TimeDelta::FromSeconds(45));
245 InitializeChromeElf();
247 // TODO(erikwright): Remove this and the implementation of the experiment by
248 // September 2014.
249 InitializeDisableTerminateOnHeapCorruptionExperiment();
252 // static
253 void ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
254 const CommandLine& parsed_command_line) {
255 // Clear this var so child processes don't show the dialog by default.
256 scoped_ptr<base::Environment> env(base::Environment::Create());
257 env->UnSetVar(env_vars::kShowRestart);
259 // For non-interactive tests we don't restart on crash.
260 if (env->HasVar(env_vars::kHeadless))
261 return;
263 // If the known command-line test options are used we don't create the
264 // environment block which means we don't get the restart dialog.
265 if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) ||
266 parsed_command_line.HasSwitch(switches::kBrowserAssertTest) ||
267 parsed_command_line.HasSwitch(switches::kNoErrorDialogs))
268 return;
270 // The encoding we use for the info is "title|context|direction" where
271 // direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
272 // on the current locale.
273 base::string16 dlg_strings(l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE));
274 dlg_strings.push_back('|');
275 base::string16 adjusted_string(
276 l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT));
277 base::i18n::AdjustStringForLocaleDirection(&adjusted_string);
278 dlg_strings.append(adjusted_string);
279 dlg_strings.push_back('|');
280 dlg_strings.append(base::ASCIIToUTF16(
281 base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale));
283 env->SetVar(env_vars::kRestartInfo, base::UTF16ToUTF8(dlg_strings));
286 // static
287 void ChromeBrowserMainPartsWin::RegisterApplicationRestart(
288 const CommandLine& parsed_command_line) {
289 DCHECK(base::win::GetVersion() >= base::win::VERSION_VISTA);
290 base::ScopedNativeLibrary library(base::FilePath(L"kernel32.dll"));
291 // Get the function pointer for RegisterApplicationRestart.
292 RegisterApplicationRestartProc register_application_restart =
293 reinterpret_cast<RegisterApplicationRestartProc>(
294 library.GetFunctionPointer("RegisterApplicationRestart"));
295 if (!register_application_restart) {
296 LOG(WARNING) << "Cannot find RegisterApplicationRestart in kernel32.dll";
297 return;
299 // The Windows Restart Manager expects a string of command line flags only,
300 // without the program.
301 CommandLine command_line(CommandLine::NO_PROGRAM);
302 command_line.AppendArguments(parsed_command_line, false);
303 if (!command_line.HasSwitch(switches::kRestoreLastSession))
304 command_line.AppendSwitch(switches::kRestoreLastSession);
306 // Restart Chrome if the computer is restarted as the result of an update.
307 // This could be extended to handle crashes, hangs, and patches.
308 HRESULT hr = register_application_restart(
309 command_line.GetCommandLineString().c_str(),
310 RESTART_NO_CRASH | RESTART_NO_HANG | RESTART_NO_PATCH);
311 if (FAILED(hr)) {
312 if (hr == E_INVALIDARG) {
313 LOG(WARNING) << "Command line too long for RegisterApplicationRestart";
314 } else {
315 NOTREACHED() << "RegisterApplicationRestart failed. hr: " << hr <<
316 ", command_line: " << command_line.GetCommandLineString();
321 // static
322 int ChromeBrowserMainPartsWin::HandleIconsCommands(
323 const CommandLine& parsed_command_line) {
324 if (parsed_command_line.HasSwitch(switches::kHideIcons)) {
325 base::string16 cp_applet;
326 base::win::Version version = base::win::GetVersion();
327 if (version >= base::win::VERSION_VISTA) {
328 cp_applet.assign(L"Programs and Features"); // Windows Vista and later.
329 } else if (version >= base::win::VERSION_XP) {
330 cp_applet.assign(L"Add/Remove Programs"); // Windows XP.
331 } else {
332 return chrome::RESULT_CODE_UNSUPPORTED_PARAM; // Not supported
335 const base::string16 msg =
336 l10n_util::GetStringFUTF16(IDS_HIDE_ICONS_NOT_SUPPORTED, cp_applet);
337 const base::string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
338 const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST;
339 if (IDOK == ui::MessageBox(NULL, msg, caption, flags))
340 ShellExecute(NULL, NULL, L"appwiz.cpl", NULL, NULL, SW_SHOWNORMAL);
342 // Exit as we are not launching the browser.
343 return content::RESULT_CODE_NORMAL_EXIT;
345 // We don't hide icons so we shouldn't do anything special to show them
346 return chrome::RESULT_CODE_UNSUPPORTED_PARAM;
349 // static
350 bool ChromeBrowserMainPartsWin::CheckMachineLevelInstall() {
351 // TODO(tommi): Check if using the default distribution is always the right
352 // thing to do.
353 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
354 Version version;
355 InstallUtil::GetChromeVersion(dist, true, &version);
356 if (version.IsValid()) {
357 base::FilePath exe_path;
358 PathService::Get(base::DIR_EXE, &exe_path);
359 std::wstring exe = exe_path.value();
360 base::FilePath user_exe_path(installer::GetChromeInstallPath(false, dist));
361 if (base::FilePath::CompareEqualIgnoreCase(exe, user_exe_path.value())) {
362 bool is_metro = base::win::IsMetroProcess();
363 if (!is_metro) {
364 // The dialog cannot be shown in Win8 Metro as doing so hangs Chrome on
365 // an invisible dialog.
366 // TODO (gab): Get rid of this dialog altogether and auto-launch
367 // system-level Chrome instead.
368 const base::string16 text =
369 l10n_util::GetStringUTF16(IDS_MACHINE_LEVEL_INSTALL_CONFLICT);
370 const base::string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
371 const UINT flags = MB_OK | MB_ICONERROR | MB_TOPMOST;
372 ui::MessageBox(NULL, text, caption, flags);
374 CommandLine uninstall_cmd(
375 InstallUtil::GetChromeUninstallCmd(false, dist->GetType()));
376 if (!uninstall_cmd.GetProgram().empty()) {
377 uninstall_cmd.AppendSwitch(installer::switches::kSelfDestruct);
378 uninstall_cmd.AppendSwitch(installer::switches::kForceUninstall);
379 uninstall_cmd.AppendSwitch(
380 installer::switches::kDoNotRemoveSharedItems);
382 // Trigger Active Setup for the system-level Chrome to make sure
383 // per-user shortcuts to the system-level Chrome are created. Skip this
384 // if the system-level Chrome will undergo first run anyway, as Active
385 // Setup is triggered on system-level Chrome's first run.
386 // TODO(gab): Instead of having callers of Active Setup think about
387 // other callers, have Active Setup itself register when it ran and
388 // no-op otherwise (http://crbug.com/346843).
389 if (!first_run::IsChromeFirstRun())
390 uninstall_cmd.AppendSwitch(installer::switches::kTriggerActiveSetup);
392 const base::FilePath setup_exe(uninstall_cmd.GetProgram());
393 const base::string16 params(uninstall_cmd.GetArgumentsString());
395 SHELLEXECUTEINFO sei = { sizeof(sei) };
396 sei.fMask = SEE_MASK_NOASYNC;
397 sei.nShow = SW_SHOWNORMAL;
398 sei.lpFile = setup_exe.value().c_str();
399 sei.lpParameters = params.c_str();
400 // On Windows 8 SEE_MASK_FLAG_LOG_USAGE is necessary to guarantee we
401 // flip to the Desktop when launching.
402 if (is_metro)
403 sei.fMask |= SEE_MASK_FLAG_LOG_USAGE;
405 if (!::ShellExecuteEx(&sei))
406 DPCHECK(false);
408 return true;
411 return false;
414 base::string16 TranslationDelegate::GetLocalizedString(
415 int installer_string_id) {
416 int resource_id = 0;
417 switch (installer_string_id) {
418 // HANDLE_STRING is used by the DO_INSTALLER_STRING_MAPPING macro which is in
419 // the generated header installer_util_strings.h.
420 #define HANDLE_STRING(base_id, chrome_id) \
421 case base_id: \
422 resource_id = chrome_id; \
423 break;
424 DO_INSTALLER_STRING_MAPPING
425 #undef HANDLE_STRING
426 default:
427 NOTREACHED();
429 if (resource_id)
430 return l10n_util::GetStringUTF16(resource_id);
431 return base::string16();
434 // static
435 void ChromeBrowserMainPartsWin::SetupInstallerUtilStrings() {
436 CR_DEFINE_STATIC_LOCAL(TranslationDelegate, delegate, ());
437 installer::SetTranslationDelegate(&delegate);