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_enumerator.h"
15 #include "base/files/file_path.h"
16 #include "base/files/file_util.h"
17 #include "base/i18n/rtl.h"
18 #include "base/location.h"
19 #include "base/macros.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/metrics/histogram.h"
22 #include "base/path_service.h"
23 #include "base/scoped_native_library.h"
24 #include "base/strings/string_number_conversions.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/win/metro.h"
27 #include "base/win/win_util.h"
28 #include "base/win/windows_version.h"
29 #include "base/win/wrapped_window_proc.h"
30 #include "chrome/browser/browser_util_win.h"
31 #include "chrome/browser/chrome_elf_init_win.h"
32 #include "chrome/browser/first_run/first_run.h"
33 #include "chrome/browser/install_verification/win/install_verification.h"
34 #include "chrome/browser/prefs/incognito_mode_prefs.h"
35 #include "chrome/browser/profiles/profile_info_cache.h"
36 #include "chrome/browser/profiles/profile_shortcut_manager.h"
37 #include "chrome/browser/shell_integration.h"
38 #include "chrome/browser/ui/simple_message_box.h"
39 #include "chrome/browser/ui/uninstall_browser_prompt.h"
40 #include "chrome/chrome_watcher/chrome_watcher_main_api.h"
41 #include "chrome/common/chrome_constants.h"
42 #include "chrome/common/chrome_paths.h"
43 #include "chrome/common/chrome_result_codes.h"
44 #include "chrome/common/chrome_switches.h"
45 #include "chrome/common/chrome_utility_messages.h"
46 #include "chrome/common/chrome_version_info.h"
47 #include "chrome/common/env_vars.h"
48 #include "chrome/grit/chromium_strings.h"
49 #include "chrome/grit/generated_resources.h"
50 #include "chrome/installer/util/browser_distribution.h"
51 #include "chrome/installer/util/helper.h"
52 #include "chrome/installer/util/install_util.h"
53 #include "chrome/installer/util/l10n_string_util.h"
54 #include "chrome/installer/util/shell_util.h"
55 #include "content/public/browser/browser_thread.h"
56 #include "content/public/browser/utility_process_host.h"
57 #include "content/public/browser/utility_process_host_client.h"
58 #include "content/public/common/content_switches.h"
59 #include "content/public/common/dwrite_font_platform_win.h"
60 #include "content/public/common/main_function_params.h"
61 #include "installer_util_strings/installer_util_strings.h"
62 #include "ui/base/cursor/cursor_loader_win.h"
63 #include "ui/base/l10n/l10n_util.h"
64 #include "ui/base/l10n/l10n_util_win.h"
65 #include "ui/base/ui_base_switches.h"
66 #include "ui/base/win/message_box_win.h"
67 #include "ui/gfx/platform_font_win.h"
68 #include "ui/gfx/switches.h"
69 #include "ui/gfx/win/direct_write.h"
70 #include "ui/strings/grit/app_locale_settings.h"
72 #if defined(GOOGLE_CHROME_BUILD)
73 #include "chrome/browser/google/did_run_updater_win.h"
77 #include "syzygy/kasko/api/reporter.h"
82 typedef HRESULT (STDAPICALLTYPE
* RegisterApplicationRestartProc
)(
83 const wchar_t* command_line
,
86 void InitializeWindowProcExceptions() {
87 // Get the breakpad pointer from chrome.exe
88 base::win::WinProcExceptionFilter exception_filter
=
89 reinterpret_cast<base::win::WinProcExceptionFilter
>(
90 ::GetProcAddress(::GetModuleHandle(
91 chrome::kBrowserProcessExecutableName
),
92 "CrashForException"));
93 exception_filter
= base::win::SetWinProcExceptionFilter(exception_filter
);
94 DCHECK(!exception_filter
);
97 // gfx::Font callbacks
98 void AdjustUIFont(LOGFONT
* logfont
) {
99 l10n_util::AdjustUIFont(logfont
);
102 int GetMinimumFontSize() {
104 base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE
),
106 return min_font_size
;
109 class TranslationDelegate
: public installer::TranslationDelegate
{
111 base::string16
GetLocalizedString(int installer_string_id
) override
;
114 void ExecuteFontCacheBuildTask(const base::FilePath
& path
) {
115 base::WeakPtr
<content::UtilityProcessHost
> utility_process_host(
116 content::UtilityProcessHost::Create(NULL
, NULL
)->AsWeakPtr());
117 utility_process_host
->SetName(l10n_util::GetStringUTF16(
118 IDS_UTILITY_PROCESS_FONT_CACHE_BUILDER_NAME
));
119 utility_process_host
->DisableSandbox();
120 utility_process_host
->Send(
121 new ChromeUtilityHostMsg_BuildDirectWriteFontCache(path
));
125 void ObserveFailedCrashReportDirectory(const base::FilePath
& path
, bool error
) {
129 base::FileEnumerator
enumerator(path
, true, base::FileEnumerator::FILES
);
130 for (base::FilePath report_file
= enumerator
.Next(); !report_file
.empty();
131 report_file
= enumerator
.Next()) {
132 if (report_file
.Extension() ==
133 kasko::api::kPermanentFailureMinidumpExtension
) {
134 UMA_HISTOGRAM_BOOLEAN("CrashReport.PermanentUploadFailure", true);
136 bool result
= base::DeleteFile(report_file
, false);
141 void StartFailedKaskoCrashReportWatcher(base::FilePathWatcher
* watcher
) {
142 base::FilePath watcher_data_directory
;
143 if (!PathService::Get(chrome::DIR_WATCHER_DATA
, &watcher_data_directory
)) {
146 base::FilePath permanent_failure_directory
=
147 watcher_data_directory
.Append(kPermanentlyFailedReportsSubdir
);
148 if (!watcher
->Watch(permanent_failure_directory
, true,
149 base::Bind(&ObserveFailedCrashReportDirectory
))) {
153 // Call it once to observe any files present prior to the Watch() call.
154 ObserveFailedCrashReportDirectory(permanent_failure_directory
, false);
161 void ShowCloseBrowserFirstMessageBox() {
162 int message_id
= IDS_UNINSTALL_CLOSE_APP
;
163 if (base::win::GetVersion() >= base::win::VERSION_WIN8
&&
164 (ShellIntegration::GetDefaultBrowser() == ShellIntegration::IS_DEFAULT
)) {
165 message_id
= IDS_UNINSTALL_CLOSE_APP_IMMERSIVE
;
167 chrome::ShowMessageBox(NULL
,
168 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME
),
169 l10n_util::GetStringUTF16(message_id
),
170 chrome::MESSAGE_BOX_TYPE_WARNING
);
173 int DoUninstallTasks(bool chrome_still_running
) {
174 // We want to show a warning to user (and exit) if Chrome is already running
175 // *before* we show the uninstall confirmation dialog box. But while the
176 // uninstall confirmation dialog is up, user might start Chrome, so we
177 // check once again after user acknowledges Uninstall dialog.
178 if (chrome_still_running
) {
179 ShowCloseBrowserFirstMessageBox();
180 return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE
;
182 int result
= chrome::ShowUninstallBrowserPrompt();
183 if (browser_util::IsBrowserAlreadyRunning()) {
184 ShowCloseBrowserFirstMessageBox();
185 return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE
;
188 if (result
!= chrome::RESULT_CODE_UNINSTALL_USER_CANCEL
) {
189 // The following actions are just best effort.
190 // TODO(gab): Look into removing this code which is now redundant with the
191 // work done by setup.exe on uninstall.
192 VLOG(1) << "Executing uninstall actions";
193 base::FilePath chrome_exe
;
194 if (PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
195 ShellUtil::ShortcutLocation user_shortcut_locations
[] = {
196 ShellUtil::SHORTCUT_LOCATION_DESKTOP
,
197 ShellUtil::SHORTCUT_LOCATION_QUICK_LAUNCH
,
198 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_DIR
,
199 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR
,
201 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
202 for (size_t i
= 0; i
< arraysize(user_shortcut_locations
); ++i
) {
203 if (!ShellUtil::RemoveShortcuts(user_shortcut_locations
[i
], dist
,
204 ShellUtil::CURRENT_USER
, chrome_exe
)) {
205 VLOG(1) << "Failed to delete shortcut at location "
206 << user_shortcut_locations
[i
];
216 // ChromeBrowserMainPartsWin ---------------------------------------------------
218 ChromeBrowserMainPartsWin::ChromeBrowserMainPartsWin(
219 const content::MainFunctionParams
& parameters
)
220 : ChromeBrowserMainParts(parameters
) {
221 if (base::win::IsMetroProcess()) {
222 typedef const wchar_t* (*GetMetroSwitches
)(void);
223 GetMetroSwitches metro_switches_proc
= reinterpret_cast<GetMetroSwitches
>(
224 GetProcAddress(base::win::GetMetroModule(),
225 "GetMetroCommandLineSwitches"));
226 if (metro_switches_proc
) {
227 base::string16 metro_switches
= (*metro_switches_proc
)();
228 if (!metro_switches
.empty()) {
229 base::CommandLine
extra_switches(base::CommandLine::NO_PROGRAM
);
230 extra_switches
.ParseFromString(metro_switches
);
231 base::CommandLine::ForCurrentProcess()->AppendArguments(extra_switches
,
238 ChromeBrowserMainPartsWin::~ChromeBrowserMainPartsWin() {
241 void ChromeBrowserMainPartsWin::ToolkitInitialized() {
242 ChromeBrowserMainParts::ToolkitInitialized();
243 gfx::PlatformFontWin::adjust_font_callback
= &AdjustUIFont
;
244 gfx::PlatformFontWin::get_minimum_font_size_callback
= &GetMinimumFontSize
;
245 ui::CursorLoaderWin::SetCursorResourceModule(chrome::kBrowserResourcesDll
);
248 void ChromeBrowserMainPartsWin::PreMainMessageLoopStart() {
249 // installer_util references strings that are normally compiled into
250 // setup.exe. In Chrome, these strings are in the locale files.
251 SetupInstallerUtilStrings();
253 ChromeBrowserMainParts::PreMainMessageLoopStart();
254 if (!parameters().ui_task
) {
255 // Make sure that we know how to handle exceptions from the message loop.
256 InitializeWindowProcExceptions();
259 // Prime the parental controls cache on Windows.
260 ignore_result(IncognitoModePrefs::ArePlatformParentalControlsEnabled());
263 int ChromeBrowserMainPartsWin::PreCreateThreads() {
264 int rv
= ChromeBrowserMainParts::PreCreateThreads();
266 // TODO(viettrungluu): why don't we run this earlier?
267 if (!parsed_command_line().HasSwitch(switches::kNoErrorDialogs
) &&
268 base::win::GetVersion() < base::win::VERSION_XP
) {
269 chrome::ShowMessageBox(NULL
,
270 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME
),
271 l10n_util::GetStringUTF16(IDS_UNSUPPORTED_OS_PRE_WIN_XP
),
272 chrome::MESSAGE_BOX_TYPE_WARNING
);
278 void ChromeBrowserMainPartsWin::ShowMissingLocaleMessageBox() {
280 base::ASCIIToUTF16(chrome_browser::kMissingLocaleDataMessage
),
281 base::ASCIIToUTF16(chrome_browser::kMissingLocaleDataTitle
),
282 MB_OK
| MB_ICONERROR
| MB_TOPMOST
);
285 void ChromeBrowserMainPartsWin::PostProfileInit() {
286 ChromeBrowserMainParts::PostProfileInit();
288 // DirectWrite support is mainly available Windows 7 and up.
289 if (gfx::win::ShouldUseDirectWrite()) {
291 profile()->GetPath().AppendASCII(content::kFontCacheSharedSectionName
));
292 // This function will create a read only section if cache file exists
293 // otherwise it will spawn utility process to build cache file, which will
294 // be used during next browser start/postprofileinit.
295 if (!content::LoadFontCache(path
)) {
296 // We delay building of font cache until first startup page loads.
297 // During first renderer start there are lot of things happening
298 // simultaneously some of them are:
299 // - Renderer is going through all font files on the system to create
300 // a font collection.
301 // - Renderer loading up startup URL, accessing HTML/JS File cache,
303 // - Extension initialization.
304 // We delay building of cache mainly to avoid parallel font file
305 // loading along with Renderer. Some systems have significant number of
306 // font files which takes long time to process.
307 // Related information is at http://crbug.com/436195.
308 const int kBuildFontCacheDelaySec
= 30;
309 content::BrowserThread::PostDelayedTask(
310 content::BrowserThread::IO
,
312 base::Bind(ExecuteFontCacheBuildTask
, path
),
313 base::TimeDelta::FromSeconds(kBuildFontCacheDelaySec
));
318 void ChromeBrowserMainPartsWin::PostBrowserStart() {
319 ChromeBrowserMainParts::PostBrowserStart();
321 UMA_HISTOGRAM_BOOLEAN("Windows.Tablet", base::win::IsTabletDevice());
323 // Set up a task to verify installed modules in the current process. Use a
324 // delay to reduce the impact on startup time.
325 content::BrowserThread::GetMessageLoopProxyForThread(
326 content::BrowserThread::UI
)->PostDelayedTask(
328 base::Bind(&VerifyInstallation
),
329 base::TimeDelta::FromSeconds(45));
331 InitializeChromeElf();
334 content::BrowserThread::PostDelayedTask(
335 content::BrowserThread::FILE, FROM_HERE
,
336 base::Bind(&StartFailedKaskoCrashReportWatcher
,
337 base::Unretained(&failed_kasko_crash_report_watcher_
)),
338 base::TimeDelta::FromMinutes(5));
341 #if defined(GOOGLE_CHROME_BUILD)
342 did_run_updater_
.reset(new DidRunUpdater
);
347 void ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
348 const base::CommandLine
& parsed_command_line
) {
349 // Clear this var so child processes don't show the dialog by default.
350 scoped_ptr
<base::Environment
> env(base::Environment::Create());
351 env
->UnSetVar(env_vars::kShowRestart
);
353 // For non-interactive tests we don't restart on crash.
354 if (env
->HasVar(env_vars::kHeadless
))
357 // If the known command-line test options are used we don't create the
358 // environment block which means we don't get the restart dialog.
359 if (parsed_command_line
.HasSwitch(switches::kBrowserCrashTest
) ||
360 parsed_command_line
.HasSwitch(switches::kNoErrorDialogs
))
363 // The encoding we use for the info is "title|context|direction" where
364 // direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
365 // on the current locale.
366 base::string16
dlg_strings(
367 l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE
));
368 dlg_strings
.push_back('|');
369 base::string16
adjusted_string(
370 l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT
));
371 base::i18n::AdjustStringForLocaleDirection(&adjusted_string
);
372 dlg_strings
.append(adjusted_string
);
373 dlg_strings
.push_back('|');
374 dlg_strings
.append(base::ASCIIToUTF16(
375 base::i18n::IsRTL() ? env_vars::kRtlLocale
: env_vars::kLtrLocale
));
377 env
->SetVar(env_vars::kRestartInfo
, base::UTF16ToUTF8(dlg_strings
));
381 void ChromeBrowserMainPartsWin::RegisterApplicationRestart(
382 const base::CommandLine
& parsed_command_line
) {
383 DCHECK(base::win::GetVersion() >= base::win::VERSION_VISTA
);
384 base::ScopedNativeLibrary
library(base::FilePath(L
"kernel32.dll"));
385 // Get the function pointer for RegisterApplicationRestart.
386 RegisterApplicationRestartProc register_application_restart
=
387 reinterpret_cast<RegisterApplicationRestartProc
>(
388 library
.GetFunctionPointer("RegisterApplicationRestart"));
389 if (!register_application_restart
) {
390 LOG(WARNING
) << "Cannot find RegisterApplicationRestart in kernel32.dll";
393 // The Windows Restart Manager expects a string of command line flags only,
394 // without the program.
395 base::CommandLine
command_line(base::CommandLine::NO_PROGRAM
);
396 command_line
.AppendArguments(parsed_command_line
, false);
397 if (!command_line
.HasSwitch(switches::kRestoreLastSession
))
398 command_line
.AppendSwitch(switches::kRestoreLastSession
);
400 // Restart Chrome if the computer is restarted as the result of an update.
401 // This could be extended to handle crashes, hangs, and patches.
402 HRESULT hr
= register_application_restart(
403 command_line
.GetCommandLineString().c_str(),
404 RESTART_NO_CRASH
| RESTART_NO_HANG
| RESTART_NO_PATCH
);
406 if (hr
== E_INVALIDARG
) {
407 LOG(WARNING
) << "Command line too long for RegisterApplicationRestart";
409 NOTREACHED() << "RegisterApplicationRestart failed. hr: " << hr
<<
410 ", command_line: " << command_line
.GetCommandLineString();
416 int ChromeBrowserMainPartsWin::HandleIconsCommands(
417 const base::CommandLine
& parsed_command_line
) {
418 if (parsed_command_line
.HasSwitch(switches::kHideIcons
)) {
419 base::string16 cp_applet
;
420 base::win::Version version
= base::win::GetVersion();
421 if (version
>= base::win::VERSION_VISTA
) {
422 cp_applet
.assign(L
"Programs and Features"); // Windows Vista and later.
423 } else if (version
>= base::win::VERSION_XP
) {
424 cp_applet
.assign(L
"Add/Remove Programs"); // Windows XP.
426 return chrome::RESULT_CODE_UNSUPPORTED_PARAM
; // Not supported
429 const base::string16 msg
=
430 l10n_util::GetStringFUTF16(IDS_HIDE_ICONS_NOT_SUPPORTED
, cp_applet
);
431 const base::string16 caption
= l10n_util::GetStringUTF16(IDS_PRODUCT_NAME
);
432 const UINT flags
= MB_OKCANCEL
| MB_ICONWARNING
| MB_TOPMOST
;
433 if (IDOK
== ui::MessageBox(NULL
, msg
, caption
, flags
))
434 ShellExecute(NULL
, NULL
, L
"appwiz.cpl", NULL
, NULL
, SW_SHOWNORMAL
);
436 // Exit as we are not launching the browser.
437 return content::RESULT_CODE_NORMAL_EXIT
;
439 // We don't hide icons so we shouldn't do anything special to show them
440 return chrome::RESULT_CODE_UNSUPPORTED_PARAM
;
444 bool ChromeBrowserMainPartsWin::CheckMachineLevelInstall() {
445 // TODO(tommi): Check if using the default distribution is always the right
447 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
449 InstallUtil::GetChromeVersion(dist
, true, &version
);
450 if (version
.IsValid()) {
451 base::FilePath exe_path
;
452 PathService::Get(base::DIR_EXE
, &exe_path
);
453 std::wstring exe
= exe_path
.value();
454 base::FilePath
user_exe_path(installer::GetChromeInstallPath(false, dist
));
455 if (base::FilePath::CompareEqualIgnoreCase(exe
, user_exe_path
.value())) {
456 bool is_metro
= base::win::IsMetroProcess();
458 // The dialog cannot be shown in Win8 Metro as doing so hangs Chrome on
459 // an invisible dialog.
460 // TODO (gab): Get rid of this dialog altogether and auto-launch
461 // system-level Chrome instead.
462 const base::string16 text
=
463 l10n_util::GetStringUTF16(IDS_MACHINE_LEVEL_INSTALL_CONFLICT
);
464 const base::string16 caption
=
465 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME
);
466 const UINT flags
= MB_OK
| MB_ICONERROR
| MB_TOPMOST
;
467 ui::MessageBox(NULL
, text
, caption
, flags
);
469 base::CommandLine
uninstall_cmd(
470 InstallUtil::GetChromeUninstallCmd(false, dist
->GetType()));
471 if (!uninstall_cmd
.GetProgram().empty()) {
472 uninstall_cmd
.AppendSwitch(installer::switches::kSelfDestruct
);
473 uninstall_cmd
.AppendSwitch(installer::switches::kForceUninstall
);
474 uninstall_cmd
.AppendSwitch(
475 installer::switches::kDoNotRemoveSharedItems
);
477 // Trigger Active Setup for the system-level Chrome to make sure
478 // per-user shortcuts to the system-level Chrome are created. Skip this
479 // if the system-level Chrome will undergo first run anyway, as Active
480 // Setup is triggered on system-level Chrome's first run.
481 // TODO(gab): Instead of having callers of Active Setup think about
482 // other callers, have Active Setup itself register when it ran and
483 // no-op otherwise (http://crbug.com/346843).
484 if (!first_run::IsChromeFirstRun())
485 uninstall_cmd
.AppendSwitch(installer::switches::kTriggerActiveSetup
);
487 const base::FilePath
setup_exe(uninstall_cmd
.GetProgram());
488 const base::string16
params(uninstall_cmd
.GetArgumentsString());
490 SHELLEXECUTEINFO sei
= { sizeof(sei
) };
491 sei
.fMask
= SEE_MASK_NOASYNC
;
492 sei
.nShow
= SW_SHOWNORMAL
;
493 sei
.lpFile
= setup_exe
.value().c_str();
494 sei
.lpParameters
= params
.c_str();
495 // On Windows 8 SEE_MASK_FLAG_LOG_USAGE is necessary to guarantee we
496 // flip to the Desktop when launching.
498 sei
.fMask
|= SEE_MASK_FLAG_LOG_USAGE
;
500 if (!::ShellExecuteEx(&sei
))
509 base::string16
TranslationDelegate::GetLocalizedString(
510 int installer_string_id
) {
512 switch (installer_string_id
) {
513 // HANDLE_STRING is used by the DO_INSTALLER_STRING_MAPPING macro which is in
514 // the generated header installer_util_strings.h.
515 #define HANDLE_STRING(base_id, chrome_id) \
517 resource_id = chrome_id; \
519 DO_INSTALLER_STRING_MAPPING
525 return l10n_util::GetStringUTF16(resource_id
);
526 return base::string16();
530 void ChromeBrowserMainPartsWin::SetupInstallerUtilStrings() {
531 CR_DEFINE_STATIC_LOCAL(TranslationDelegate
, delegate
, ());
532 installer::SetTranslationDelegate(&delegate
);