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/message_loop.h"
15 #include "base/path_service.h"
16 #include "base/string_util.h"
17 #include "base/stringprintf.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/utf_string_conversions.h"
20 #include "base/win/registry.h"
21 #include "base/win/scoped_comptr.h"
22 #include "base/win/scoped_propvariant.h"
23 #include "base/win/shortcut.h"
24 #include "base/win/windows_version.h"
25 #include "chrome/browser/web_applications/web_app.h"
26 #include "chrome/common/chrome_constants.h"
27 #include "chrome/common/chrome_paths_internal.h"
28 #include "chrome/common/chrome_switches.h"
29 #include "chrome/installer/setup/setup_util.h"
30 #include "chrome/installer/util/browser_distribution.h"
31 #include "chrome/installer/util/create_reg_key_work_item.h"
32 #include "chrome/installer/util/install_util.h"
33 #include "chrome/installer/util/set_reg_value_work_item.h"
34 #include "chrome/installer/util/shell_util.h"
35 #include "chrome/installer/util/util_constants.h"
36 #include "chrome/installer/util/work_item.h"
37 #include "chrome/installer/util/work_item_list.h"
38 #include "content/public/browser/browser_thread.h"
40 using content::BrowserThread
;
44 const wchar_t kAppListAppNameSuffix
[] = L
"AppList";
46 // Helper function for ShellIntegration::GetAppId to generates profile id
47 // from profile path. "profile_id" is composed of sanitized basenames of
48 // user data dir and profile dir joined by a ".".
49 string16
GetProfileIdFromPath(const base::FilePath
& profile_path
) {
50 // Return empty string if profile_path is empty
51 if (profile_path
.empty())
54 base::FilePath default_user_data_dir
;
55 // Return empty string if profile_path is in default user data
56 // dir and is the default profile.
57 if (chrome::GetDefaultUserDataDirectory(&default_user_data_dir
) &&
58 profile_path
.DirName() == default_user_data_dir
&&
59 profile_path
.BaseName().value() ==
60 ASCIIToUTF16(chrome::kInitialProfile
)) {
64 // Get joined basenames of user data dir and profile.
65 string16 basenames
= profile_path
.DirName().BaseName().value() +
66 L
"." + profile_path
.BaseName().value();
69 profile_id
.reserve(basenames
.size());
71 // Generate profile_id from sanitized basenames.
72 for (size_t i
= 0; i
< basenames
.length(); ++i
) {
73 if (IsAsciiAlpha(basenames
[i
]) ||
74 IsAsciiDigit(basenames
[i
]) ||
76 profile_id
+= basenames
[i
];
82 string16
GetAppListAppName() {
83 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
84 string16
app_name(dist
->GetBaseAppId());
85 app_name
.append(kAppListAppNameSuffix
);
89 // Gets expected app id for given Chrome (based on |command_line| and
90 // |is_per_user_install|).
91 string16
GetExpectedAppId(const CommandLine
& command_line
,
92 bool is_per_user_install
) {
93 base::FilePath user_data_dir
;
94 if (command_line
.HasSwitch(switches::kUserDataDir
))
95 user_data_dir
= command_line
.GetSwitchValuePath(switches::kUserDataDir
);
97 chrome::GetDefaultUserDataDirectory(&user_data_dir
);
98 DCHECK(!user_data_dir
.empty());
100 base::FilePath profile_subdir
;
101 if (command_line
.HasSwitch(switches::kProfileDirectory
)) {
103 command_line
.GetSwitchValuePath(switches::kProfileDirectory
);
105 profile_subdir
= base::FilePath(ASCIIToUTF16(chrome::kInitialProfile
));
107 DCHECK(!profile_subdir
.empty());
109 base::FilePath profile_path
= user_data_dir
.Append(profile_subdir
);
111 if (command_line
.HasSwitch(switches::kApp
)) {
112 app_name
= UTF8ToUTF16(web_app::GenerateApplicationNameFromURL(
113 GURL(command_line
.GetSwitchValueASCII(switches::kApp
))));
114 } else if (command_line
.HasSwitch(switches::kAppId
)) {
115 app_name
= UTF8ToUTF16(web_app::GenerateApplicationNameFromExtensionId(
116 command_line
.GetSwitchValueASCII(switches::kAppId
)));
117 } else if (command_line
.HasSwitch(switches::kShowAppList
)) {
118 app_name
= GetAppListAppName();
120 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
121 app_name
= ShellUtil::GetBrowserModelId(dist
, is_per_user_install
);
123 DCHECK(!app_name
.empty());
125 return ShellIntegration::GetAppModelIdForProfile(app_name
, profile_path
);
128 void MigrateChromiumShortcutsCallback() {
129 // This should run on the file thread.
130 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
132 // Get full path of chrome.
133 base::FilePath chrome_exe
;
134 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
))
137 // Locations to check for shortcuts migration.
138 static const struct {
140 const wchar_t* sub_dir
;
143 base::DIR_TASKBAR_PINS
,
146 base::DIR_USER_DESKTOP
,
149 base::DIR_START_MENU
,
153 L
"Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\StartMenu"
157 for (int i
= 0; i
< arraysize(kLocations
); ++i
) {
159 if (!PathService::Get(kLocations
[i
].location_id
, &path
)) {
164 if (kLocations
[i
].sub_dir
)
165 path
= path
.Append(kLocations
[i
].sub_dir
);
167 bool check_dual_mode
= (kLocations
[i
].location_id
== base::DIR_START_MENU
);
168 ShellIntegration::MigrateShortcutsInPathInternal(chrome_exe
, path
,
173 ShellIntegration::DefaultWebClientState
174 GetDefaultWebClientStateFromShellUtilDefaultState(
175 ShellUtil::DefaultState default_state
) {
176 switch (default_state
) {
177 case ShellUtil::NOT_DEFAULT
:
178 return ShellIntegration::NOT_DEFAULT
;
179 case ShellUtil::IS_DEFAULT
:
180 return ShellIntegration::IS_DEFAULT
;
182 DCHECK_EQ(ShellUtil::UNKNOWN_DEFAULT
, default_state
);
183 return ShellIntegration::UNKNOWN_DEFAULT
;
189 ShellIntegration::DefaultWebClientSetPermission
190 ShellIntegration::CanSetAsDefaultBrowser() {
191 if (!BrowserDistribution::GetDistribution()->CanSetAsDefault())
192 return SET_DEFAULT_NOT_ALLOWED
;
194 if (ShellUtil::CanMakeChromeDefaultUnattended())
195 return SET_DEFAULT_UNATTENDED
;
197 return SET_DEFAULT_INTERACTIVE
;
200 bool ShellIntegration::SetAsDefaultBrowser() {
201 base::FilePath chrome_exe
;
202 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
203 LOG(ERROR
) << "Error getting app exe path";
207 // From UI currently we only allow setting default browser for current user.
208 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
209 if (!ShellUtil::MakeChromeDefault(dist
, ShellUtil::CURRENT_USER
,
210 chrome_exe
.value(), true)) {
211 LOG(ERROR
) << "Chrome could not be set as default browser.";
215 VLOG(1) << "Chrome registered as default browser.";
219 bool ShellIntegration::SetAsDefaultProtocolClient(const std::string
& protocol
) {
220 if (protocol
.empty())
223 base::FilePath chrome_exe
;
224 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
225 LOG(ERROR
) << "Error getting app exe path";
229 string16
wprotocol(UTF8ToUTF16(protocol
));
230 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
231 if (!ShellUtil::MakeChromeDefaultProtocolClient(dist
, chrome_exe
.value(),
233 LOG(ERROR
) << "Chrome could not be set as default handler for "
238 VLOG(1) << "Chrome registered as default handler for " << protocol
<< ".";
242 bool ShellIntegration::SetAsDefaultBrowserInteractive() {
243 base::FilePath chrome_exe
;
244 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
245 NOTREACHED() << "Error getting app exe path";
249 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
250 if (!ShellUtil::ShowMakeChromeDefaultSystemUI(dist
, chrome_exe
.value())) {
251 LOG(ERROR
) << "Failed to launch the set-default-browser Windows UI.";
255 VLOG(1) << "Set-default-browser Windows UI completed.";
259 bool ShellIntegration::SetAsDefaultProtocolClientInteractive(
260 const std::string
& protocol
) {
261 base::FilePath chrome_exe
;
262 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
263 NOTREACHED() << "Error getting app exe path";
267 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
268 string16
wprotocol(UTF8ToUTF16(protocol
));
269 if (!ShellUtil::ShowMakeChromeDefaultProtocolClientSystemUI(
270 dist
, chrome_exe
.value(), wprotocol
)) {
271 LOG(ERROR
) << "Failed to launch the set-default-client Windows UI.";
275 VLOG(1) << "Set-default-client Windows UI completed.";
279 ShellIntegration::DefaultWebClientState
ShellIntegration::GetDefaultBrowser() {
280 return GetDefaultWebClientStateFromShellUtilDefaultState(
281 ShellUtil::GetChromeDefaultState());
284 ShellIntegration::DefaultWebClientState
285 ShellIntegration::IsDefaultProtocolClient(const std::string
& protocol
) {
286 return GetDefaultWebClientStateFromShellUtilDefaultState(
287 ShellUtil::GetChromeDefaultProtocolClientState(UTF8ToUTF16(protocol
)));
290 std::string
ShellIntegration::GetApplicationForProtocol(const GURL
& url
) {
291 // TODO(calamity): this will be implemented when external_protocol_dialog is
292 // refactored on windows.
294 return std::string();
297 // There is no reliable way to say which browser is default on a machine (each
298 // browser can have some of the protocols/shortcuts). So we look for only HTTP
299 // protocol handler. Even this handler is located at different places in
300 // registry on XP and Vista:
301 // - HKCR\http\shell\open\command (XP)
302 // - HKCU\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\
303 // http\UserChoice (Vista)
304 // This method checks if Firefox is defualt browser by checking these
305 // locations and returns true if Firefox traces are found there. In case of
306 // error (or if Firefox is not found)it returns the default value which
308 bool ShellIntegration::IsFirefoxDefaultBrowser() {
309 bool ff_default
= false;
310 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
312 base::win::RegKey
key(HKEY_CURRENT_USER
,
313 ShellUtil::kRegVistaUrlPrefs
, KEY_READ
);
314 if (key
.Valid() && (key
.ReadValue(L
"Progid", &app_cmd
) == ERROR_SUCCESS
) &&
315 app_cmd
== L
"FirefoxURL")
318 string16
key_path(L
"http");
319 key_path
.append(ShellUtil::kRegShellOpen
);
320 base::win::RegKey
key(HKEY_CLASSES_ROOT
, key_path
.c_str(), KEY_READ
);
322 if (key
.Valid() && (key
.ReadValue(L
"", &app_cmd
) == ERROR_SUCCESS
) &&
323 string16::npos
!= StringToLowerASCII(app_cmd
).find(L
"firefox"))
329 string16
ShellIntegration::GetAppModelIdForProfile(
330 const string16
& app_name
,
331 const base::FilePath
& profile_path
) {
332 std::vector
<string16
> components
;
333 components
.push_back(app_name
);
334 const string16
profile_id(GetProfileIdFromPath(profile_path
));
335 if (!profile_id
.empty())
336 components
.push_back(profile_id
);
337 return ShellUtil::BuildAppModelId(components
);
340 string16
ShellIntegration::GetChromiumModelIdForProfile(
341 const base::FilePath
& profile_path
) {
342 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
343 base::FilePath chrome_exe
;
344 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
346 return dist
->GetBaseAppId();
348 return GetAppModelIdForProfile(
349 ShellUtil::GetBrowserModelId(
350 dist
, InstallUtil::IsPerUserInstall(chrome_exe
.value().c_str())),
354 string16
ShellIntegration::GetAppListAppModelIdForProfile(
355 const base::FilePath
& profile_path
) {
356 return ShellIntegration::GetAppModelIdForProfile(
357 GetAppListAppName(), profile_path
);
360 string16
ShellIntegration::GetChromiumIconLocation() {
361 // Determine the path to chrome.exe. If we can't determine what that is,
362 // we have bigger fish to fry...
363 base::FilePath chrome_exe
;
364 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
369 return ShellUtil::FormatIconLocation(
371 BrowserDistribution::GetDistribution()->GetIconIndex());
374 void ShellIntegration::MigrateChromiumShortcuts() {
375 if (base::win::GetVersion() < base::win::VERSION_WIN7
)
378 // This needs to happen eventually (e.g. so that the appid is fixed and the
379 // run-time Chrome icon is merged with the taskbar shortcut), but this is not
380 // urgent and shouldn't delay Chrome startup.
381 static const int64 kMigrateChromiumShortcutsDelaySeconds
= 15;
382 BrowserThread::PostDelayedTask(
383 BrowserThread::FILE, FROM_HERE
,
384 base::Bind(&MigrateChromiumShortcutsCallback
),
385 base::TimeDelta::FromSeconds(kMigrateChromiumShortcutsDelaySeconds
));
388 int ShellIntegration::MigrateShortcutsInPathInternal(
389 const base::FilePath
& chrome_exe
,
390 const base::FilePath
& path
,
391 bool check_dual_mode
) {
392 DCHECK(base::win::GetVersion() >= base::win::VERSION_WIN7
);
394 // Enumerate all pinned shortcuts in the given path directly.
395 file_util::FileEnumerator
shortcuts_enum(
396 path
, false, // not recursive
397 file_util::FileEnumerator::FILES
, FILE_PATH_LITERAL("*.lnk"));
399 bool is_per_user_install
=
400 InstallUtil::IsPerUserInstall(chrome_exe
.value().c_str());
402 int shortcuts_migrated
= 0;
403 base::FilePath target_path
;
405 base::win::ScopedPropVariant propvariant
;
406 for (base::FilePath shortcut
= shortcuts_enum
.Next(); !shortcut
.empty();
407 shortcut
= shortcuts_enum
.Next()) {
408 // TODO(gab): Use ProgramCompare instead of comparing FilePaths below once
409 // it is fixed to work with FilePaths with spaces.
410 if (!base::win::ResolveShortcut(shortcut
, &target_path
, &arguments
) ||
411 chrome_exe
!= target_path
) {
414 CommandLine
command_line(CommandLine::FromString(base::StringPrintf(
415 L
"\"%ls\" %ls", target_path
.value().c_str(), arguments
.c_str())));
417 // Get the expected AppId for this Chrome shortcut.
418 string16
expected_app_id(
419 GetExpectedAppId(command_line
, is_per_user_install
));
420 if (expected_app_id
.empty())
423 // Load the shortcut.
424 base::win::ScopedComPtr
<IShellLink
> shell_link
;
425 base::win::ScopedComPtr
<IPersistFile
> persist_file
;
426 if (FAILED(shell_link
.CreateInstance(CLSID_ShellLink
, NULL
,
427 CLSCTX_INPROC_SERVER
)) ||
428 FAILED(persist_file
.QueryFrom(shell_link
)) ||
429 FAILED(persist_file
->Load(shortcut
.value().c_str(), STGM_READ
))) {
430 DLOG(WARNING
) << "Failed loading shortcut at " << shortcut
.value();
434 // Any properties that need to be updated on the shortcut will be stored in
435 // |updated_properties|.
436 base::win::ShortcutProperties updated_properties
;
438 // Validate the existing app id for the shortcut.
439 base::win::ScopedComPtr
<IPropertyStore
> property_store
;
441 if (FAILED(property_store
.QueryFrom(shell_link
)) ||
442 property_store
->GetValue(PKEY_AppUserModel_ID
,
443 propvariant
.Receive()) != S_OK
) {
444 // When in doubt, prefer not updating the shortcut.
448 switch (propvariant
.get().vt
) {
450 // If there is no app_id set, set our app_id if one is expected.
451 if (!expected_app_id
.empty())
452 updated_properties
.set_app_id(expected_app_id
);
455 if (expected_app_id
!= string16(propvariant
.get().pwszVal
))
456 updated_properties
.set_app_id(expected_app_id
);
464 // Only set dual mode if the expected app id is the default app id.
465 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
466 string16
default_chromium_model_id(
467 ShellUtil::GetBrowserModelId(dist
, is_per_user_install
));
468 if (check_dual_mode
&& expected_app_id
== default_chromium_model_id
) {
470 if (property_store
->GetValue(PKEY_AppUserModel_IsDualMode
,
471 propvariant
.Receive()) != S_OK
) {
472 // When in doubt, prefer to not update the shortcut.
476 switch (propvariant
.get().vt
) {
478 // If dual_mode is not set at all, make sure it gets set to true.
479 updated_properties
.set_dual_mode(true);
482 // If it is set to false, make sure it gets set to true as well.
483 if (!propvariant
.get().boolVal
)
484 updated_properties
.set_dual_mode(true);
493 persist_file
.Release();
494 shell_link
.Release();
496 // Update the shortcut if some of its properties need to be updated.
497 if (updated_properties
.options
&&
498 base::win::CreateOrUpdateShortcutLink(
499 shortcut
, updated_properties
,
500 base::win::SHORTCUT_UPDATE_EXISTING
)) {
501 ++shortcuts_migrated
;
504 return shortcuts_migrated
;
507 base::FilePath
ShellIntegration::GetStartMenuShortcut(
508 const base::FilePath
& chrome_exe
) {
509 static const int kFolderIds
[] = {
510 base::DIR_COMMON_START_MENU
,
511 base::DIR_START_MENU
,
513 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
514 string16
shortcut_name(dist
->GetAppShortCutName());
515 base::FilePath shortcut
;
517 // Check both the common and the per-user Start Menu folders for system-level
520 InstallUtil::IsPerUserInstall(chrome_exe
.value().c_str()) ? 1 : 0;
521 for (; folder
< arraysize(kFolderIds
); ++folder
) {
522 if (!PathService::Get(kFolderIds
[folder
], &shortcut
)) {
527 shortcut
= shortcut
.Append(shortcut_name
).Append(shortcut_name
+
529 if (file_util::PathExists(shortcut
))
533 return base::FilePath();