Add ICU message format support
[chromium-blink-merge.git] / chrome / browser / web_applications / web_app_win.cc
blob787d51e5316e2c5dd7ccee5f2e40f16cf8cb4f09
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"
7 #include <shlobj.h>
9 #include "base/command_line.h"
10 #include "base/files/file_enumerator.h"
11 #include "base/files/file_util.h"
12 #include "base/logging.h"
13 #include "base/md5.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/path_service.h"
16 #include "base/strings/string16.h"
17 #include "base/strings/string_piece.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/win/shortcut.h"
21 #include "base/win/windows_version.h"
22 #include "chrome/browser/profiles/profile.h"
23 #include "chrome/browser/web_applications/update_shortcut_worker_win.h"
24 #include "chrome/common/chrome_switches.h"
25 #include "chrome/installer/util/browser_distribution.h"
26 #include "chrome/installer/util/install_util.h"
27 #include "chrome/installer/util/shell_util.h"
28 #include "chrome/installer/util/util_constants.h"
29 #include "content/public/browser/browser_thread.h"
30 #include "extensions/common/extension.h"
31 #include "net/base/mime_util.h"
32 #include "ui/base/win/shell.h"
33 #include "ui/gfx/icon_util.h"
34 #include "ui/gfx/image/image.h"
35 #include "ui/gfx/image/image_family.h"
37 namespace {
39 const base::FilePath::CharType kIconChecksumFileExt[] =
40 FILE_PATH_LITERAL(".ico.md5");
42 const base::FilePath::CharType kAppShimExe[] =
43 FILE_PATH_LITERAL("app_shim.exe");
45 // Calculates checksum of an icon family using MD5.
46 // The checksum is derived from all of the icons in the family.
47 void GetImageCheckSum(const gfx::ImageFamily& image, base::MD5Digest* digest) {
48 DCHECK(digest);
49 base::MD5Context md5_context;
50 base::MD5Init(&md5_context);
52 for (gfx::ImageFamily::const_iterator it = image.begin(); it != image.end();
53 ++it) {
54 SkBitmap bitmap = it->AsBitmap();
56 SkAutoLockPixels image_lock(bitmap);
57 base::StringPiece image_data(
58 reinterpret_cast<const char*>(bitmap.getPixels()), bitmap.getSize());
59 base::MD5Update(&md5_context, image_data);
62 base::MD5Final(digest, &md5_context);
65 // Saves |image| as an |icon_file| with the checksum.
66 bool SaveIconWithCheckSum(const base::FilePath& icon_file,
67 const gfx::ImageFamily& image) {
68 if (!IconUtil::CreateIconFileFromImageFamily(image, icon_file))
69 return false;
71 base::MD5Digest digest;
72 GetImageCheckSum(image, &digest);
74 base::FilePath cheksum_file(icon_file.ReplaceExtension(kIconChecksumFileExt));
75 return base::WriteFile(cheksum_file,
76 reinterpret_cast<const char*>(&digest),
77 sizeof(digest)) == sizeof(digest);
80 // Returns true if |icon_file| is missing or different from |image|.
81 bool ShouldUpdateIcon(const base::FilePath& icon_file,
82 const gfx::ImageFamily& image) {
83 base::FilePath checksum_file(
84 icon_file.ReplaceExtension(kIconChecksumFileExt));
86 // Returns true if icon_file or checksum file is missing.
87 if (!base::PathExists(icon_file) ||
88 !base::PathExists(checksum_file))
89 return true;
91 base::MD5Digest persisted_image_checksum;
92 if (sizeof(persisted_image_checksum) != base::ReadFile(checksum_file,
93 reinterpret_cast<char*>(&persisted_image_checksum),
94 sizeof(persisted_image_checksum)))
95 return true;
97 base::MD5Digest downloaded_image_checksum;
98 GetImageCheckSum(image, &downloaded_image_checksum);
100 // Update icon if checksums are not equal.
101 return memcmp(&persisted_image_checksum, &downloaded_image_checksum,
102 sizeof(base::MD5Digest)) != 0;
105 // Returns true if |shortcut_file_name| matches profile |profile_path|, and has
106 // an --app-id flag.
107 bool IsAppShortcutForProfile(const base::FilePath& shortcut_file_name,
108 const base::FilePath& profile_path) {
109 base::string16 cmd_line_string;
110 if (base::win::ResolveShortcut(shortcut_file_name, NULL, &cmd_line_string)) {
111 cmd_line_string = L"program " + cmd_line_string;
112 base::CommandLine shortcut_cmd_line =
113 base::CommandLine::FromString(cmd_line_string);
114 return shortcut_cmd_line.HasSwitch(switches::kProfileDirectory) &&
115 shortcut_cmd_line.GetSwitchValuePath(switches::kProfileDirectory) ==
116 profile_path.BaseName() &&
117 shortcut_cmd_line.HasSwitch(switches::kAppId);
120 return false;
123 // Finds shortcuts in |shortcut_path| that match profile for |profile_path| and
124 // extension with title |shortcut_name|.
125 // If |shortcut_name| is empty, finds all shortcuts matching |profile_path|.
126 std::vector<base::FilePath> FindAppShortcutsByProfileAndTitle(
127 const base::FilePath& shortcut_path,
128 const base::FilePath& profile_path,
129 const base::string16& shortcut_name) {
130 std::vector<base::FilePath> shortcut_paths;
132 if (shortcut_name.empty()) {
133 // Find all shortcuts for this profile.
134 base::FileEnumerator files(shortcut_path, false,
135 base::FileEnumerator::FILES,
136 FILE_PATH_LITERAL("*.lnk"));
137 base::FilePath shortcut_file = files.Next();
138 while (!shortcut_file.empty()) {
139 if (IsAppShortcutForProfile(shortcut_file, profile_path))
140 shortcut_paths.push_back(shortcut_file);
141 shortcut_file = files.Next();
143 } else {
144 // Find all shortcuts matching |shortcut_name|.
145 base::FilePath base_path = shortcut_path.
146 Append(web_app::internals::GetSanitizedFileName(shortcut_name)).
147 AddExtension(FILE_PATH_LITERAL(".lnk"));
149 const int fileNamesToCheck = 10;
150 for (int i = 0; i < fileNamesToCheck; ++i) {
151 base::FilePath shortcut_file = base_path;
152 if (i > 0) {
153 shortcut_file = shortcut_file.InsertBeforeExtensionASCII(
154 base::StringPrintf(" (%d)", i));
156 if (base::PathExists(shortcut_file) &&
157 IsAppShortcutForProfile(shortcut_file, profile_path)) {
158 shortcut_paths.push_back(shortcut_file);
163 return shortcut_paths;
166 // Creates application shortcuts in a given set of paths.
167 // |shortcut_paths| is a list of directories in which shortcuts should be
168 // created. If |creation_reason| is SHORTCUT_CREATION_AUTOMATED and there is an
169 // existing shortcut to this app for this profile, does nothing (succeeding).
170 // Returns true on success, false on failure.
171 // Must be called on the FILE thread.
172 bool CreateShortcutsInPaths(
173 const base::FilePath& web_app_path,
174 const web_app::ShortcutInfo& shortcut_info,
175 const std::vector<base::FilePath>& shortcut_paths,
176 web_app::ShortcutCreationReason creation_reason,
177 std::vector<base::FilePath>* out_filenames) {
178 // Ensure web_app_path exists.
179 if (!base::PathExists(web_app_path) &&
180 !base::CreateDirectory(web_app_path)) {
181 return false;
184 // Generates file name to use with persisted ico and shortcut file.
185 base::FilePath icon_file =
186 web_app::internals::GetIconFilePath(web_app_path, shortcut_info.title);
187 if (!web_app::internals::CheckAndSaveIcon(icon_file, shortcut_info.favicon,
188 false)) {
189 return false;
192 base::FilePath chrome_exe;
193 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
194 NOTREACHED();
195 return false;
198 // Working directory.
199 base::FilePath working_dir(chrome_exe.DirName());
201 base::CommandLine cmd_line(base::CommandLine::NO_PROGRAM);
202 cmd_line = ShellIntegration::CommandLineArgsForLauncher(shortcut_info.url,
203 shortcut_info.extension_id, shortcut_info.profile_path);
205 // TODO(evan): we rely on the fact that command_line_string() is
206 // properly quoted for a Windows command line. The method on
207 // base::CommandLine should probably be renamed to better reflect that
208 // fact.
209 base::string16 wide_switches(cmd_line.GetCommandLineString());
211 // Sanitize description
212 base::string16 description = shortcut_info.description;
213 if (description.length() >= MAX_PATH)
214 description.resize(MAX_PATH - 1);
216 // Generates app id from web app url and profile path.
217 std::string app_name(web_app::GenerateApplicationNameFromInfo(shortcut_info));
218 base::string16 app_id(ShellIntegration::GetAppModelIdForProfile(
219 base::UTF8ToUTF16(app_name), shortcut_info.profile_path));
221 bool success = true;
222 for (size_t i = 0; i < shortcut_paths.size(); ++i) {
223 base::FilePath shortcut_file =
224 shortcut_paths[i]
225 .Append(
226 web_app::internals::GetSanitizedFileName(shortcut_info.title))
227 .AddExtension(installer::kLnkExt);
228 if (creation_reason == web_app::SHORTCUT_CREATION_AUTOMATED) {
229 // Check whether there is an existing shortcut to this app.
230 std::vector<base::FilePath> shortcut_files =
231 FindAppShortcutsByProfileAndTitle(shortcut_paths[i],
232 shortcut_info.profile_path,
233 shortcut_info.title);
234 if (!shortcut_files.empty())
235 continue;
237 if (shortcut_paths[i] != web_app_path) {
238 int unique_number =
239 base::GetUniquePathNumber(shortcut_file,
240 base::FilePath::StringType());
241 if (unique_number == -1) {
242 success = false;
243 continue;
244 } else if (unique_number > 0) {
245 shortcut_file = shortcut_file.InsertBeforeExtensionASCII(
246 base::StringPrintf(" (%d)", unique_number));
249 base::win::ShortcutProperties shortcut_properties;
250 shortcut_properties.set_target(chrome_exe);
251 shortcut_properties.set_working_dir(working_dir);
252 shortcut_properties.set_arguments(wide_switches);
253 shortcut_properties.set_description(description);
254 shortcut_properties.set_icon(icon_file, 0);
255 shortcut_properties.set_app_id(app_id);
256 shortcut_properties.set_dual_mode(false);
257 if (!base::PathExists(shortcut_file.DirName()) &&
258 !base::CreateDirectory(shortcut_file.DirName())) {
259 NOTREACHED();
260 return false;
262 success = base::win::CreateOrUpdateShortcutLink(
263 shortcut_file, shortcut_properties,
264 base::win::SHORTCUT_CREATE_ALWAYS) && success;
265 if (out_filenames)
266 out_filenames->push_back(shortcut_file);
269 return success;
272 // Gets the directories with shortcuts for an app, and deletes the shortcuts.
273 // This will search the standard locations for shortcuts named |title| that open
274 // in the profile with |profile_path|.
275 // |was_pinned_to_taskbar| will be set to true if there was previously a
276 // shortcut pinned to the taskbar for this app; false otherwise.
277 // If |web_app_path| is empty, this will not delete shortcuts from the web app
278 // directory. If |title| is empty, all shortcuts for this profile will be
279 // deleted.
280 // |shortcut_paths| will be populated with a list of directories where shortcuts
281 // for this app were found (and deleted). This will delete duplicate shortcuts,
282 // but only return each path once, even if it contained multiple deleted
283 // shortcuts. Both of these may be NULL.
284 void GetShortcutLocationsAndDeleteShortcuts(
285 const base::FilePath& web_app_path,
286 const base::FilePath& profile_path,
287 const base::string16& title,
288 bool* was_pinned_to_taskbar,
289 std::vector<base::FilePath>* shortcut_paths) {
290 DCHECK(content::BrowserThread::FILE);
292 // Get all possible locations for shortcuts.
293 web_app::ShortcutLocations all_shortcut_locations;
294 all_shortcut_locations.in_quick_launch_bar = true;
295 all_shortcut_locations.on_desktop = true;
296 // Delete shortcuts from the Chrome Apps subdirectory.
297 // This matches the subdir name set by CreateApplicationShortcutView::Accept
298 // for Chrome apps (not URL apps, but this function does not apply for them).
299 all_shortcut_locations.applications_menu_location =
300 web_app::APP_MENU_LOCATION_SUBDIR_CHROMEAPPS;
301 std::vector<base::FilePath> all_paths = web_app::internals::GetShortcutPaths(
302 all_shortcut_locations);
303 if (base::win::GetVersion() >= base::win::VERSION_WIN7 &&
304 !web_app_path.empty()) {
305 all_paths.push_back(web_app_path);
308 if (was_pinned_to_taskbar) {
309 // Determine if there is a link to this app in the TaskBar pin directory.
310 base::FilePath taskbar_pin_path;
311 if (PathService::Get(base::DIR_TASKBAR_PINS, &taskbar_pin_path)) {
312 std::vector<base::FilePath> taskbar_pin_files =
313 FindAppShortcutsByProfileAndTitle(taskbar_pin_path, profile_path,
314 title);
315 *was_pinned_to_taskbar = !taskbar_pin_files.empty();
316 } else {
317 *was_pinned_to_taskbar = false;
321 for (std::vector<base::FilePath>::const_iterator i = all_paths.begin();
322 i != all_paths.end(); ++i) {
323 std::vector<base::FilePath> shortcut_files =
324 FindAppShortcutsByProfileAndTitle(*i, profile_path, title);
325 if (shortcut_paths && !shortcut_files.empty()) {
326 shortcut_paths->push_back(*i);
328 for (std::vector<base::FilePath>::const_iterator j = shortcut_files.begin();
329 j != shortcut_files.end(); ++j) {
330 // Any shortcut could have been pinned, either by chrome or the user, so
331 // they are all unpinned.
332 base::win::UnpinShortcutFromTaskbar(*j);
333 base::DeleteFile(*j, false);
338 void CreateIconAndSetRelaunchDetails(
339 const base::FilePath& web_app_path,
340 const base::FilePath& icon_file,
341 scoped_ptr<web_app::ShortcutInfo> shortcut_info,
342 HWND hwnd) {
343 DCHECK(content::BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread());
345 base::CommandLine command_line = ShellIntegration::CommandLineArgsForLauncher(
346 shortcut_info->url, shortcut_info->extension_id,
347 shortcut_info->profile_path);
349 base::FilePath chrome_exe;
350 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
351 NOTREACHED();
352 return;
354 command_line.SetProgram(chrome_exe);
355 ui::win::SetRelaunchDetailsForWindow(command_line.GetCommandLineString(),
356 shortcut_info->title, hwnd);
358 if (!base::PathExists(web_app_path) && !base::CreateDirectory(web_app_path))
359 return;
361 ui::win::SetAppIconForWindow(icon_file.value(), hwnd);
362 web_app::internals::CheckAndSaveIcon(icon_file, shortcut_info->favicon, true);
365 void OnShortcutInfoLoadedForSetRelaunchDetails(
366 HWND hwnd,
367 scoped_ptr<web_app::ShortcutInfo> shortcut_info) {
368 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
370 // Set window's icon to the one we're about to create/update in the web app
371 // path. The icon cache will refresh on icon creation.
372 base::FilePath web_app_path = web_app::GetWebAppDataDirectory(
373 shortcut_info->profile_path, shortcut_info->extension_id,
374 shortcut_info->url);
375 base::FilePath icon_file =
376 web_app::internals::GetIconFilePath(web_app_path, shortcut_info->title);
377 content::BrowserThread::PostBlockingPoolTask(
378 FROM_HERE, base::Bind(&CreateIconAndSetRelaunchDetails, web_app_path,
379 icon_file, base::Passed(&shortcut_info), hwnd));
382 // Creates an "app shim exe" by linking or copying the generic app shim exe.
383 // This is the binary that will be run when the user opens a file with this
384 // application. The name and icon of the binary will be used on the Open With
385 // menu. For this reason, we cannot simply launch chrome.exe. We give the app
386 // shim exe the same name as the application (with no ".exe" extension), so that
387 // the correct title will appear on the Open With menu. (Note: we also need a
388 // separate binary per app because Windows only allows a single association with
389 // each executable.)
390 // |path| is the full path of the shim binary to be created.
391 bool CreateAppShimBinary(const base::FilePath& path) {
392 // TODO(mgiuca): Hard-link instead of copying, if on the same file system.
393 // Get the Chrome version directory (the directory containing the chrome.dll
394 // module). This is the directory where app_shim.exe is located.
395 base::FilePath chrome_version_directory;
396 if (!PathService::Get(base::DIR_MODULE, &chrome_version_directory)) {
397 NOTREACHED();
398 return false;
401 base::FilePath generic_shim_path =
402 chrome_version_directory.Append(kAppShimExe);
403 if (!base::CopyFile(generic_shim_path, path)) {
404 if (!base::PathExists(generic_shim_path)) {
405 LOG(ERROR) << "Could not find app shim exe at "
406 << generic_shim_path.value();
407 } else {
408 LOG(ERROR) << "Could not copy app shim exe to " << path.value();
410 return false;
413 return true;
416 // Gets the full command line for calling the shim binary. This will include a
417 // placeholder "%1" argument, which Windows will substitute with the filename
418 // chosen by the user.
419 base::CommandLine GetAppShimCommandLine(const base::FilePath& app_shim_path,
420 const std::string& extension_id,
421 const base::FilePath& profile_path) {
422 // Get the command-line to pass to the shim (e.g., "chrome.exe --app-id=...").
423 base::CommandLine chrome_cmd_line =
424 ShellIntegration::CommandLineArgsForLauncher(GURL(), extension_id,
425 profile_path);
426 chrome_cmd_line.AppendArg("%1");
428 // Get the command-line for calling the shim (e.g.,
429 // "app_shim [--chrome-sxs] -- --app-id=...").
430 base::CommandLine shim_cmd_line(app_shim_path);
431 // If this is a canary build, launch the shim in canary mode.
432 if (InstallUtil::IsChromeSxSProcess())
433 shim_cmd_line.AppendSwitch(installer::switches::kChromeSxS);
434 // Ensure all subsequent switches are treated as args to the shim.
435 shim_cmd_line.AppendArg("--");
436 for (size_t i = 1; i < chrome_cmd_line.argv().size(); ++i)
437 shim_cmd_line.AppendArgNative(chrome_cmd_line.argv()[i]);
439 return shim_cmd_line;
442 // Gets the set of file extensions associated with a particular file handler.
443 // Uses both the MIME types and extensions.
444 void GetHandlerFileExtensions(const extensions::FileHandlerInfo& handler,
445 std::set<base::string16>* exts) {
446 for (const auto& mime : handler.types) {
447 std::vector<base::string16> mime_type_extensions;
448 net::GetExtensionsForMimeType(mime, &mime_type_extensions);
449 exts->insert(mime_type_extensions.begin(), mime_type_extensions.end());
451 for (const auto& ext : handler.extensions)
452 exts->insert(base::UTF8ToUTF16(ext));
455 // Creates operating system file type associations for a given app.
456 // This is the platform specific implementation of the CreateFileAssociations
457 // function, and is executed on the FILE thread.
458 // Returns true on success, false on failure.
459 bool CreateFileAssociationsForApp(
460 const std::string& extension_id,
461 const base::string16& title,
462 const base::FilePath& profile_path,
463 const extensions::FileHandlersInfo& file_handlers_info) {
464 base::FilePath web_app_path =
465 web_app::GetWebAppDataDirectory(profile_path, extension_id, GURL());
466 base::FilePath file_name = web_app::internals::GetSanitizedFileName(title);
468 // The progid is "chrome-APPID-HANDLERID". This is the internal name Windows
469 // will use for file associations with this application.
470 base::string16 progid_base = L"chrome-";
471 progid_base += base::UTF8ToUTF16(extension_id);
473 // Create the app shim binary (see CreateAppShimBinary for rationale). Get the
474 // command line for the shim.
475 base::FilePath app_shim_path = web_app_path.Append(file_name);
476 if (!CreateAppShimBinary(app_shim_path))
477 return false;
479 base::CommandLine shim_cmd_line(
480 GetAppShimCommandLine(app_shim_path, extension_id, profile_path));
482 // TODO(mgiuca): Get the file type name from the manifest, or generate a
483 // default one. (If this is blank, Windows will generate one of the form
484 // '<EXT> file'.)
485 base::string16 file_type_name = L"";
487 // TODO(mgiuca): Generate a new icon for this application's file associations
488 // that looks like a page with the application icon inside.
489 base::FilePath icon_file =
490 web_app::internals::GetIconFilePath(web_app_path, title);
492 // Create a separate file association (ProgId) for each handler. This allows
493 // each handler to have its own filetype name and icon, and also a different
494 // command line (so the app can see which handler was invoked).
495 size_t num_successes = 0;
496 for (const auto& handler : file_handlers_info) {
497 base::string16 progid = progid_base + L"-" + base::UTF8ToUTF16(handler.id);
499 std::set<base::string16> exts;
500 GetHandlerFileExtensions(handler, &exts);
502 if (ShellUtil::AddFileAssociations(progid, shim_cmd_line, file_type_name,
503 icon_file, exts)) {
504 ++num_successes;
508 if (num_successes == 0) {
509 // There were no successes; delete the shim.
510 base::DeleteFile(app_shim_path, false);
511 } else {
512 // There were some successes; tell Windows Explorer to update its cache.
513 SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST | SHCNF_FLUSHNOWAIT,
514 nullptr, nullptr);
517 return num_successes == file_handlers_info.size();
520 } // namespace
522 namespace web_app {
524 base::FilePath CreateShortcutInWebAppDir(
525 const base::FilePath& web_app_dir,
526 scoped_ptr<ShortcutInfo> shortcut_info) {
527 std::vector<base::FilePath> paths;
528 paths.push_back(web_app_dir);
529 std::vector<base::FilePath> out_filenames;
530 base::FilePath web_app_dir_shortcut =
531 web_app_dir.Append(internals::GetSanitizedFileName(shortcut_info->title))
532 .AddExtension(installer::kLnkExt);
533 if (!PathExists(web_app_dir_shortcut)) {
534 CreateShortcutsInPaths(web_app_dir, *shortcut_info, paths,
535 SHORTCUT_CREATION_BY_USER, &out_filenames);
536 DCHECK_EQ(out_filenames.size(), 1u);
537 DCHECK_EQ(out_filenames[0].value(), web_app_dir_shortcut.value());
538 } else {
539 internals::CheckAndSaveIcon(
540 internals::GetIconFilePath(web_app_dir, shortcut_info->title),
541 shortcut_info->favicon, true);
543 return web_app_dir_shortcut;
546 void UpdateRelaunchDetailsForApp(Profile* profile,
547 const extensions::Extension* extension,
548 HWND hwnd) {
549 web_app::GetShortcutInfoForApp(
550 extension,
551 profile,
552 base::Bind(&OnShortcutInfoLoadedForSetRelaunchDetails, hwnd));
555 void UpdateShortcutsForAllApps(Profile* profile,
556 const base::Closure& callback) {
557 callback.Run();
560 namespace internals {
562 bool CheckAndSaveIcon(const base::FilePath& icon_file,
563 const gfx::ImageFamily& image,
564 bool refresh_shell_icon_cache) {
565 if (!ShouldUpdateIcon(icon_file, image))
566 return true;
568 if (!SaveIconWithCheckSum(icon_file, image))
569 return false;
571 if (refresh_shell_icon_cache) {
572 // Refresh shell's icon cache. This call is quite disruptive as user would
573 // see explorer rebuilding the icon cache. It would be great that we find
574 // a better way to achieve this.
575 SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST | SHCNF_FLUSHNOWAIT, NULL,
576 NULL);
578 return true;
581 bool CreatePlatformShortcuts(
582 const base::FilePath& web_app_path,
583 scoped_ptr<ShortcutInfo> shortcut_info,
584 const extensions::FileHandlersInfo& file_handlers_info,
585 const ShortcutLocations& creation_locations,
586 ShortcutCreationReason creation_reason) {
587 DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
589 // Nothing to do on Windows for hidden apps.
590 if (creation_locations.applications_menu_location == APP_MENU_LOCATION_HIDDEN)
591 return true;
593 // Shortcut paths under which to create shortcuts.
594 std::vector<base::FilePath> shortcut_paths =
595 GetShortcutPaths(creation_locations);
597 bool pin_to_taskbar = creation_locations.in_quick_launch_bar &&
598 (base::win::GetVersion() >= base::win::VERSION_WIN7);
600 // Create/update the shortcut in the web app path for the "Pin To Taskbar"
601 // option in Win7. We use the web app path shortcut because we will overwrite
602 // it rather than appending unique numbers if the shortcut already exists.
603 // This prevents pinned apps from having unique numbers in their names.
604 if (pin_to_taskbar)
605 shortcut_paths.push_back(web_app_path);
607 if (shortcut_paths.empty())
608 return false;
610 if (!CreateShortcutsInPaths(web_app_path, *shortcut_info, shortcut_paths,
611 creation_reason, NULL))
612 return false;
614 if (pin_to_taskbar) {
615 base::FilePath file_name = GetSanitizedFileName(shortcut_info->title);
616 // Use the web app path shortcut for pinning to avoid having unique numbers
617 // in the application name.
618 base::FilePath shortcut_to_pin = web_app_path.Append(file_name).
619 AddExtension(installer::kLnkExt);
620 if (!base::win::PinShortcutToTaskbar(shortcut_to_pin))
621 return false;
624 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
625 switches::kEnableAppsFileAssociations)) {
626 CreateFileAssociationsForApp(
627 shortcut_info->extension_id, shortcut_info->title,
628 shortcut_info->profile_path, file_handlers_info);
631 return true;
634 void UpdatePlatformShortcuts(
635 const base::FilePath& web_app_path,
636 const base::string16& old_app_title,
637 scoped_ptr<ShortcutInfo> shortcut_info,
638 const extensions::FileHandlersInfo& file_handlers_info) {
639 DCHECK_CURRENTLY_ON(content::BrowserThread::FILE);
641 // Generates file name to use with persisted ico and shortcut file.
642 base::FilePath file_name =
643 web_app::internals::GetSanitizedFileName(shortcut_info->title);
645 if (old_app_title != shortcut_info->title) {
646 // The app's title has changed. Delete all existing app shortcuts and
647 // recreate them in any locations they already existed (but do not add them
648 // to locations where they do not currently exist).
649 bool was_pinned_to_taskbar;
650 std::vector<base::FilePath> shortcut_paths;
651 GetShortcutLocationsAndDeleteShortcuts(
652 web_app_path, shortcut_info->profile_path, old_app_title,
653 &was_pinned_to_taskbar, &shortcut_paths);
654 CreateShortcutsInPaths(web_app_path, *shortcut_info, shortcut_paths,
655 SHORTCUT_CREATION_BY_USER, NULL);
656 // If the shortcut was pinned to the taskbar,
657 // GetShortcutLocationsAndDeleteShortcuts will have deleted it. In that
658 // case, re-pin it.
659 if (was_pinned_to_taskbar) {
660 base::FilePath file_name = GetSanitizedFileName(shortcut_info->title);
661 // Use the web app path shortcut for pinning to avoid having unique
662 // numbers in the application name.
663 base::FilePath shortcut_to_pin = web_app_path.Append(file_name).
664 AddExtension(installer::kLnkExt);
665 base::win::PinShortcutToTaskbar(shortcut_to_pin);
669 // Update the icon if necessary.
670 base::FilePath icon_file =
671 GetIconFilePath(web_app_path, shortcut_info->title);
672 CheckAndSaveIcon(icon_file, shortcut_info->favicon, true);
675 void DeletePlatformShortcuts(const base::FilePath& web_app_path,
676 scoped_ptr<ShortcutInfo> shortcut_info) {
677 GetShortcutLocationsAndDeleteShortcuts(web_app_path,
678 shortcut_info->profile_path,
679 shortcut_info->title, NULL, NULL);
681 // If there are no more shortcuts in the Chrome Apps subdirectory, remove it.
682 base::FilePath chrome_apps_dir;
683 if (ShellUtil::GetShortcutPath(
684 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR,
685 BrowserDistribution::GetDistribution(),
686 ShellUtil::CURRENT_USER,
687 &chrome_apps_dir)) {
688 if (base::IsDirectoryEmpty(chrome_apps_dir))
689 base::DeleteFile(chrome_apps_dir, false);
693 void DeleteAllShortcutsForProfile(const base::FilePath& profile_path) {
694 GetShortcutLocationsAndDeleteShortcuts(base::FilePath(), profile_path, L"",
695 NULL, NULL);
697 // If there are no more shortcuts in the Chrome Apps subdirectory, remove it.
698 base::FilePath chrome_apps_dir;
699 if (ShellUtil::GetShortcutPath(
700 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR,
701 BrowserDistribution::GetDistribution(),
702 ShellUtil::CURRENT_USER,
703 &chrome_apps_dir)) {
704 if (base::IsDirectoryEmpty(chrome_apps_dir))
705 base::DeleteFile(chrome_apps_dir, false);
709 std::vector<base::FilePath> GetShortcutPaths(
710 const ShortcutLocations& creation_locations) {
711 // Shortcut paths under which to create shortcuts.
712 std::vector<base::FilePath> shortcut_paths;
713 // Locations to add to shortcut_paths.
714 struct {
715 bool use_this_location;
716 ShellUtil::ShortcutLocation location_id;
717 } locations[] = {
719 creation_locations.on_desktop,
720 ShellUtil::SHORTCUT_LOCATION_DESKTOP
721 }, {
722 creation_locations.applications_menu_location ==
723 APP_MENU_LOCATION_ROOT,
724 ShellUtil::SHORTCUT_LOCATION_START_MENU_ROOT
725 }, {
726 creation_locations.applications_menu_location ==
727 APP_MENU_LOCATION_SUBDIR_CHROME,
728 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_DIR
729 }, {
730 creation_locations.applications_menu_location ==
731 APP_MENU_LOCATION_SUBDIR_CHROMEAPPS,
732 ShellUtil::SHORTCUT_LOCATION_START_MENU_CHROME_APPS_DIR
733 }, {
734 // For Win7+, |in_quick_launch_bar| indicates that we are pinning to
735 // taskbar. This needs to be handled by callers.
736 creation_locations.in_quick_launch_bar &&
737 base::win::GetVersion() < base::win::VERSION_WIN7,
738 ShellUtil::SHORTCUT_LOCATION_QUICK_LAUNCH
742 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
743 // Populate shortcut_paths.
744 for (int i = 0; i < arraysize(locations); ++i) {
745 if (locations[i].use_this_location) {
746 base::FilePath path;
747 if (!ShellUtil::GetShortcutPath(locations[i].location_id,
748 dist,
749 ShellUtil::CURRENT_USER,
750 &path)) {
751 NOTREACHED();
752 continue;
754 shortcut_paths.push_back(path);
757 return shortcut_paths;
760 base::FilePath GetIconFilePath(const base::FilePath& web_app_path,
761 const base::string16& title) {
762 return web_app_path.Append(GetSanitizedFileName(title))
763 .AddExtension(FILE_PATH_LITERAL(".ico"));
766 } // namespace internals
768 void UpdateShortcutForTabContents(content::WebContents* web_contents) {
769 // UpdateShortcutWorker will delete itself when it's done.
770 UpdateShortcutWorker* worker = new UpdateShortcutWorker(web_contents);
771 worker->Run();
774 } // namespace web_app