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/shell_integration_linux.h"
15 #include <sys/types.h>
21 #include "base/base_paths.h"
22 #include "base/command_line.h"
23 #include "base/environment.h"
24 #include "base/files/file_enumerator.h"
25 #include "base/files/file_path.h"
26 #include "base/files/file_util.h"
27 #include "base/files/scoped_temp_dir.h"
28 #include "base/i18n/file_util_icu.h"
29 #include "base/memory/ref_counted_memory.h"
30 #include "base/memory/scoped_ptr.h"
31 #include "base/message_loop/message_loop.h"
32 #include "base/nix/xdg_util.h"
33 #include "base/path_service.h"
34 #include "base/posix/eintr_wrapper.h"
35 #include "base/process/kill.h"
36 #include "base/process/launch.h"
37 #include "base/strings/string_number_conversions.h"
38 #include "base/strings/string_tokenizer.h"
39 #include "base/strings/string_util.h"
40 #include "base/strings/utf_string_conversions.h"
41 #include "base/threading/thread.h"
42 #include "base/threading/thread_restrictions.h"
43 #include "build/build_config.h"
44 #include "chrome/browser/shell_integration.h"
45 #include "chrome/common/channel_info.h"
46 #include "chrome/common/chrome_constants.h"
47 #include "chrome/common/chrome_switches.h"
48 #include "components/version_info/version_info.h"
49 #include "content/public/browser/browser_thread.h"
50 #include "grit/chrome_unscaled_resources.h"
51 #include "ui/base/resource/resource_bundle.h"
52 #include "ui/gfx/image/image_family.h"
55 using content::BrowserThread
;
59 // The Categories for the App Launcher desktop shortcut. Should be the same as
60 // the Chrome desktop shortcut, so they are in the same sub-menu.
61 const char kAppListCategories
[] = "Network;WebBrowser;";
63 // Helper to launch xdg scripts. We don't want them to ask any questions on the
64 // terminal etc. The function returns true if the utility launches and exits
65 // cleanly, in which case |exit_code| returns the utility's exit code.
66 bool LaunchXdgUtility(const std::vector
<std::string
>& argv
, int* exit_code
) {
67 // xdg-settings internally runs xdg-mime, which uses mv to move newly-created
68 // files on top of originals after making changes to them. In the event that
69 // the original files are owned by another user (e.g. root, which can happen
70 // if they are updated within sudo), mv will prompt the user to confirm if
71 // standard input is a terminal (otherwise it just does it). So make sure it's
72 // not, to avoid locking everything up waiting for mv.
73 *exit_code
= EXIT_FAILURE
;
74 int devnull
= open("/dev/null", O_RDONLY
);
77 base::FileHandleMappingVector no_stdin
;
78 no_stdin
.push_back(std::make_pair(devnull
, STDIN_FILENO
));
80 base::LaunchOptions options
;
81 options
.fds_to_remap
= &no_stdin
;
82 base::Process process
= base::LaunchProcess(argv
, options
);
84 if (!process
.IsValid())
86 return process
.WaitForExit(exit_code
);
89 std::string
CreateShortcutIcon(const gfx::ImageFamily
& icon_images
,
90 const base::FilePath
& shortcut_filename
) {
91 if (icon_images
.empty())
94 // TODO(phajdan.jr): Report errors from this function, possibly as infobars.
95 base::ScopedTempDir temp_dir
;
96 if (!temp_dir
.CreateUniqueTempDir())
99 base::FilePath temp_file_path
= temp_dir
.path().Append(
100 shortcut_filename
.ReplaceExtension("png"));
101 std::string icon_name
= temp_file_path
.BaseName().RemoveExtension().value();
103 for (gfx::ImageFamily::const_iterator it
= icon_images
.begin();
104 it
!= icon_images
.end(); ++it
) {
105 int width
= it
->Width();
106 scoped_refptr
<base::RefCountedMemory
> png_data
= it
->As1xPNGBytes();
107 if (png_data
->size() == 0) {
108 // If the bitmap could not be encoded to PNG format, skip it.
109 LOG(WARNING
) << "Could not encode icon " << icon_name
<< ".png at size "
113 int bytes_written
= base::WriteFile(temp_file_path
,
114 png_data
->front_as
<char>(),
117 if (bytes_written
!= static_cast<int>(png_data
->size()))
118 return std::string();
120 std::vector
<std::string
> argv
;
121 argv
.push_back("xdg-icon-resource");
122 argv
.push_back("install");
124 // Always install in user mode, even if someone runs the browser as root
126 argv
.push_back("--mode");
127 argv
.push_back("user");
129 argv
.push_back("--size");
130 argv
.push_back(base::IntToString(width
));
132 argv
.push_back(temp_file_path
.value());
133 argv
.push_back(icon_name
);
135 if (!LaunchXdgUtility(argv
, &exit_code
) || exit_code
) {
136 LOG(WARNING
) << "Could not install icon " << icon_name
<< ".png at size "
143 bool CreateShortcutOnDesktop(const base::FilePath
& shortcut_filename
,
144 const std::string
& contents
) {
145 // Make sure that we will later call openat in a secure way.
146 DCHECK_EQ(shortcut_filename
.BaseName().value(), shortcut_filename
.value());
148 base::FilePath desktop_path
;
149 if (!PathService::Get(base::DIR_USER_DESKTOP
, &desktop_path
))
152 int desktop_fd
= open(desktop_path
.value().c_str(), O_RDONLY
| O_DIRECTORY
);
156 int fd
= openat(desktop_fd
, shortcut_filename
.value().c_str(),
157 O_CREAT
| O_EXCL
| O_WRONLY
,
158 S_IRWXU
| S_IRGRP
| S_IXGRP
| S_IROTH
| S_IXOTH
);
160 if (IGNORE_EINTR(close(desktop_fd
)) < 0)
161 PLOG(ERROR
) << "close";
165 if (!base::WriteFileDescriptor(fd
, contents
.c_str(), contents
.size())) {
166 // Delete the file. No shortuct is better than corrupted one. Use unlinkat
167 // to make sure we're deleting the file in the directory we think we are.
168 // Even if an attacker manager to put something other at
169 // |shortcut_filename| we'll just undo his action.
170 unlinkat(desktop_fd
, shortcut_filename
.value().c_str(), 0);
173 if (IGNORE_EINTR(close(fd
)) < 0)
174 PLOG(ERROR
) << "close";
176 if (IGNORE_EINTR(close(desktop_fd
)) < 0)
177 PLOG(ERROR
) << "close";
182 void DeleteShortcutOnDesktop(const base::FilePath
& shortcut_filename
) {
183 base::FilePath desktop_path
;
184 if (PathService::Get(base::DIR_USER_DESKTOP
, &desktop_path
))
185 base::DeleteFile(desktop_path
.Append(shortcut_filename
), false);
188 // Creates a shortcut with |shortcut_filename| and |contents| in the system
189 // applications menu. If |directory_filename| is non-empty, creates a sub-menu
190 // with |directory_filename| and |directory_contents|, and stores the shortcut
191 // under the sub-menu.
192 bool CreateShortcutInApplicationsMenu(const base::FilePath
& shortcut_filename
,
193 const std::string
& contents
,
194 const base::FilePath
& directory_filename
,
195 const std::string
& directory_contents
) {
196 base::ScopedTempDir temp_dir
;
197 if (!temp_dir
.CreateUniqueTempDir())
200 base::FilePath temp_directory_path
;
201 if (!directory_filename
.empty()) {
202 temp_directory_path
= temp_dir
.path().Append(directory_filename
);
204 int bytes_written
= base::WriteFile(temp_directory_path
,
205 directory_contents
.data(),
206 directory_contents
.length());
208 if (bytes_written
!= static_cast<int>(directory_contents
.length()))
212 base::FilePath temp_file_path
= temp_dir
.path().Append(shortcut_filename
);
214 int bytes_written
= base::WriteFile(temp_file_path
, contents
.data(),
217 if (bytes_written
!= static_cast<int>(contents
.length()))
220 std::vector
<std::string
> argv
;
221 argv
.push_back("xdg-desktop-menu");
222 argv
.push_back("install");
224 // Always install in user mode, even if someone runs the browser as root
226 argv
.push_back("--mode");
227 argv
.push_back("user");
229 // If provided, install the shortcut file inside the given directory.
230 if (!directory_filename
.empty())
231 argv
.push_back(temp_directory_path
.value());
232 argv
.push_back(temp_file_path
.value());
234 LaunchXdgUtility(argv
, &exit_code
);
235 return exit_code
== 0;
238 void DeleteShortcutInApplicationsMenu(
239 const base::FilePath
& shortcut_filename
,
240 const base::FilePath
& directory_filename
) {
241 std::vector
<std::string
> argv
;
242 argv
.push_back("xdg-desktop-menu");
243 argv
.push_back("uninstall");
245 // Uninstall in user mode, to match the install.
246 argv
.push_back("--mode");
247 argv
.push_back("user");
249 // The file does not need to exist anywhere - xdg-desktop-menu will uninstall
250 // items from the menu with a matching name.
251 // If |directory_filename| is supplied, this will also remove the item from
252 // the directory, and remove the directory if it is empty.
253 if (!directory_filename
.empty())
254 argv
.push_back(directory_filename
.value());
255 argv
.push_back(shortcut_filename
.value());
257 LaunchXdgUtility(argv
, &exit_code
);
260 #if defined(USE_GLIB)
261 // Quote a string such that it appears as one verbatim argument for the Exec
262 // key in a desktop file.
263 std::string
QuoteArgForDesktopFileExec(const std::string
& arg
) {
264 // http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s06.html
266 // Quoting is only necessary if the argument has a reserved character.
267 if (arg
.find_first_of(" \t\n\"'\\><~|&;$*?#()`") == std::string::npos
)
268 return arg
; // No quoting necessary.
270 std::string quoted
= "\"";
271 for (size_t i
= 0; i
< arg
.size(); ++i
) {
272 // Note that the set of backslashed characters is smaller than the
273 // set of reserved characters.
289 // Quote a command line so it is suitable for use as the Exec key in a desktop
290 // file. Note: This should be used instead of GetCommandLineString, which does
291 // not properly quote the string; this function is designed for the Exec key.
292 std::string
QuoteCommandLineForDesktopFileExec(
293 const base::CommandLine
& command_line
) {
294 // http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s06.html
296 std::string quoted_path
= "";
297 const base::CommandLine::StringVector
& argv
= command_line
.argv();
298 for (base::CommandLine::StringVector::const_iterator i
= argv
.begin();
299 i
!= argv
.end(); ++i
) {
300 if (i
!= argv
.begin())
302 quoted_path
+= QuoteArgForDesktopFileExec(*i
);
308 const char kDesktopEntry
[] = "Desktop Entry";
310 const char kXdgOpenShebang
[] = "#!/usr/bin/env xdg-open";
313 const char kXdgSettings
[] = "xdg-settings";
314 const char kXdgSettingsDefaultBrowser
[] = "default-web-browser";
315 const char kXdgSettingsDefaultSchemeHandler
[] = "default-url-scheme-handler";
317 const char kDirectoryFilename
[] = "chrome-apps.directory";
319 #if defined(GOOGLE_CHROME_BUILD)
320 const char kAppListDesktopName
[] = "chrome-app-list";
321 #else // CHROMIUM_BUILD
322 const char kAppListDesktopName
[] = "chromium-app-list";
325 // Utility function to get the path to the version of a script shipped with
326 // Chrome. |script| gives the name of the script. |chrome_version| returns the
327 // path to the Chrome version of the script, and the return value of the
328 // function is true if the function is successful and the Chrome version is
329 // not the script found on the PATH.
330 bool GetChromeVersionOfScript(const std::string
& script
,
331 std::string
* chrome_version
) {
332 // Get the path to the Chrome version.
333 base::FilePath chrome_dir
;
334 if (!PathService::Get(base::DIR_EXE
, &chrome_dir
))
337 base::FilePath chrome_version_path
= chrome_dir
.Append(script
);
338 *chrome_version
= chrome_version_path
.value();
340 // Check if this is different to the one on path.
341 std::vector
<std::string
> argv
;
342 argv
.push_back("which");
343 argv
.push_back(script
);
344 std::string path_version
;
345 if (base::GetAppOutput(base::CommandLine(argv
), &path_version
)) {
346 // Remove trailing newline
347 path_version
.erase(path_version
.length() - 1, 1);
348 base::FilePath
path_version_path(path_version
);
349 return (chrome_version_path
!= path_version_path
);
354 // Value returned by xdg-settings if it can't understand our request.
355 const int EXIT_XDG_SETTINGS_SYNTAX_ERROR
= 1;
357 // We delegate the difficulty of setting the default browser and default url
358 // scheme handler in Linux desktop environments to an xdg utility, xdg-settings.
360 // When calling this script we first try to use the script on PATH. If that
361 // fails we then try to use the script that we have included. This gives
362 // scripts on the system priority over ours, as distribution vendors may have
363 // tweaked the script, but still allows our copy to be used if the script on the
364 // system fails, as the system copy may be missing capabilities of the Chrome
367 // If |protocol| is empty this function sets Chrome as the default browser,
368 // otherwise it sets Chrome as the default handler application for |protocol|.
369 bool SetDefaultWebClient(const std::string
& protocol
) {
370 #if defined(OS_CHROMEOS)
373 scoped_ptr
<base::Environment
> env(base::Environment::Create());
375 std::vector
<std::string
> argv
;
376 argv
.push_back(kXdgSettings
);
377 argv
.push_back("set");
378 if (protocol
.empty()) {
379 argv
.push_back(kXdgSettingsDefaultBrowser
);
381 argv
.push_back(kXdgSettingsDefaultSchemeHandler
);
382 argv
.push_back(protocol
);
384 argv
.push_back(shell_integration_linux::GetDesktopName(env
.get()));
387 bool ran_ok
= LaunchXdgUtility(argv
, &exit_code
);
388 if (ran_ok
&& exit_code
== EXIT_XDG_SETTINGS_SYNTAX_ERROR
) {
389 if (GetChromeVersionOfScript(kXdgSettings
, &argv
[0])) {
390 ran_ok
= LaunchXdgUtility(argv
, &exit_code
);
394 return ran_ok
&& exit_code
== EXIT_SUCCESS
;
398 // If |protocol| is empty this function checks if Chrome is the default browser,
399 // otherwise it checks if Chrome is the default handler application for
401 ShellIntegration::DefaultWebClientState
GetIsDefaultWebClient(
402 const std::string
& protocol
) {
403 #if defined(OS_CHROMEOS)
404 return ShellIntegration::UNKNOWN_DEFAULT
;
406 base::ThreadRestrictions::AssertIOAllowed();
408 scoped_ptr
<base::Environment
> env(base::Environment::Create());
410 std::vector
<std::string
> argv
;
411 argv
.push_back(kXdgSettings
);
412 argv
.push_back("check");
413 if (protocol
.empty()) {
414 argv
.push_back(kXdgSettingsDefaultBrowser
);
416 argv
.push_back(kXdgSettingsDefaultSchemeHandler
);
417 argv
.push_back(protocol
);
419 argv
.push_back(shell_integration_linux::GetDesktopName(env
.get()));
423 bool ran_ok
= base::GetAppOutputWithExitCode(base::CommandLine(argv
), &reply
,
425 if (ran_ok
&& success_code
== EXIT_XDG_SETTINGS_SYNTAX_ERROR
) {
426 if (GetChromeVersionOfScript(kXdgSettings
, &argv
[0])) {
427 ran_ok
= base::GetAppOutputWithExitCode(base::CommandLine(argv
), &reply
,
432 if (!ran_ok
|| success_code
!= EXIT_SUCCESS
) {
433 // xdg-settings failed: we can't determine or set the default browser.
434 return ShellIntegration::UNKNOWN_DEFAULT
;
437 // Allow any reply that starts with "yes".
438 return (reply
.find("yes") == 0) ? ShellIntegration::IS_DEFAULT
:
439 ShellIntegration::NOT_DEFAULT
;
443 // Get the value of NoDisplay from the [Desktop Entry] section of a .desktop
444 // file, given in |shortcut_contents|. If the key is not found, returns false.
445 bool GetNoDisplayFromDesktopFile(const std::string
& shortcut_contents
) {
446 #if defined(USE_GLIB)
447 // An empty file causes a crash with glib <= 2.32, so special case here.
448 if (shortcut_contents
.empty())
451 GKeyFile
* key_file
= g_key_file_new();
453 if (!g_key_file_load_from_data(key_file
, shortcut_contents
.c_str(),
454 shortcut_contents
.size(), G_KEY_FILE_NONE
,
456 LOG(WARNING
) << "Unable to read desktop file template: " << err
->message
;
458 g_key_file_free(key_file
);
462 bool nodisplay
= false;
463 char* nodisplay_c_string
= g_key_file_get_string(key_file
, kDesktopEntry
,
465 if (nodisplay_c_string
) {
466 if (!g_strcmp0(nodisplay_c_string
, "true"))
468 g_free(nodisplay_c_string
);
473 g_key_file_free(key_file
);
481 // Gets the path to the Chrome executable or wrapper script.
482 // Returns an empty path if the executable path could not be found, which should
484 base::FilePath
GetChromeExePath() {
485 // Try to get the name of the wrapper script that launched Chrome.
486 scoped_ptr
<base::Environment
> environment(base::Environment::Create());
487 std::string wrapper_script
;
488 if (environment
->GetVar("CHROME_WRAPPER", &wrapper_script
))
489 return base::FilePath(wrapper_script
);
491 // Just return the name of the executable path for Chrome.
492 base::FilePath chrome_exe_path
;
493 PathService::Get(base::FILE_EXE
, &chrome_exe_path
);
494 return chrome_exe_path
;
500 ShellIntegration::DefaultWebClientSetPermission
501 ShellIntegration::CanSetAsDefaultBrowser() {
502 return SET_DEFAULT_UNATTENDED
;
506 bool ShellIntegration::SetAsDefaultBrowser() {
507 return SetDefaultWebClient(std::string());
511 bool ShellIntegration::SetAsDefaultProtocolClient(
512 const std::string
& protocol
) {
513 return SetDefaultWebClient(protocol
);
517 ShellIntegration::DefaultWebClientState
518 ShellIntegration::GetDefaultBrowser() {
519 return GetIsDefaultWebClient(std::string());
523 base::string16
ShellIntegration::GetApplicationNameForProtocol(
525 return base::ASCIIToUTF16("xdg-open");
529 ShellIntegration::DefaultWebClientState
530 ShellIntegration::IsDefaultProtocolClient(const std::string
& protocol
) {
531 return GetIsDefaultWebClient(protocol
);
535 bool ShellIntegration::IsFirefoxDefaultBrowser() {
536 std::vector
<std::string
> argv
;
537 argv
.push_back(kXdgSettings
);
538 argv
.push_back("get");
539 argv
.push_back(kXdgSettingsDefaultBrowser
);
542 // We don't care about the return value here.
543 base::GetAppOutput(base::CommandLine(argv
), &browser
);
544 return browser
.find("irefox") != std::string::npos
;
547 namespace shell_integration_linux
{
549 base::FilePath
GetDataWriteLocation(base::Environment
* env
) {
550 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
552 return base::nix::GetXDGDirectory(env
, "XDG_DATA_HOME", ".local/share");
555 std::vector
<base::FilePath
> GetDataSearchLocations(base::Environment
* env
) {
556 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
558 std::vector
<base::FilePath
> search_paths
;
559 base::FilePath write_location
= GetDataWriteLocation(env
);
560 search_paths
.push_back(write_location
);
562 std::string xdg_data_dirs
;
563 if (env
->GetVar("XDG_DATA_DIRS", &xdg_data_dirs
) && !xdg_data_dirs
.empty()) {
564 base::StringTokenizer
tokenizer(xdg_data_dirs
, ":");
565 while (tokenizer
.GetNext()) {
566 base::FilePath
data_dir(tokenizer
.token());
567 search_paths
.push_back(data_dir
);
570 search_paths
.push_back(base::FilePath("/usr/local/share"));
571 search_paths
.push_back(base::FilePath("/usr/share"));
577 std::string
GetProgramClassName() {
578 scoped_ptr
<base::Environment
> env(base::Environment::Create());
579 std::string
desktop_file(GetDesktopName(env
.get()));
580 std::size_t last
= desktop_file
.find(".desktop");
581 if (last
!= std::string::npos
)
582 return desktop_file
.substr(0, last
);
586 std::string
GetDesktopName(base::Environment
* env
) {
587 #if defined(GOOGLE_CHROME_BUILD)
588 version_info::Channel
product_channel(chrome::GetChannel());
589 switch (product_channel
) {
590 case version_info::Channel::DEV
:
591 return "google-chrome-unstable.desktop";
592 case version_info::Channel::BETA
:
593 return "google-chrome-beta.desktop";
595 return "google-chrome.desktop";
597 #else // CHROMIUM_BUILD
598 // Allow $CHROME_DESKTOP to override the built-in value, so that development
599 // versions can set themselves as the default without interfering with
600 // non-official, packaged versions using the built-in value.
602 if (env
->GetVar("CHROME_DESKTOP", &name
) && !name
.empty())
604 return "chromium-browser.desktop";
608 std::string
GetIconName() {
609 #if defined(GOOGLE_CHROME_BUILD)
610 return "google-chrome";
611 #else // CHROMIUM_BUILD
612 return "chromium-browser";
616 web_app::ShortcutLocations
GetExistingShortcutLocations(
617 base::Environment
* env
,
618 const base::FilePath
& profile_path
,
619 const std::string
& extension_id
) {
620 base::FilePath desktop_path
;
621 // If Get returns false, just leave desktop_path empty.
622 PathService::Get(base::DIR_USER_DESKTOP
, &desktop_path
);
623 return GetExistingShortcutLocations(env
, profile_path
, extension_id
,
627 web_app::ShortcutLocations
GetExistingShortcutLocations(
628 base::Environment
* env
,
629 const base::FilePath
& profile_path
,
630 const std::string
& extension_id
,
631 const base::FilePath
& desktop_path
) {
632 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
634 base::FilePath shortcut_filename
= GetExtensionShortcutFilename(
635 profile_path
, extension_id
);
636 DCHECK(!shortcut_filename
.empty());
637 web_app::ShortcutLocations locations
;
639 // Determine whether there is a shortcut on desktop.
640 if (!desktop_path
.empty()) {
641 locations
.on_desktop
=
642 base::PathExists(desktop_path
.Append(shortcut_filename
));
645 // Determine whether there is a shortcut in the applications directory.
646 std::string shortcut_contents
;
647 if (GetExistingShortcutContents(env
, shortcut_filename
, &shortcut_contents
)) {
648 // If the shortcut contents contain NoDisplay=true, it should be hidden.
649 // Otherwise since these shortcuts are for apps, they are always in the
650 // "Chrome Apps" directory.
651 locations
.applications_menu_location
=
652 GetNoDisplayFromDesktopFile(shortcut_contents
)
653 ? web_app::APP_MENU_LOCATION_HIDDEN
654 : web_app::APP_MENU_LOCATION_SUBDIR_CHROMEAPPS
;
660 bool GetExistingShortcutContents(base::Environment
* env
,
661 const base::FilePath
& desktop_filename
,
662 std::string
* output
) {
663 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
665 std::vector
<base::FilePath
> search_paths
= GetDataSearchLocations(env
);
667 for (std::vector
<base::FilePath
>::const_iterator i
= search_paths
.begin();
668 i
!= search_paths
.end(); ++i
) {
669 base::FilePath path
= i
->Append("applications").Append(desktop_filename
);
670 VLOG(1) << "Looking for desktop file in " << path
.value();
671 if (base::PathExists(path
)) {
672 VLOG(1) << "Found desktop file at " << path
.value();
673 return base::ReadFileToString(path
, output
);
680 base::FilePath
GetWebShortcutFilename(const GURL
& url
) {
681 // Use a prefix, because xdg-desktop-menu requires it.
682 std::string filename
=
683 std::string(chrome::kBrowserProcessExecutableName
) + "-" + url
.spec();
684 base::i18n::ReplaceIllegalCharactersInPath(&filename
, '_');
686 base::FilePath desktop_path
;
687 if (!PathService::Get(base::DIR_USER_DESKTOP
, &desktop_path
))
688 return base::FilePath();
690 base::FilePath filepath
= desktop_path
.Append(filename
);
691 base::FilePath
alternative_filepath(filepath
.value() + ".desktop");
692 for (size_t i
= 1; i
< 100; ++i
) {
693 if (base::PathExists(base::FilePath(alternative_filepath
))) {
694 alternative_filepath
= base::FilePath(
695 filepath
.value() + "_" + base::SizeTToString(i
) + ".desktop");
697 return base::FilePath(alternative_filepath
).BaseName();
701 return base::FilePath();
704 base::FilePath
GetExtensionShortcutFilename(const base::FilePath
& profile_path
,
705 const std::string
& extension_id
) {
706 DCHECK(!extension_id
.empty());
708 // Use a prefix, because xdg-desktop-menu requires it.
709 std::string
filename(chrome::kBrowserProcessExecutableName
);
711 .append(extension_id
)
713 .append(profile_path
.BaseName().value());
714 base::i18n::ReplaceIllegalCharactersInPath(&filename
, '_');
715 // Spaces in filenames break xdg-desktop-menu
716 // (see https://bugs.freedesktop.org/show_bug.cgi?id=66605).
717 base::ReplaceChars(filename
, " ", "_", &filename
);
718 return base::FilePath(filename
.append(".desktop"));
721 std::vector
<base::FilePath
> GetExistingProfileShortcutFilenames(
722 const base::FilePath
& profile_path
,
723 const base::FilePath
& directory
) {
724 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
726 // Use a prefix, because xdg-desktop-menu requires it.
727 std::string
prefix(chrome::kBrowserProcessExecutableName
);
729 std::string
suffix("-");
730 suffix
.append(profile_path
.BaseName().value());
731 base::i18n::ReplaceIllegalCharactersInPath(&suffix
, '_');
732 // Spaces in filenames break xdg-desktop-menu
733 // (see https://bugs.freedesktop.org/show_bug.cgi?id=66605).
734 base::ReplaceChars(suffix
, " ", "_", &suffix
);
735 std::string glob
= prefix
+ "*" + suffix
+ ".desktop";
737 base::FileEnumerator
files(directory
, false, base::FileEnumerator::FILES
,
739 base::FilePath shortcut_file
= files
.Next();
740 std::vector
<base::FilePath
> shortcut_paths
;
741 while (!shortcut_file
.empty()) {
742 shortcut_paths
.push_back(shortcut_file
.BaseName());
743 shortcut_file
= files
.Next();
745 return shortcut_paths
;
748 std::string
GetDesktopFileContents(
749 const base::FilePath
& chrome_exe_path
,
750 const std::string
& app_name
,
752 const std::string
& extension_id
,
753 const base::string16
& title
,
754 const std::string
& icon_name
,
755 const base::FilePath
& profile_path
,
756 const std::string
& categories
,
758 base::CommandLine cmd_line
=
759 ShellIntegration::CommandLineArgsForLauncher(url
, extension_id
,
761 cmd_line
.SetProgram(chrome_exe_path
);
762 return GetDesktopFileContentsForCommand(cmd_line
, app_name
, url
, title
,
763 icon_name
, categories
, no_display
);
766 std::string
GetDesktopFileContentsForCommand(
767 const base::CommandLine
& command_line
,
768 const std::string
& app_name
,
770 const base::string16
& title
,
771 const std::string
& icon_name
,
772 const std::string
& categories
,
774 #if defined(USE_GLIB)
775 // Although not required by the spec, Nautilus on Ubuntu Karmic creates its
776 // launchers with an xdg-open shebang. Follow that convention.
777 std::string output_buffer
= std::string(kXdgOpenShebang
) + "\n";
779 // See http://standards.freedesktop.org/desktop-entry-spec/latest/
780 GKeyFile
* key_file
= g_key_file_new();
782 // Set keys with fixed values.
783 g_key_file_set_string(key_file
, kDesktopEntry
, "Version", "1.0");
784 g_key_file_set_string(key_file
, kDesktopEntry
, "Terminal", "false");
785 g_key_file_set_string(key_file
, kDesktopEntry
, "Type", "Application");
787 // Set the "Name" key.
788 std::string final_title
= base::UTF16ToUTF8(title
);
789 // Make sure no endline characters can slip in and possibly introduce
790 // additional lines (like Exec, which makes it a security risk). Also
791 // use the URL as a default when the title is empty.
792 if (final_title
.empty() ||
793 final_title
.find("\n") != std::string::npos
||
794 final_title
.find("\r") != std::string::npos
) {
795 final_title
= url
.spec();
797 g_key_file_set_string(key_file
, kDesktopEntry
, "Name", final_title
.c_str());
799 // Set the "Exec" key.
800 std::string final_path
= QuoteCommandLineForDesktopFileExec(command_line
);
801 g_key_file_set_string(key_file
, kDesktopEntry
, "Exec", final_path
.c_str());
803 // Set the "Icon" key.
804 if (!icon_name
.empty()) {
805 g_key_file_set_string(key_file
, kDesktopEntry
, "Icon", icon_name
.c_str());
807 g_key_file_set_string(key_file
, kDesktopEntry
, "Icon",
808 GetIconName().c_str());
811 // Set the "Categories" key.
812 if (!categories
.empty()) {
813 g_key_file_set_string(
814 key_file
, kDesktopEntry
, "Categories", categories
.c_str());
817 // Set the "NoDisplay" key.
819 g_key_file_set_string(key_file
, kDesktopEntry
, "NoDisplay", "true");
821 std::string wmclass
= web_app::GetWMClassFromAppName(app_name
);
822 g_key_file_set_string(key_file
, kDesktopEntry
, "StartupWMClass",
826 gchar
* data_dump
= g_key_file_to_data(key_file
, &length
, NULL
);
828 // If strlen(data_dump[0]) == 0, this check will fail.
829 if (data_dump
[0] == '\n') {
830 // Older versions of glib produce a leading newline. If this is the case,
831 // remove it to avoid double-newline after the shebang.
832 output_buffer
+= (data_dump
+ 1);
834 output_buffer
+= data_dump
;
839 g_key_file_free(key_file
);
840 return output_buffer
;
843 return std::string();
847 std::string
GetDirectoryFileContents(const base::string16
& title
,
848 const std::string
& icon_name
) {
849 #if defined(USE_GLIB)
850 // See http://standards.freedesktop.org/desktop-entry-spec/latest/
851 GKeyFile
* key_file
= g_key_file_new();
853 g_key_file_set_string(key_file
, kDesktopEntry
, "Version", "1.0");
854 g_key_file_set_string(key_file
, kDesktopEntry
, "Type", "Directory");
855 std::string final_title
= base::UTF16ToUTF8(title
);
856 g_key_file_set_string(key_file
, kDesktopEntry
, "Name", final_title
.c_str());
857 if (!icon_name
.empty()) {
858 g_key_file_set_string(key_file
, kDesktopEntry
, "Icon", icon_name
.c_str());
860 g_key_file_set_string(key_file
, kDesktopEntry
, "Icon",
861 GetIconName().c_str());
865 gchar
* data_dump
= g_key_file_to_data(key_file
, &length
, NULL
);
866 std::string output_buffer
;
868 // If strlen(data_dump[0]) == 0, this check will fail.
869 if (data_dump
[0] == '\n') {
870 // Older versions of glib produce a leading newline. If this is the case,
871 // remove it to avoid double-newline after the shebang.
872 output_buffer
+= (data_dump
+ 1);
874 output_buffer
+= data_dump
;
879 g_key_file_free(key_file
);
880 return output_buffer
;
883 return std::string();
887 bool CreateDesktopShortcut(
888 const web_app::ShortcutInfo
& shortcut_info
,
889 const web_app::ShortcutLocations
& creation_locations
) {
890 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
892 base::FilePath shortcut_filename
;
893 if (!shortcut_info
.extension_id
.empty()) {
894 shortcut_filename
= GetExtensionShortcutFilename(
895 shortcut_info
.profile_path
, shortcut_info
.extension_id
);
896 // For extensions we do not want duplicate shortcuts. So, delete any that
897 // already exist and replace them.
898 if (creation_locations
.on_desktop
)
899 DeleteShortcutOnDesktop(shortcut_filename
);
901 if (creation_locations
.applications_menu_location
!=
902 web_app::APP_MENU_LOCATION_NONE
) {
903 DeleteShortcutInApplicationsMenu(shortcut_filename
, base::FilePath());
906 shortcut_filename
= GetWebShortcutFilename(shortcut_info
.url
);
908 if (shortcut_filename
.empty())
911 std::string icon_name
=
912 CreateShortcutIcon(shortcut_info
.favicon
, shortcut_filename
);
914 std::string app_name
=
915 web_app::GenerateApplicationNameFromInfo(shortcut_info
);
919 base::FilePath chrome_exe_path
= GetChromeExePath();
920 if (chrome_exe_path
.empty()) {
925 if (creation_locations
.on_desktop
) {
926 std::string contents
= GetDesktopFileContents(
930 shortcut_info
.extension_id
,
933 shortcut_info
.profile_path
,
936 success
= CreateShortcutOnDesktop(shortcut_filename
, contents
);
939 if (creation_locations
.applications_menu_location
==
940 web_app::APP_MENU_LOCATION_NONE
) {
944 base::FilePath directory_filename
;
945 std::string directory_contents
;
946 switch (creation_locations
.applications_menu_location
) {
947 case web_app::APP_MENU_LOCATION_ROOT
:
948 case web_app::APP_MENU_LOCATION_HIDDEN
:
950 case web_app::APP_MENU_LOCATION_SUBDIR_CHROMEAPPS
:
951 directory_filename
= base::FilePath(kDirectoryFilename
);
952 directory_contents
= GetDirectoryFileContents(
953 ShellIntegration::GetAppShortcutsSubdirName(), "");
960 // Set NoDisplay=true if hidden. This will hide the application from
961 // user-facing menus.
962 std::string contents
= GetDesktopFileContents(
966 shortcut_info
.extension_id
,
969 shortcut_info
.profile_path
,
971 creation_locations
.applications_menu_location
==
972 web_app::APP_MENU_LOCATION_HIDDEN
);
973 success
= CreateShortcutInApplicationsMenu(
974 shortcut_filename
, contents
, directory_filename
, directory_contents
) &&
980 bool CreateAppListDesktopShortcut(
981 const std::string
& wm_class
,
982 const std::string
& title
) {
983 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
985 base::FilePath
desktop_name(kAppListDesktopName
);
986 base::FilePath shortcut_filename
= desktop_name
.AddExtension("desktop");
988 // We do not want duplicate shortcuts. Delete any that already exist and
990 DeleteShortcutInApplicationsMenu(shortcut_filename
, base::FilePath());
992 base::FilePath chrome_exe_path
= GetChromeExePath();
993 if (chrome_exe_path
.empty()) {
998 gfx::ImageFamily icon_images
;
999 ResourceBundle
& resource_bundle
= ResourceBundle::GetSharedInstance();
1000 icon_images
.Add(*resource_bundle
.GetImageSkiaNamed(IDR_APP_LIST_16
));
1001 icon_images
.Add(*resource_bundle
.GetImageSkiaNamed(IDR_APP_LIST_32
));
1002 icon_images
.Add(*resource_bundle
.GetImageSkiaNamed(IDR_APP_LIST_48
));
1003 icon_images
.Add(*resource_bundle
.GetImageSkiaNamed(IDR_APP_LIST_256
));
1004 std::string icon_name
= CreateShortcutIcon(icon_images
, desktop_name
);
1006 base::CommandLine
command_line(chrome_exe_path
);
1007 command_line
.AppendSwitch(switches::kShowAppList
);
1008 std::string contents
=
1009 GetDesktopFileContentsForCommand(command_line
,
1012 base::UTF8ToUTF16(title
),
1016 return CreateShortcutInApplicationsMenu(
1017 shortcut_filename
, contents
, base::FilePath(), "");
1020 void DeleteDesktopShortcuts(const base::FilePath
& profile_path
,
1021 const std::string
& extension_id
) {
1022 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
1024 base::FilePath shortcut_filename
= GetExtensionShortcutFilename(
1025 profile_path
, extension_id
);
1026 DCHECK(!shortcut_filename
.empty());
1028 DeleteShortcutOnDesktop(shortcut_filename
);
1029 // Delete shortcuts from |kDirectoryFilename|.
1030 // Note that it is possible that shortcuts were not created in the Chrome Apps
1031 // directory. It doesn't matter: this will still delete the shortcut even if
1032 // it isn't in the directory.
1033 DeleteShortcutInApplicationsMenu(shortcut_filename
,
1034 base::FilePath(kDirectoryFilename
));
1037 void DeleteAllDesktopShortcuts(const base::FilePath
& profile_path
) {
1038 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
1040 scoped_ptr
<base::Environment
> env(base::Environment::Create());
1042 // Delete shortcuts from Desktop.
1043 base::FilePath desktop_path
;
1044 if (PathService::Get(base::DIR_USER_DESKTOP
, &desktop_path
)) {
1045 std::vector
<base::FilePath
> shortcut_filenames_desktop
=
1046 GetExistingProfileShortcutFilenames(profile_path
, desktop_path
);
1047 for (const auto& shortcut
: shortcut_filenames_desktop
) {
1048 DeleteShortcutOnDesktop(shortcut
);
1052 // Delete shortcuts from |kDirectoryFilename|.
1053 base::FilePath applications_menu
= GetDataWriteLocation(env
.get());
1054 applications_menu
= applications_menu
.AppendASCII("applications");
1055 std::vector
<base::FilePath
> shortcut_filenames_app_menu
=
1056 GetExistingProfileShortcutFilenames(profile_path
, applications_menu
);
1057 for (const auto& menu
: shortcut_filenames_app_menu
) {
1058 DeleteShortcutInApplicationsMenu(menu
, base::FilePath(kDirectoryFilename
));
1062 } // namespace shell_integration_linux