Revert of Add button to add new FSP services to Files app. (patchset #8 id:140001...
[chromium-blink-merge.git] / chrome / browser / chrome_browser_main_win.cc
blobce9f4a20ace675ef95d3e5d148e427c429beac0d
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_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"
74 #endif
76 #if defined(KASKO)
77 #include "syzygy/kasko/api/reporter.h"
78 #endif
80 namespace {
82 typedef HRESULT (STDAPICALLTYPE* RegisterApplicationRestartProc)(
83 const wchar_t* command_line,
84 DWORD flags);
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() {
103 int min_font_size;
104 base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE),
105 &min_font_size);
106 return min_font_size;
109 class TranslationDelegate : public installer::TranslationDelegate {
110 public:
111 virtual 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->DisableSandbox();
118 utility_process_host->Send(
119 new ChromeUtilityHostMsg_BuildDirectWriteFontCache(path));
122 #if defined(KASKO)
123 void ObserveFailedCrashReportDirectory(const base::FilePath& path, bool error) {
124 DCHECK(!error);
125 if (error)
126 return;
127 base::FileEnumerator enumerator(path, true, base::FileEnumerator::FILES);
128 for (base::FilePath report_file = enumerator.Next(); !report_file.empty();
129 report_file = enumerator.Next()) {
130 if (report_file.Extension() ==
131 kasko::api::kPermanentFailureMinidumpExtension) {
132 UMA_HISTOGRAM_BOOLEAN("CrashReport.PermanentUploadFailure", true);
134 bool result = base::DeleteFile(report_file, false);
135 DCHECK(result);
139 void StartFailedKaskoCrashReportWatcher(base::FilePathWatcher* watcher) {
140 base::FilePath watcher_data_directory;
141 if (!PathService::Get(chrome::DIR_WATCHER_DATA, &watcher_data_directory)) {
142 NOTREACHED();
143 } else {
144 base::FilePath permanent_failure_directory =
145 watcher_data_directory.Append(kPermanentlyFailedReportsSubdir);
146 if (!watcher->Watch(permanent_failure_directory, true,
147 base::Bind(&ObserveFailedCrashReportDirectory))) {
148 NOTREACHED();
151 // Call it once to observe any files present prior to the Watch() call.
152 ObserveFailedCrashReportDirectory(permanent_failure_directory, false);
155 #endif
157 } // namespace
159 void ShowCloseBrowserFirstMessageBox() {
160 int message_id = IDS_UNINSTALL_CLOSE_APP;
161 if (base::win::GetVersion() >= base::win::VERSION_WIN8 &&
162 (ShellIntegration::GetDefaultBrowser() == ShellIntegration::IS_DEFAULT)) {
163 message_id = IDS_UNINSTALL_CLOSE_APP_IMMERSIVE;
165 chrome::ShowMessageBox(NULL,
166 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
167 l10n_util::GetStringUTF16(message_id),
168 chrome::MESSAGE_BOX_TYPE_WARNING);
171 int DoUninstallTasks(bool chrome_still_running) {
172 // We want to show a warning to user (and exit) if Chrome is already running
173 // *before* we show the uninstall confirmation dialog box. But while the
174 // uninstall confirmation dialog is up, user might start Chrome, so we
175 // check once again after user acknowledges Uninstall dialog.
176 if (chrome_still_running) {
177 ShowCloseBrowserFirstMessageBox();
178 return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE;
180 int result = chrome::ShowUninstallBrowserPrompt();
181 if (browser_util::IsBrowserAlreadyRunning()) {
182 ShowCloseBrowserFirstMessageBox();
183 return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE;
186 if (result != chrome::RESULT_CODE_UNINSTALL_USER_CANCEL) {
187 // The following actions are just best effort.
188 // TODO(gab): Look into removing this code which is now redundant with the
189 // work done by setup.exe on uninstall.
190 VLOG(1) << "Executing uninstall actions";
191 base::FilePath chrome_exe;
192 if (PathService::Get(base::FILE_EXE, &chrome_exe)) {
193 ShellUtil::ShortcutLocation user_shortcut_locations[] = {
194 ShellUtil::SHORTCUT_LOCATION_DESKTOP,
195 ShellUtil::SHORTCUT_LOCATION_QUICK_LAUNCH,
196 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_DIR,
197 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR,
199 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
200 for (size_t i = 0; i < arraysize(user_shortcut_locations); ++i) {
201 if (!ShellUtil::RemoveShortcuts(user_shortcut_locations[i], dist,
202 ShellUtil::CURRENT_USER, chrome_exe)) {
203 VLOG(1) << "Failed to delete shortcut at location "
204 << user_shortcut_locations[i];
207 } else {
208 NOTREACHED();
211 return result;
214 // ChromeBrowserMainPartsWin ---------------------------------------------------
216 ChromeBrowserMainPartsWin::ChromeBrowserMainPartsWin(
217 const content::MainFunctionParams& parameters)
218 : ChromeBrowserMainParts(parameters) {
219 if (base::win::IsMetroProcess()) {
220 typedef const wchar_t* (*GetMetroSwitches)(void);
221 GetMetroSwitches metro_switches_proc = reinterpret_cast<GetMetroSwitches>(
222 GetProcAddress(base::win::GetMetroModule(),
223 "GetMetroCommandLineSwitches"));
224 if (metro_switches_proc) {
225 base::string16 metro_switches = (*metro_switches_proc)();
226 if (!metro_switches.empty()) {
227 base::CommandLine extra_switches(base::CommandLine::NO_PROGRAM);
228 extra_switches.ParseFromString(metro_switches);
229 base::CommandLine::ForCurrentProcess()->AppendArguments(extra_switches,
230 false);
236 ChromeBrowserMainPartsWin::~ChromeBrowserMainPartsWin() {
239 void ChromeBrowserMainPartsWin::ToolkitInitialized() {
240 ChromeBrowserMainParts::ToolkitInitialized();
241 gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;
242 gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;
243 ui::CursorLoaderWin::SetCursorResourceModule(chrome::kBrowserResourcesDll);
246 void ChromeBrowserMainPartsWin::PreMainMessageLoopStart() {
247 // installer_util references strings that are normally compiled into
248 // setup.exe. In Chrome, these strings are in the locale files.
249 SetupInstallerUtilStrings();
251 ChromeBrowserMainParts::PreMainMessageLoopStart();
252 if (!parameters().ui_task) {
253 // Make sure that we know how to handle exceptions from the message loop.
254 InitializeWindowProcExceptions();
257 // Prime the parental controls cache on Windows.
258 ignore_result(IncognitoModePrefs::ArePlatformParentalControlsEnabled());
261 int ChromeBrowserMainPartsWin::PreCreateThreads() {
262 int rv = ChromeBrowserMainParts::PreCreateThreads();
264 // TODO(viettrungluu): why don't we run this earlier?
265 if (!parsed_command_line().HasSwitch(switches::kNoErrorDialogs) &&
266 base::win::GetVersion() < base::win::VERSION_XP) {
267 chrome::ShowMessageBox(NULL,
268 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
269 l10n_util::GetStringUTF16(IDS_UNSUPPORTED_OS_PRE_WIN_XP),
270 chrome::MESSAGE_BOX_TYPE_WARNING);
273 return rv;
276 void ChromeBrowserMainPartsWin::ShowMissingLocaleMessageBox() {
277 ui::MessageBox(NULL,
278 base::ASCIIToUTF16(chrome_browser::kMissingLocaleDataMessage),
279 base::ASCIIToUTF16(chrome_browser::kMissingLocaleDataTitle),
280 MB_OK | MB_ICONERROR | MB_TOPMOST);
283 void ChromeBrowserMainPartsWin::PostProfileInit() {
284 ChromeBrowserMainParts::PostProfileInit();
286 // DirectWrite support is mainly available Windows 7 and up.
287 if (gfx::win::ShouldUseDirectWrite()) {
288 base::FilePath path(
289 profile()->GetPath().AppendASCII(content::kFontCacheSharedSectionName));
290 // This function will create a read only section if cache file exists
291 // otherwise it will spawn utility process to build cache file, which will
292 // be used during next browser start/postprofileinit.
293 if (!content::LoadFontCache(path)) {
294 // We delay building of font cache until first startup page loads.
295 // During first renderer start there are lot of things happening
296 // simultaneously some of them are:
297 // - Renderer is going through all font files on the system to create
298 // a font collection.
299 // - Renderer loading up startup URL, accessing HTML/JS File cache,
300 // net activity etc.
301 // - Extension initialization.
302 // We delay building of cache mainly to avoid parallel font file
303 // loading along with Renderer. Some systems have significant number of
304 // font files which takes long time to process.
305 // Related information is at http://crbug.com/436195.
306 const int kBuildFontCacheDelaySec = 30;
307 content::BrowserThread::PostDelayedTask(
308 content::BrowserThread::IO,
309 FROM_HERE,
310 base::Bind(ExecuteFontCacheBuildTask, path),
311 base::TimeDelta::FromSeconds(kBuildFontCacheDelaySec));
316 void ChromeBrowserMainPartsWin::PostBrowserStart() {
317 ChromeBrowserMainParts::PostBrowserStart();
319 UMA_HISTOGRAM_BOOLEAN("Windows.Tablet", base::win::IsTabletDevice());
321 // Set up a task to verify installed modules in the current process. Use a
322 // delay to reduce the impact on startup time.
323 content::BrowserThread::GetMessageLoopProxyForThread(
324 content::BrowserThread::UI)->PostDelayedTask(
325 FROM_HERE,
326 base::Bind(&VerifyInstallation),
327 base::TimeDelta::FromSeconds(45));
329 InitializeChromeElf();
331 #if defined(KASKO)
332 content::BrowserThread::PostDelayedTask(
333 content::BrowserThread::FILE, FROM_HERE,
334 base::Bind(&StartFailedKaskoCrashReportWatcher,
335 base::Unretained(&failed_kasko_crash_report_watcher_)),
336 base::TimeDelta::FromMinutes(5));
337 #endif
339 #if defined(GOOGLE_CHROME_BUILD)
340 did_run_updater_.reset(new DidRunUpdater);
341 #endif
344 // static
345 void ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
346 const base::CommandLine& parsed_command_line) {
347 // Clear this var so child processes don't show the dialog by default.
348 scoped_ptr<base::Environment> env(base::Environment::Create());
349 env->UnSetVar(env_vars::kShowRestart);
351 // For non-interactive tests we don't restart on crash.
352 if (env->HasVar(env_vars::kHeadless))
353 return;
355 // If the known command-line test options are used we don't create the
356 // environment block which means we don't get the restart dialog.
357 if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) ||
358 parsed_command_line.HasSwitch(switches::kNoErrorDialogs))
359 return;
361 // The encoding we use for the info is "title|context|direction" where
362 // direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
363 // on the current locale.
364 base::string16 dlg_strings(l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE));
365 dlg_strings.push_back('|');
366 base::string16 adjusted_string(
367 l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT));
368 base::i18n::AdjustStringForLocaleDirection(&adjusted_string);
369 dlg_strings.append(adjusted_string);
370 dlg_strings.push_back('|');
371 dlg_strings.append(base::ASCIIToUTF16(
372 base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale));
374 env->SetVar(env_vars::kRestartInfo, base::UTF16ToUTF8(dlg_strings));
377 // static
378 void ChromeBrowserMainPartsWin::RegisterApplicationRestart(
379 const base::CommandLine& parsed_command_line) {
380 DCHECK(base::win::GetVersion() >= base::win::VERSION_VISTA);
381 base::ScopedNativeLibrary library(base::FilePath(L"kernel32.dll"));
382 // Get the function pointer for RegisterApplicationRestart.
383 RegisterApplicationRestartProc register_application_restart =
384 reinterpret_cast<RegisterApplicationRestartProc>(
385 library.GetFunctionPointer("RegisterApplicationRestart"));
386 if (!register_application_restart) {
387 LOG(WARNING) << "Cannot find RegisterApplicationRestart in kernel32.dll";
388 return;
390 // The Windows Restart Manager expects a string of command line flags only,
391 // without the program.
392 base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
393 command_line.AppendArguments(parsed_command_line, false);
394 if (!command_line.HasSwitch(switches::kRestoreLastSession))
395 command_line.AppendSwitch(switches::kRestoreLastSession);
397 // Restart Chrome if the computer is restarted as the result of an update.
398 // This could be extended to handle crashes, hangs, and patches.
399 HRESULT hr = register_application_restart(
400 command_line.GetCommandLineString().c_str(),
401 RESTART_NO_CRASH | RESTART_NO_HANG | RESTART_NO_PATCH);
402 if (FAILED(hr)) {
403 if (hr == E_INVALIDARG) {
404 LOG(WARNING) << "Command line too long for RegisterApplicationRestart";
405 } else {
406 NOTREACHED() << "RegisterApplicationRestart failed. hr: " << hr <<
407 ", command_line: " << command_line.GetCommandLineString();
412 // static
413 int ChromeBrowserMainPartsWin::HandleIconsCommands(
414 const base::CommandLine& parsed_command_line) {
415 if (parsed_command_line.HasSwitch(switches::kHideIcons)) {
416 base::string16 cp_applet;
417 base::win::Version version = base::win::GetVersion();
418 if (version >= base::win::VERSION_VISTA) {
419 cp_applet.assign(L"Programs and Features"); // Windows Vista and later.
420 } else if (version >= base::win::VERSION_XP) {
421 cp_applet.assign(L"Add/Remove Programs"); // Windows XP.
422 } else {
423 return chrome::RESULT_CODE_UNSUPPORTED_PARAM; // Not supported
426 const base::string16 msg =
427 l10n_util::GetStringFUTF16(IDS_HIDE_ICONS_NOT_SUPPORTED, cp_applet);
428 const base::string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
429 const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST;
430 if (IDOK == ui::MessageBox(NULL, msg, caption, flags))
431 ShellExecute(NULL, NULL, L"appwiz.cpl", NULL, NULL, SW_SHOWNORMAL);
433 // Exit as we are not launching the browser.
434 return content::RESULT_CODE_NORMAL_EXIT;
436 // We don't hide icons so we shouldn't do anything special to show them
437 return chrome::RESULT_CODE_UNSUPPORTED_PARAM;
440 // static
441 bool ChromeBrowserMainPartsWin::CheckMachineLevelInstall() {
442 // TODO(tommi): Check if using the default distribution is always the right
443 // thing to do.
444 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
445 Version version;
446 InstallUtil::GetChromeVersion(dist, true, &version);
447 if (version.IsValid()) {
448 base::FilePath exe_path;
449 PathService::Get(base::DIR_EXE, &exe_path);
450 std::wstring exe = exe_path.value();
451 base::FilePath user_exe_path(installer::GetChromeInstallPath(false, dist));
452 if (base::FilePath::CompareEqualIgnoreCase(exe, user_exe_path.value())) {
453 bool is_metro = base::win::IsMetroProcess();
454 if (!is_metro) {
455 // The dialog cannot be shown in Win8 Metro as doing so hangs Chrome on
456 // an invisible dialog.
457 // TODO (gab): Get rid of this dialog altogether and auto-launch
458 // system-level Chrome instead.
459 const base::string16 text =
460 l10n_util::GetStringUTF16(IDS_MACHINE_LEVEL_INSTALL_CONFLICT);
461 const base::string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
462 const UINT flags = MB_OK | MB_ICONERROR | MB_TOPMOST;
463 ui::MessageBox(NULL, text, caption, flags);
465 base::CommandLine uninstall_cmd(
466 InstallUtil::GetChromeUninstallCmd(false, dist->GetType()));
467 if (!uninstall_cmd.GetProgram().empty()) {
468 uninstall_cmd.AppendSwitch(installer::switches::kSelfDestruct);
469 uninstall_cmd.AppendSwitch(installer::switches::kForceUninstall);
470 uninstall_cmd.AppendSwitch(
471 installer::switches::kDoNotRemoveSharedItems);
473 // Trigger Active Setup for the system-level Chrome to make sure
474 // per-user shortcuts to the system-level Chrome are created. Skip this
475 // if the system-level Chrome will undergo first run anyway, as Active
476 // Setup is triggered on system-level Chrome's first run.
477 // TODO(gab): Instead of having callers of Active Setup think about
478 // other callers, have Active Setup itself register when it ran and
479 // no-op otherwise (http://crbug.com/346843).
480 if (!first_run::IsChromeFirstRun())
481 uninstall_cmd.AppendSwitch(installer::switches::kTriggerActiveSetup);
483 const base::FilePath setup_exe(uninstall_cmd.GetProgram());
484 const base::string16 params(uninstall_cmd.GetArgumentsString());
486 SHELLEXECUTEINFO sei = { sizeof(sei) };
487 sei.fMask = SEE_MASK_NOASYNC;
488 sei.nShow = SW_SHOWNORMAL;
489 sei.lpFile = setup_exe.value().c_str();
490 sei.lpParameters = params.c_str();
491 // On Windows 8 SEE_MASK_FLAG_LOG_USAGE is necessary to guarantee we
492 // flip to the Desktop when launching.
493 if (is_metro)
494 sei.fMask |= SEE_MASK_FLAG_LOG_USAGE;
496 if (!::ShellExecuteEx(&sei))
497 DPCHECK(false);
499 return true;
502 return false;
505 base::string16 TranslationDelegate::GetLocalizedString(
506 int installer_string_id) {
507 int resource_id = 0;
508 switch (installer_string_id) {
509 // HANDLE_STRING is used by the DO_INSTALLER_STRING_MAPPING macro which is in
510 // the generated header installer_util_strings.h.
511 #define HANDLE_STRING(base_id, chrome_id) \
512 case base_id: \
513 resource_id = chrome_id; \
514 break;
515 DO_INSTALLER_STRING_MAPPING
516 #undef HANDLE_STRING
517 default:
518 NOTREACHED();
520 if (resource_id)
521 return l10n_util::GetStringUTF16(resource_id);
522 return base::string16();
525 // static
526 void ChromeBrowserMainPartsWin::SetupInstallerUtilStrings() {
527 CR_DEFINE_STATIC_LOCAL(TranslationDelegate, delegate, ());
528 installer::SetTranslationDelegate(&delegate);