web_app_win.cc revision c5cede9ae108bb15f6b7a8aea21c7e1fefa2834c
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/update_shortcut_worker_win.h"
21#include "chrome/browser/web_applications/web_app.h"
22#include "chrome/common/chrome_switches.h"
23#include "chrome/installer/util/browser_distribution.h"
24#include "chrome/installer/util/shell_util.h"
25#include "chrome/installer/util/util_constants.h"
26#include "content/public/browser/browser_thread.h"
27#include "ui/gfx/icon_util.h"
28#include "ui/gfx/image/image.h"
29#include "ui/gfx/image/image_family.h"
30
31namespace {
32
33const base::FilePath::CharType kIconChecksumFileExt[] =
34    FILE_PATH_LITERAL(".ico.md5");
35
36// Calculates checksum of an icon family using MD5.
37// The checksum is derived from all of the icons in the family.
38void GetImageCheckSum(const gfx::ImageFamily& image, base::MD5Digest* digest) {
39  DCHECK(digest);
40  base::MD5Context md5_context;
41  base::MD5Init(&md5_context);
42
43  for (gfx::ImageFamily::const_iterator it = image.begin(); it != image.end();
44       ++it) {
45    SkBitmap bitmap = it->AsBitmap();
46
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);
51  }
52
53  base::MD5Final(digest, &md5_context);
54}
55
56// Saves |image| as an |icon_file| with the checksum.
57bool SaveIconWithCheckSum(const base::FilePath& icon_file,
58                          const gfx::ImageFamily& image) {
59  if (!IconUtil::CreateIconFileFromImageFamily(image, icon_file))
60    return false;
61
62  base::MD5Digest digest;
63  GetImageCheckSum(image, &digest);
64
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);
69}
70
71// Returns true if |icon_file| is missing or different from |image|.
72bool ShouldUpdateIcon(const base::FilePath& icon_file,
73                      const gfx::ImageFamily& image) {
74  base::FilePath checksum_file(
75      icon_file.ReplaceExtension(kIconChecksumFileExt));
76
77  // Returns true if icon_file or checksum file is missing.
78  if (!base::PathExists(icon_file) ||
79      !base::PathExists(checksum_file))
80    return true;
81
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)))
86    return true;
87
88  base::MD5Digest downloaded_image_checksum;
89  GetImageCheckSum(image, &downloaded_image_checksum);
90
91  // Update icon if checksums are not equal.
92  return memcmp(&persisted_image_checksum, &downloaded_image_checksum,
93                sizeof(base::MD5Digest)) != 0;
94}
95
96// Returns true if |shortcut_file_name| matches profile |profile_path|, and has
97// an --app-id flag.
98bool 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);
108  }
109
110  return false;
111}
112
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|.
116std::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;
121
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();
132    }
133  } else {
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"));
138
139    const int fileNamesToCheck = 10;
140    for (int i = 0; i < fileNamesToCheck; ++i) {
141      base::FilePath shortcut_file = base_path;
142      if (i > 0) {
143        shortcut_file = shortcut_file.InsertBeforeExtensionASCII(
144            base::StringPrintf(" (%d)", i));
145      }
146      if (base::PathExists(shortcut_file) &&
147          IsAppShortcutForProfile(shortcut_file, profile_path)) {
148        shortcut_paths.push_back(shortcut_file);
149      }
150    }
151  }
152
153  return shortcut_paths;
154}
155
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.
162bool CreateShortcutsInPaths(
163    const base::FilePath& web_app_path,
164    const ShellIntegration::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)) {
171    return false;
172  }
173
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)) {
178    return false;
179  }
180
181  base::FilePath chrome_exe;
182  if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
183    NOTREACHED();
184    return false;
185  }
186
187  // Working directory.
188  base::FilePath working_dir(chrome_exe.DirName());
189
190  CommandLine cmd_line(CommandLine::NO_PROGRAM);
191  cmd_line = ShellIntegration::CommandLineArgsForLauncher(shortcut_info.url,
192      shortcut_info.extension_id, shortcut_info.profile_path);
193
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
197  // fact.
198  base::string16 wide_switches(cmd_line.GetCommandLineString());
199
200  // Sanitize description
201  base::string16 description = shortcut_info.description;
202  if (description.length() >= MAX_PATH)
203    description.resize(MAX_PATH - 1);
204
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));
209
210  bool success = true;
211  for (size_t i = 0; i < shortcut_paths.size(); ++i) {
212    base::FilePath shortcut_file =
213        shortcut_paths[i]
214            .Append(
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())
224        continue;
225    }
226    if (shortcut_paths[i] != web_app_path) {
227      int unique_number =
228          base::GetUniquePathNumber(shortcut_file,
229                                    base::FilePath::StringType());
230      if (unique_number == -1) {
231        success = false;
232        continue;
233      } else if (unique_number > 0) {
234        shortcut_file = shortcut_file.InsertBeforeExtensionASCII(
235            base::StringPrintf(" (%d)", unique_number));
236      }
237    }
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())) {
248      NOTREACHED();
249      return false;
250    }
251    success = base::win::CreateOrUpdateShortcutLink(
252        shortcut_file, shortcut_properties,
253        base::win::SHORTCUT_CREATE_ALWAYS) && success;
254    if (out_filenames)
255      out_filenames->push_back(shortcut_file);
256  }
257
258  return success;
259}
260
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
268// deleted.
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.
273void 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));
280
281  // Get all possible locations for shortcuts.
282  ShellIntegration::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      ShellIntegration::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);
295  }
296
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,
303                                            title);
304      *was_pinned_to_taskbar = !taskbar_pin_files.empty();
305    } else {
306      *was_pinned_to_taskbar = false;
307    }
308  }
309
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);
316    }
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);
323    }
324  }
325}
326
327}  // namespace
328
329namespace web_app {
330
331base::FilePath CreateShortcutInWebAppDir(
332    const base::FilePath& web_app_dir,
333    const ShellIntegration::ShortcutInfo& shortcut_info) {
334  std::vector<base::FilePath> paths;
335  paths.push_back(web_app_dir);
336  std::vector<base::FilePath> out_filenames;
337  base::FilePath web_app_dir_shortcut =
338      web_app_dir.Append(internals::GetSanitizedFileName(shortcut_info.title))
339          .AddExtension(installer::kLnkExt);
340  if (!PathExists(web_app_dir_shortcut)) {
341    CreateShortcutsInPaths(web_app_dir,
342                           shortcut_info,
343                           paths,
344                           SHORTCUT_CREATION_BY_USER,
345                           &out_filenames);
346    DCHECK_EQ(out_filenames.size(), 1u);
347    DCHECK_EQ(out_filenames[0].value(), web_app_dir_shortcut.value());
348  } else {
349    internals::CheckAndSaveIcon(
350        internals::GetIconFilePath(web_app_dir, shortcut_info.title),
351        shortcut_info.favicon);
352  }
353  return web_app_dir_shortcut;
354}
355
356namespace internals {
357
358// Saves |image| to |icon_file| if the file is outdated and refresh shell's
359// icon cache to ensure correct icon is displayed. Returns true if icon_file
360// is up to date or successfully updated.
361bool CheckAndSaveIcon(const base::FilePath& icon_file,
362                      const gfx::ImageFamily& image) {
363  if (ShouldUpdateIcon(icon_file, image)) {
364    if (SaveIconWithCheckSum(icon_file, image)) {
365      // Refresh shell's icon cache. This call is quite disruptive as user would
366      // see explorer rebuilding the icon cache. It would be great that we find
367      // a better way to achieve this.
368      SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST | SHCNF_FLUSHNOWAIT,
369                     NULL, NULL);
370    } else {
371      return false;
372    }
373  }
374
375  return true;
376}
377
378bool CreatePlatformShortcuts(
379    const base::FilePath& web_app_path,
380    const ShellIntegration::ShortcutInfo& shortcut_info,
381    const ShellIntegration::ShortcutLocations& creation_locations,
382    ShortcutCreationReason creation_reason) {
383  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
384
385  // Shortcut paths under which to create shortcuts.
386  std::vector<base::FilePath> shortcut_paths =
387      GetShortcutPaths(creation_locations);
388
389  bool pin_to_taskbar = creation_locations.in_quick_launch_bar &&
390                        (base::win::GetVersion() >= base::win::VERSION_WIN7);
391
392  // Create/update the shortcut in the web app path for the "Pin To Taskbar"
393  // option in Win7. We use the web app path shortcut because we will overwrite
394  // it rather than appending unique numbers if the shortcut already exists.
395  // This prevents pinned apps from having unique numbers in their names.
396  if (pin_to_taskbar)
397    shortcut_paths.push_back(web_app_path);
398
399  if (shortcut_paths.empty())
400    return false;
401
402  if (!CreateShortcutsInPaths(web_app_path, shortcut_info, shortcut_paths,
403                              creation_reason, NULL))
404    return false;
405
406  if (pin_to_taskbar) {
407    base::FilePath file_name = GetSanitizedFileName(shortcut_info.title);
408    // Use the web app path shortcut for pinning to avoid having unique numbers
409    // in the application name.
410    base::FilePath shortcut_to_pin = web_app_path.Append(file_name).
411        AddExtension(installer::kLnkExt);
412    if (!base::win::TaskbarPinShortcutLink(shortcut_to_pin.value().c_str()))
413      return false;
414  }
415
416  return true;
417}
418
419void UpdatePlatformShortcuts(
420    const base::FilePath& web_app_path,
421    const base::string16& old_app_title,
422    const ShellIntegration::ShortcutInfo& shortcut_info) {
423  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
424
425  // Generates file name to use with persisted ico and shortcut file.
426  base::FilePath file_name =
427      web_app::internals::GetSanitizedFileName(shortcut_info.title);
428
429  if (old_app_title != shortcut_info.title) {
430    // The app's title has changed. Delete all existing app shortcuts and
431    // recreate them in any locations they already existed (but do not add them
432    // to locations where they do not currently exist).
433    bool was_pinned_to_taskbar;
434    std::vector<base::FilePath> shortcut_paths;
435    GetShortcutLocationsAndDeleteShortcuts(
436        web_app_path, shortcut_info.profile_path, old_app_title,
437        &was_pinned_to_taskbar, &shortcut_paths);
438    CreateShortcutsInPaths(web_app_path, shortcut_info, shortcut_paths,
439                           SHORTCUT_CREATION_BY_USER, NULL);
440    // If the shortcut was pinned to the taskbar,
441    // GetShortcutLocationsAndDeleteShortcuts will have deleted it. In that
442    // case, re-pin it.
443    if (was_pinned_to_taskbar) {
444      base::FilePath file_name = GetSanitizedFileName(shortcut_info.title);
445      // Use the web app path shortcut for pinning to avoid having unique
446      // numbers in the application name.
447      base::FilePath shortcut_to_pin = web_app_path.Append(file_name).
448          AddExtension(installer::kLnkExt);
449      base::win::TaskbarPinShortcutLink(shortcut_to_pin.value().c_str());
450    }
451  }
452
453  // Update the icon if necessary.
454  base::FilePath icon_file = GetIconFilePath(web_app_path, shortcut_info.title);
455  CheckAndSaveIcon(icon_file, shortcut_info.favicon);
456}
457
458void DeletePlatformShortcuts(
459    const base::FilePath& web_app_path,
460    const ShellIntegration::ShortcutInfo& shortcut_info) {
461  GetShortcutLocationsAndDeleteShortcuts(
462      web_app_path, shortcut_info.profile_path, shortcut_info.title, NULL,
463      NULL);
464
465  // If there are no more shortcuts in the Chrome Apps subdirectory, remove it.
466  base::FilePath chrome_apps_dir;
467  if (ShellUtil::GetShortcutPath(
468          ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR,
469          BrowserDistribution::GetDistribution(),
470          ShellUtil::CURRENT_USER,
471          &chrome_apps_dir)) {
472    if (base::IsDirectoryEmpty(chrome_apps_dir))
473      base::DeleteFile(chrome_apps_dir, false);
474  }
475}
476
477void DeleteAllShortcutsForProfile(const base::FilePath& profile_path) {
478  GetShortcutLocationsAndDeleteShortcuts(base::FilePath(), profile_path, L"",
479                                         NULL, NULL);
480
481  // If there are no more shortcuts in the Chrome Apps subdirectory, remove it.
482  base::FilePath chrome_apps_dir;
483  if (ShellUtil::GetShortcutPath(
484          ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR,
485          BrowserDistribution::GetDistribution(),
486          ShellUtil::CURRENT_USER,
487          &chrome_apps_dir)) {
488    if (base::IsDirectoryEmpty(chrome_apps_dir))
489      base::DeleteFile(chrome_apps_dir, false);
490  }
491}
492
493std::vector<base::FilePath> GetShortcutPaths(
494    const ShellIntegration::ShortcutLocations& creation_locations) {
495  // Shortcut paths under which to create shortcuts.
496  std::vector<base::FilePath> shortcut_paths;
497  // Locations to add to shortcut_paths.
498  struct {
499    bool use_this_location;
500    ShellUtil::ShortcutLocation location_id;
501  } locations[] = {
502    {
503      creation_locations.on_desktop,
504      ShellUtil::SHORTCUT_LOCATION_DESKTOP
505    }, {
506      creation_locations.applications_menu_location ==
507          ShellIntegration::APP_MENU_LOCATION_ROOT,
508      ShellUtil::SHORTCUT_LOCATION_START_MENU_ROOT
509    }, {
510      creation_locations.applications_menu_location ==
511          ShellIntegration::APP_MENU_LOCATION_SUBDIR_CHROME,
512      ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_DIR
513    }, {
514      creation_locations.applications_menu_location ==
515          ShellIntegration::APP_MENU_LOCATION_SUBDIR_CHROMEAPPS,
516      ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR
517    }, {
518      // For Win7+, |in_quick_launch_bar| indicates that we are pinning to
519      // taskbar. This needs to be handled by callers.
520      creation_locations.in_quick_launch_bar &&
521          base::win::GetVersion() < base::win::VERSION_WIN7,
522      ShellUtil::SHORTCUT_LOCATION_QUICK_LAUNCH
523    }
524  };
525
526  BrowserDistribution* dist = BrowserDistribution::GetDistribution();
527  // Populate shortcut_paths.
528  for (int i = 0; i < arraysize(locations); ++i) {
529    if (locations[i].use_this_location) {
530      base::FilePath path;
531      if (!ShellUtil::GetShortcutPath(locations[i].location_id,
532                                      dist,
533                                      ShellUtil::CURRENT_USER,
534                                      &path)) {
535        NOTREACHED();
536        continue;
537      }
538      shortcut_paths.push_back(path);
539    }
540  }
541  return shortcut_paths;
542}
543
544base::FilePath GetIconFilePath(const base::FilePath& web_app_path,
545                               const base::string16& title) {
546  return web_app_path.Append(GetSanitizedFileName(title))
547      .AddExtension(FILE_PATH_LITERAL(".ico"));
548}
549
550}  // namespace internals
551
552void UpdateShortcutForTabContents(content::WebContents* web_contents) {
553  // UpdateShortcutWorker will delete itself when it's done.
554  UpdateShortcutWorker* worker = new UpdateShortcutWorker(web_contents);
555  worker->Run();
556}
557
558}  // namespace web_app
559