web_app_win.cc revision a1401311d1ab56c4ed0a474bd38c108f75cb0cd9
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/web_applications/web_app_win.h" 6 7#include <shlobj.h> 8 9#include "base/command_line.h" 10#include "base/file_util.h" 11#include "base/files/file_enumerator.h" 12#include "base/logging.h" 13#include "base/md5.h" 14#include "base/path_service.h" 15#include "base/strings/string_piece.h" 16#include "base/strings/stringprintf.h" 17#include "base/strings/utf_string_conversions.h" 18#include "base/win/shortcut.h" 19#include "base/win/windows_version.h" 20#include "chrome/browser/web_applications/web_app.h" 21#include "chrome/common/chrome_switches.h" 22#include "chrome/installer/util/browser_distribution.h" 23#include "chrome/installer/util/shell_util.h" 24#include "chrome/installer/util/util_constants.h" 25#include "content/public/browser/browser_thread.h" 26#include "ui/gfx/icon_util.h" 27#include "ui/gfx/image/image.h" 28#include "ui/gfx/image/image_family.h" 29 30namespace { 31 32const base::FilePath::CharType kIconChecksumFileExt[] = 33 FILE_PATH_LITERAL(".ico.md5"); 34 35// Width and height of icons exported to .ico files. 36 37// Calculates checksum of an icon family using MD5. 38// The checksum is derived from all of the icons in the family. 39void GetImageCheckSum(const gfx::ImageFamily& image, base::MD5Digest* digest) { 40 DCHECK(digest); 41 base::MD5Context md5_context; 42 base::MD5Init(&md5_context); 43 44 for (gfx::ImageFamily::const_iterator it = image.begin(); it != image.end(); 45 ++it) { 46 SkBitmap bitmap = it->AsBitmap(); 47 48 SkAutoLockPixels image_lock(bitmap); 49 base::StringPiece image_data( 50 reinterpret_cast<const char*>(bitmap.getPixels()), bitmap.getSize()); 51 base::MD5Update(&md5_context, image_data); 52 } 53 54 base::MD5Final(digest, &md5_context); 55} 56 57// Saves |image| as an |icon_file| with the checksum. 58bool SaveIconWithCheckSum(const base::FilePath& icon_file, 59 const gfx::ImageFamily& image) { 60 if (!IconUtil::CreateIconFileFromImageFamily(image, icon_file)) 61 return false; 62 63 base::MD5Digest digest; 64 GetImageCheckSum(image, &digest); 65 66 base::FilePath cheksum_file(icon_file.ReplaceExtension(kIconChecksumFileExt)); 67 return base::WriteFile(cheksum_file, 68 reinterpret_cast<const char*>(&digest), 69 sizeof(digest)) == sizeof(digest); 70} 71 72// Returns true if |icon_file| is missing or different from |image|. 73bool ShouldUpdateIcon(const base::FilePath& icon_file, 74 const gfx::ImageFamily& image) { 75 base::FilePath checksum_file( 76 icon_file.ReplaceExtension(kIconChecksumFileExt)); 77 78 // Returns true if icon_file or checksum file is missing. 79 if (!base::PathExists(icon_file) || 80 !base::PathExists(checksum_file)) 81 return true; 82 83 base::MD5Digest persisted_image_checksum; 84 if (sizeof(persisted_image_checksum) != base::ReadFile(checksum_file, 85 reinterpret_cast<char*>(&persisted_image_checksum), 86 sizeof(persisted_image_checksum))) 87 return true; 88 89 base::MD5Digest downloaded_image_checksum; 90 GetImageCheckSum(image, &downloaded_image_checksum); 91 92 // Update icon if checksums are not equal. 93 return memcmp(&persisted_image_checksum, &downloaded_image_checksum, 94 sizeof(base::MD5Digest)) != 0; 95} 96 97// Returns true if |shortcut_file_name| matches profile |profile_path|, and has 98// an --app-id flag. 99bool IsAppShortcutForProfile(const base::FilePath& shortcut_file_name, 100 const base::FilePath& profile_path) { 101 base::string16 cmd_line_string; 102 if (base::win::ResolveShortcut(shortcut_file_name, NULL, &cmd_line_string)) { 103 cmd_line_string = L"program " + cmd_line_string; 104 CommandLine shortcut_cmd_line = CommandLine::FromString(cmd_line_string); 105 return shortcut_cmd_line.HasSwitch(switches::kProfileDirectory) && 106 shortcut_cmd_line.GetSwitchValuePath(switches::kProfileDirectory) == 107 profile_path.BaseName() && 108 shortcut_cmd_line.HasSwitch(switches::kAppId); 109 } 110 111 return false; 112} 113 114// Finds shortcuts in |shortcut_path| that match profile for |profile_path| and 115// extension with title |shortcut_name|. 116// If |shortcut_name| is empty, finds all shortcuts matching |profile_path|. 117std::vector<base::FilePath> FindAppShortcutsByProfileAndTitle( 118 const base::FilePath& shortcut_path, 119 const base::FilePath& profile_path, 120 const base::string16& shortcut_name) { 121 std::vector<base::FilePath> shortcut_paths; 122 123 if (shortcut_name.empty()) { 124 // Find all shortcuts for this profile. 125 base::FileEnumerator files(shortcut_path, false, 126 base::FileEnumerator::FILES, 127 FILE_PATH_LITERAL("*.lnk")); 128 base::FilePath shortcut_file = files.Next(); 129 while (!shortcut_file.empty()) { 130 if (IsAppShortcutForProfile(shortcut_file, profile_path)) 131 shortcut_paths.push_back(shortcut_file); 132 shortcut_file = files.Next(); 133 } 134 } else { 135 // Find all shortcuts matching |shortcut_name|. 136 base::FilePath base_path = shortcut_path. 137 Append(web_app::internals::GetSanitizedFileName(shortcut_name)). 138 AddExtension(FILE_PATH_LITERAL(".lnk")); 139 140 const int fileNamesToCheck = 10; 141 for (int i = 0; i < fileNamesToCheck; ++i) { 142 base::FilePath shortcut_file = base_path; 143 if (i > 0) { 144 shortcut_file = shortcut_file.InsertBeforeExtensionASCII( 145 base::StringPrintf(" (%d)", i)); 146 } 147 if (base::PathExists(shortcut_file) && 148 IsAppShortcutForProfile(shortcut_file, profile_path)) { 149 shortcut_paths.push_back(shortcut_file); 150 } 151 } 152 } 153 154 return shortcut_paths; 155} 156 157// Creates application shortcuts in a given set of paths. 158// |shortcut_paths| is a list of directories in which shortcuts should be 159// created. If |creation_reason| is SHORTCUT_CREATION_AUTOMATED and there is an 160// existing shortcut to this app for this profile, does nothing (succeeding). 161// Returns true on success, false on failure. 162// Must be called on the FILE thread. 163bool CreateShortcutsInPaths( 164 const base::FilePath& web_app_path, 165 const ShellIntegration::ShortcutInfo& shortcut_info, 166 const std::vector<base::FilePath>& shortcut_paths, 167 web_app::ShortcutCreationReason creation_reason, 168 std::vector<base::FilePath>* out_filenames) { 169 // Ensure web_app_path exists. 170 if (!base::PathExists(web_app_path) && 171 !base::CreateDirectory(web_app_path)) { 172 return false; 173 } 174 175 // Generates file name to use with persisted ico and shortcut file. 176 base::FilePath file_name = 177 web_app::internals::GetSanitizedFileName(shortcut_info.title); 178 179 // Creates an ico file to use with shortcut. 180 base::FilePath icon_file = web_app_path.Append(file_name).AddExtension( 181 FILE_PATH_LITERAL(".ico")); 182 if (!web_app::internals::CheckAndSaveIcon(icon_file, shortcut_info.favicon)) { 183 return false; 184 } 185 186 base::FilePath chrome_exe; 187 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) { 188 NOTREACHED(); 189 return false; 190 } 191 192 // Working directory. 193 base::FilePath working_dir(chrome_exe.DirName()); 194 195 CommandLine cmd_line(CommandLine::NO_PROGRAM); 196 cmd_line = ShellIntegration::CommandLineArgsForLauncher(shortcut_info.url, 197 shortcut_info.extension_id, shortcut_info.profile_path); 198 199 // TODO(evan): we rely on the fact that command_line_string() is 200 // properly quoted for a Windows command line. The method on 201 // CommandLine should probably be renamed to better reflect that 202 // fact. 203 base::string16 wide_switches(cmd_line.GetCommandLineString()); 204 205 // Sanitize description 206 base::string16 description = shortcut_info.description; 207 if (description.length() >= MAX_PATH) 208 description.resize(MAX_PATH - 1); 209 210 // Generates app id from web app url and profile path. 211 std::string app_name(web_app::GenerateApplicationNameFromInfo(shortcut_info)); 212 base::string16 app_id(ShellIntegration::GetAppModelIdForProfile( 213 base::UTF8ToUTF16(app_name), shortcut_info.profile_path)); 214 215 bool success = true; 216 for (size_t i = 0; i < shortcut_paths.size(); ++i) { 217 base::FilePath shortcut_file = shortcut_paths[i].Append(file_name). 218 AddExtension(installer::kLnkExt); 219 if (creation_reason == web_app::SHORTCUT_CREATION_AUTOMATED) { 220 // Check whether there is an existing shortcut to this app. 221 std::vector<base::FilePath> shortcut_files = 222 FindAppShortcutsByProfileAndTitle(shortcut_paths[i], 223 shortcut_info.profile_path, 224 shortcut_info.title); 225 if (!shortcut_files.empty()) 226 continue; 227 } 228 if (shortcut_paths[i] != web_app_path) { 229 int unique_number = 230 base::GetUniquePathNumber(shortcut_file, 231 base::FilePath::StringType()); 232 if (unique_number == -1) { 233 success = false; 234 continue; 235 } else if (unique_number > 0) { 236 shortcut_file = shortcut_file.InsertBeforeExtensionASCII( 237 base::StringPrintf(" (%d)", unique_number)); 238 } 239 } 240 base::win::ShortcutProperties shortcut_properties; 241 shortcut_properties.set_target(chrome_exe); 242 shortcut_properties.set_working_dir(working_dir); 243 shortcut_properties.set_arguments(wide_switches); 244 shortcut_properties.set_description(description); 245 shortcut_properties.set_icon(icon_file, 0); 246 shortcut_properties.set_app_id(app_id); 247 shortcut_properties.set_dual_mode(false); 248 if (!base::PathExists(shortcut_file.DirName()) && 249 !base::CreateDirectory(shortcut_file.DirName())) { 250 NOTREACHED(); 251 return false; 252 } 253 success = base::win::CreateOrUpdateShortcutLink( 254 shortcut_file, shortcut_properties, 255 base::win::SHORTCUT_CREATE_ALWAYS) && success; 256 if (out_filenames) 257 out_filenames->push_back(shortcut_file); 258 } 259 260 return success; 261} 262 263// Gets the directories with shortcuts for an app, and deletes the shortcuts. 264// This will search the standard locations for shortcuts named |title| that open 265// in the profile with |profile_path|. 266// |was_pinned_to_taskbar| will be set to true if there was previously a 267// shortcut pinned to the taskbar for this app; false otherwise. 268// If |web_app_path| is empty, this will not delete shortcuts from the web app 269// directory. If |title| is empty, all shortcuts for this profile will be 270// deleted. 271// |shortcut_paths| will be populated with a list of directories where shortcuts 272// for this app were found (and deleted). This will delete duplicate shortcuts, 273// but only return each path once, even if it contained multiple deleted 274// shortcuts. Both of these may be NULL. 275void GetShortcutLocationsAndDeleteShortcuts( 276 const base::FilePath& web_app_path, 277 const base::FilePath& profile_path, 278 const base::string16& title, 279 bool* was_pinned_to_taskbar, 280 std::vector<base::FilePath>* shortcut_paths) { 281 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE)); 282 283 // Get all possible locations for shortcuts. 284 ShellIntegration::ShortcutLocations all_shortcut_locations; 285 all_shortcut_locations.in_quick_launch_bar = true; 286 all_shortcut_locations.on_desktop = true; 287 // Delete shortcuts from the Chrome Apps subdirectory. 288 // This matches the subdir name set by CreateApplicationShortcutView::Accept 289 // for Chrome apps (not URL apps, but this function does not apply for them). 290 all_shortcut_locations.applications_menu_location = 291 ShellIntegration::APP_MENU_LOCATION_SUBDIR_CHROMEAPPS; 292 std::vector<base::FilePath> all_paths = web_app::internals::GetShortcutPaths( 293 all_shortcut_locations); 294 if (base::win::GetVersion() >= base::win::VERSION_WIN7 && 295 !web_app_path.empty()) { 296 all_paths.push_back(web_app_path); 297 } 298 299 if (was_pinned_to_taskbar) { 300 // Determine if there is a link to this app in the TaskBar pin directory. 301 base::FilePath taskbar_pin_path; 302 if (PathService::Get(base::DIR_TASKBAR_PINS, &taskbar_pin_path)) { 303 std::vector<base::FilePath> taskbar_pin_files = 304 FindAppShortcutsByProfileAndTitle(taskbar_pin_path, profile_path, 305 title); 306 *was_pinned_to_taskbar = !taskbar_pin_files.empty(); 307 } else { 308 *was_pinned_to_taskbar = false; 309 } 310 } 311 312 for (std::vector<base::FilePath>::const_iterator i = all_paths.begin(); 313 i != all_paths.end(); ++i) { 314 std::vector<base::FilePath> shortcut_files = 315 FindAppShortcutsByProfileAndTitle(*i, profile_path, title); 316 if (shortcut_paths && !shortcut_files.empty()) { 317 shortcut_paths->push_back(*i); 318 } 319 for (std::vector<base::FilePath>::const_iterator j = shortcut_files.begin(); 320 j != shortcut_files.end(); ++j) { 321 // Any shortcut could have been pinned, either by chrome or the user, so 322 // they are all unpinned. 323 base::win::TaskbarUnpinShortcutLink(j->value().c_str()); 324 base::DeleteFile(*j, false); 325 } 326 } 327} 328 329} // namespace 330 331namespace web_app { 332 333base::FilePath CreateShortcutInWebAppDir( 334 const base::FilePath& web_app_dir, 335 const ShellIntegration::ShortcutInfo& shortcut_info) { 336 std::vector<base::FilePath> paths; 337 paths.push_back(web_app_dir); 338 std::vector<base::FilePath> out_filenames; 339 CreateShortcutsInPaths(web_app_dir, shortcut_info, paths, 340 SHORTCUT_CREATION_BY_USER, &out_filenames); 341 DCHECK_EQ(out_filenames.size(), 1u); 342 return out_filenames[0]; 343} 344 345namespace internals { 346 347// Saves |image| to |icon_file| if the file is outdated and refresh shell's 348// icon cache to ensure correct icon is displayed. Returns true if icon_file 349// is up to date or successfully updated. 350bool CheckAndSaveIcon(const base::FilePath& icon_file, 351 const gfx::ImageFamily& image) { 352 if (ShouldUpdateIcon(icon_file, image)) { 353 if (SaveIconWithCheckSum(icon_file, image)) { 354 // Refresh shell's icon cache. This call is quite disruptive as user would 355 // see explorer rebuilding the icon cache. It would be great that we find 356 // a better way to achieve this. 357 SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST | SHCNF_FLUSHNOWAIT, 358 NULL, NULL); 359 } else { 360 return false; 361 } 362 } 363 364 return true; 365} 366 367bool CreatePlatformShortcuts( 368 const base::FilePath& web_app_path, 369 const ShellIntegration::ShortcutInfo& shortcut_info, 370 const ShellIntegration::ShortcutLocations& creation_locations, 371 ShortcutCreationReason creation_reason) { 372 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE)); 373 374 // Shortcut paths under which to create shortcuts. 375 std::vector<base::FilePath> shortcut_paths = 376 GetShortcutPaths(creation_locations); 377 378 bool pin_to_taskbar = creation_locations.in_quick_launch_bar && 379 (base::win::GetVersion() >= base::win::VERSION_WIN7); 380 381 // Create/update the shortcut in the web app path for the "Pin To Taskbar" 382 // option in Win7. We use the web app path shortcut because we will overwrite 383 // it rather than appending unique numbers if the shortcut already exists. 384 // This prevents pinned apps from having unique numbers in their names. 385 if (pin_to_taskbar) 386 shortcut_paths.push_back(web_app_path); 387 388 if (shortcut_paths.empty()) 389 return false; 390 391 if (!CreateShortcutsInPaths(web_app_path, shortcut_info, shortcut_paths, 392 creation_reason, NULL)) 393 return false; 394 395 if (pin_to_taskbar) { 396 base::FilePath file_name = 397 web_app::internals::GetSanitizedFileName(shortcut_info.title); 398 // Use the web app path shortcut for pinning to avoid having unique numbers 399 // in the application name. 400 base::FilePath shortcut_to_pin = web_app_path.Append(file_name). 401 AddExtension(installer::kLnkExt); 402 if (!base::win::TaskbarPinShortcutLink(shortcut_to_pin.value().c_str())) 403 return false; 404 } 405 406 return true; 407} 408 409void UpdatePlatformShortcuts( 410 const base::FilePath& web_app_path, 411 const base::string16& old_app_title, 412 const ShellIntegration::ShortcutInfo& shortcut_info) { 413 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE)); 414 415 // Generates file name to use with persisted ico and shortcut file. 416 base::FilePath file_name = 417 web_app::internals::GetSanitizedFileName(shortcut_info.title); 418 419 if (old_app_title != shortcut_info.title) { 420 // The app's title has changed. Delete all existing app shortcuts and 421 // recreate them in any locations they already existed (but do not add them 422 // to locations where they do not currently exist). 423 bool was_pinned_to_taskbar; 424 std::vector<base::FilePath> shortcut_paths; 425 GetShortcutLocationsAndDeleteShortcuts( 426 web_app_path, shortcut_info.profile_path, old_app_title, 427 &was_pinned_to_taskbar, &shortcut_paths); 428 CreateShortcutsInPaths(web_app_path, shortcut_info, shortcut_paths, 429 SHORTCUT_CREATION_BY_USER, NULL); 430 // If the shortcut was pinned to the taskbar, 431 // GetShortcutLocationsAndDeleteShortcuts will have deleted it. In that 432 // case, re-pin it. 433 if (was_pinned_to_taskbar) { 434 base::FilePath file_name = 435 web_app::internals::GetSanitizedFileName(shortcut_info.title); 436 // Use the web app path shortcut for pinning to avoid having unique 437 // numbers in the application name. 438 base::FilePath shortcut_to_pin = web_app_path.Append(file_name). 439 AddExtension(installer::kLnkExt); 440 base::win::TaskbarPinShortcutLink(shortcut_to_pin.value().c_str()); 441 } 442 } 443 444 // If an icon file exists, and is out of date, replace it with the new icon 445 // and let the shell know the icon has been modified. 446 base::FilePath icon_file = web_app_path.Append(file_name).AddExtension( 447 FILE_PATH_LITERAL(".ico")); 448 if (base::PathExists(icon_file)) { 449 web_app::internals::CheckAndSaveIcon(icon_file, shortcut_info.favicon); 450 } 451} 452 453void DeletePlatformShortcuts( 454 const base::FilePath& web_app_path, 455 const ShellIntegration::ShortcutInfo& shortcut_info) { 456 GetShortcutLocationsAndDeleteShortcuts( 457 web_app_path, shortcut_info.profile_path, shortcut_info.title, NULL, 458 NULL); 459 460 // If there are no more shortcuts in the Chrome Apps subdirectory, remove it. 461 base::FilePath chrome_apps_dir; 462 if (ShellUtil::GetShortcutPath( 463 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR, 464 BrowserDistribution::GetDistribution(), 465 ShellUtil::CURRENT_USER, 466 &chrome_apps_dir)) { 467 if (base::IsDirectoryEmpty(chrome_apps_dir)) 468 base::DeleteFile(chrome_apps_dir, false); 469 } 470} 471 472void DeleteAllShortcutsForProfile(const base::FilePath& profile_path) { 473 GetShortcutLocationsAndDeleteShortcuts(base::FilePath(), profile_path, L"", 474 NULL, NULL); 475 476 // If there are no more shortcuts in the Chrome Apps subdirectory, remove it. 477 base::FilePath chrome_apps_dir; 478 if (ShellUtil::GetShortcutPath( 479 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR, 480 BrowserDistribution::GetDistribution(), 481 ShellUtil::CURRENT_USER, 482 &chrome_apps_dir)) { 483 if (base::IsDirectoryEmpty(chrome_apps_dir)) 484 base::DeleteFile(chrome_apps_dir, false); 485 } 486} 487 488std::vector<base::FilePath> GetShortcutPaths( 489 const ShellIntegration::ShortcutLocations& creation_locations) { 490 // Shortcut paths under which to create shortcuts. 491 std::vector<base::FilePath> shortcut_paths; 492 // Locations to add to shortcut_paths. 493 struct { 494 bool use_this_location; 495 ShellUtil::ShortcutLocation location_id; 496 } locations[] = { 497 { 498 creation_locations.on_desktop, 499 ShellUtil::SHORTCUT_LOCATION_DESKTOP 500 }, { 501 creation_locations.applications_menu_location == 502 ShellIntegration::APP_MENU_LOCATION_ROOT, 503 ShellUtil::SHORTCUT_LOCATION_START_MENU_ROOT 504 }, { 505 creation_locations.applications_menu_location == 506 ShellIntegration::APP_MENU_LOCATION_SUBDIR_CHROME, 507 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_DIR 508 }, { 509 creation_locations.applications_menu_location == 510 ShellIntegration::APP_MENU_LOCATION_SUBDIR_CHROMEAPPS, 511 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR 512 }, { 513 // For Win7+, |in_quick_launch_bar| indicates that we are pinning to 514 // taskbar. This needs to be handled by callers. 515 creation_locations.in_quick_launch_bar && 516 base::win::GetVersion() < base::win::VERSION_WIN7, 517 ShellUtil::SHORTCUT_LOCATION_QUICK_LAUNCH 518 } 519 }; 520 521 BrowserDistribution* dist = BrowserDistribution::GetDistribution(); 522 // Populate shortcut_paths. 523 for (int i = 0; i < arraysize(locations); ++i) { 524 if (locations[i].use_this_location) { 525 base::FilePath path; 526 if (!ShellUtil::GetShortcutPath(locations[i].location_id, 527 dist, 528 ShellUtil::CURRENT_USER, 529 &path)) { 530 NOTREACHED(); 531 continue; 532 } 533 shortcut_paths.push_back(path); 534 } 535 } 536 return shortcut_paths; 537} 538 539} // namespace internals 540 541} // namespace web_app 542