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"
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.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/web_applications/web_app.h"
27 #include "chrome/common/chrome_constants.h"
28 #include "chrome/common/chrome_paths_internal.h"
29 #include "chrome/common/chrome_switches.h"
30 #include "chrome/installer/setup/setup_util.h"
31 #include "chrome/installer/util/browser_distribution.h"
32 #include "chrome/installer/util/create_reg_key_work_item.h"
33 #include "chrome/installer/util/install_util.h"
34 #include "chrome/installer/util/set_reg_value_work_item.h"
35 #include "chrome/installer/util/shell_util.h"
36 #include "chrome/installer/util/util_constants.h"
37 #include "chrome/installer/util/work_item.h"
38 #include "chrome/installer/util/work_item_list.h"
39 #include "content/public/browser/browser_thread.h"
41 using content::BrowserThread
;
45 const wchar_t kAppListAppNameSuffix
[] = L
"AppList";
47 // Helper function for ShellIntegration::GetAppId to generates profile id
48 // from profile path. "profile_id" is composed of sanitized basenames of
49 // user data dir and profile dir joined by a ".".
50 string16
GetProfileIdFromPath(const base::FilePath
& profile_path
) {
51 // Return empty string if profile_path is empty
52 if (profile_path
.empty())
55 base::FilePath default_user_data_dir
;
56 // Return empty string if profile_path is in default user data
57 // dir and is the default profile.
58 if (chrome::GetDefaultUserDataDirectory(&default_user_data_dir
) &&
59 profile_path
.DirName() == default_user_data_dir
&&
60 profile_path
.BaseName().value() ==
61 ASCIIToUTF16(chrome::kInitialProfile
)) {
65 // Get joined basenames of user data dir and profile.
66 string16 basenames
= profile_path
.DirName().BaseName().value() +
67 L
"." + profile_path
.BaseName().value();
70 profile_id
.reserve(basenames
.size());
72 // Generate profile_id from sanitized basenames.
73 for (size_t i
= 0; i
< basenames
.length(); ++i
) {
74 if (IsAsciiAlpha(basenames
[i
]) ||
75 IsAsciiDigit(basenames
[i
]) ||
77 profile_id
+= basenames
[i
];
83 string16
GetAppListAppName() {
84 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
85 string16
app_name(dist
->GetBaseAppId());
86 app_name
.append(kAppListAppNameSuffix
);
90 // Gets expected app id for given Chrome (based on |command_line| and
91 // |is_per_user_install|).
92 string16
GetExpectedAppId(const CommandLine
& command_line
,
93 bool is_per_user_install
) {
94 base::FilePath user_data_dir
;
95 if (command_line
.HasSwitch(switches::kUserDataDir
))
96 user_data_dir
= command_line
.GetSwitchValuePath(switches::kUserDataDir
);
98 chrome::GetDefaultUserDataDirectory(&user_data_dir
);
99 DCHECK(!user_data_dir
.empty());
101 base::FilePath profile_subdir
;
102 if (command_line
.HasSwitch(switches::kProfileDirectory
)) {
104 command_line
.GetSwitchValuePath(switches::kProfileDirectory
);
106 profile_subdir
= base::FilePath(ASCIIToUTF16(chrome::kInitialProfile
));
108 DCHECK(!profile_subdir
.empty());
110 base::FilePath profile_path
= user_data_dir
.Append(profile_subdir
);
112 if (command_line
.HasSwitch(switches::kApp
)) {
113 app_name
= UTF8ToUTF16(web_app::GenerateApplicationNameFromURL(
114 GURL(command_line
.GetSwitchValueASCII(switches::kApp
))));
115 } else if (command_line
.HasSwitch(switches::kAppId
)) {
116 app_name
= UTF8ToUTF16(web_app::GenerateApplicationNameFromExtensionId(
117 command_line
.GetSwitchValueASCII(switches::kAppId
)));
118 } else if (command_line
.HasSwitch(switches::kShowAppList
)) {
119 app_name
= GetAppListAppName();
121 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
122 app_name
= ShellUtil::GetBrowserModelId(dist
, is_per_user_install
);
124 DCHECK(!app_name
.empty());
126 return ShellIntegration::GetAppModelIdForProfile(app_name
, profile_path
);
129 void MigrateChromiumShortcutsCallback() {
130 // This should run on the file thread.
131 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
133 // Get full path of chrome.
134 base::FilePath chrome_exe
;
135 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
))
138 // Locations to check for shortcuts migration.
139 static const struct {
141 const wchar_t* sub_dir
;
144 base::DIR_TASKBAR_PINS
,
147 base::DIR_USER_DESKTOP
,
150 base::DIR_START_MENU
,
154 L
"Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\StartMenu"
158 for (int i
= 0; i
< arraysize(kLocations
); ++i
) {
160 if (!PathService::Get(kLocations
[i
].location_id
, &path
)) {
165 if (kLocations
[i
].sub_dir
)
166 path
= path
.Append(kLocations
[i
].sub_dir
);
168 bool check_dual_mode
= (kLocations
[i
].location_id
== base::DIR_START_MENU
);
169 ShellIntegration::MigrateShortcutsInPathInternal(chrome_exe
, path
,
174 ShellIntegration::DefaultWebClientState
175 GetDefaultWebClientStateFromShellUtilDefaultState(
176 ShellUtil::DefaultState default_state
) {
177 switch (default_state
) {
178 case ShellUtil::NOT_DEFAULT
:
179 return ShellIntegration::NOT_DEFAULT
;
180 case ShellUtil::IS_DEFAULT
:
181 return ShellIntegration::IS_DEFAULT
;
183 DCHECK_EQ(ShellUtil::UNKNOWN_DEFAULT
, default_state
);
184 return ShellIntegration::UNKNOWN_DEFAULT
;
190 ShellIntegration::DefaultWebClientSetPermission
191 ShellIntegration::CanSetAsDefaultBrowser() {
192 if (!BrowserDistribution::GetDistribution()->CanSetAsDefault())
193 return SET_DEFAULT_NOT_ALLOWED
;
195 if (ShellUtil::CanMakeChromeDefaultUnattended())
196 return SET_DEFAULT_UNATTENDED
;
198 return SET_DEFAULT_INTERACTIVE
;
201 bool ShellIntegration::SetAsDefaultBrowser() {
202 base::FilePath chrome_exe
;
203 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
204 LOG(ERROR
) << "Error getting app exe path";
208 // From UI currently we only allow setting default browser for current user.
209 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
210 if (!ShellUtil::MakeChromeDefault(dist
, ShellUtil::CURRENT_USER
,
211 chrome_exe
.value(), true)) {
212 LOG(ERROR
) << "Chrome could not be set as default browser.";
216 VLOG(1) << "Chrome registered as default browser.";
220 bool ShellIntegration::SetAsDefaultProtocolClient(const std::string
& protocol
) {
221 if (protocol
.empty())
224 base::FilePath chrome_exe
;
225 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
226 LOG(ERROR
) << "Error getting app exe path";
230 string16
wprotocol(UTF8ToUTF16(protocol
));
231 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
232 if (!ShellUtil::MakeChromeDefaultProtocolClient(dist
, chrome_exe
.value(),
234 LOG(ERROR
) << "Chrome could not be set as default handler for "
239 VLOG(1) << "Chrome registered as default handler for " << protocol
<< ".";
243 bool ShellIntegration::SetAsDefaultBrowserInteractive() {
244 base::FilePath chrome_exe
;
245 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
246 NOTREACHED() << "Error getting app exe path";
250 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
251 if (!ShellUtil::ShowMakeChromeDefaultSystemUI(dist
, chrome_exe
.value())) {
252 LOG(ERROR
) << "Failed to launch the set-default-browser Windows UI.";
256 VLOG(1) << "Set-default-browser Windows UI completed.";
260 bool ShellIntegration::SetAsDefaultProtocolClientInteractive(
261 const std::string
& protocol
) {
262 base::FilePath chrome_exe
;
263 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
264 NOTREACHED() << "Error getting app exe path";
268 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
269 string16
wprotocol(UTF8ToUTF16(protocol
));
270 if (!ShellUtil::ShowMakeChromeDefaultProtocolClientSystemUI(
271 dist
, chrome_exe
.value(), wprotocol
)) {
272 LOG(ERROR
) << "Failed to launch the set-default-client Windows UI.";
276 VLOG(1) << "Set-default-client Windows UI completed.";
280 ShellIntegration::DefaultWebClientState
ShellIntegration::GetDefaultBrowser() {
281 return GetDefaultWebClientStateFromShellUtilDefaultState(
282 ShellUtil::GetChromeDefaultState());
285 ShellIntegration::DefaultWebClientState
286 ShellIntegration::IsDefaultProtocolClient(const std::string
& protocol
) {
287 return GetDefaultWebClientStateFromShellUtilDefaultState(
288 ShellUtil::GetChromeDefaultProtocolClientState(UTF8ToUTF16(protocol
)));
291 std::string
ShellIntegration::GetApplicationForProtocol(const GURL
& url
) {
292 // TODO(calamity): this will be implemented when external_protocol_dialog is
293 // refactored on windows.
295 return std::string();
298 // There is no reliable way to say which browser is default on a machine (each
299 // browser can have some of the protocols/shortcuts). So we look for only HTTP
300 // protocol handler. Even this handler is located at different places in
301 // registry on XP and Vista:
302 // - HKCR\http\shell\open\command (XP)
303 // - HKCU\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\
304 // http\UserChoice (Vista)
305 // This method checks if Firefox is defualt browser by checking these
306 // locations and returns true if Firefox traces are found there. In case of
307 // error (or if Firefox is not found)it returns the default value which
309 bool ShellIntegration::IsFirefoxDefaultBrowser() {
310 bool ff_default
= false;
311 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
313 base::win::RegKey
key(HKEY_CURRENT_USER
,
314 ShellUtil::kRegVistaUrlPrefs
, KEY_READ
);
315 if (key
.Valid() && (key
.ReadValue(L
"Progid", &app_cmd
) == ERROR_SUCCESS
) &&
316 app_cmd
== L
"FirefoxURL")
319 string16
key_path(L
"http");
320 key_path
.append(ShellUtil::kRegShellOpen
);
321 base::win::RegKey
key(HKEY_CLASSES_ROOT
, key_path
.c_str(), KEY_READ
);
323 if (key
.Valid() && (key
.ReadValue(L
"", &app_cmd
) == ERROR_SUCCESS
) &&
324 string16::npos
!= StringToLowerASCII(app_cmd
).find(L
"firefox"))
330 string16
ShellIntegration::GetAppModelIdForProfile(
331 const string16
& app_name
,
332 const base::FilePath
& profile_path
) {
333 std::vector
<string16
> components
;
334 components
.push_back(app_name
);
335 const string16
profile_id(GetProfileIdFromPath(profile_path
));
336 if (!profile_id
.empty())
337 components
.push_back(profile_id
);
338 return ShellUtil::BuildAppModelId(components
);
341 string16
ShellIntegration::GetChromiumModelIdForProfile(
342 const base::FilePath
& profile_path
) {
343 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
344 base::FilePath chrome_exe
;
345 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
347 return dist
->GetBaseAppId();
349 return GetAppModelIdForProfile(
350 ShellUtil::GetBrowserModelId(
351 dist
, InstallUtil::IsPerUserInstall(chrome_exe
.value().c_str())),
355 string16
ShellIntegration::GetAppListAppModelIdForProfile(
356 const base::FilePath
& profile_path
) {
357 return ShellIntegration::GetAppModelIdForProfile(
358 GetAppListAppName(), profile_path
);
361 string16
ShellIntegration::GetChromiumIconLocation() {
362 // Determine the path to chrome.exe. If we can't determine what that is,
363 // we have bigger fish to fry...
364 base::FilePath chrome_exe
;
365 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
370 return ShellUtil::FormatIconLocation(
372 BrowserDistribution::GetDistribution()->GetIconIndex());
375 void ShellIntegration::MigrateChromiumShortcuts() {
376 if (base::win::GetVersion() < base::win::VERSION_WIN7
)
379 // This needs to happen eventually (e.g. so that the appid is fixed and the
380 // run-time Chrome icon is merged with the taskbar shortcut), but this is not
381 // urgent and shouldn't delay Chrome startup.
382 static const int64 kMigrateChromiumShortcutsDelaySeconds
= 15;
383 BrowserThread::PostDelayedTask(
384 BrowserThread::FILE, FROM_HERE
,
385 base::Bind(&MigrateChromiumShortcutsCallback
),
386 base::TimeDelta::FromSeconds(kMigrateChromiumShortcutsDelaySeconds
));
389 int ShellIntegration::MigrateShortcutsInPathInternal(
390 const base::FilePath
& chrome_exe
,
391 const base::FilePath
& path
,
392 bool check_dual_mode
) {
393 DCHECK(base::win::GetVersion() >= base::win::VERSION_WIN7
);
395 // Enumerate all pinned shortcuts in the given path directly.
396 base::FileEnumerator
shortcuts_enum(
397 path
, false, // not recursive
398 base::FileEnumerator::FILES
, FILE_PATH_LITERAL("*.lnk"));
400 bool is_per_user_install
=
401 InstallUtil::IsPerUserInstall(chrome_exe
.value().c_str());
403 int shortcuts_migrated
= 0;
404 base::FilePath target_path
;
406 base::win::ScopedPropVariant propvariant
;
407 for (base::FilePath shortcut
= shortcuts_enum
.Next(); !shortcut
.empty();
408 shortcut
= shortcuts_enum
.Next()) {
409 // TODO(gab): Use ProgramCompare instead of comparing FilePaths below once
410 // it is fixed to work with FilePaths with spaces.
411 if (!base::win::ResolveShortcut(shortcut
, &target_path
, &arguments
) ||
412 chrome_exe
!= target_path
) {
415 CommandLine
command_line(CommandLine::FromString(base::StringPrintf(
416 L
"\"%ls\" %ls", target_path
.value().c_str(), arguments
.c_str())));
418 // Get the expected AppId for this Chrome shortcut.
419 string16
expected_app_id(
420 GetExpectedAppId(command_line
, is_per_user_install
));
421 if (expected_app_id
.empty())
424 // Load the shortcut.
425 base::win::ScopedComPtr
<IShellLink
> shell_link
;
426 base::win::ScopedComPtr
<IPersistFile
> persist_file
;
427 if (FAILED(shell_link
.CreateInstance(CLSID_ShellLink
, NULL
,
428 CLSCTX_INPROC_SERVER
)) ||
429 FAILED(persist_file
.QueryFrom(shell_link
)) ||
430 FAILED(persist_file
->Load(shortcut
.value().c_str(), STGM_READ
))) {
431 DLOG(WARNING
) << "Failed loading shortcut at " << shortcut
.value();
435 // Any properties that need to be updated on the shortcut will be stored in
436 // |updated_properties|.
437 base::win::ShortcutProperties updated_properties
;
439 // Validate the existing app id for the shortcut.
440 base::win::ScopedComPtr
<IPropertyStore
> property_store
;
442 if (FAILED(property_store
.QueryFrom(shell_link
)) ||
443 property_store
->GetValue(PKEY_AppUserModel_ID
,
444 propvariant
.Receive()) != S_OK
) {
445 // When in doubt, prefer not updating the shortcut.
449 switch (propvariant
.get().vt
) {
451 // If there is no app_id set, set our app_id if one is expected.
452 if (!expected_app_id
.empty())
453 updated_properties
.set_app_id(expected_app_id
);
456 if (expected_app_id
!= string16(propvariant
.get().pwszVal
))
457 updated_properties
.set_app_id(expected_app_id
);
465 // Only set dual mode if the expected app id is the default app id.
466 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
467 string16
default_chromium_model_id(
468 ShellUtil::GetBrowserModelId(dist
, is_per_user_install
));
469 if (check_dual_mode
&& expected_app_id
== default_chromium_model_id
) {
471 if (property_store
->GetValue(PKEY_AppUserModel_IsDualMode
,
472 propvariant
.Receive()) != S_OK
) {
473 // When in doubt, prefer to not update the shortcut.
477 switch (propvariant
.get().vt
) {
479 // If dual_mode is not set at all, make sure it gets set to true.
480 updated_properties
.set_dual_mode(true);
483 // If it is set to false, make sure it gets set to true as well.
484 if (!propvariant
.get().boolVal
)
485 updated_properties
.set_dual_mode(true);
494 persist_file
.Release();
495 shell_link
.Release();
497 // Update the shortcut if some of its properties need to be updated.
498 if (updated_properties
.options
&&
499 base::win::CreateOrUpdateShortcutLink(
500 shortcut
, updated_properties
,
501 base::win::SHORTCUT_UPDATE_EXISTING
)) {
502 ++shortcuts_migrated
;
505 return shortcuts_migrated
;
508 base::FilePath
ShellIntegration::GetStartMenuShortcut(
509 const base::FilePath
& chrome_exe
) {
510 static const int kFolderIds
[] = {
511 base::DIR_COMMON_START_MENU
,
512 base::DIR_START_MENU
,
514 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
515 string16
shortcut_name(dist
->GetAppShortCutName());
516 base::FilePath shortcut
;
518 // Check both the common and the per-user Start Menu folders for system-level
521 InstallUtil::IsPerUserInstall(chrome_exe
.value().c_str()) ? 1 : 0;
522 for (; folder
< arraysize(kFolderIds
); ++folder
) {
523 if (!PathService::Get(kFolderIds
[folder
], &shortcut
)) {
528 shortcut
= shortcut
.Append(shortcut_name
).Append(shortcut_name
+
530 if (file_util::PathExists(shortcut
))
534 return base::FilePath();