NaCl: Update revision in DEPS, r12770 -> r12773
[chromium-blink-merge.git] / chrome / browser / shell_integration_win.cc
blob3b8ac546e1e9d44256803a56a8d9113497b7a2f8
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/shell_integration.h"
7 #include <windows.h>
8 #include <shobjidl.h>
9 #include <propkey.h>
11 #include "base/bind.h"
12 #include "base/command_line.h"
13 #include "base/file_util.h"
14 #include "base/files/file_enumerator.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/path_service.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/win/registry.h"
22 #include "base/win/scoped_comptr.h"
23 #include "base/win/scoped_propvariant.h"
24 #include "base/win/shortcut.h"
25 #include "base/win/windows_version.h"
26 #include "chrome/browser/policy/policy_path_parser.h"
27 #include "chrome/browser/web_applications/web_app.h"
28 #include "chrome/common/chrome_constants.h"
29 #include "chrome/common/chrome_paths_internal.h"
30 #include "chrome/common/chrome_switches.h"
31 #include "chrome/installer/setup/setup_util.h"
32 #include "chrome/installer/util/browser_distribution.h"
33 #include "chrome/installer/util/create_reg_key_work_item.h"
34 #include "chrome/installer/util/install_util.h"
35 #include "chrome/installer/util/set_reg_value_work_item.h"
36 #include "chrome/installer/util/shell_util.h"
37 #include "chrome/installer/util/util_constants.h"
38 #include "chrome/installer/util/work_item.h"
39 #include "chrome/installer/util/work_item_list.h"
40 #include "content/public/browser/browser_thread.h"
42 using content::BrowserThread;
44 namespace {
46 const wchar_t kAppListAppNameSuffix[] = L"AppList";
48 // Helper function for ShellIntegration::GetAppId to generates profile id
49 // from profile path. "profile_id" is composed of sanitized basenames of
50 // user data dir and profile dir joined by a ".".
51 base::string16 GetProfileIdFromPath(const base::FilePath& profile_path) {
52 // Return empty string if profile_path is empty
53 if (profile_path.empty())
54 return base::string16();
56 base::FilePath default_user_data_dir;
57 // Return empty string if profile_path is in default user data
58 // dir and is the default profile.
59 if (chrome::GetDefaultUserDataDirectory(&default_user_data_dir) &&
60 profile_path.DirName() == default_user_data_dir &&
61 profile_path.BaseName().value() ==
62 base::ASCIIToUTF16(chrome::kInitialProfile)) {
63 return base::string16();
66 // Get joined basenames of user data dir and profile.
67 base::string16 basenames = profile_path.DirName().BaseName().value() +
68 L"." + profile_path.BaseName().value();
70 base::string16 profile_id;
71 profile_id.reserve(basenames.size());
73 // Generate profile_id from sanitized basenames.
74 for (size_t i = 0; i < basenames.length(); ++i) {
75 if (IsAsciiAlpha(basenames[i]) ||
76 IsAsciiDigit(basenames[i]) ||
77 basenames[i] == L'.')
78 profile_id += basenames[i];
81 return profile_id;
84 base::string16 GetAppListAppName() {
85 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
86 base::string16 app_name(dist->GetBaseAppId());
87 app_name.append(kAppListAppNameSuffix);
88 return app_name;
91 // Gets expected app id for given Chrome (based on |command_line| and
92 // |is_per_user_install|).
93 base::string16 GetExpectedAppId(const CommandLine& command_line,
94 bool is_per_user_install) {
95 base::FilePath user_data_dir;
96 if (command_line.HasSwitch(switches::kUserDataDir))
97 user_data_dir = command_line.GetSwitchValuePath(switches::kUserDataDir);
98 else
99 chrome::GetDefaultUserDataDirectory(&user_data_dir);
100 // Adjust with any policy that overrides any other way to set the path.
101 policy::path_parser::CheckUserDataDirPolicy(&user_data_dir);
102 DCHECK(!user_data_dir.empty());
104 base::FilePath profile_subdir;
105 if (command_line.HasSwitch(switches::kProfileDirectory)) {
106 profile_subdir =
107 command_line.GetSwitchValuePath(switches::kProfileDirectory);
108 } else {
109 profile_subdir =
110 base::FilePath(base::ASCIIToUTF16(chrome::kInitialProfile));
112 DCHECK(!profile_subdir.empty());
114 base::FilePath profile_path = user_data_dir.Append(profile_subdir);
115 base::string16 app_name;
116 if (command_line.HasSwitch(switches::kApp)) {
117 app_name = base::UTF8ToUTF16(web_app::GenerateApplicationNameFromURL(
118 GURL(command_line.GetSwitchValueASCII(switches::kApp))));
119 } else if (command_line.HasSwitch(switches::kAppId)) {
120 app_name = base::UTF8ToUTF16(
121 web_app::GenerateApplicationNameFromExtensionId(
122 command_line.GetSwitchValueASCII(switches::kAppId)));
123 } else if (command_line.HasSwitch(switches::kShowAppList)) {
124 app_name = GetAppListAppName();
125 } else {
126 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
127 app_name = ShellUtil::GetBrowserModelId(dist, is_per_user_install);
129 DCHECK(!app_name.empty());
131 return ShellIntegration::GetAppModelIdForProfile(app_name, profile_path);
134 void MigrateChromiumShortcutsCallback() {
135 // This should run on the file thread.
136 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
138 // Get full path of chrome.
139 base::FilePath chrome_exe;
140 if (!PathService::Get(base::FILE_EXE, &chrome_exe))
141 return;
143 // Locations to check for shortcuts migration.
144 static const struct {
145 int location_id;
146 const wchar_t* sub_dir;
147 } kLocations[] = {
149 base::DIR_TASKBAR_PINS,
150 NULL
151 }, {
152 base::DIR_USER_DESKTOP,
153 NULL
154 }, {
155 base::DIR_START_MENU,
156 NULL
157 }, {
158 base::DIR_APP_DATA,
159 L"Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\StartMenu"
163 for (int i = 0; i < arraysize(kLocations); ++i) {
164 base::FilePath path;
165 if (!PathService::Get(kLocations[i].location_id, &path)) {
166 NOTREACHED();
167 continue;
170 if (kLocations[i].sub_dir)
171 path = path.Append(kLocations[i].sub_dir);
173 bool check_dual_mode = (kLocations[i].location_id == base::DIR_START_MENU);
174 ShellIntegration::MigrateShortcutsInPathInternal(chrome_exe, path,
175 check_dual_mode);
179 ShellIntegration::DefaultWebClientState
180 GetDefaultWebClientStateFromShellUtilDefaultState(
181 ShellUtil::DefaultState default_state) {
182 switch (default_state) {
183 case ShellUtil::NOT_DEFAULT:
184 return ShellIntegration::NOT_DEFAULT;
185 case ShellUtil::IS_DEFAULT:
186 return ShellIntegration::IS_DEFAULT;
187 default:
188 DCHECK_EQ(ShellUtil::UNKNOWN_DEFAULT, default_state);
189 return ShellIntegration::UNKNOWN_DEFAULT;
193 } // namespace
195 ShellIntegration::DefaultWebClientSetPermission
196 ShellIntegration::CanSetAsDefaultBrowser() {
197 BrowserDistribution* distribution = BrowserDistribution::GetDistribution();
198 if (distribution->GetDefaultBrowserControlPolicy() !=
199 BrowserDistribution::DEFAULT_BROWSER_FULL_CONTROL)
200 return SET_DEFAULT_NOT_ALLOWED;
202 if (ShellUtil::CanMakeChromeDefaultUnattended())
203 return SET_DEFAULT_UNATTENDED;
204 else
205 return SET_DEFAULT_INTERACTIVE;
208 bool ShellIntegration::SetAsDefaultBrowser() {
209 base::FilePath chrome_exe;
210 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
211 LOG(ERROR) << "Error getting app exe path";
212 return false;
215 // From UI currently we only allow setting default browser for current user.
216 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
217 if (!ShellUtil::MakeChromeDefault(dist, ShellUtil::CURRENT_USER,
218 chrome_exe.value(), true)) {
219 LOG(ERROR) << "Chrome could not be set as default browser.";
220 return false;
223 VLOG(1) << "Chrome registered as default browser.";
224 return true;
227 bool ShellIntegration::SetAsDefaultProtocolClient(const std::string& protocol) {
228 if (protocol.empty())
229 return false;
231 base::FilePath chrome_exe;
232 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
233 LOG(ERROR) << "Error getting app exe path";
234 return false;
237 base::string16 wprotocol(base::UTF8ToUTF16(protocol));
238 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
239 if (!ShellUtil::MakeChromeDefaultProtocolClient(dist, chrome_exe.value(),
240 wprotocol)) {
241 LOG(ERROR) << "Chrome could not be set as default handler for "
242 << protocol << ".";
243 return false;
246 VLOG(1) << "Chrome registered as default handler for " << protocol << ".";
247 return true;
250 bool ShellIntegration::SetAsDefaultBrowserInteractive() {
251 base::FilePath chrome_exe;
252 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
253 NOTREACHED() << "Error getting app exe path";
254 return false;
257 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
258 if (!ShellUtil::ShowMakeChromeDefaultSystemUI(dist, chrome_exe.value())) {
259 LOG(ERROR) << "Failed to launch the set-default-browser Windows UI.";
260 return false;
263 VLOG(1) << "Set-default-browser Windows UI completed.";
264 return true;
267 bool ShellIntegration::SetAsDefaultProtocolClientInteractive(
268 const std::string& protocol) {
269 base::FilePath chrome_exe;
270 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
271 NOTREACHED() << "Error getting app exe path";
272 return false;
275 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
276 base::string16 wprotocol(base::UTF8ToUTF16(protocol));
277 if (!ShellUtil::ShowMakeChromeDefaultProtocolClientSystemUI(
278 dist, chrome_exe.value(), wprotocol)) {
279 LOG(ERROR) << "Failed to launch the set-default-client Windows UI.";
280 return false;
283 VLOG(1) << "Set-default-client Windows UI completed.";
284 return true;
287 ShellIntegration::DefaultWebClientState ShellIntegration::GetDefaultBrowser() {
288 return GetDefaultWebClientStateFromShellUtilDefaultState(
289 ShellUtil::GetChromeDefaultState());
292 ShellIntegration::DefaultWebClientState
293 ShellIntegration::IsDefaultProtocolClient(const std::string& protocol) {
294 return GetDefaultWebClientStateFromShellUtilDefaultState(
295 ShellUtil::GetChromeDefaultProtocolClientState(
296 base::UTF8ToUTF16(protocol)));
299 base::string16 ShellIntegration::GetApplicationForProtocol(const GURL& url) {
300 std::wstring url_spec = base::ASCIIToWide(url.possibly_invalid_spec());
301 std::wstring cmd_key_path =
302 base::ASCIIToWide(url.scheme() + "\\shell\\open\\command");
303 base::win::RegKey cmd_key(HKEY_CLASSES_ROOT, cmd_key_path.c_str(), KEY_READ);
304 size_t split_offset = url_spec.find(L':');
305 if (split_offset == std::wstring::npos)
306 return std::wstring();
307 std::wstring parameters = url_spec.substr(split_offset + 1,
308 url_spec.length() - 1);
309 std::wstring application_to_launch;
310 if (cmd_key.ReadValue(NULL, &application_to_launch) == ERROR_SUCCESS) {
311 ReplaceSubstringsAfterOffset(&application_to_launch, 0, L"%1", parameters);
312 return application_to_launch;
315 return std::wstring();
318 // There is no reliable way to say which browser is default on a machine (each
319 // browser can have some of the protocols/shortcuts). So we look for only HTTP
320 // protocol handler. Even this handler is located at different places in
321 // registry on XP and Vista:
322 // - HKCR\http\shell\open\command (XP)
323 // - HKCU\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\
324 // http\UserChoice (Vista)
325 // This method checks if Firefox is defualt browser by checking these
326 // locations and returns true if Firefox traces are found there. In case of
327 // error (or if Firefox is not found)it returns the default value which
328 // is false.
329 bool ShellIntegration::IsFirefoxDefaultBrowser() {
330 bool ff_default = false;
331 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
332 base::string16 app_cmd;
333 base::win::RegKey key(HKEY_CURRENT_USER,
334 ShellUtil::kRegVistaUrlPrefs, KEY_READ);
335 if (key.Valid() && (key.ReadValue(L"Progid", &app_cmd) == ERROR_SUCCESS) &&
336 app_cmd == L"FirefoxURL")
337 ff_default = true;
338 } else {
339 base::string16 key_path(L"http");
340 key_path.append(ShellUtil::kRegShellOpen);
341 base::win::RegKey key(HKEY_CLASSES_ROOT, key_path.c_str(), KEY_READ);
342 base::string16 app_cmd;
343 if (key.Valid() && (key.ReadValue(L"", &app_cmd) == ERROR_SUCCESS) &&
344 base::string16::npos != StringToLowerASCII(app_cmd).find(L"firefox"))
345 ff_default = true;
347 return ff_default;
350 base::string16 ShellIntegration::GetAppModelIdForProfile(
351 const base::string16& app_name,
352 const base::FilePath& profile_path) {
353 std::vector<base::string16> components;
354 components.push_back(app_name);
355 const base::string16 profile_id(GetProfileIdFromPath(profile_path));
356 if (!profile_id.empty())
357 components.push_back(profile_id);
358 return ShellUtil::BuildAppModelId(components);
361 base::string16 ShellIntegration::GetChromiumModelIdForProfile(
362 const base::FilePath& profile_path) {
363 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
364 base::FilePath chrome_exe;
365 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
366 NOTREACHED();
367 return dist->GetBaseAppId();
369 return GetAppModelIdForProfile(
370 ShellUtil::GetBrowserModelId(
371 dist, InstallUtil::IsPerUserInstall(chrome_exe.value().c_str())),
372 profile_path);
375 base::string16 ShellIntegration::GetAppListAppModelIdForProfile(
376 const base::FilePath& profile_path) {
377 return ShellIntegration::GetAppModelIdForProfile(
378 GetAppListAppName(), profile_path);
381 void ShellIntegration::MigrateChromiumShortcuts() {
382 if (base::win::GetVersion() < base::win::VERSION_WIN7)
383 return;
385 // This needs to happen eventually (e.g. so that the appid is fixed and the
386 // run-time Chrome icon is merged with the taskbar shortcut), but this is not
387 // urgent and shouldn't delay Chrome startup.
388 static const int64 kMigrateChromiumShortcutsDelaySeconds = 15;
389 BrowserThread::PostDelayedTask(
390 BrowserThread::FILE, FROM_HERE,
391 base::Bind(&MigrateChromiumShortcutsCallback),
392 base::TimeDelta::FromSeconds(kMigrateChromiumShortcutsDelaySeconds));
395 int ShellIntegration::MigrateShortcutsInPathInternal(
396 const base::FilePath& chrome_exe,
397 const base::FilePath& path,
398 bool check_dual_mode) {
399 DCHECK(base::win::GetVersion() >= base::win::VERSION_WIN7);
401 // Enumerate all pinned shortcuts in the given path directly.
402 base::FileEnumerator shortcuts_enum(
403 path, false, // not recursive
404 base::FileEnumerator::FILES, FILE_PATH_LITERAL("*.lnk"));
406 bool is_per_user_install =
407 InstallUtil::IsPerUserInstall(chrome_exe.value().c_str());
409 int shortcuts_migrated = 0;
410 base::FilePath target_path;
411 base::string16 arguments;
412 base::win::ScopedPropVariant propvariant;
413 for (base::FilePath shortcut = shortcuts_enum.Next(); !shortcut.empty();
414 shortcut = shortcuts_enum.Next()) {
415 // TODO(gab): Use ProgramCompare instead of comparing FilePaths below once
416 // it is fixed to work with FilePaths with spaces.
417 if (!base::win::ResolveShortcut(shortcut, &target_path, &arguments) ||
418 chrome_exe != target_path) {
419 continue;
421 CommandLine command_line(CommandLine::FromString(base::StringPrintf(
422 L"\"%ls\" %ls", target_path.value().c_str(), arguments.c_str())));
424 // Get the expected AppId for this Chrome shortcut.
425 base::string16 expected_app_id(
426 GetExpectedAppId(command_line, is_per_user_install));
427 if (expected_app_id.empty())
428 continue;
430 // Load the shortcut.
431 base::win::ScopedComPtr<IShellLink> shell_link;
432 base::win::ScopedComPtr<IPersistFile> persist_file;
433 if (FAILED(shell_link.CreateInstance(CLSID_ShellLink, NULL,
434 CLSCTX_INPROC_SERVER)) ||
435 FAILED(persist_file.QueryFrom(shell_link)) ||
436 FAILED(persist_file->Load(shortcut.value().c_str(), STGM_READ))) {
437 DLOG(WARNING) << "Failed loading shortcut at " << shortcut.value();
438 continue;
441 // Any properties that need to be updated on the shortcut will be stored in
442 // |updated_properties|.
443 base::win::ShortcutProperties updated_properties;
445 // Validate the existing app id for the shortcut.
446 base::win::ScopedComPtr<IPropertyStore> property_store;
447 propvariant.Reset();
448 if (FAILED(property_store.QueryFrom(shell_link)) ||
449 property_store->GetValue(PKEY_AppUserModel_ID,
450 propvariant.Receive()) != S_OK) {
451 // When in doubt, prefer not updating the shortcut.
452 NOTREACHED();
453 continue;
454 } else {
455 switch (propvariant.get().vt) {
456 case VT_EMPTY:
457 // If there is no app_id set, set our app_id if one is expected.
458 if (!expected_app_id.empty())
459 updated_properties.set_app_id(expected_app_id);
460 break;
461 case VT_LPWSTR:
462 if (expected_app_id != base::string16(propvariant.get().pwszVal))
463 updated_properties.set_app_id(expected_app_id);
464 break;
465 default:
466 NOTREACHED();
467 continue;
471 // Only set dual mode if the expected app id is the default app id.
472 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
473 base::string16 default_chromium_model_id(
474 ShellUtil::GetBrowserModelId(dist, is_per_user_install));
475 if (check_dual_mode && expected_app_id == default_chromium_model_id) {
476 propvariant.Reset();
477 if (property_store->GetValue(PKEY_AppUserModel_IsDualMode,
478 propvariant.Receive()) != S_OK) {
479 // When in doubt, prefer to not update the shortcut.
480 NOTREACHED();
481 continue;
482 } else {
483 switch (propvariant.get().vt) {
484 case VT_EMPTY:
485 // If dual_mode is not set at all, make sure it gets set to true.
486 updated_properties.set_dual_mode(true);
487 break;
488 case VT_BOOL:
489 // If it is set to false, make sure it gets set to true as well.
490 if (!propvariant.get().boolVal)
491 updated_properties.set_dual_mode(true);
492 break;
493 default:
494 NOTREACHED();
495 continue;
500 persist_file.Release();
501 shell_link.Release();
503 // Update the shortcut if some of its properties need to be updated.
504 if (updated_properties.options &&
505 base::win::CreateOrUpdateShortcutLink(
506 shortcut, updated_properties,
507 base::win::SHORTCUT_UPDATE_EXISTING)) {
508 ++shortcuts_migrated;
511 return shortcuts_migrated;
514 base::FilePath ShellIntegration::GetStartMenuShortcut(
515 const base::FilePath& chrome_exe) {
516 static const int kFolderIds[] = {
517 base::DIR_COMMON_START_MENU,
518 base::DIR_START_MENU,
520 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
521 base::string16 shortcut_name(
522 dist->GetShortcutName(BrowserDistribution::SHORTCUT_CHROME));
523 base::FilePath shortcut;
525 // Check both the common and the per-user Start Menu folders for system-level
526 // installs.
527 size_t folder =
528 InstallUtil::IsPerUserInstall(chrome_exe.value().c_str()) ? 1 : 0;
529 for (; folder < arraysize(kFolderIds); ++folder) {
530 if (!PathService::Get(kFolderIds[folder], &shortcut)) {
531 NOTREACHED();
532 continue;
535 shortcut = shortcut.Append(shortcut_name).Append(shortcut_name +
536 installer::kLnkExt);
537 if (base::PathExists(shortcut))
538 return shortcut;
541 return base::FilePath();