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