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/web_applications/web_app_win.h"
9 #include "base/command_line.h"
10 #include "base/file_util.h"
11 #include "base/files/file_enumerator.h"
12 #include "base/logging.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/update_shortcut_worker_win.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/base/win/shell.h"
27 #include "ui/gfx/icon_util.h"
28 #include "ui/gfx/image/image.h"
29 #include "ui/gfx/image/image_family.h"
33 const base::FilePath::CharType kIconChecksumFileExt[] =
34 FILE_PATH_LITERAL(".ico.md5");
36 // Calculates checksum of an icon family using MD5.
37 // The checksum is derived from all of the icons in the family.
38 void GetImageCheckSum(const gfx::ImageFamily& image, base::MD5Digest* digest) {
40 base::MD5Context md5_context;
41 base::MD5Init(&md5_context);
43 for (gfx::ImageFamily::const_iterator it = image.begin(); it != image.end();
45 SkBitmap bitmap = it->AsBitmap();
47 SkAutoLockPixels image_lock(bitmap);
48 base::StringPiece image_data(
49 reinterpret_cast<const char*>(bitmap.getPixels()), bitmap.getSize());
50 base::MD5Update(&md5_context, image_data);
53 base::MD5Final(digest, &md5_context);
56 // Saves |image| as an |icon_file| with the checksum.
57 bool SaveIconWithCheckSum(const base::FilePath& icon_file,
58 const gfx::ImageFamily& image) {
59 if (!IconUtil::CreateIconFileFromImageFamily(image, icon_file))
62 base::MD5Digest digest;
63 GetImageCheckSum(image, &digest);
65 base::FilePath cheksum_file(icon_file.ReplaceExtension(kIconChecksumFileExt));
66 return base::WriteFile(cheksum_file,
67 reinterpret_cast<const char*>(&digest),
68 sizeof(digest)) == sizeof(digest);
71 // Returns true if |icon_file| is missing or different from |image|.
72 bool ShouldUpdateIcon(const base::FilePath& icon_file,
73 const gfx::ImageFamily& image) {
74 base::FilePath checksum_file(
75 icon_file.ReplaceExtension(kIconChecksumFileExt));
77 // Returns true if icon_file or checksum file is missing.
78 if (!base::PathExists(icon_file) ||
79 !base::PathExists(checksum_file))
82 base::MD5Digest persisted_image_checksum;
83 if (sizeof(persisted_image_checksum) != base::ReadFile(checksum_file,
84 reinterpret_cast<char*>(&persisted_image_checksum),
85 sizeof(persisted_image_checksum)))
88 base::MD5Digest downloaded_image_checksum;
89 GetImageCheckSum(image, &downloaded_image_checksum);
91 // Update icon if checksums are not equal.
92 return memcmp(&persisted_image_checksum, &downloaded_image_checksum,
93 sizeof(base::MD5Digest)) != 0;
96 // Returns true if |shortcut_file_name| matches profile |profile_path|, and has
98 bool IsAppShortcutForProfile(const base::FilePath& shortcut_file_name,
99 const base::FilePath& profile_path) {
100 base::string16 cmd_line_string;
101 if (base::win::ResolveShortcut(shortcut_file_name, NULL, &cmd_line_string)) {
102 cmd_line_string = L"program " + cmd_line_string;
103 CommandLine shortcut_cmd_line = CommandLine::FromString(cmd_line_string);
104 return shortcut_cmd_line.HasSwitch(switches::kProfileDirectory) &&
105 shortcut_cmd_line.GetSwitchValuePath(switches::kProfileDirectory) ==
106 profile_path.BaseName() &&
107 shortcut_cmd_line.HasSwitch(switches::kAppId);
113 // Finds shortcuts in |shortcut_path| that match profile for |profile_path| and
114 // extension with title |shortcut_name|.
115 // If |shortcut_name| is empty, finds all shortcuts matching |profile_path|.
116 std::vector<base::FilePath> FindAppShortcutsByProfileAndTitle(
117 const base::FilePath& shortcut_path,
118 const base::FilePath& profile_path,
119 const base::string16& shortcut_name) {
120 std::vector<base::FilePath> shortcut_paths;
122 if (shortcut_name.empty()) {
123 // Find all shortcuts for this profile.
124 base::FileEnumerator files(shortcut_path, false,
125 base::FileEnumerator::FILES,
126 FILE_PATH_LITERAL("*.lnk"));
127 base::FilePath shortcut_file = files.Next();
128 while (!shortcut_file.empty()) {
129 if (IsAppShortcutForProfile(shortcut_file, profile_path))
130 shortcut_paths.push_back(shortcut_file);
131 shortcut_file = files.Next();
134 // Find all shortcuts matching |shortcut_name|.
135 base::FilePath base_path = shortcut_path.
136 Append(web_app::internals::GetSanitizedFileName(shortcut_name)).
137 AddExtension(FILE_PATH_LITERAL(".lnk"));
139 const int fileNamesToCheck = 10;
140 for (int i = 0; i < fileNamesToCheck; ++i) {
141 base::FilePath shortcut_file = base_path;
143 shortcut_file = shortcut_file.InsertBeforeExtensionASCII(
144 base::StringPrintf(" (%d)", i));
146 if (base::PathExists(shortcut_file) &&
147 IsAppShortcutForProfile(shortcut_file, profile_path)) {
148 shortcut_paths.push_back(shortcut_file);
153 return shortcut_paths;
156 // Creates application shortcuts in a given set of paths.
157 // |shortcut_paths| is a list of directories in which shortcuts should be
158 // created. If |creation_reason| is SHORTCUT_CREATION_AUTOMATED and there is an
159 // existing shortcut to this app for this profile, does nothing (succeeding).
160 // Returns true on success, false on failure.
161 // Must be called on the FILE thread.
162 bool CreateShortcutsInPaths(
163 const base::FilePath& web_app_path,
164 const web_app::ShortcutInfo& shortcut_info,
165 const std::vector<base::FilePath>& shortcut_paths,
166 web_app::ShortcutCreationReason creation_reason,
167 std::vector<base::FilePath>* out_filenames) {
168 // Ensure web_app_path exists.
169 if (!base::PathExists(web_app_path) &&
170 !base::CreateDirectory(web_app_path)) {
174 // Generates file name to use with persisted ico and shortcut file.
175 base::FilePath icon_file =
176 web_app::internals::GetIconFilePath(web_app_path, shortcut_info.title);
177 if (!web_app::internals::CheckAndSaveIcon(icon_file, shortcut_info.favicon)) {
181 base::FilePath chrome_exe;
182 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
187 // Working directory.
188 base::FilePath working_dir(chrome_exe.DirName());
190 CommandLine cmd_line(CommandLine::NO_PROGRAM);
191 cmd_line = ShellIntegration::CommandLineArgsForLauncher(shortcut_info.url,
192 shortcut_info.extension_id, shortcut_info.profile_path);
194 // TODO(evan): we rely on the fact that command_line_string() is
195 // properly quoted for a Windows command line. The method on
196 // CommandLine should probably be renamed to better reflect that
198 base::string16 wide_switches(cmd_line.GetCommandLineString());
200 // Sanitize description
201 base::string16 description = shortcut_info.description;
202 if (description.length() >= MAX_PATH)
203 description.resize(MAX_PATH - 1);
205 // Generates app id from web app url and profile path.
206 std::string app_name(web_app::GenerateApplicationNameFromInfo(shortcut_info));
207 base::string16 app_id(ShellIntegration::GetAppModelIdForProfile(
208 base::UTF8ToUTF16(app_name), shortcut_info.profile_path));
211 for (size_t i = 0; i < shortcut_paths.size(); ++i) {
212 base::FilePath shortcut_file =
215 web_app::internals::GetSanitizedFileName(shortcut_info.title))
216 .AddExtension(installer::kLnkExt);
217 if (creation_reason == web_app::SHORTCUT_CREATION_AUTOMATED) {
218 // Check whether there is an existing shortcut to this app.
219 std::vector<base::FilePath> shortcut_files =
220 FindAppShortcutsByProfileAndTitle(shortcut_paths[i],
221 shortcut_info.profile_path,
222 shortcut_info.title);
223 if (!shortcut_files.empty())
226 if (shortcut_paths[i] != web_app_path) {
228 base::GetUniquePathNumber(shortcut_file,
229 base::FilePath::StringType());
230 if (unique_number == -1) {
233 } else if (unique_number > 0) {
234 shortcut_file = shortcut_file.InsertBeforeExtensionASCII(
235 base::StringPrintf(" (%d)", unique_number));
238 base::win::ShortcutProperties shortcut_properties;
239 shortcut_properties.set_target(chrome_exe);
240 shortcut_properties.set_working_dir(working_dir);
241 shortcut_properties.set_arguments(wide_switches);
242 shortcut_properties.set_description(description);
243 shortcut_properties.set_icon(icon_file, 0);
244 shortcut_properties.set_app_id(app_id);
245 shortcut_properties.set_dual_mode(false);
246 if (!base::PathExists(shortcut_file.DirName()) &&
247 !base::CreateDirectory(shortcut_file.DirName())) {
251 success = base::win::CreateOrUpdateShortcutLink(
252 shortcut_file, shortcut_properties,
253 base::win::SHORTCUT_CREATE_ALWAYS) && success;
255 out_filenames->push_back(shortcut_file);
261 // Gets the directories with shortcuts for an app, and deletes the shortcuts.
262 // This will search the standard locations for shortcuts named |title| that open
263 // in the profile with |profile_path|.
264 // |was_pinned_to_taskbar| will be set to true if there was previously a
265 // shortcut pinned to the taskbar for this app; false otherwise.
266 // If |web_app_path| is empty, this will not delete shortcuts from the web app
267 // directory. If |title| is empty, all shortcuts for this profile will be
269 // |shortcut_paths| will be populated with a list of directories where shortcuts
270 // for this app were found (and deleted). This will delete duplicate shortcuts,
271 // but only return each path once, even if it contained multiple deleted
272 // shortcuts. Both of these may be NULL.
273 void GetShortcutLocationsAndDeleteShortcuts(
274 const base::FilePath& web_app_path,
275 const base::FilePath& profile_path,
276 const base::string16& title,
277 bool* was_pinned_to_taskbar,
278 std::vector<base::FilePath>* shortcut_paths) {
279 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
281 // Get all possible locations for shortcuts.
282 web_app::ShortcutLocations all_shortcut_locations;
283 all_shortcut_locations.in_quick_launch_bar = true;
284 all_shortcut_locations.on_desktop = true;
285 // Delete shortcuts from the Chrome Apps subdirectory.
286 // This matches the subdir name set by CreateApplicationShortcutView::Accept
287 // for Chrome apps (not URL apps, but this function does not apply for them).
288 all_shortcut_locations.applications_menu_location =
289 web_app::APP_MENU_LOCATION_SUBDIR_CHROMEAPPS;
290 std::vector<base::FilePath> all_paths = web_app::internals::GetShortcutPaths(
291 all_shortcut_locations);
292 if (base::win::GetVersion() >= base::win::VERSION_WIN7 &&
293 !web_app_path.empty()) {
294 all_paths.push_back(web_app_path);
297 if (was_pinned_to_taskbar) {
298 // Determine if there is a link to this app in the TaskBar pin directory.
299 base::FilePath taskbar_pin_path;
300 if (PathService::Get(base::DIR_TASKBAR_PINS, &taskbar_pin_path)) {
301 std::vector<base::FilePath> taskbar_pin_files =
302 FindAppShortcutsByProfileAndTitle(taskbar_pin_path, profile_path,
304 *was_pinned_to_taskbar = !taskbar_pin_files.empty();
306 *was_pinned_to_taskbar = false;
310 for (std::vector<base::FilePath>::const_iterator i = all_paths.begin();
311 i != all_paths.end(); ++i) {
312 std::vector<base::FilePath> shortcut_files =
313 FindAppShortcutsByProfileAndTitle(*i, profile_path, title);
314 if (shortcut_paths && !shortcut_files.empty()) {
315 shortcut_paths->push_back(*i);
317 for (std::vector<base::FilePath>::const_iterator j = shortcut_files.begin();
318 j != shortcut_files.end(); ++j) {
319 // Any shortcut could have been pinned, either by chrome or the user, so
320 // they are all unpinned.
321 base::win::TaskbarUnpinShortcutLink(j->value().c_str());
322 base::DeleteFile(*j, false);
327 void CreateIconAndSetRelaunchDetails(const base::FilePath& web_app_path,
328 const base::FilePath& icon_file,
329 const web_app::ShortcutInfo& shortcut_info,
331 DCHECK(content::BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread());
333 CommandLine command_line =
334 ShellIntegration::CommandLineArgsForLauncher(shortcut_info.url,
335 shortcut_info.extension_id,
336 shortcut_info.profile_path);
338 base::FilePath chrome_exe;
339 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
343 command_line.SetProgram(chrome_exe);
344 ui::win::SetRelaunchDetailsForWindow(
345 command_line.GetCommandLineString(), shortcut_info.title, hwnd);
347 if (!base::PathExists(web_app_path) && !base::CreateDirectory(web_app_path))
350 ui::win::SetAppIconForWindow(icon_file.value(), hwnd);
351 web_app::internals::CheckAndSaveIcon(icon_file, shortcut_info.favicon);
354 void OnShortcutInfoLoadedForSetRelaunchDetails(
356 const web_app::ShortcutInfo& shortcut_info) {
357 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
359 // Set window's icon to the one we're about to create/update in the web app
360 // path. The icon cache will refresh on icon creation.
361 base::FilePath web_app_path =
362 web_app::GetWebAppDataDirectory(shortcut_info.profile_path,
363 shortcut_info.extension_id,
365 base::FilePath icon_file =
366 web_app_path.Append(web_app::internals::GetSanitizedFileName(
367 shortcut_info.title))
368 .ReplaceExtension(FILE_PATH_LITERAL(".ico"));
370 content::BrowserThread::PostBlockingPoolTask(
372 base::Bind(&CreateIconAndSetRelaunchDetails,
383 base::FilePath CreateShortcutInWebAppDir(const base::FilePath& web_app_dir,
384 const ShortcutInfo& shortcut_info) {
385 std::vector<base::FilePath> paths;
386 paths.push_back(web_app_dir);
387 std::vector<base::FilePath> out_filenames;
388 base::FilePath web_app_dir_shortcut =
389 web_app_dir.Append(internals::GetSanitizedFileName(shortcut_info.title))
390 .AddExtension(installer::kLnkExt);
391 if (!PathExists(web_app_dir_shortcut)) {
392 CreateShortcutsInPaths(web_app_dir,
395 SHORTCUT_CREATION_BY_USER,
397 DCHECK_EQ(out_filenames.size(), 1u);
398 DCHECK_EQ(out_filenames[0].value(), web_app_dir_shortcut.value());
400 internals::CheckAndSaveIcon(
401 internals::GetIconFilePath(web_app_dir, shortcut_info.title),
402 shortcut_info.favicon);
404 return web_app_dir_shortcut;
407 void UpdateRelaunchDetailsForApp(Profile* profile,
408 const extensions::Extension* extension,
410 web_app::GetShortcutInfoForApp(
413 base::Bind(&OnShortcutInfoLoadedForSetRelaunchDetails, hwnd));
416 void UpdateShortcutsForAllApps(Profile* profile,
417 const base::Closure& callback) {
421 namespace internals {
423 // Saves |image| to |icon_file| if the file is outdated and refresh shell's
424 // icon cache to ensure correct icon is displayed. Returns true if icon_file
425 // is up to date or successfully updated.
426 bool CheckAndSaveIcon(const base::FilePath& icon_file,
427 const gfx::ImageFamily& image) {
428 if (ShouldUpdateIcon(icon_file, image)) {
429 if (SaveIconWithCheckSum(icon_file, image)) {
430 // Refresh shell's icon cache. This call is quite disruptive as user would
431 // see explorer rebuilding the icon cache. It would be great that we find
432 // a better way to achieve this.
433 SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST | SHCNF_FLUSHNOWAIT,
443 bool CreatePlatformShortcuts(
444 const base::FilePath& web_app_path,
445 const ShortcutInfo& shortcut_info,
446 const extensions::FileHandlersInfo& file_handlers_info,
447 const ShortcutLocations& creation_locations,
448 ShortcutCreationReason creation_reason) {
449 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
451 // Nothing to do on Windows for hidden apps.
452 if (creation_locations.applications_menu_location == APP_MENU_LOCATION_HIDDEN)
455 // Shortcut paths under which to create shortcuts.
456 std::vector<base::FilePath> shortcut_paths =
457 GetShortcutPaths(creation_locations);
459 bool pin_to_taskbar = creation_locations.in_quick_launch_bar &&
460 (base::win::GetVersion() >= base::win::VERSION_WIN7);
462 // Create/update the shortcut in the web app path for the "Pin To Taskbar"
463 // option in Win7. We use the web app path shortcut because we will overwrite
464 // it rather than appending unique numbers if the shortcut already exists.
465 // This prevents pinned apps from having unique numbers in their names.
467 shortcut_paths.push_back(web_app_path);
469 if (shortcut_paths.empty())
472 if (!CreateShortcutsInPaths(web_app_path, shortcut_info, shortcut_paths,
473 creation_reason, NULL))
476 if (pin_to_taskbar) {
477 base::FilePath file_name = GetSanitizedFileName(shortcut_info.title);
478 // Use the web app path shortcut for pinning to avoid having unique numbers
479 // in the application name.
480 base::FilePath shortcut_to_pin = web_app_path.Append(file_name).
481 AddExtension(installer::kLnkExt);
482 if (!base::win::TaskbarPinShortcutLink(shortcut_to_pin.value().c_str()))
489 void UpdatePlatformShortcuts(
490 const base::FilePath& web_app_path,
491 const base::string16& old_app_title,
492 const ShortcutInfo& shortcut_info,
493 const extensions::FileHandlersInfo& file_handlers_info) {
494 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
496 // Generates file name to use with persisted ico and shortcut file.
497 base::FilePath file_name =
498 web_app::internals::GetSanitizedFileName(shortcut_info.title);
500 if (old_app_title != shortcut_info.title) {
501 // The app's title has changed. Delete all existing app shortcuts and
502 // recreate them in any locations they already existed (but do not add them
503 // to locations where they do not currently exist).
504 bool was_pinned_to_taskbar;
505 std::vector<base::FilePath> shortcut_paths;
506 GetShortcutLocationsAndDeleteShortcuts(
507 web_app_path, shortcut_info.profile_path, old_app_title,
508 &was_pinned_to_taskbar, &shortcut_paths);
509 CreateShortcutsInPaths(web_app_path, shortcut_info, shortcut_paths,
510 SHORTCUT_CREATION_BY_USER, NULL);
511 // If the shortcut was pinned to the taskbar,
512 // GetShortcutLocationsAndDeleteShortcuts will have deleted it. In that
514 if (was_pinned_to_taskbar) {
515 base::FilePath file_name = GetSanitizedFileName(shortcut_info.title);
516 // Use the web app path shortcut for pinning to avoid having unique
517 // numbers in the application name.
518 base::FilePath shortcut_to_pin = web_app_path.Append(file_name).
519 AddExtension(installer::kLnkExt);
520 base::win::TaskbarPinShortcutLink(shortcut_to_pin.value().c_str());
524 // Update the icon if necessary.
525 base::FilePath icon_file = GetIconFilePath(web_app_path, shortcut_info.title);
526 CheckAndSaveIcon(icon_file, shortcut_info.favicon);
529 void DeletePlatformShortcuts(const base::FilePath& web_app_path,
530 const ShortcutInfo& shortcut_info) {
531 GetShortcutLocationsAndDeleteShortcuts(
532 web_app_path, shortcut_info.profile_path, shortcut_info.title, NULL,
535 // If there are no more shortcuts in the Chrome Apps subdirectory, remove it.
536 base::FilePath chrome_apps_dir;
537 if (ShellUtil::GetShortcutPath(
538 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR,
539 BrowserDistribution::GetDistribution(),
540 ShellUtil::CURRENT_USER,
542 if (base::IsDirectoryEmpty(chrome_apps_dir))
543 base::DeleteFile(chrome_apps_dir, false);
547 void DeleteAllShortcutsForProfile(const base::FilePath& profile_path) {
548 GetShortcutLocationsAndDeleteShortcuts(base::FilePath(), profile_path, L"",
551 // If there are no more shortcuts in the Chrome Apps subdirectory, remove it.
552 base::FilePath chrome_apps_dir;
553 if (ShellUtil::GetShortcutPath(
554 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR,
555 BrowserDistribution::GetDistribution(),
556 ShellUtil::CURRENT_USER,
558 if (base::IsDirectoryEmpty(chrome_apps_dir))
559 base::DeleteFile(chrome_apps_dir, false);
563 std::vector<base::FilePath> GetShortcutPaths(
564 const ShortcutLocations& creation_locations) {
565 // Shortcut paths under which to create shortcuts.
566 std::vector<base::FilePath> shortcut_paths;
567 // Locations to add to shortcut_paths.
569 bool use_this_location;
570 ShellUtil::ShortcutLocation location_id;
573 creation_locations.on_desktop,
574 ShellUtil::SHORTCUT_LOCATION_DESKTOP
576 creation_locations.applications_menu_location ==
577 APP_MENU_LOCATION_ROOT,
578 ShellUtil::SHORTCUT_LOCATION_START_MENU_ROOT
580 creation_locations.applications_menu_location ==
581 APP_MENU_LOCATION_SUBDIR_CHROME,
582 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_DIR
584 creation_locations.applications_menu_location ==
585 APP_MENU_LOCATION_SUBDIR_CHROMEAPPS,
586 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR
588 // For Win7+, |in_quick_launch_bar| indicates that we are pinning to
589 // taskbar. This needs to be handled by callers.
590 creation_locations.in_quick_launch_bar &&
591 base::win::GetVersion() < base::win::VERSION_WIN7,
592 ShellUtil::SHORTCUT_LOCATION_QUICK_LAUNCH
596 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
597 // Populate shortcut_paths.
598 for (int i = 0; i < arraysize(locations); ++i) {
599 if (locations[i].use_this_location) {
601 if (!ShellUtil::GetShortcutPath(locations[i].location_id,
603 ShellUtil::CURRENT_USER,
608 shortcut_paths.push_back(path);
611 return shortcut_paths;
614 base::FilePath GetIconFilePath(const base::FilePath& web_app_path,
615 const base::string16& title) {
616 return web_app_path.Append(GetSanitizedFileName(title))
617 .AddExtension(FILE_PATH_LITERAL(".ico"));
620 } // namespace internals
622 void UpdateShortcutForTabContents(content::WebContents* web_contents) {
623 // UpdateShortcutWorker will delete itself when it's done.
624 UpdateShortcutWorker* worker = new UpdateShortcutWorker(web_contents);
628 } // namespace web_app