Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(321)

Side by Side Diff: chrome/browser/shell_integration_win.cc

Issue 12321107: Move shell integration code from chrome/browser to apps (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Created 7 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
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.
4
5 #include "chrome/browser/shell_integration.h"
6
7 #include <windows.h>
8 #include <shobjidl.h>
9 #include <propkey.h>
10
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"
39
40 using content::BrowserThread;
41
42 namespace {
43
44 const wchar_t kAppListAppNameSuffix[] = L"AppList";
45
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())
52 return string16();
53
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)) {
61 return string16();
62 }
63
64 // Get joined basenames of user data dir and profile.
65 string16 basenames = profile_path.DirName().BaseName().value() +
66 L"." + profile_path.BaseName().value();
67
68 string16 profile_id;
69 profile_id.reserve(basenames.size());
70
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]) ||
75 basenames[i] == L'.')
76 profile_id += basenames[i];
77 }
78
79 return profile_id;
80 }
81
82 string16 GetAppListAppName() {
83 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
84 string16 app_name(dist->GetBaseAppId());
85 app_name.append(kAppListAppNameSuffix);
86 return app_name;
87 }
88
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 profile_path;
94 if (command_line.HasSwitch(switches::kUserDataDir)) {
95 profile_path =
96 command_line.GetSwitchValuePath(switches::kUserDataDir).AppendASCII(
97 chrome::kInitialProfile);
98 }
99
100 string16 app_name;
101 if (command_line.HasSwitch(switches::kApp)) {
102 app_name = UTF8ToUTF16(web_app::GenerateApplicationNameFromURL(
103 GURL(command_line.GetSwitchValueASCII(switches::kApp))));
104 } else if (command_line.HasSwitch(switches::kAppId)) {
105 app_name = UTF8ToUTF16(web_app::GenerateApplicationNameFromExtensionId(
106 command_line.GetSwitchValueASCII(switches::kAppId)));
107 } else if (command_line.HasSwitch(switches::kShowAppList)) {
108 app_name = GetAppListAppName();
109 } else {
110 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
111 app_name = ShellUtil::GetBrowserModelId(dist, is_per_user_install);
112 }
113
114 return ShellIntegration::GetAppModelIdForProfile(app_name, profile_path);
115 }
116
117 void MigrateChromiumShortcutsCallback() {
118 // This should run on the file thread.
119 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
120
121 // Get full path of chrome.
122 base::FilePath chrome_exe;
123 if (!PathService::Get(base::FILE_EXE, &chrome_exe))
124 return;
125
126 // Locations to check for shortcuts migration.
127 static const struct {
128 int location_id;
129 const wchar_t* sub_dir;
130 } kLocations[] = {
131 {
132 base::DIR_TASKBAR_PINS,
133 NULL
134 }, {
135 base::DIR_USER_DESKTOP,
136 NULL
137 }, {
138 base::DIR_START_MENU,
139 NULL
140 }, {
141 base::DIR_APP_DATA,
142 L"Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\StartMenu"
143 }
144 };
145
146 for (int i = 0; i < arraysize(kLocations); ++i) {
147 base::FilePath path;
148 if (!PathService::Get(kLocations[i].location_id, &path)) {
149 NOTREACHED();
150 continue;
151 }
152
153 if (kLocations[i].sub_dir)
154 path = path.Append(kLocations[i].sub_dir);
155
156 bool check_dual_mode = (kLocations[i].location_id == base::DIR_START_MENU);
157 ShellIntegration::MigrateShortcutsInPathInternal(chrome_exe, path,
158 check_dual_mode);
159 }
160 }
161
162 ShellIntegration::DefaultWebClientState
163 GetDefaultWebClientStateFromShellUtilDefaultState(
164 ShellUtil::DefaultState default_state) {
165 switch (default_state) {
166 case ShellUtil::NOT_DEFAULT:
167 return ShellIntegration::NOT_DEFAULT;
168 case ShellUtil::IS_DEFAULT:
169 return ShellIntegration::IS_DEFAULT;
170 default:
171 DCHECK_EQ(ShellUtil::UNKNOWN_DEFAULT, default_state);
172 return ShellIntegration::UNKNOWN_DEFAULT;
173 }
174 }
175
176 } // namespace
177
178 ShellIntegration::DefaultWebClientSetPermission
179 ShellIntegration::CanSetAsDefaultBrowser() {
180 if (!BrowserDistribution::GetDistribution()->CanSetAsDefault())
181 return SET_DEFAULT_NOT_ALLOWED;
182
183 if (ShellUtil::CanMakeChromeDefaultUnattended())
184 return SET_DEFAULT_UNATTENDED;
185 else
186 return SET_DEFAULT_INTERACTIVE;
187 }
188
189 bool ShellIntegration::SetAsDefaultBrowser() {
190 base::FilePath chrome_exe;
191 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
192 LOG(ERROR) << "Error getting app exe path";
193 return false;
194 }
195
196 // From UI currently we only allow setting default browser for current user.
197 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
198 if (!ShellUtil::MakeChromeDefault(dist, ShellUtil::CURRENT_USER,
199 chrome_exe.value(), true)) {
200 LOG(ERROR) << "Chrome could not be set as default browser.";
201 return false;
202 }
203
204 VLOG(1) << "Chrome registered as default browser.";
205 return true;
206 }
207
208 bool ShellIntegration::SetAsDefaultProtocolClient(const std::string& protocol) {
209 if (protocol.empty())
210 return false;
211
212 base::FilePath chrome_exe;
213 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
214 LOG(ERROR) << "Error getting app exe path";
215 return false;
216 }
217
218 string16 wprotocol(UTF8ToUTF16(protocol));
219 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
220 if (!ShellUtil::MakeChromeDefaultProtocolClient(dist, chrome_exe.value(),
221 wprotocol)) {
222 LOG(ERROR) << "Chrome could not be set as default handler for "
223 << protocol << ".";
224 return false;
225 }
226
227 VLOG(1) << "Chrome registered as default handler for " << protocol << ".";
228 return true;
229 }
230
231 bool ShellIntegration::SetAsDefaultBrowserInteractive() {
232 base::FilePath chrome_exe;
233 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
234 NOTREACHED() << "Error getting app exe path";
235 return false;
236 }
237
238 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
239 if (!ShellUtil::ShowMakeChromeDefaultSystemUI(dist, chrome_exe.value())) {
240 LOG(ERROR) << "Failed to launch the set-default-browser Windows UI.";
241 return false;
242 }
243
244 VLOG(1) << "Set-default-browser Windows UI completed.";
245 return true;
246 }
247
248 bool ShellIntegration::SetAsDefaultProtocolClientInteractive(
249 const std::string& protocol) {
250 base::FilePath chrome_exe;
251 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
252 NOTREACHED() << "Error getting app exe path";
253 return false;
254 }
255
256 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
257 string16 wprotocol(UTF8ToUTF16(protocol));
258 if (!ShellUtil::ShowMakeChromeDefaultProtocolClientSystemUI(
259 dist, chrome_exe.value(), wprotocol)) {
260 LOG(ERROR) << "Failed to launch the set-default-client Windows UI.";
261 return false;
262 }
263
264 VLOG(1) << "Set-default-client Windows UI completed.";
265 return true;
266 }
267
268 ShellIntegration::DefaultWebClientState ShellIntegration::GetDefaultBrowser() {
269 return GetDefaultWebClientStateFromShellUtilDefaultState(
270 ShellUtil::GetChromeDefaultState());
271 }
272
273 ShellIntegration::DefaultWebClientState
274 ShellIntegration::IsDefaultProtocolClient(const std::string& protocol) {
275 return GetDefaultWebClientStateFromShellUtilDefaultState(
276 ShellUtil::GetChromeDefaultProtocolClientState(UTF8ToUTF16(protocol)));
277 }
278
279 std::string ShellIntegration::GetApplicationForProtocol(const GURL& url) {
280 // TODO(calamity): this will be implemented when external_protocol_dialog is
281 // refactored on windows.
282 NOTREACHED();
283 return std::string();
284 }
285
286 // There is no reliable way to say which browser is default on a machine (each
287 // browser can have some of the protocols/shortcuts). So we look for only HTTP
288 // protocol handler. Even this handler is located at different places in
289 // registry on XP and Vista:
290 // - HKCR\http\shell\open\command (XP)
291 // - HKCU\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\
292 // http\UserChoice (Vista)
293 // This method checks if Firefox is defualt browser by checking these
294 // locations and returns true if Firefox traces are found there. In case of
295 // error (or if Firefox is not found)it returns the default value which
296 // is false.
297 bool ShellIntegration::IsFirefoxDefaultBrowser() {
298 bool ff_default = false;
299 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
300 string16 app_cmd;
301 base::win::RegKey key(HKEY_CURRENT_USER,
302 ShellUtil::kRegVistaUrlPrefs, KEY_READ);
303 if (key.Valid() && (key.ReadValue(L"Progid", &app_cmd) == ERROR_SUCCESS) &&
304 app_cmd == L"FirefoxURL")
305 ff_default = true;
306 } else {
307 string16 key_path(L"http");
308 key_path.append(ShellUtil::kRegShellOpen);
309 base::win::RegKey key(HKEY_CLASSES_ROOT, key_path.c_str(), KEY_READ);
310 string16 app_cmd;
311 if (key.Valid() && (key.ReadValue(L"", &app_cmd) == ERROR_SUCCESS) &&
312 string16::npos != StringToLowerASCII(app_cmd).find(L"firefox"))
313 ff_default = true;
314 }
315 return ff_default;
316 }
317
318 string16 ShellIntegration::GetAppModelIdForProfile(
319 const string16& app_name,
320 const base::FilePath& profile_path) {
321 std::vector<string16> components;
322 components.push_back(app_name);
323 const string16 profile_id(GetProfileIdFromPath(profile_path));
324 if (!profile_id.empty())
325 components.push_back(profile_id);
326 return ShellUtil::BuildAppModelId(components);
327 }
328
329 string16 ShellIntegration::GetChromiumModelIdForProfile(
330 const base::FilePath& profile_path) {
331 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
332 base::FilePath chrome_exe;
333 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
334 NOTREACHED();
335 return dist->GetBaseAppId();
336 }
337 return GetAppModelIdForProfile(
338 ShellUtil::GetBrowserModelId(
339 dist, InstallUtil::IsPerUserInstall(chrome_exe.value().c_str())),
340 profile_path);
341 }
342
343 string16 ShellIntegration::GetAppListAppModelIdForProfile(
344 const base::FilePath& profile_path) {
345 return ShellIntegration::GetAppModelIdForProfile(
346 GetAppListAppName(), profile_path);
347 }
348
349 string16 ShellIntegration::GetChromiumIconLocation() {
350 // Determine the path to chrome.exe. If we can't determine what that is,
351 // we have bigger fish to fry...
352 base::FilePath chrome_exe;
353 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
354 NOTREACHED();
355 return string16();
356 }
357
358 return ShellUtil::FormatIconLocation(
359 chrome_exe.value(),
360 BrowserDistribution::GetDistribution()->GetIconIndex());
361 }
362
363 void ShellIntegration::MigrateChromiumShortcuts() {
364 if (base::win::GetVersion() < base::win::VERSION_WIN7)
365 return;
366
367 // This needs to happen eventually (e.g. so that the appid is fixed and the
368 // run-time Chrome icon is merged with the taskbar shortcut), but this is not
369 // urgent and shouldn't delay Chrome startup.
370 static const int64 kMigrateChromiumShortcutsDelaySeconds = 15;
371 BrowserThread::PostDelayedTask(
372 BrowserThread::FILE, FROM_HERE,
373 base::Bind(&MigrateChromiumShortcutsCallback),
374 base::TimeDelta::FromSeconds(kMigrateChromiumShortcutsDelaySeconds));
375 }
376
377 int ShellIntegration::MigrateShortcutsInPathInternal(
378 const base::FilePath& chrome_exe,
379 const base::FilePath& path,
380 bool check_dual_mode) {
381 DCHECK(base::win::GetVersion() >= base::win::VERSION_WIN7);
382
383 // Enumerate all pinned shortcuts in the given path directly.
384 file_util::FileEnumerator shortcuts_enum(
385 path, false, // not recursive
386 file_util::FileEnumerator::FILES, FILE_PATH_LITERAL("*.lnk"));
387
388 bool is_per_user_install =
389 InstallUtil::IsPerUserInstall(chrome_exe.value().c_str());
390
391 int shortcuts_migrated = 0;
392 base::FilePath target_path;
393 string16 arguments;
394 base::win::ScopedPropVariant propvariant;
395 for (base::FilePath shortcut = shortcuts_enum.Next(); !shortcut.empty();
396 shortcut = shortcuts_enum.Next()) {
397 // TODO(gab): Use ProgramCompare instead of comparing FilePaths below once
398 // it is fixed to work with FilePaths with spaces.
399 if (!base::win::ResolveShortcut(shortcut, &target_path, &arguments) ||
400 chrome_exe != target_path) {
401 continue;
402 }
403 CommandLine command_line(CommandLine::FromString(base::StringPrintf(
404 L"\"%ls\" %ls", target_path.value().c_str(), arguments.c_str())));
405
406 // Get the expected AppId for this Chrome shortcut.
407 string16 expected_app_id(
408 GetExpectedAppId(command_line, is_per_user_install));
409 if (expected_app_id.empty())
410 continue;
411
412 // Load the shortcut.
413 base::win::ScopedComPtr<IShellLink> shell_link;
414 base::win::ScopedComPtr<IPersistFile> persist_file;
415 if (FAILED(shell_link.CreateInstance(CLSID_ShellLink, NULL,
416 CLSCTX_INPROC_SERVER)) ||
417 FAILED(persist_file.QueryFrom(shell_link)) ||
418 FAILED(persist_file->Load(shortcut.value().c_str(), STGM_READ))) {
419 DLOG(WARNING) << "Failed loading shortcut at " << shortcut.value();
420 continue;
421 }
422
423 // Any properties that need to be updated on the shortcut will be stored in
424 // |updated_properties|.
425 base::win::ShortcutProperties updated_properties;
426
427 // Validate the existing app id for the shortcut.
428 base::win::ScopedComPtr<IPropertyStore> property_store;
429 propvariant.Reset();
430 if (FAILED(property_store.QueryFrom(shell_link)) ||
431 property_store->GetValue(PKEY_AppUserModel_ID,
432 propvariant.Receive()) != S_OK) {
433 // When in doubt, prefer not updating the shortcut.
434 NOTREACHED();
435 continue;
436 } else {
437 switch (propvariant.get().vt) {
438 case VT_EMPTY:
439 // If there is no app_id set, set our app_id if one is expected.
440 if (!expected_app_id.empty())
441 updated_properties.set_app_id(expected_app_id);
442 break;
443 case VT_LPWSTR:
444 if (expected_app_id != string16(propvariant.get().pwszVal))
445 updated_properties.set_app_id(expected_app_id);
446 break;
447 default:
448 NOTREACHED();
449 continue;
450 }
451 }
452
453 if (check_dual_mode) {
454 propvariant.Reset();
455 if (property_store->GetValue(PKEY_AppUserModel_IsDualMode,
456 propvariant.Receive()) != S_OK) {
457 // When in doubt, prefer to not update the shortcut.
458 NOTREACHED();
459 continue;
460 } else {
461 switch (propvariant.get().vt) {
462 case VT_EMPTY:
463 // If dual_mode is not set at all, make sure it gets set to true.
464 updated_properties.set_dual_mode(true);
465 break;
466 case VT_BOOL:
467 // If it is set to false, make sure it gets set to true as well.
468 if (!propvariant.get().boolVal)
469 updated_properties.set_dual_mode(true);
470 break;
471 default:
472 NOTREACHED();
473 continue;
474 }
475 }
476 }
477
478 persist_file.Release();
479 shell_link.Release();
480
481 // Update the shortcut if some of its properties need to be updated.
482 if (updated_properties.options &&
483 base::win::CreateOrUpdateShortcutLink(
484 shortcut, updated_properties,
485 base::win::SHORTCUT_UPDATE_EXISTING)) {
486 ++shortcuts_migrated;
487 }
488 }
489 return shortcuts_migrated;
490 }
491
492 base::FilePath ShellIntegration::GetStartMenuShortcut(
493 const base::FilePath& chrome_exe) {
494 static const int kFolderIds[] = {
495 base::DIR_COMMON_START_MENU,
496 base::DIR_START_MENU,
497 };
498 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
499 string16 shortcut_name(dist->GetAppShortCutName());
500 base::FilePath shortcut;
501
502 // Check both the common and the per-user Start Menu folders for system-level
503 // installs.
504 size_t folder =
505 InstallUtil::IsPerUserInstall(chrome_exe.value().c_str()) ? 1 : 0;
506 for (; folder < arraysize(kFolderIds); ++folder) {
507 if (!PathService::Get(kFolderIds[folder], &shortcut)) {
508 NOTREACHED();
509 continue;
510 }
511
512 shortcut = shortcut.Append(shortcut_name).Append(shortcut_name +
513 installer::kLnkExt);
514 if (file_util::PathExists(shortcut))
515 return shortcut;
516 }
517
518 return base::FilePath();
519 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698