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"
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"
74 typedef HRESULT (STDAPICALLTYPE
* RegisterApplicationRestartProc
)(
75 const wchar_t* command_line
,
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() {
96 base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE
),
101 class TranslationDelegate
: public installer::TranslationDelegate
{
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
));
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
];
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 CommandLine
extra_switches(CommandLine::NO_PROGRAM
);
185 extra_switches
.ParseFromString(metro_switches
);
186 CommandLine::ForCurrentProcess()->AppendArguments(extra_switches
,
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
);
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();
216 IncognitoModePrefs::InitializePlatformParentalControls();
219 int ChromeBrowserMainPartsWin::PreCreateThreads() {
220 int rv
= ChromeBrowserMainParts::PreCreateThreads();
222 // TODO(viettrungluu): why don't we run this earlier?
223 if (!parsed_command_line().HasSwitch(switches::kNoErrorDialogs
) &&
224 base::win::GetVersion() < base::win::VERSION_XP
) {
225 chrome::ShowMessageBox(NULL
,
226 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME
),
227 l10n_util::GetStringUTF16(IDS_UNSUPPORTED_OS_PRE_WIN_XP
),
228 chrome::MESSAGE_BOX_TYPE_WARNING
);
231 // Windows 8+ provides a mode where by a process cannot call Win32K/GDI
232 // functions in the kernel (win32k.sys). If we are on Windows 8+ and if
233 // we are launched with the kEnableWin32kRendererLockDown switch then we
234 // force the PDF pepper plugin to run out of process. This is because the
235 // PDF plugin uses GDI for text rendering which does not work in the
236 // Win32K lockdown mode. Running it out of process ensures that the process
237 // launched for the plugin does not have the Win32K lockdown mode enabled.
239 // Revisit this when the pdf plugin uses skia and stops using GDI.
240 if (CommandLine::ForCurrentProcess()->HasSwitch(
241 switches::kEnableWin32kRendererLockDown
) &&
242 base::win::GetVersion() >= base::win::VERSION_WIN8
) {
243 CommandLine::ForCurrentProcess()->AppendSwitch(
244 switches::kEnableOutOfProcessPdf
);
249 void ChromeBrowserMainPartsWin::ShowMissingLocaleMessageBox() {
251 base::ASCIIToUTF16(chrome_browser::kMissingLocaleDataMessage
),
252 base::ASCIIToUTF16(chrome_browser::kMissingLocaleDataTitle
),
253 MB_OK
| MB_ICONERROR
| MB_TOPMOST
);
256 void ChromeBrowserMainPartsWin::PostProfileInit() {
257 ChromeBrowserMainParts::PostProfileInit();
259 // DirectWrite support is mainly available Windows 7 and up.
260 if (gfx::win::ShouldUseDirectWrite()) {
262 profile()->GetPath().AppendASCII(content::kFontCacheSharedSectionName
));
263 // This function will create a read only section if cache file exists
264 // otherwise it will spawn utility process to build cache file, which will
265 // be used during next browser start/postprofileinit.
266 if (!content::LoadFontCache(path
)) {
267 content::BrowserThread::PostTask(
268 content::BrowserThread::IO
, FROM_HERE
,
269 base::Bind(ExecuteFontCacheBuildTask
, path
));
274 void ChromeBrowserMainPartsWin::PostBrowserStart() {
275 ChromeBrowserMainParts::PostBrowserStart();
277 UMA_HISTOGRAM_BOOLEAN("Windows.Tablet", base::win::IsTabletDevice());
279 // Set up a task to verify installed modules in the current process. Use a
280 // delay to reduce the impact on startup time.
281 content::BrowserThread::GetMessageLoopProxyForThread(
282 content::BrowserThread::UI
)->PostDelayedTask(
284 base::Bind(&VerifyInstallation
),
285 base::TimeDelta::FromSeconds(45));
287 InitializeChromeElf();
289 // TODO(erikwright): Remove this and the implementation of the experiment by
291 InitializeDisableTerminateOnHeapCorruptionExperiment();
293 #if defined(GOOGLE_CHROME_BUILD)
294 did_run_updater_
.reset(new DidRunUpdater
);
299 void ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
300 const CommandLine
& parsed_command_line
) {
301 // Clear this var so child processes don't show the dialog by default.
302 scoped_ptr
<base::Environment
> env(base::Environment::Create());
303 env
->UnSetVar(env_vars::kShowRestart
);
305 // For non-interactive tests we don't restart on crash.
306 if (env
->HasVar(env_vars::kHeadless
))
309 // If the known command-line test options are used we don't create the
310 // environment block which means we don't get the restart dialog.
311 if (parsed_command_line
.HasSwitch(switches::kBrowserCrashTest
) ||
312 parsed_command_line
.HasSwitch(switches::kBrowserAssertTest
) ||
313 parsed_command_line
.HasSwitch(switches::kNoErrorDialogs
))
316 // The encoding we use for the info is "title|context|direction" where
317 // direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
318 // on the current locale.
319 base::string16
dlg_strings(l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE
));
320 dlg_strings
.push_back('|');
321 base::string16
adjusted_string(
322 l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT
));
323 base::i18n::AdjustStringForLocaleDirection(&adjusted_string
);
324 dlg_strings
.append(adjusted_string
);
325 dlg_strings
.push_back('|');
326 dlg_strings
.append(base::ASCIIToUTF16(
327 base::i18n::IsRTL() ? env_vars::kRtlLocale
: env_vars::kLtrLocale
));
329 env
->SetVar(env_vars::kRestartInfo
, base::UTF16ToUTF8(dlg_strings
));
333 void ChromeBrowserMainPartsWin::RegisterApplicationRestart(
334 const CommandLine
& parsed_command_line
) {
335 DCHECK(base::win::GetVersion() >= base::win::VERSION_VISTA
);
336 base::ScopedNativeLibrary
library(base::FilePath(L
"kernel32.dll"));
337 // Get the function pointer for RegisterApplicationRestart.
338 RegisterApplicationRestartProc register_application_restart
=
339 reinterpret_cast<RegisterApplicationRestartProc
>(
340 library
.GetFunctionPointer("RegisterApplicationRestart"));
341 if (!register_application_restart
) {
342 LOG(WARNING
) << "Cannot find RegisterApplicationRestart in kernel32.dll";
345 // The Windows Restart Manager expects a string of command line flags only,
346 // without the program.
347 CommandLine
command_line(CommandLine::NO_PROGRAM
);
348 command_line
.AppendArguments(parsed_command_line
, false);
349 if (!command_line
.HasSwitch(switches::kRestoreLastSession
))
350 command_line
.AppendSwitch(switches::kRestoreLastSession
);
352 // Restart Chrome if the computer is restarted as the result of an update.
353 // This could be extended to handle crashes, hangs, and patches.
354 HRESULT hr
= register_application_restart(
355 command_line
.GetCommandLineString().c_str(),
356 RESTART_NO_CRASH
| RESTART_NO_HANG
| RESTART_NO_PATCH
);
358 if (hr
== E_INVALIDARG
) {
359 LOG(WARNING
) << "Command line too long for RegisterApplicationRestart";
361 NOTREACHED() << "RegisterApplicationRestart failed. hr: " << hr
<<
362 ", command_line: " << command_line
.GetCommandLineString();
368 int ChromeBrowserMainPartsWin::HandleIconsCommands(
369 const CommandLine
& parsed_command_line
) {
370 if (parsed_command_line
.HasSwitch(switches::kHideIcons
)) {
371 base::string16 cp_applet
;
372 base::win::Version version
= base::win::GetVersion();
373 if (version
>= base::win::VERSION_VISTA
) {
374 cp_applet
.assign(L
"Programs and Features"); // Windows Vista and later.
375 } else if (version
>= base::win::VERSION_XP
) {
376 cp_applet
.assign(L
"Add/Remove Programs"); // Windows XP.
378 return chrome::RESULT_CODE_UNSUPPORTED_PARAM
; // Not supported
381 const base::string16 msg
=
382 l10n_util::GetStringFUTF16(IDS_HIDE_ICONS_NOT_SUPPORTED
, cp_applet
);
383 const base::string16 caption
= l10n_util::GetStringUTF16(IDS_PRODUCT_NAME
);
384 const UINT flags
= MB_OKCANCEL
| MB_ICONWARNING
| MB_TOPMOST
;
385 if (IDOK
== ui::MessageBox(NULL
, msg
, caption
, flags
))
386 ShellExecute(NULL
, NULL
, L
"appwiz.cpl", NULL
, NULL
, SW_SHOWNORMAL
);
388 // Exit as we are not launching the browser.
389 return content::RESULT_CODE_NORMAL_EXIT
;
391 // We don't hide icons so we shouldn't do anything special to show them
392 return chrome::RESULT_CODE_UNSUPPORTED_PARAM
;
396 bool ChromeBrowserMainPartsWin::CheckMachineLevelInstall() {
397 // TODO(tommi): Check if using the default distribution is always the right
399 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
401 InstallUtil::GetChromeVersion(dist
, true, &version
);
402 if (version
.IsValid()) {
403 base::FilePath exe_path
;
404 PathService::Get(base::DIR_EXE
, &exe_path
);
405 std::wstring exe
= exe_path
.value();
406 base::FilePath
user_exe_path(installer::GetChromeInstallPath(false, dist
));
407 if (base::FilePath::CompareEqualIgnoreCase(exe
, user_exe_path
.value())) {
408 bool is_metro
= base::win::IsMetroProcess();
410 // The dialog cannot be shown in Win8 Metro as doing so hangs Chrome on
411 // an invisible dialog.
412 // TODO (gab): Get rid of this dialog altogether and auto-launch
413 // system-level Chrome instead.
414 const base::string16 text
=
415 l10n_util::GetStringUTF16(IDS_MACHINE_LEVEL_INSTALL_CONFLICT
);
416 const base::string16 caption
= l10n_util::GetStringUTF16(IDS_PRODUCT_NAME
);
417 const UINT flags
= MB_OK
| MB_ICONERROR
| MB_TOPMOST
;
418 ui::MessageBox(NULL
, text
, caption
, flags
);
420 CommandLine
uninstall_cmd(
421 InstallUtil::GetChromeUninstallCmd(false, dist
->GetType()));
422 if (!uninstall_cmd
.GetProgram().empty()) {
423 uninstall_cmd
.AppendSwitch(installer::switches::kSelfDestruct
);
424 uninstall_cmd
.AppendSwitch(installer::switches::kForceUninstall
);
425 uninstall_cmd
.AppendSwitch(
426 installer::switches::kDoNotRemoveSharedItems
);
428 // Trigger Active Setup for the system-level Chrome to make sure
429 // per-user shortcuts to the system-level Chrome are created. Skip this
430 // if the system-level Chrome will undergo first run anyway, as Active
431 // Setup is triggered on system-level Chrome's first run.
432 // TODO(gab): Instead of having callers of Active Setup think about
433 // other callers, have Active Setup itself register when it ran and
434 // no-op otherwise (http://crbug.com/346843).
435 if (!first_run::IsChromeFirstRun())
436 uninstall_cmd
.AppendSwitch(installer::switches::kTriggerActiveSetup
);
438 const base::FilePath
setup_exe(uninstall_cmd
.GetProgram());
439 const base::string16
params(uninstall_cmd
.GetArgumentsString());
441 SHELLEXECUTEINFO sei
= { sizeof(sei
) };
442 sei
.fMask
= SEE_MASK_NOASYNC
;
443 sei
.nShow
= SW_SHOWNORMAL
;
444 sei
.lpFile
= setup_exe
.value().c_str();
445 sei
.lpParameters
= params
.c_str();
446 // On Windows 8 SEE_MASK_FLAG_LOG_USAGE is necessary to guarantee we
447 // flip to the Desktop when launching.
449 sei
.fMask
|= SEE_MASK_FLAG_LOG_USAGE
;
451 if (!::ShellExecuteEx(&sei
))
460 base::string16
TranslationDelegate::GetLocalizedString(
461 int installer_string_id
) {
463 switch (installer_string_id
) {
464 // HANDLE_STRING is used by the DO_INSTALLER_STRING_MAPPING macro which is in
465 // the generated header installer_util_strings.h.
466 #define HANDLE_STRING(base_id, chrome_id) \
468 resource_id = chrome_id; \
470 DO_INSTALLER_STRING_MAPPING
476 return l10n_util::GetStringUTF16(resource_id
);
477 return base::string16();
481 void ChromeBrowserMainPartsWin::SetupInstallerUtilStrings() {
482 CR_DEFINE_STATIC_LOCAL(TranslationDelegate
, delegate
, ());
483 installer::SetTranslationDelegate(&delegate
);