ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main_win.cc
blob822cd3c6b057a9a45ce7a1fb211f7cfacbeceae8
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/files/file_util.h"
16 #include "base/i18n/rtl.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/metrics/histogram.h"
19 #include "base/path_service.h"
20 #include "base/scoped_native_library.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/win/metro.h"
24 #include "base/win/win_util.h"
25 #include "base/win/windows_version.h"
26 #include "base/win/wrapped_window_proc.h"
27 #include "chrome/browser/browser_util_win.h"
28 #include "chrome/browser/chrome_elf_init_win.h"
29 #include "chrome/browser/first_run/first_run.h"
30 #include "chrome/browser/install_verification/win/install_verification.h"
31 #include "chrome/browser/prefs/incognito_mode_prefs.h"
32 #include "chrome/browser/profiles/profile_info_cache.h"
33 #include "chrome/browser/profiles/profile_shortcut_manager.h"
34 #include "chrome/browser/shell_integration.h"
35 #include "chrome/browser/ui/simple_message_box.h"
36 #include "chrome/browser/ui/uninstall_browser_prompt.h"
37 #include "chrome/common/chrome_constants.h"
38 #include "chrome/common/chrome_result_codes.h"
39 #include "chrome/common/chrome_switches.h"
40 #include "chrome/common/chrome_utility_messages.h"
41 #include "chrome/common/chrome_version_info.h"
42 #include "chrome/common/env_vars.h"
43 #include "chrome/common/terminate_on_heap_corruption_experiment_win.h"
44 #include "chrome/grit/chromium_strings.h"
45 #include "chrome/grit/generated_resources.h"
46 #include "chrome/installer/util/browser_distribution.h"
47 #include "chrome/installer/util/helper.h"
48 #include "chrome/installer/util/install_util.h"
49 #include "chrome/installer/util/l10n_string_util.h"
50 #include "chrome/installer/util/shell_util.h"
51 #include "content/public/browser/browser_thread.h"
52 #include "content/public/browser/utility_process_host.h"
53 #include "content/public/browser/utility_process_host_client.h"
54 #include "content/public/common/content_switches.h"
55 #include "content/public/common/dwrite_font_platform_win.h"
56 #include "content/public/common/main_function_params.h"
57 #include "installer_util_strings/installer_util_strings.h"
58 #include "ui/base/cursor/cursor_loader_win.h"
59 #include "ui/base/l10n/l10n_util.h"
60 #include "ui/base/l10n/l10n_util_win.h"
61 #include "ui/base/ui_base_switches.h"
62 #include "ui/base/win/message_box_win.h"
63 #include "ui/gfx/platform_font_win.h"
64 #include "ui/gfx/switches.h"
65 #include "ui/gfx/win/direct_write.h"
66 #include "ui/strings/grit/app_locale_settings.h"
68 #if defined(GOOGLE_CHROME_BUILD)
69 #include "chrome/browser/google/did_run_updater_win.h"
70 #endif
72 namespace {
74 typedef HRESULT (STDAPICALLTYPE* RegisterApplicationRestartProc)(
75 const wchar_t* command_line,
76 DWORD flags);
78 void InitializeWindowProcExceptions() {
79 // Get the breakpad pointer from chrome.exe
80 base::win::WinProcExceptionFilter exception_filter =
81 reinterpret_cast<base::win::WinProcExceptionFilter>(
82 ::GetProcAddress(::GetModuleHandle(
83 chrome::kBrowserProcessExecutableName),
84 "CrashForException"));
85 exception_filter = base::win::SetWinProcExceptionFilter(exception_filter);
86 DCHECK(!exception_filter);
89 // gfx::Font callbacks
90 void AdjustUIFont(LOGFONT* logfont) {
91 l10n_util::AdjustUIFont(logfont);
94 int GetMinimumFontSize() {
95 int min_font_size;
96 base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE),
97 &min_font_size);
98 return min_font_size;
101 class TranslationDelegate : public installer::TranslationDelegate {
102 public:
103 virtual base::string16 GetLocalizedString(int installer_string_id) override;
106 void ExecuteFontCacheBuildTask(const base::FilePath& path) {
107 base::WeakPtr<content::UtilityProcessHost> utility_process_host(
108 content::UtilityProcessHost::Create(NULL, NULL)->AsWeakPtr());
109 utility_process_host->DisableSandbox();
110 utility_process_host->Send(
111 new ChromeUtilityHostMsg_BuildDirectWriteFontCache(path));
114 } // namespace
116 void ShowCloseBrowserFirstMessageBox() {
117 int message_id = IDS_UNINSTALL_CLOSE_APP;
118 if (base::win::GetVersion() >= base::win::VERSION_WIN8 &&
119 (ShellIntegration::GetDefaultBrowser() == ShellIntegration::IS_DEFAULT)) {
120 message_id = IDS_UNINSTALL_CLOSE_APP_IMMERSIVE;
122 chrome::ShowMessageBox(NULL,
123 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
124 l10n_util::GetStringUTF16(message_id),
125 chrome::MESSAGE_BOX_TYPE_WARNING);
128 int DoUninstallTasks(bool chrome_still_running) {
129 // We want to show a warning to user (and exit) if Chrome is already running
130 // *before* we show the uninstall confirmation dialog box. But while the
131 // uninstall confirmation dialog is up, user might start Chrome, so we
132 // check once again after user acknowledges Uninstall dialog.
133 if (chrome_still_running) {
134 ShowCloseBrowserFirstMessageBox();
135 return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE;
137 int result = chrome::ShowUninstallBrowserPrompt();
138 if (browser_util::IsBrowserAlreadyRunning()) {
139 ShowCloseBrowserFirstMessageBox();
140 return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE;
143 if (result != chrome::RESULT_CODE_UNINSTALL_USER_CANCEL) {
144 // The following actions are just best effort.
145 // TODO(gab): Look into removing this code which is now redundant with the
146 // work done by setup.exe on uninstall.
147 VLOG(1) << "Executing uninstall actions";
148 base::FilePath chrome_exe;
149 if (PathService::Get(base::FILE_EXE, &chrome_exe)) {
150 ShellUtil::ShortcutLocation user_shortcut_locations[] = {
151 ShellUtil::SHORTCUT_LOCATION_DESKTOP,
152 ShellUtil::SHORTCUT_LOCATION_QUICK_LAUNCH,
153 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_DIR,
154 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR,
156 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
157 for (size_t i = 0; i < arraysize(user_shortcut_locations); ++i) {
158 if (!ShellUtil::RemoveShortcuts(user_shortcut_locations[i], dist,
159 ShellUtil::CURRENT_USER, chrome_exe)) {
160 VLOG(1) << "Failed to delete shortcut at location "
161 << user_shortcut_locations[i];
164 } else {
165 NOTREACHED();
168 return result;
171 // ChromeBrowserMainPartsWin ---------------------------------------------------
173 ChromeBrowserMainPartsWin::ChromeBrowserMainPartsWin(
174 const content::MainFunctionParams& parameters)
175 : ChromeBrowserMainParts(parameters) {
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 base::CommandLine extra_switches(base::CommandLine::NO_PROGRAM);
185 extra_switches.ParseFromString(metro_switches);
186 base::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 ui::CursorLoaderWin::SetCursorResourceModule(chrome::kBrowserResourcesDll);
203 void ChromeBrowserMainPartsWin::PreMainMessageLoopStart() {
204 // installer_util references strings that are normally compiled into
205 // setup.exe. In Chrome, these strings are in the locale files.
206 SetupInstallerUtilStrings();
208 ChromeBrowserMainParts::PreMainMessageLoopStart();
209 if (!parameters().ui_task) {
210 // Make sure that we know how to handle exceptions from the message loop.
211 InitializeWindowProcExceptions();
214 IncognitoModePrefs::InitializePlatformParentalControls();
217 int ChromeBrowserMainPartsWin::PreCreateThreads() {
218 int rv = ChromeBrowserMainParts::PreCreateThreads();
220 // TODO(viettrungluu): why don't we run this earlier?
221 if (!parsed_command_line().HasSwitch(switches::kNoErrorDialogs) &&
222 base::win::GetVersion() < base::win::VERSION_XP) {
223 chrome::ShowMessageBox(NULL,
224 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
225 l10n_util::GetStringUTF16(IDS_UNSUPPORTED_OS_PRE_WIN_XP),
226 chrome::MESSAGE_BOX_TYPE_WARNING);
229 return rv;
232 void ChromeBrowserMainPartsWin::ShowMissingLocaleMessageBox() {
233 ui::MessageBox(NULL,
234 base::ASCIIToUTF16(chrome_browser::kMissingLocaleDataMessage),
235 base::ASCIIToUTF16(chrome_browser::kMissingLocaleDataTitle),
236 MB_OK | MB_ICONERROR | MB_TOPMOST);
239 void ChromeBrowserMainPartsWin::PostProfileInit() {
240 ChromeBrowserMainParts::PostProfileInit();
242 // DirectWrite support is mainly available Windows 7 and up.
243 if (gfx::win::ShouldUseDirectWrite()) {
244 base::FilePath path(
245 profile()->GetPath().AppendASCII(content::kFontCacheSharedSectionName));
246 // This function will create a read only section if cache file exists
247 // otherwise it will spawn utility process to build cache file, which will
248 // be used during next browser start/postprofileinit.
249 if (!content::LoadFontCache(path)) {
250 content::BrowserThread::PostTask(
251 content::BrowserThread::IO, FROM_HERE,
252 base::Bind(ExecuteFontCacheBuildTask, path));
257 void ChromeBrowserMainPartsWin::PostBrowserStart() {
258 ChromeBrowserMainParts::PostBrowserStart();
260 UMA_HISTOGRAM_BOOLEAN("Windows.Tablet", base::win::IsTabletDevice());
262 // Set up a task to verify installed modules in the current process. Use a
263 // delay to reduce the impact on startup time.
264 content::BrowserThread::GetMessageLoopProxyForThread(
265 content::BrowserThread::UI)->PostDelayedTask(
266 FROM_HERE,
267 base::Bind(&VerifyInstallation),
268 base::TimeDelta::FromSeconds(45));
270 InitializeChromeElf();
272 // TODO(erikwright): Remove this and the implementation of the experiment by
273 // September 2014.
274 InitializeDisableTerminateOnHeapCorruptionExperiment();
276 #if defined(GOOGLE_CHROME_BUILD)
277 did_run_updater_.reset(new DidRunUpdater);
278 #endif
281 // static
282 void ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
283 const base::CommandLine& parsed_command_line) {
284 // Clear this var so child processes don't show the dialog by default.
285 scoped_ptr<base::Environment> env(base::Environment::Create());
286 env->UnSetVar(env_vars::kShowRestart);
288 // For non-interactive tests we don't restart on crash.
289 if (env->HasVar(env_vars::kHeadless))
290 return;
292 // If the known command-line test options are used we don't create the
293 // environment block which means we don't get the restart dialog.
294 if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) ||
295 parsed_command_line.HasSwitch(switches::kNoErrorDialogs))
296 return;
298 // The encoding we use for the info is "title|context|direction" where
299 // direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
300 // on the current locale.
301 base::string16 dlg_strings(l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE));
302 dlg_strings.push_back('|');
303 base::string16 adjusted_string(
304 l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT));
305 base::i18n::AdjustStringForLocaleDirection(&adjusted_string);
306 dlg_strings.append(adjusted_string);
307 dlg_strings.push_back('|');
308 dlg_strings.append(base::ASCIIToUTF16(
309 base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale));
311 env->SetVar(env_vars::kRestartInfo, base::UTF16ToUTF8(dlg_strings));
314 // static
315 void ChromeBrowserMainPartsWin::RegisterApplicationRestart(
316 const base::CommandLine& parsed_command_line) {
317 DCHECK(base::win::GetVersion() >= base::win::VERSION_VISTA);
318 base::ScopedNativeLibrary library(base::FilePath(L"kernel32.dll"));
319 // Get the function pointer for RegisterApplicationRestart.
320 RegisterApplicationRestartProc register_application_restart =
321 reinterpret_cast<RegisterApplicationRestartProc>(
322 library.GetFunctionPointer("RegisterApplicationRestart"));
323 if (!register_application_restart) {
324 LOG(WARNING) << "Cannot find RegisterApplicationRestart in kernel32.dll";
325 return;
327 // The Windows Restart Manager expects a string of command line flags only,
328 // without the program.
329 base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
330 command_line.AppendArguments(parsed_command_line, false);
331 if (!command_line.HasSwitch(switches::kRestoreLastSession))
332 command_line.AppendSwitch(switches::kRestoreLastSession);
334 // Restart Chrome if the computer is restarted as the result of an update.
335 // This could be extended to handle crashes, hangs, and patches.
336 HRESULT hr = register_application_restart(
337 command_line.GetCommandLineString().c_str(),
338 RESTART_NO_CRASH | RESTART_NO_HANG | RESTART_NO_PATCH);
339 if (FAILED(hr)) {
340 if (hr == E_INVALIDARG) {
341 LOG(WARNING) << "Command line too long for RegisterApplicationRestart";
342 } else {
343 NOTREACHED() << "RegisterApplicationRestart failed. hr: " << hr <<
344 ", command_line: " << command_line.GetCommandLineString();
349 // static
350 int ChromeBrowserMainPartsWin::HandleIconsCommands(
351 const base::CommandLine& parsed_command_line) {
352 if (parsed_command_line.HasSwitch(switches::kHideIcons)) {
353 base::string16 cp_applet;
354 base::win::Version version = base::win::GetVersion();
355 if (version >= base::win::VERSION_VISTA) {
356 cp_applet.assign(L"Programs and Features"); // Windows Vista and later.
357 } else if (version >= base::win::VERSION_XP) {
358 cp_applet.assign(L"Add/Remove Programs"); // Windows XP.
359 } else {
360 return chrome::RESULT_CODE_UNSUPPORTED_PARAM; // Not supported
363 const base::string16 msg =
364 l10n_util::GetStringFUTF16(IDS_HIDE_ICONS_NOT_SUPPORTED, cp_applet);
365 const base::string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
366 const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST;
367 if (IDOK == ui::MessageBox(NULL, msg, caption, flags))
368 ShellExecute(NULL, NULL, L"appwiz.cpl", NULL, NULL, SW_SHOWNORMAL);
370 // Exit as we are not launching the browser.
371 return content::RESULT_CODE_NORMAL_EXIT;
373 // We don't hide icons so we shouldn't do anything special to show them
374 return chrome::RESULT_CODE_UNSUPPORTED_PARAM;
377 // static
378 bool ChromeBrowserMainPartsWin::CheckMachineLevelInstall() {
379 // TODO(tommi): Check if using the default distribution is always the right
380 // thing to do.
381 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
382 Version version;
383 InstallUtil::GetChromeVersion(dist, true, &version);
384 if (version.IsValid()) {
385 base::FilePath exe_path;
386 PathService::Get(base::DIR_EXE, &exe_path);
387 std::wstring exe = exe_path.value();
388 base::FilePath user_exe_path(installer::GetChromeInstallPath(false, dist));
389 if (base::FilePath::CompareEqualIgnoreCase(exe, user_exe_path.value())) {
390 bool is_metro = base::win::IsMetroProcess();
391 if (!is_metro) {
392 // The dialog cannot be shown in Win8 Metro as doing so hangs Chrome on
393 // an invisible dialog.
394 // TODO (gab): Get rid of this dialog altogether and auto-launch
395 // system-level Chrome instead.
396 const base::string16 text =
397 l10n_util::GetStringUTF16(IDS_MACHINE_LEVEL_INSTALL_CONFLICT);
398 const base::string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
399 const UINT flags = MB_OK | MB_ICONERROR | MB_TOPMOST;
400 ui::MessageBox(NULL, text, caption, flags);
402 base::CommandLine uninstall_cmd(
403 InstallUtil::GetChromeUninstallCmd(false, dist->GetType()));
404 if (!uninstall_cmd.GetProgram().empty()) {
405 uninstall_cmd.AppendSwitch(installer::switches::kSelfDestruct);
406 uninstall_cmd.AppendSwitch(installer::switches::kForceUninstall);
407 uninstall_cmd.AppendSwitch(
408 installer::switches::kDoNotRemoveSharedItems);
410 // Trigger Active Setup for the system-level Chrome to make sure
411 // per-user shortcuts to the system-level Chrome are created. Skip this
412 // if the system-level Chrome will undergo first run anyway, as Active
413 // Setup is triggered on system-level Chrome's first run.
414 // TODO(gab): Instead of having callers of Active Setup think about
415 // other callers, have Active Setup itself register when it ran and
416 // no-op otherwise (http://crbug.com/346843).
417 if (!first_run::IsChromeFirstRun())
418 uninstall_cmd.AppendSwitch(installer::switches::kTriggerActiveSetup);
420 const base::FilePath setup_exe(uninstall_cmd.GetProgram());
421 const base::string16 params(uninstall_cmd.GetArgumentsString());
423 SHELLEXECUTEINFO sei = { sizeof(sei) };
424 sei.fMask = SEE_MASK_NOASYNC;
425 sei.nShow = SW_SHOWNORMAL;
426 sei.lpFile = setup_exe.value().c_str();
427 sei.lpParameters = params.c_str();
428 // On Windows 8 SEE_MASK_FLAG_LOG_USAGE is necessary to guarantee we
429 // flip to the Desktop when launching.
430 if (is_metro)
431 sei.fMask |= SEE_MASK_FLAG_LOG_USAGE;
433 if (!::ShellExecuteEx(&sei))
434 DPCHECK(false);
436 return true;
439 return false;
442 base::string16 TranslationDelegate::GetLocalizedString(
443 int installer_string_id) {
444 int resource_id = 0;
445 switch (installer_string_id) {
446 // HANDLE_STRING is used by the DO_INSTALLER_STRING_MAPPING macro which is in
447 // the generated header installer_util_strings.h.
448 #define HANDLE_STRING(base_id, chrome_id) \
449 case base_id: \
450 resource_id = chrome_id; \
451 break;
452 DO_INSTALLER_STRING_MAPPING
453 #undef HANDLE_STRING
454 default:
455 NOTREACHED();
457 if (resource_id)
458 return l10n_util::GetStringUTF16(resource_id);
459 return base::string16();
462 // static
463 void ChromeBrowserMainPartsWin::SetupInstallerUtilStrings() {
464 CR_DEFINE_STATIC_LOCAL(TranslationDelegate, delegate, ());
465 installer::SetTranslationDelegate(&delegate);