SkBitmap::Config is deprecated, use SkColorType instead
[chromium-blink-merge.git] / chrome / browser / shell_integration_win.cc
blob137823b795e9bde44a48c41d6dc5242652394233
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 <shlwapi.h>
9 #include <shobjidl.h>
10 #include <propkey.h>
12 #include "base/bind.h"
13 #include "base/command_line.h"
14 #include "base/file_util.h"
15 #include "base/files/file_enumerator.h"
16 #include "base/message_loop/message_loop.h"
17 #include "base/path_service.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/win/registry.h"
23 #include "base/win/scoped_comptr.h"
24 #include "base/win/scoped_propvariant.h"
25 #include "base/win/shortcut.h"
26 #include "base/win/windows_version.h"
27 #include "chrome/browser/policy/policy_path_parser.h"
28 #include "chrome/browser/web_applications/web_app.h"
29 #include "chrome/common/chrome_constants.h"
30 #include "chrome/common/chrome_paths_internal.h"
31 #include "chrome/common/chrome_switches.h"
32 #include "chrome/installer/setup/setup_util.h"
33 #include "chrome/installer/util/browser_distribution.h"
34 #include "chrome/installer/util/create_reg_key_work_item.h"
35 #include "chrome/installer/util/install_util.h"
36 #include "chrome/installer/util/set_reg_value_work_item.h"
37 #include "chrome/installer/util/shell_util.h"
38 #include "chrome/installer/util/util_constants.h"
39 #include "chrome/installer/util/work_item.h"
40 #include "chrome/installer/util/work_item_list.h"
41 #include "content/public/browser/browser_thread.h"
43 using content::BrowserThread;
45 namespace {
47 const wchar_t kAppListAppNameSuffix[] = L"AppList";
49 // Helper function for ShellIntegration::GetAppId to generates profile id
50 // from profile path. "profile_id" is composed of sanitized basenames of
51 // user data dir and profile dir joined by a ".".
52 base::string16 GetProfileIdFromPath(const base::FilePath& profile_path) {
53 // Return empty string if profile_path is empty
54 if (profile_path.empty())
55 return base::string16();
57 base::FilePath default_user_data_dir;
58 // Return empty string if profile_path is in default user data
59 // dir and is the default profile.
60 if (chrome::GetDefaultUserDataDirectory(&default_user_data_dir) &&
61 profile_path.DirName() == default_user_data_dir &&
62 profile_path.BaseName().value() ==
63 base::ASCIIToUTF16(chrome::kInitialProfile)) {
64 return base::string16();
67 // Get joined basenames of user data dir and profile.
68 base::string16 basenames = profile_path.DirName().BaseName().value() +
69 L"." + profile_path.BaseName().value();
71 base::string16 profile_id;
72 profile_id.reserve(basenames.size());
74 // Generate profile_id from sanitized basenames.
75 for (size_t i = 0; i < basenames.length(); ++i) {
76 if (IsAsciiAlpha(basenames[i]) ||
77 IsAsciiDigit(basenames[i]) ||
78 basenames[i] == L'.')
79 profile_id += basenames[i];
82 return profile_id;
85 base::string16 GetAppListAppName() {
86 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
87 base::string16 app_name(dist->GetBaseAppId());
88 app_name.append(kAppListAppNameSuffix);
89 return app_name;
92 // Gets expected app id for given Chrome (based on |command_line| and
93 // |is_per_user_install|).
94 base::string16 GetExpectedAppId(const CommandLine& command_line,
95 bool is_per_user_install) {
96 base::FilePath user_data_dir;
97 if (command_line.HasSwitch(switches::kUserDataDir))
98 user_data_dir = command_line.GetSwitchValuePath(switches::kUserDataDir);
99 else
100 chrome::GetDefaultUserDataDirectory(&user_data_dir);
101 // Adjust with any policy that overrides any other way to set the path.
102 policy::path_parser::CheckUserDataDirPolicy(&user_data_dir);
103 DCHECK(!user_data_dir.empty());
105 base::FilePath profile_subdir;
106 if (command_line.HasSwitch(switches::kProfileDirectory)) {
107 profile_subdir =
108 command_line.GetSwitchValuePath(switches::kProfileDirectory);
109 } else {
110 profile_subdir =
111 base::FilePath(base::ASCIIToUTF16(chrome::kInitialProfile));
113 DCHECK(!profile_subdir.empty());
115 base::FilePath profile_path = user_data_dir.Append(profile_subdir);
116 base::string16 app_name;
117 if (command_line.HasSwitch(switches::kApp)) {
118 app_name = base::UTF8ToUTF16(web_app::GenerateApplicationNameFromURL(
119 GURL(command_line.GetSwitchValueASCII(switches::kApp))));
120 } else if (command_line.HasSwitch(switches::kAppId)) {
121 app_name = base::UTF8ToUTF16(
122 web_app::GenerateApplicationNameFromExtensionId(
123 command_line.GetSwitchValueASCII(switches::kAppId)));
124 } else if (command_line.HasSwitch(switches::kShowAppList)) {
125 app_name = GetAppListAppName();
126 } else {
127 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
128 app_name = ShellUtil::GetBrowserModelId(dist, is_per_user_install);
130 DCHECK(!app_name.empty());
132 return ShellIntegration::GetAppModelIdForProfile(app_name, profile_path);
135 void MigrateChromiumShortcutsCallback() {
136 // This should run on the file thread.
137 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
139 // Get full path of chrome.
140 base::FilePath chrome_exe;
141 if (!PathService::Get(base::FILE_EXE, &chrome_exe))
142 return;
144 // Locations to check for shortcuts migration.
145 static const struct {
146 int location_id;
147 const wchar_t* sub_dir;
148 } kLocations[] = {
150 base::DIR_TASKBAR_PINS,
151 NULL
152 }, {
153 base::DIR_USER_DESKTOP,
154 NULL
155 }, {
156 base::DIR_START_MENU,
157 NULL
158 }, {
159 base::DIR_APP_DATA,
160 L"Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\StartMenu"
164 for (int i = 0; i < arraysize(kLocations); ++i) {
165 base::FilePath path;
166 if (!PathService::Get(kLocations[i].location_id, &path)) {
167 NOTREACHED();
168 continue;
171 if (kLocations[i].sub_dir)
172 path = path.Append(kLocations[i].sub_dir);
174 bool check_dual_mode = (kLocations[i].location_id == base::DIR_START_MENU);
175 ShellIntegration::MigrateShortcutsInPathInternal(chrome_exe, path,
176 check_dual_mode);
180 // Windows 8 introduced a new protocol->executable binding system which cannot
181 // be retrieved in the HKCR registry subkey method implemented below. We call
182 // AssocQueryString with the new Win8-only flag ASSOCF_IS_PROTOCOL instead.
183 base::string16 GetAppForProtocolUsingAssocQuery(const GURL& url) {
184 base::string16 url_scheme = base::ASCIIToWide(url.scheme());
185 // Don't attempt to query protocol association on an empty string.
186 if (url_scheme.empty())
187 return base::string16();
189 // Query AssocQueryString for a human-readable description of the program
190 // that will be invoked given the provided URL spec. This is used only to
191 // populate the external protocol dialog box the user sees when invoking
192 // an unknown external protocol.
193 wchar_t out_buffer[1024];
194 DWORD buffer_size = arraysize(out_buffer);
195 HRESULT hr = AssocQueryString(ASSOCF_IS_PROTOCOL,
196 ASSOCSTR_FRIENDLYAPPNAME,
197 url_scheme.c_str(),
198 NULL,
199 out_buffer,
200 &buffer_size);
201 if (FAILED(hr)) {
202 DLOG(WARNING) << "AssocQueryString failed!";
203 return base::string16();
205 return base::string16(out_buffer);
208 base::string16 GetAppForProtocolUsingRegistry(const GURL& url) {
209 base::string16 url_spec = base::ASCIIToWide(url.possibly_invalid_spec());
210 const base::string16 cmd_key_path =
211 base::ASCIIToWide(url.scheme() + "\\shell\\open\\command");
212 base::win::RegKey cmd_key(HKEY_CLASSES_ROOT,
213 cmd_key_path.c_str(),
214 KEY_READ);
215 size_t split_offset = url_spec.find(L':');
216 if (split_offset == base::string16::npos)
217 return base::string16();
218 const base::string16 parameters = url_spec.substr(split_offset + 1,
219 url_spec.length() - 1);
220 base::string16 application_to_launch;
221 if (cmd_key.ReadValue(NULL, &application_to_launch) == ERROR_SUCCESS) {
222 ReplaceSubstringsAfterOffset(&application_to_launch,
224 L"%1",
225 parameters);
226 return application_to_launch;
228 return base::string16();
232 ShellIntegration::DefaultWebClientState
233 GetDefaultWebClientStateFromShellUtilDefaultState(
234 ShellUtil::DefaultState default_state) {
235 switch (default_state) {
236 case ShellUtil::NOT_DEFAULT:
237 return ShellIntegration::NOT_DEFAULT;
238 case ShellUtil::IS_DEFAULT:
239 return ShellIntegration::IS_DEFAULT;
240 default:
241 DCHECK_EQ(ShellUtil::UNKNOWN_DEFAULT, default_state);
242 return ShellIntegration::UNKNOWN_DEFAULT;
246 } // namespace
248 ShellIntegration::DefaultWebClientSetPermission
249 ShellIntegration::CanSetAsDefaultBrowser() {
250 BrowserDistribution* distribution = BrowserDistribution::GetDistribution();
251 if (distribution->GetDefaultBrowserControlPolicy() !=
252 BrowserDistribution::DEFAULT_BROWSER_FULL_CONTROL)
253 return SET_DEFAULT_NOT_ALLOWED;
255 if (ShellUtil::CanMakeChromeDefaultUnattended())
256 return SET_DEFAULT_UNATTENDED;
257 else
258 return SET_DEFAULT_INTERACTIVE;
261 bool ShellIntegration::SetAsDefaultBrowser() {
262 base::FilePath chrome_exe;
263 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
264 LOG(ERROR) << "Error getting app exe path";
265 return false;
268 // From UI currently we only allow setting default browser for current user.
269 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
270 if (!ShellUtil::MakeChromeDefault(dist, ShellUtil::CURRENT_USER,
271 chrome_exe.value(), true)) {
272 LOG(ERROR) << "Chrome could not be set as default browser.";
273 return false;
276 VLOG(1) << "Chrome registered as default browser.";
277 return true;
280 bool ShellIntegration::SetAsDefaultProtocolClient(const std::string& protocol) {
281 if (protocol.empty())
282 return false;
284 base::FilePath chrome_exe;
285 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
286 LOG(ERROR) << "Error getting app exe path";
287 return false;
290 base::string16 wprotocol(base::UTF8ToUTF16(protocol));
291 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
292 if (!ShellUtil::MakeChromeDefaultProtocolClient(dist, chrome_exe.value(),
293 wprotocol)) {
294 LOG(ERROR) << "Chrome could not be set as default handler for "
295 << protocol << ".";
296 return false;
299 VLOG(1) << "Chrome registered as default handler for " << protocol << ".";
300 return true;
303 bool ShellIntegration::SetAsDefaultBrowserInteractive() {
304 base::FilePath chrome_exe;
305 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
306 NOTREACHED() << "Error getting app exe path";
307 return false;
310 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
311 if (!ShellUtil::ShowMakeChromeDefaultSystemUI(dist, chrome_exe.value())) {
312 LOG(ERROR) << "Failed to launch the set-default-browser Windows UI.";
313 return false;
316 VLOG(1) << "Set-default-browser Windows UI completed.";
317 return true;
320 bool ShellIntegration::SetAsDefaultProtocolClientInteractive(
321 const std::string& protocol) {
322 base::FilePath chrome_exe;
323 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
324 NOTREACHED() << "Error getting app exe path";
325 return false;
328 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
329 base::string16 wprotocol(base::UTF8ToUTF16(protocol));
330 if (!ShellUtil::ShowMakeChromeDefaultProtocolClientSystemUI(
331 dist, chrome_exe.value(), wprotocol)) {
332 LOG(ERROR) << "Failed to launch the set-default-client Windows UI.";
333 return false;
336 VLOG(1) << "Set-default-client Windows UI completed.";
337 return true;
340 ShellIntegration::DefaultWebClientState ShellIntegration::GetDefaultBrowser() {
341 return GetDefaultWebClientStateFromShellUtilDefaultState(
342 ShellUtil::GetChromeDefaultState());
345 ShellIntegration::DefaultWebClientState
346 ShellIntegration::IsDefaultProtocolClient(const std::string& protocol) {
347 return GetDefaultWebClientStateFromShellUtilDefaultState(
348 ShellUtil::GetChromeDefaultProtocolClientState(
349 base::UTF8ToUTF16(protocol)));
352 base::string16 ShellIntegration::GetApplicationNameForProtocol(
353 const GURL& url) {
354 // Windows 8 or above requires a new protocol association query.
355 if (base::win::GetVersion() >= base::win::VERSION_WIN8)
356 return GetAppForProtocolUsingAssocQuery(url);
357 else
358 return GetAppForProtocolUsingRegistry(url);
361 // There is no reliable way to say which browser is default on a machine (each
362 // browser can have some of the protocols/shortcuts). So we look for only HTTP
363 // protocol handler. Even this handler is located at different places in
364 // registry on XP and Vista:
365 // - HKCR\http\shell\open\command (XP)
366 // - HKCU\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\
367 // http\UserChoice (Vista)
368 // This method checks if Firefox is defualt browser by checking these
369 // locations and returns true if Firefox traces are found there. In case of
370 // error (or if Firefox is not found)it returns the default value which
371 // is false.
372 bool ShellIntegration::IsFirefoxDefaultBrowser() {
373 bool ff_default = false;
374 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
375 base::string16 app_cmd;
376 base::win::RegKey key(HKEY_CURRENT_USER,
377 ShellUtil::kRegVistaUrlPrefs, KEY_READ);
378 if (key.Valid() && (key.ReadValue(L"Progid", &app_cmd) == ERROR_SUCCESS) &&
379 app_cmd == L"FirefoxURL")
380 ff_default = true;
381 } else {
382 base::string16 key_path(L"http");
383 key_path.append(ShellUtil::kRegShellOpen);
384 base::win::RegKey key(HKEY_CLASSES_ROOT, key_path.c_str(), KEY_READ);
385 base::string16 app_cmd;
386 if (key.Valid() && (key.ReadValue(L"", &app_cmd) == ERROR_SUCCESS) &&
387 base::string16::npos != StringToLowerASCII(app_cmd).find(L"firefox"))
388 ff_default = true;
390 return ff_default;
393 base::string16 ShellIntegration::GetAppModelIdForProfile(
394 const base::string16& app_name,
395 const base::FilePath& profile_path) {
396 std::vector<base::string16> components;
397 components.push_back(app_name);
398 const base::string16 profile_id(GetProfileIdFromPath(profile_path));
399 if (!profile_id.empty())
400 components.push_back(profile_id);
401 return ShellUtil::BuildAppModelId(components);
404 base::string16 ShellIntegration::GetChromiumModelIdForProfile(
405 const base::FilePath& profile_path) {
406 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
407 base::FilePath chrome_exe;
408 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
409 NOTREACHED();
410 return dist->GetBaseAppId();
412 return GetAppModelIdForProfile(
413 ShellUtil::GetBrowserModelId(
414 dist, InstallUtil::IsPerUserInstall(chrome_exe.value().c_str())),
415 profile_path);
418 base::string16 ShellIntegration::GetAppListAppModelIdForProfile(
419 const base::FilePath& profile_path) {
420 return ShellIntegration::GetAppModelIdForProfile(
421 GetAppListAppName(), profile_path);
424 void ShellIntegration::MigrateChromiumShortcuts() {
425 if (base::win::GetVersion() < base::win::VERSION_WIN7)
426 return;
428 // This needs to happen eventually (e.g. so that the appid is fixed and the
429 // run-time Chrome icon is merged with the taskbar shortcut), but this is not
430 // urgent and shouldn't delay Chrome startup.
431 static const int64 kMigrateChromiumShortcutsDelaySeconds = 15;
432 BrowserThread::PostDelayedTask(
433 BrowserThread::FILE, FROM_HERE,
434 base::Bind(&MigrateChromiumShortcutsCallback),
435 base::TimeDelta::FromSeconds(kMigrateChromiumShortcutsDelaySeconds));
438 int ShellIntegration::MigrateShortcutsInPathInternal(
439 const base::FilePath& chrome_exe,
440 const base::FilePath& path,
441 bool check_dual_mode) {
442 DCHECK(base::win::GetVersion() >= base::win::VERSION_WIN7);
444 // Enumerate all pinned shortcuts in the given path directly.
445 base::FileEnumerator shortcuts_enum(
446 path, false, // not recursive
447 base::FileEnumerator::FILES, FILE_PATH_LITERAL("*.lnk"));
449 bool is_per_user_install =
450 InstallUtil::IsPerUserInstall(chrome_exe.value().c_str());
452 int shortcuts_migrated = 0;
453 base::FilePath target_path;
454 base::string16 arguments;
455 base::win::ScopedPropVariant propvariant;
456 for (base::FilePath shortcut = shortcuts_enum.Next(); !shortcut.empty();
457 shortcut = shortcuts_enum.Next()) {
458 // TODO(gab): Use ProgramCompare instead of comparing FilePaths below once
459 // it is fixed to work with FilePaths with spaces.
460 if (!base::win::ResolveShortcut(shortcut, &target_path, &arguments) ||
461 chrome_exe != target_path) {
462 continue;
464 CommandLine command_line(CommandLine::FromString(base::StringPrintf(
465 L"\"%ls\" %ls", target_path.value().c_str(), arguments.c_str())));
467 // Get the expected AppId for this Chrome shortcut.
468 base::string16 expected_app_id(
469 GetExpectedAppId(command_line, is_per_user_install));
470 if (expected_app_id.empty())
471 continue;
473 // Load the shortcut.
474 base::win::ScopedComPtr<IShellLink> shell_link;
475 base::win::ScopedComPtr<IPersistFile> persist_file;
476 if (FAILED(shell_link.CreateInstance(CLSID_ShellLink, NULL,
477 CLSCTX_INPROC_SERVER)) ||
478 FAILED(persist_file.QueryFrom(shell_link)) ||
479 FAILED(persist_file->Load(shortcut.value().c_str(), STGM_READ))) {
480 DLOG(WARNING) << "Failed loading shortcut at " << shortcut.value();
481 continue;
484 // Any properties that need to be updated on the shortcut will be stored in
485 // |updated_properties|.
486 base::win::ShortcutProperties updated_properties;
488 // Validate the existing app id for the shortcut.
489 base::win::ScopedComPtr<IPropertyStore> property_store;
490 propvariant.Reset();
491 if (FAILED(property_store.QueryFrom(shell_link)) ||
492 property_store->GetValue(PKEY_AppUserModel_ID,
493 propvariant.Receive()) != S_OK) {
494 // When in doubt, prefer not updating the shortcut.
495 NOTREACHED();
496 continue;
497 } else {
498 switch (propvariant.get().vt) {
499 case VT_EMPTY:
500 // If there is no app_id set, set our app_id if one is expected.
501 if (!expected_app_id.empty())
502 updated_properties.set_app_id(expected_app_id);
503 break;
504 case VT_LPWSTR:
505 if (expected_app_id != base::string16(propvariant.get().pwszVal))
506 updated_properties.set_app_id(expected_app_id);
507 break;
508 default:
509 NOTREACHED();
510 continue;
514 // Only set dual mode if the expected app id is the default app id.
515 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
516 base::string16 default_chromium_model_id(
517 ShellUtil::GetBrowserModelId(dist, is_per_user_install));
518 if (check_dual_mode && expected_app_id == default_chromium_model_id) {
519 propvariant.Reset();
520 if (property_store->GetValue(PKEY_AppUserModel_IsDualMode,
521 propvariant.Receive()) != S_OK) {
522 // When in doubt, prefer to not update the shortcut.
523 NOTREACHED();
524 continue;
525 } else {
526 switch (propvariant.get().vt) {
527 case VT_EMPTY:
528 // If dual_mode is not set at all, make sure it gets set to true.
529 updated_properties.set_dual_mode(true);
530 break;
531 case VT_BOOL:
532 // If it is set to false, make sure it gets set to true as well.
533 if (!propvariant.get().boolVal)
534 updated_properties.set_dual_mode(true);
535 break;
536 default:
537 NOTREACHED();
538 continue;
543 persist_file.Release();
544 shell_link.Release();
546 // Update the shortcut if some of its properties need to be updated.
547 if (updated_properties.options &&
548 base::win::CreateOrUpdateShortcutLink(
549 shortcut, updated_properties,
550 base::win::SHORTCUT_UPDATE_EXISTING)) {
551 ++shortcuts_migrated;
554 return shortcuts_migrated;
557 base::FilePath ShellIntegration::GetStartMenuShortcut(
558 const base::FilePath& chrome_exe) {
559 static const int kFolderIds[] = {
560 base::DIR_COMMON_START_MENU,
561 base::DIR_START_MENU,
563 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
564 base::string16 shortcut_name(
565 dist->GetShortcutName(BrowserDistribution::SHORTCUT_CHROME));
566 base::FilePath shortcut;
568 // Check both the common and the per-user Start Menu folders for system-level
569 // installs.
570 size_t folder =
571 InstallUtil::IsPerUserInstall(chrome_exe.value().c_str()) ? 1 : 0;
572 for (; folder < arraysize(kFolderIds); ++folder) {
573 if (!PathService::Get(kFolderIds[folder], &shortcut)) {
574 NOTREACHED();
575 continue;
578 shortcut = shortcut.Append(shortcut_name).Append(shortcut_name +
579 installer::kLnkExt);
580 if (base::PathExists(shortcut))
581 return shortcut;
584 return base::FilePath();