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