[Metrics] Make MetricsStateManager take a callback param to check if UMA is enabled.
[chromium-blink-merge.git] / chrome / browser / shell_integration_linux.cc
blobd24712aba5c5fb63b3b0170b29fffe7e6b1aeb39
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"
7 #include <fcntl.h>
9 #if defined(USE_GLIB)
10 #include <glib.h>
11 #endif
13 #include <stdlib.h>
14 #include <sys/stat.h>
15 #include <sys/types.h>
16 #include <unistd.h>
18 #include <string>
19 #include <vector>
21 #include "base/base_paths.h"
22 #include "base/command_line.h"
23 #include "base/environment.h"
24 #include "base/file_util.h"
25 #include "base/files/file_enumerator.h"
26 #include "base/files/file_path.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/path_service.h"
33 #include "base/posix/eintr_wrapper.h"
34 #include "base/process/kill.h"
35 #include "base/process/launch.h"
36 #include "base/strings/string_number_conversions.h"
37 #include "base/strings/string_tokenizer.h"
38 #include "base/strings/string_util.h"
39 #include "base/strings/utf_string_conversions.h"
40 #include "base/threading/thread.h"
41 #include "base/threading/thread_restrictions.h"
42 #include "build/build_config.h"
43 #include "chrome/browser/shell_integration.h"
44 #include "chrome/common/chrome_constants.h"
45 #include "chrome/common/chrome_switches.h"
46 #include "chrome/common/chrome_version_info.h"
47 #include "content/public/browser/browser_thread.h"
48 #include "grit/chrome_unscaled_resources.h"
49 #include "ui/base/resource/resource_bundle.h"
50 #include "ui/gfx/image/image_family.h"
51 #include "url/gurl.h"
53 using content::BrowserThread;
55 namespace {
57 // The Categories for the App Launcher desktop shortcut. Should be the same as
58 // the Chrome desktop shortcut, so they are in the same sub-menu.
59 const char kAppListCategories[] = "Network;WebBrowser;";
61 // Helper to launch xdg scripts. We don't want them to ask any questions on the
62 // terminal etc. The function returns true if the utility launches and exits
63 // cleanly, in which case |exit_code| returns the utility's exit code.
64 bool LaunchXdgUtility(const std::vector<std::string>& argv, int* exit_code) {
65 // xdg-settings internally runs xdg-mime, which uses mv to move newly-created
66 // files on top of originals after making changes to them. In the event that
67 // the original files are owned by another user (e.g. root, which can happen
68 // if they are updated within sudo), mv will prompt the user to confirm if
69 // standard input is a terminal (otherwise it just does it). So make sure it's
70 // not, to avoid locking everything up waiting for mv.
71 *exit_code = EXIT_FAILURE;
72 int devnull = open("/dev/null", O_RDONLY);
73 if (devnull < 0)
74 return false;
75 base::FileHandleMappingVector no_stdin;
76 no_stdin.push_back(std::make_pair(devnull, STDIN_FILENO));
78 base::ProcessHandle handle;
79 base::LaunchOptions options;
80 options.fds_to_remap = &no_stdin;
81 if (!base::LaunchProcess(argv, options, &handle)) {
82 close(devnull);
83 return false;
85 close(devnull);
87 return base::WaitForExitCode(handle, exit_code);
90 std::string CreateShortcutIcon(const gfx::ImageFamily& icon_images,
91 const base::FilePath& shortcut_filename) {
92 if (icon_images.empty())
93 return std::string();
95 // TODO(phajdan.jr): Report errors from this function, possibly as infobars.
96 base::ScopedTempDir temp_dir;
97 if (!temp_dir.CreateUniqueTempDir())
98 return std::string();
100 base::FilePath temp_file_path = temp_dir.path().Append(
101 shortcut_filename.ReplaceExtension("png"));
102 std::string icon_name = temp_file_path.BaseName().RemoveExtension().value();
104 for (gfx::ImageFamily::const_iterator it = icon_images.begin();
105 it != icon_images.end(); ++it) {
106 int width = it->Width();
107 scoped_refptr<base::RefCountedMemory> png_data = it->As1xPNGBytes();
108 if (png_data->size() == 0) {
109 // If the bitmap could not be encoded to PNG format, skip it.
110 LOG(WARNING) << "Could not encode icon " << icon_name << ".png at size "
111 << width << ".";
112 continue;
114 int bytes_written = base::WriteFile(temp_file_path,
115 png_data->front_as<char>(),
116 png_data->size());
118 if (bytes_written != static_cast<int>(png_data->size()))
119 return std::string();
121 std::vector<std::string> argv;
122 argv.push_back("xdg-icon-resource");
123 argv.push_back("install");
125 // Always install in user mode, even if someone runs the browser as root
126 // (people do that).
127 argv.push_back("--mode");
128 argv.push_back("user");
130 argv.push_back("--size");
131 argv.push_back(base::IntToString(width));
133 argv.push_back(temp_file_path.value());
134 argv.push_back(icon_name);
135 int exit_code;
136 if (!LaunchXdgUtility(argv, &exit_code) || exit_code) {
137 LOG(WARNING) << "Could not install icon " << icon_name << ".png at size "
138 << width << ".";
141 return icon_name;
144 bool CreateShortcutOnDesktop(const base::FilePath& shortcut_filename,
145 const std::string& contents) {
146 // Make sure that we will later call openat in a secure way.
147 DCHECK_EQ(shortcut_filename.BaseName().value(), shortcut_filename.value());
149 base::FilePath desktop_path;
150 if (!PathService::Get(base::DIR_USER_DESKTOP, &desktop_path))
151 return false;
153 int desktop_fd = open(desktop_path.value().c_str(), O_RDONLY | O_DIRECTORY);
154 if (desktop_fd < 0)
155 return false;
157 int fd = openat(desktop_fd, shortcut_filename.value().c_str(),
158 O_CREAT | O_EXCL | O_WRONLY,
159 S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
160 if (fd < 0) {
161 if (IGNORE_EINTR(close(desktop_fd)) < 0)
162 PLOG(ERROR) << "close";
163 return false;
166 ssize_t bytes_written = base::WriteFileDescriptor(fd, contents.data(),
167 contents.length());
168 if (IGNORE_EINTR(close(fd)) < 0)
169 PLOG(ERROR) << "close";
171 if (bytes_written != static_cast<ssize_t>(contents.length())) {
172 // Delete the file. No shortuct is better than corrupted one. Use unlinkat
173 // to make sure we're deleting the file in the directory we think we are.
174 // Even if an attacker manager to put something other at
175 // |shortcut_filename| we'll just undo his action.
176 unlinkat(desktop_fd, shortcut_filename.value().c_str(), 0);
179 if (IGNORE_EINTR(close(desktop_fd)) < 0)
180 PLOG(ERROR) << "close";
182 return true;
185 void DeleteShortcutOnDesktop(const base::FilePath& shortcut_filename) {
186 base::FilePath desktop_path;
187 if (PathService::Get(base::DIR_USER_DESKTOP, &desktop_path))
188 base::DeleteFile(desktop_path.Append(shortcut_filename), false);
191 // Creates a shortcut with |shortcut_filename| and |contents| in the system
192 // applications menu. If |directory_filename| is non-empty, creates a sub-menu
193 // with |directory_filename| and |directory_contents|, and stores the shortcut
194 // under the sub-menu.
195 bool CreateShortcutInApplicationsMenu(const base::FilePath& shortcut_filename,
196 const std::string& contents,
197 const base::FilePath& directory_filename,
198 const std::string& directory_contents) {
199 base::ScopedTempDir temp_dir;
200 if (!temp_dir.CreateUniqueTempDir())
201 return false;
203 base::FilePath temp_directory_path;
204 if (!directory_filename.empty()) {
205 temp_directory_path = temp_dir.path().Append(directory_filename);
207 int bytes_written = base::WriteFile(temp_directory_path,
208 directory_contents.data(),
209 directory_contents.length());
211 if (bytes_written != static_cast<int>(directory_contents.length()))
212 return false;
215 base::FilePath temp_file_path = temp_dir.path().Append(shortcut_filename);
217 int bytes_written = base::WriteFile(temp_file_path, contents.data(),
218 contents.length());
220 if (bytes_written != static_cast<int>(contents.length()))
221 return false;
223 std::vector<std::string> argv;
224 argv.push_back("xdg-desktop-menu");
225 argv.push_back("install");
227 // Always install in user mode, even if someone runs the browser as root
228 // (people do that).
229 argv.push_back("--mode");
230 argv.push_back("user");
232 // If provided, install the shortcut file inside the given directory.
233 if (!directory_filename.empty())
234 argv.push_back(temp_directory_path.value());
235 argv.push_back(temp_file_path.value());
236 int exit_code;
237 LaunchXdgUtility(argv, &exit_code);
238 return exit_code == 0;
241 void DeleteShortcutInApplicationsMenu(
242 const base::FilePath& shortcut_filename,
243 const base::FilePath& directory_filename) {
244 std::vector<std::string> argv;
245 argv.push_back("xdg-desktop-menu");
246 argv.push_back("uninstall");
248 // Uninstall in user mode, to match the install.
249 argv.push_back("--mode");
250 argv.push_back("user");
252 // The file does not need to exist anywhere - xdg-desktop-menu will uninstall
253 // items from the menu with a matching name.
254 // If |directory_filename| is supplied, this will also remove the item from
255 // the directory, and remove the directory if it is empty.
256 if (!directory_filename.empty())
257 argv.push_back(directory_filename.value());
258 argv.push_back(shortcut_filename.value());
259 int exit_code;
260 LaunchXdgUtility(argv, &exit_code);
263 // Quote a string such that it appears as one verbatim argument for the Exec
264 // key in a desktop file.
265 std::string QuoteArgForDesktopFileExec(const std::string& arg) {
266 // http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s06.html
268 // Quoting is only necessary if the argument has a reserved character.
269 if (arg.find_first_of(" \t\n\"'\\><~|&;$*?#()`") == std::string::npos)
270 return arg; // No quoting necessary.
272 std::string quoted = "\"";
273 for (size_t i = 0; i < arg.size(); ++i) {
274 // Note that the set of backslashed characters is smaller than the
275 // set of reserved characters.
276 switch (arg[i]) {
277 case '"':
278 case '`':
279 case '$':
280 case '\\':
281 quoted += '\\';
282 break;
284 quoted += arg[i];
286 quoted += '"';
288 return quoted;
291 // Quote a command line so it is suitable for use as the Exec key in a desktop
292 // file. Note: This should be used instead of GetCommandLineString, which does
293 // not properly quote the string; this function is designed for the Exec key.
294 std::string QuoteCommandLineForDesktopFileExec(
295 const CommandLine& command_line) {
296 // http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s06.html
298 std::string quoted_path = "";
299 const CommandLine::StringVector& argv = command_line.argv();
300 for (CommandLine::StringVector::const_iterator i = argv.begin();
301 i != argv.end(); ++i) {
302 if (i != argv.begin())
303 quoted_path += " ";
304 quoted_path += QuoteArgForDesktopFileExec(*i);
307 return quoted_path;
310 const char kDesktopEntry[] = "Desktop Entry";
312 const char kXdgOpenShebang[] = "#!/usr/bin/env xdg-open";
314 const char kXdgSettings[] = "xdg-settings";
315 const char kXdgSettingsDefaultBrowser[] = "default-web-browser";
316 const char kXdgSettingsDefaultSchemeHandler[] = "default-url-scheme-handler";
318 const char kDirectoryFilename[] = "chrome-apps.directory";
320 #if defined(GOOGLE_CHROME_BUILD)
321 const char kAppListDesktopName[] = "chrome-app-list";
322 #else // CHROMIUM_BUILD
323 const char kAppListDesktopName[] = "chromium-app-list";
324 #endif
326 } // namespace
328 namespace {
330 // Utility function to get the path to the version of a script shipped with
331 // Chrome. |script| gives the name of the script. |chrome_version| returns the
332 // path to the Chrome version of the script, and the return value of the
333 // function is true if the function is successful and the Chrome version is
334 // not the script found on the PATH.
335 bool GetChromeVersionOfScript(const std::string& script,
336 std::string* chrome_version) {
337 // Get the path to the Chrome version.
338 base::FilePath chrome_dir;
339 if (!PathService::Get(base::DIR_EXE, &chrome_dir))
340 return false;
342 base::FilePath chrome_version_path = chrome_dir.Append(script);
343 *chrome_version = chrome_version_path.value();
345 // Check if this is different to the one on path.
346 std::vector<std::string> argv;
347 argv.push_back("which");
348 argv.push_back(script);
349 std::string path_version;
350 if (base::GetAppOutput(CommandLine(argv), &path_version)) {
351 // Remove trailing newline
352 path_version.erase(path_version.length() - 1, 1);
353 base::FilePath path_version_path(path_version);
354 return (chrome_version_path != path_version_path);
356 return false;
359 // Value returned by xdg-settings if it can't understand our request.
360 const int EXIT_XDG_SETTINGS_SYNTAX_ERROR = 1;
362 // We delegate the difficulty of setting the default browser and default url
363 // scheme handler in Linux desktop environments to an xdg utility, xdg-settings.
365 // When calling this script we first try to use the script on PATH. If that
366 // fails we then try to use the script that we have included. This gives
367 // scripts on the system priority over ours, as distribution vendors may have
368 // tweaked the script, but still allows our copy to be used if the script on the
369 // system fails, as the system copy may be missing capabilities of the Chrome
370 // copy.
372 // If |protocol| is empty this function sets Chrome as the default browser,
373 // otherwise it sets Chrome as the default handler application for |protocol|.
374 bool SetDefaultWebClient(const std::string& protocol) {
375 #if defined(OS_CHROMEOS)
376 return true;
377 #else
378 scoped_ptr<base::Environment> env(base::Environment::Create());
380 std::vector<std::string> argv;
381 argv.push_back(kXdgSettings);
382 argv.push_back("set");
383 if (protocol.empty()) {
384 argv.push_back(kXdgSettingsDefaultBrowser);
385 } else {
386 argv.push_back(kXdgSettingsDefaultSchemeHandler);
387 argv.push_back(protocol);
389 argv.push_back(ShellIntegrationLinux::GetDesktopName(env.get()));
391 int exit_code;
392 bool ran_ok = LaunchXdgUtility(argv, &exit_code);
393 if (ran_ok && exit_code == EXIT_XDG_SETTINGS_SYNTAX_ERROR) {
394 if (GetChromeVersionOfScript(kXdgSettings, &argv[0])) {
395 ran_ok = LaunchXdgUtility(argv, &exit_code);
399 return ran_ok && exit_code == EXIT_SUCCESS;
400 #endif
403 // If |protocol| is empty this function checks if Chrome is the default browser,
404 // otherwise it checks if Chrome is the default handler application for
405 // |protocol|.
406 ShellIntegration::DefaultWebClientState GetIsDefaultWebClient(
407 const std::string& protocol) {
408 #if defined(OS_CHROMEOS)
409 return ShellIntegration::UNKNOWN_DEFAULT;
410 #else
411 base::ThreadRestrictions::AssertIOAllowed();
413 scoped_ptr<base::Environment> env(base::Environment::Create());
415 std::vector<std::string> argv;
416 argv.push_back(kXdgSettings);
417 argv.push_back("check");
418 if (protocol.empty()) {
419 argv.push_back(kXdgSettingsDefaultBrowser);
420 } else {
421 argv.push_back(kXdgSettingsDefaultSchemeHandler);
422 argv.push_back(protocol);
424 argv.push_back(ShellIntegrationLinux::GetDesktopName(env.get()));
426 std::string reply;
427 int success_code;
428 bool ran_ok = base::GetAppOutputWithExitCode(CommandLine(argv), &reply,
429 &success_code);
430 if (ran_ok && success_code == EXIT_XDG_SETTINGS_SYNTAX_ERROR) {
431 if (GetChromeVersionOfScript(kXdgSettings, &argv[0])) {
432 ran_ok = base::GetAppOutputWithExitCode(CommandLine(argv), &reply,
433 &success_code);
437 if (!ran_ok || success_code != EXIT_SUCCESS) {
438 // xdg-settings failed: we can't determine or set the default browser.
439 return ShellIntegration::UNKNOWN_DEFAULT;
442 // Allow any reply that starts with "yes".
443 return (reply.find("yes") == 0) ? ShellIntegration::IS_DEFAULT :
444 ShellIntegration::NOT_DEFAULT;
445 #endif
448 // Get the value of NoDisplay from the [Desktop Entry] section of a .desktop
449 // file, given in |shortcut_contents|. If the key is not found, returns false.
450 bool GetNoDisplayFromDesktopFile(const std::string& shortcut_contents) {
451 #if defined(USE_GLIB)
452 // An empty file causes a crash with glib <= 2.32, so special case here.
453 if (shortcut_contents.empty())
454 return false;
456 GKeyFile* key_file = g_key_file_new();
457 GError* err = NULL;
458 if (!g_key_file_load_from_data(key_file, shortcut_contents.c_str(),
459 shortcut_contents.size(), G_KEY_FILE_NONE,
460 &err)) {
461 LOG(WARNING) << "Unable to read desktop file template: " << err->message;
462 g_error_free(err);
463 g_key_file_free(key_file);
464 return false;
467 bool nodisplay = false;
468 char* nodisplay_c_string = g_key_file_get_string(key_file, kDesktopEntry,
469 "NoDisplay", &err);
470 if (nodisplay_c_string) {
471 if (!g_strcmp0(nodisplay_c_string, "true"))
472 nodisplay = true;
473 g_free(nodisplay_c_string);
474 } else {
475 g_error_free(err);
478 g_key_file_free(key_file);
479 return nodisplay;
480 #else
481 NOTIMPLEMENTED();
482 return false;
483 #endif
486 // Gets the path to the Chrome executable or wrapper script.
487 // Returns an empty path if the executable path could not be found.
488 base::FilePath GetChromeExePath() {
489 // Try to get the name of the wrapper script that launched Chrome.
490 scoped_ptr<base::Environment> environment(base::Environment::Create());
491 std::string wrapper_script;
492 if (environment->GetVar("CHROME_WRAPPER", &wrapper_script)) {
493 return base::FilePath(wrapper_script);
496 // Just return the name of the executable path for Chrome.
497 base::FilePath chrome_exe_path;
498 PathService::Get(base::FILE_EXE, &chrome_exe_path);
499 return chrome_exe_path;
502 } // namespace
504 // static
505 ShellIntegration::DefaultWebClientSetPermission
506 ShellIntegration::CanSetAsDefaultBrowser() {
507 return SET_DEFAULT_UNATTENDED;
510 // static
511 bool ShellIntegration::SetAsDefaultBrowser() {
512 return SetDefaultWebClient(std::string());
515 // static
516 bool ShellIntegration::SetAsDefaultProtocolClient(const std::string& protocol) {
517 return SetDefaultWebClient(protocol);
520 // static
521 ShellIntegration::DefaultWebClientState ShellIntegration::GetDefaultBrowser() {
522 return GetIsDefaultWebClient(std::string());
525 // static
526 base::string16 ShellIntegration::GetApplicationNameForProtocol(
527 const GURL& url) {
528 return base::ASCIIToUTF16("xdg-open");
531 // static
532 ShellIntegration::DefaultWebClientState
533 ShellIntegration::IsDefaultProtocolClient(const std::string& protocol) {
534 return GetIsDefaultWebClient(protocol);
537 // static
538 bool ShellIntegration::IsFirefoxDefaultBrowser() {
539 std::vector<std::string> argv;
540 argv.push_back(kXdgSettings);
541 argv.push_back("get");
542 argv.push_back(kXdgSettingsDefaultBrowser);
544 std::string browser;
545 // We don't care about the return value here.
546 base::GetAppOutput(CommandLine(argv), &browser);
547 return browser.find("irefox") != std::string::npos;
550 namespace ShellIntegrationLinux {
552 bool GetDataWriteLocation(base::Environment* env, base::FilePath* search_path) {
553 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
555 std::string xdg_data_home;
556 std::string home;
557 if (env->GetVar("XDG_DATA_HOME", &xdg_data_home) && !xdg_data_home.empty()) {
558 *search_path = base::FilePath(xdg_data_home);
559 return true;
560 } else if (env->GetVar("HOME", &home) && !home.empty()) {
561 *search_path = base::FilePath(home).Append(".local").Append("share");
562 return true;
564 return false;
567 std::vector<base::FilePath> GetDataSearchLocations(base::Environment* env) {
568 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
570 std::vector<base::FilePath> search_paths;
572 base::FilePath write_location;
573 if (GetDataWriteLocation(env, &write_location))
574 search_paths.push_back(write_location);
576 std::string xdg_data_dirs;
577 if (env->GetVar("XDG_DATA_DIRS", &xdg_data_dirs) && !xdg_data_dirs.empty()) {
578 base::StringTokenizer tokenizer(xdg_data_dirs, ":");
579 while (tokenizer.GetNext()) {
580 base::FilePath data_dir(tokenizer.token());
581 search_paths.push_back(data_dir);
583 } else {
584 search_paths.push_back(base::FilePath("/usr/local/share"));
585 search_paths.push_back(base::FilePath("/usr/share"));
588 return search_paths;
591 std::string GetProgramClassName() {
592 DCHECK(CommandLine::InitializedForCurrentProcess());
593 // Get the res_name component from argv[0].
594 const CommandLine* command_line = CommandLine::ForCurrentProcess();
595 std::string class_name = command_line->GetProgram().BaseName().value();
596 if (!class_name.empty())
597 class_name[0] = base::ToUpperASCII(class_name[0]);
598 return class_name;
601 std::string GetDesktopName(base::Environment* env) {
602 #if defined(GOOGLE_CHROME_BUILD)
603 chrome::VersionInfo::Channel product_channel(
604 chrome::VersionInfo::GetChannel());
605 switch (product_channel) {
606 case chrome::VersionInfo::CHANNEL_DEV:
607 return "google-chrome-unstable.desktop";
608 case chrome::VersionInfo::CHANNEL_BETA:
609 return "google-chrome-beta.desktop";
610 default:
611 return "google-chrome.desktop";
613 #else // CHROMIUM_BUILD
614 // Allow $CHROME_DESKTOP to override the built-in value, so that development
615 // versions can set themselves as the default without interfering with
616 // non-official, packaged versions using the built-in value.
617 std::string name;
618 if (env->GetVar("CHROME_DESKTOP", &name) && !name.empty())
619 return name;
620 return "chromium-browser.desktop";
621 #endif
624 std::string GetIconName() {
625 #if defined(GOOGLE_CHROME_BUILD)
626 return "google-chrome";
627 #else // CHROMIUM_BUILD
628 return "chromium-browser";
629 #endif
632 web_app::ShortcutLocations GetExistingShortcutLocations(
633 base::Environment* env,
634 const base::FilePath& profile_path,
635 const std::string& extension_id) {
636 base::FilePath desktop_path;
637 // If Get returns false, just leave desktop_path empty.
638 PathService::Get(base::DIR_USER_DESKTOP, &desktop_path);
639 return GetExistingShortcutLocations(env, profile_path, extension_id,
640 desktop_path);
643 web_app::ShortcutLocations GetExistingShortcutLocations(
644 base::Environment* env,
645 const base::FilePath& profile_path,
646 const std::string& extension_id,
647 const base::FilePath& desktop_path) {
648 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
650 base::FilePath shortcut_filename = GetExtensionShortcutFilename(
651 profile_path, extension_id);
652 DCHECK(!shortcut_filename.empty());
653 web_app::ShortcutLocations locations;
655 // Determine whether there is a shortcut on desktop.
656 if (!desktop_path.empty()) {
657 locations.on_desktop =
658 base::PathExists(desktop_path.Append(shortcut_filename));
661 // Determine whether there is a shortcut in the applications directory.
662 std::string shortcut_contents;
663 if (GetExistingShortcutContents(env, shortcut_filename, &shortcut_contents)) {
664 // Whether this counts as "hidden" or "APP_MENU_LOCATION_SUBDIR_CHROMEAPPS"
665 // depends on whether it contains NoDisplay=true. Since these shortcuts are
666 // for apps, they are always in the "Chrome Apps" directory.
667 if (GetNoDisplayFromDesktopFile(shortcut_contents)) {
668 locations.hidden = true;
669 } else {
670 locations.applications_menu_location =
671 web_app::APP_MENU_LOCATION_SUBDIR_CHROMEAPPS;
675 return locations;
678 bool GetExistingShortcutContents(base::Environment* env,
679 const base::FilePath& desktop_filename,
680 std::string* output) {
681 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
683 std::vector<base::FilePath> search_paths = GetDataSearchLocations(env);
685 for (std::vector<base::FilePath>::const_iterator i = search_paths.begin();
686 i != search_paths.end(); ++i) {
687 base::FilePath path = i->Append("applications").Append(desktop_filename);
688 VLOG(1) << "Looking for desktop file in " << path.value();
689 if (base::PathExists(path)) {
690 VLOG(1) << "Found desktop file at " << path.value();
691 return base::ReadFileToString(path, output);
695 return false;
698 base::FilePath GetWebShortcutFilename(const GURL& url) {
699 // Use a prefix, because xdg-desktop-menu requires it.
700 std::string filename =
701 std::string(chrome::kBrowserProcessExecutableName) + "-" + url.spec();
702 file_util::ReplaceIllegalCharactersInPath(&filename, '_');
704 base::FilePath desktop_path;
705 if (!PathService::Get(base::DIR_USER_DESKTOP, &desktop_path))
706 return base::FilePath();
708 base::FilePath filepath = desktop_path.Append(filename);
709 base::FilePath alternative_filepath(filepath.value() + ".desktop");
710 for (size_t i = 1; i < 100; ++i) {
711 if (base::PathExists(base::FilePath(alternative_filepath))) {
712 alternative_filepath = base::FilePath(
713 filepath.value() + "_" + base::IntToString(i) + ".desktop");
714 } else {
715 return base::FilePath(alternative_filepath).BaseName();
719 return base::FilePath();
722 base::FilePath GetExtensionShortcutFilename(const base::FilePath& profile_path,
723 const std::string& extension_id) {
724 DCHECK(!extension_id.empty());
726 // Use a prefix, because xdg-desktop-menu requires it.
727 std::string filename(chrome::kBrowserProcessExecutableName);
728 filename.append("-")
729 .append(extension_id)
730 .append("-")
731 .append(profile_path.BaseName().value());
732 file_util::ReplaceIllegalCharactersInPath(&filename, '_');
733 // Spaces in filenames break xdg-desktop-menu
734 // (see https://bugs.freedesktop.org/show_bug.cgi?id=66605).
735 base::ReplaceChars(filename, " ", "_", &filename);
736 return base::FilePath(filename.append(".desktop"));
739 std::vector<base::FilePath> GetExistingProfileShortcutFilenames(
740 const base::FilePath& profile_path,
741 const base::FilePath& directory) {
742 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
743 // Use a prefix, because xdg-desktop-menu requires it.
744 std::string prefix(chrome::kBrowserProcessExecutableName);
745 prefix.append("-");
746 std::string suffix("-");
747 suffix.append(profile_path.BaseName().value());
748 file_util::ReplaceIllegalCharactersInPath(&suffix, '_');
749 // Spaces in filenames break xdg-desktop-menu
750 // (see https://bugs.freedesktop.org/show_bug.cgi?id=66605).
751 base::ReplaceChars(suffix, " ", "_", &suffix);
752 std::string glob = prefix + "*" + suffix + ".desktop";
754 base::FileEnumerator files(directory, false, base::FileEnumerator::FILES,
755 glob);
756 base::FilePath shortcut_file = files.Next();
757 std::vector<base::FilePath> shortcut_paths;
758 while (!shortcut_file.empty()) {
759 shortcut_paths.push_back(shortcut_file.BaseName());
760 shortcut_file = files.Next();
762 return shortcut_paths;
765 std::string GetDesktopFileContents(
766 const base::FilePath& chrome_exe_path,
767 const std::string& app_name,
768 const GURL& url,
769 const std::string& extension_id,
770 const base::string16& title,
771 const std::string& icon_name,
772 const base::FilePath& profile_path,
773 const std::string& categories,
774 bool no_display) {
775 CommandLine cmd_line = ShellIntegration::CommandLineArgsForLauncher(
776 url, extension_id, profile_path);
777 cmd_line.SetProgram(chrome_exe_path);
778 return GetDesktopFileContentsForCommand(cmd_line, app_name, url, title,
779 icon_name, categories, no_display);
782 std::string GetDesktopFileContentsForCommand(
783 const CommandLine& command_line,
784 const std::string& app_name,
785 const GURL& url,
786 const base::string16& title,
787 const std::string& icon_name,
788 const std::string& categories,
789 bool no_display) {
790 #if defined(USE_GLIB)
791 // Although not required by the spec, Nautilus on Ubuntu Karmic creates its
792 // launchers with an xdg-open shebang. Follow that convention.
793 std::string output_buffer = std::string(kXdgOpenShebang) + "\n";
795 // See http://standards.freedesktop.org/desktop-entry-spec/latest/
796 GKeyFile* key_file = g_key_file_new();
798 // Set keys with fixed values.
799 g_key_file_set_string(key_file, kDesktopEntry, "Version", "1.0");
800 g_key_file_set_string(key_file, kDesktopEntry, "Terminal", "false");
801 g_key_file_set_string(key_file, kDesktopEntry, "Type", "Application");
803 // Set the "Name" key.
804 std::string final_title = base::UTF16ToUTF8(title);
805 // Make sure no endline characters can slip in and possibly introduce
806 // additional lines (like Exec, which makes it a security risk). Also
807 // use the URL as a default when the title is empty.
808 if (final_title.empty() ||
809 final_title.find("\n") != std::string::npos ||
810 final_title.find("\r") != std::string::npos) {
811 final_title = url.spec();
813 g_key_file_set_string(key_file, kDesktopEntry, "Name", final_title.c_str());
815 // Set the "Exec" key.
816 std::string final_path = QuoteCommandLineForDesktopFileExec(command_line);
817 g_key_file_set_string(key_file, kDesktopEntry, "Exec", final_path.c_str());
819 // Set the "Icon" key.
820 if (!icon_name.empty()) {
821 g_key_file_set_string(key_file, kDesktopEntry, "Icon", icon_name.c_str());
822 } else {
823 g_key_file_set_string(key_file, kDesktopEntry, "Icon",
824 GetIconName().c_str());
827 // Set the "Categories" key.
828 if (!categories.empty()) {
829 g_key_file_set_string(
830 key_file, kDesktopEntry, "Categories", categories.c_str());
833 // Set the "NoDisplay" key.
834 if (no_display)
835 g_key_file_set_string(key_file, kDesktopEntry, "NoDisplay", "true");
837 std::string wmclass = web_app::GetWMClassFromAppName(app_name);
838 g_key_file_set_string(key_file, kDesktopEntry, "StartupWMClass",
839 wmclass.c_str());
841 gsize length = 0;
842 gchar* data_dump = g_key_file_to_data(key_file, &length, NULL);
843 if (data_dump) {
844 // If strlen(data_dump[0]) == 0, this check will fail.
845 if (data_dump[0] == '\n') {
846 // Older versions of glib produce a leading newline. If this is the case,
847 // remove it to avoid double-newline after the shebang.
848 output_buffer += (data_dump + 1);
849 } else {
850 output_buffer += data_dump;
852 g_free(data_dump);
855 g_key_file_free(key_file);
856 return output_buffer;
857 #else
858 NOTIMPLEMENTED();
859 return std::string("");
860 #endif
863 std::string GetDirectoryFileContents(const base::string16& title,
864 const std::string& icon_name) {
865 #if defined(USE_GLIB)
866 // See http://standards.freedesktop.org/desktop-entry-spec/latest/
867 GKeyFile* key_file = g_key_file_new();
869 g_key_file_set_string(key_file, kDesktopEntry, "Version", "1.0");
870 g_key_file_set_string(key_file, kDesktopEntry, "Type", "Directory");
871 std::string final_title = base::UTF16ToUTF8(title);
872 g_key_file_set_string(key_file, kDesktopEntry, "Name", final_title.c_str());
873 if (!icon_name.empty()) {
874 g_key_file_set_string(key_file, kDesktopEntry, "Icon", icon_name.c_str());
875 } else {
876 g_key_file_set_string(key_file, kDesktopEntry, "Icon",
877 GetIconName().c_str());
880 gsize length = 0;
881 gchar* data_dump = g_key_file_to_data(key_file, &length, NULL);
882 std::string output_buffer;
883 if (data_dump) {
884 // If strlen(data_dump[0]) == 0, this check will fail.
885 if (data_dump[0] == '\n') {
886 // Older versions of glib produce a leading newline. If this is the case,
887 // remove it to avoid double-newline after the shebang.
888 output_buffer += (data_dump + 1);
889 } else {
890 output_buffer += data_dump;
892 g_free(data_dump);
895 g_key_file_free(key_file);
896 return output_buffer;
897 #else
898 NOTIMPLEMENTED();
899 return std::string("");
900 #endif
903 bool CreateDesktopShortcut(
904 const web_app::ShortcutInfo& shortcut_info,
905 const web_app::ShortcutLocations& creation_locations) {
906 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
908 base::FilePath shortcut_filename;
909 if (!shortcut_info.extension_id.empty()) {
910 shortcut_filename = GetExtensionShortcutFilename(
911 shortcut_info.profile_path, shortcut_info.extension_id);
912 // For extensions we do not want duplicate shortcuts. So, delete any that
913 // already exist and replace them.
914 if (creation_locations.on_desktop)
915 DeleteShortcutOnDesktop(shortcut_filename);
916 // The 'applications_menu_location' and 'hidden' locations are actually the
917 // same place ('applications').
918 if (creation_locations.applications_menu_location !=
919 web_app::APP_MENU_LOCATION_NONE ||
920 creation_locations.hidden)
921 DeleteShortcutInApplicationsMenu(shortcut_filename, base::FilePath());
922 } else {
923 shortcut_filename = GetWebShortcutFilename(shortcut_info.url);
925 if (shortcut_filename.empty())
926 return false;
928 std::string icon_name =
929 CreateShortcutIcon(shortcut_info.favicon, shortcut_filename);
931 std::string app_name =
932 web_app::GenerateApplicationNameFromInfo(shortcut_info);
934 bool success = true;
936 base::FilePath chrome_exe_path = GetChromeExePath();
937 if (chrome_exe_path.empty()) {
938 LOG(WARNING) << "Could not get executable path.";
939 return false;
942 if (creation_locations.on_desktop) {
943 std::string contents = ShellIntegrationLinux::GetDesktopFileContents(
944 chrome_exe_path,
945 app_name,
946 shortcut_info.url,
947 shortcut_info.extension_id,
948 shortcut_info.title,
949 icon_name,
950 shortcut_info.profile_path,
952 false);
953 success = CreateShortcutOnDesktop(shortcut_filename, contents);
956 if (creation_locations.applications_menu_location !=
957 web_app::APP_MENU_LOCATION_NONE ||
958 creation_locations.hidden) {
959 base::FilePath directory_filename;
960 std::string directory_contents;
961 switch (creation_locations.applications_menu_location) {
962 case web_app::APP_MENU_LOCATION_NONE:
963 case web_app::APP_MENU_LOCATION_ROOT:
964 break;
965 case web_app::APP_MENU_LOCATION_SUBDIR_CHROMEAPPS:
966 directory_filename = base::FilePath(kDirectoryFilename);
967 directory_contents = ShellIntegrationLinux::GetDirectoryFileContents(
968 ShellIntegration::GetAppShortcutsSubdirName(), "");
969 break;
970 default:
971 NOTREACHED();
972 break;
974 // Set NoDisplay=true if hidden but not in the applications menu. This will
975 // hide the application from user-facing menus.
976 std::string contents = ShellIntegrationLinux::GetDesktopFileContents(
977 chrome_exe_path,
978 app_name,
979 shortcut_info.url,
980 shortcut_info.extension_id,
981 shortcut_info.title,
982 icon_name,
983 shortcut_info.profile_path,
985 creation_locations.applications_menu_location ==
986 web_app::APP_MENU_LOCATION_NONE);
987 success = CreateShortcutInApplicationsMenu(
988 shortcut_filename, contents, directory_filename, directory_contents) &&
989 success;
992 return success;
995 bool CreateAppListDesktopShortcut(
996 const std::string& wm_class,
997 const std::string& title) {
998 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
1000 base::FilePath desktop_name(kAppListDesktopName);
1001 base::FilePath shortcut_filename = desktop_name.AddExtension("desktop");
1003 // We do not want duplicate shortcuts. Delete any that already exist and
1004 // replace them.
1005 DeleteShortcutInApplicationsMenu(shortcut_filename, base::FilePath());
1007 base::FilePath chrome_exe_path = GetChromeExePath();
1008 if (chrome_exe_path.empty()) {
1009 LOG(WARNING) << "Could not get executable path.";
1010 return false;
1013 gfx::ImageFamily icon_images;
1014 ResourceBundle& resource_bundle = ResourceBundle::GetSharedInstance();
1015 icon_images.Add(*resource_bundle.GetImageSkiaNamed(IDR_APP_LIST_16));
1016 icon_images.Add(*resource_bundle.GetImageSkiaNamed(IDR_APP_LIST_32));
1017 icon_images.Add(*resource_bundle.GetImageSkiaNamed(IDR_APP_LIST_48));
1018 icon_images.Add(*resource_bundle.GetImageSkiaNamed(IDR_APP_LIST_256));
1019 std::string icon_name = CreateShortcutIcon(icon_images, desktop_name);
1021 CommandLine command_line(chrome_exe_path);
1022 command_line.AppendSwitch(switches::kShowAppList);
1023 std::string contents =
1024 GetDesktopFileContentsForCommand(command_line,
1025 wm_class,
1026 GURL(),
1027 base::UTF8ToUTF16(title),
1028 icon_name,
1029 kAppListCategories,
1030 false);
1031 return CreateShortcutInApplicationsMenu(
1032 shortcut_filename, contents, base::FilePath(), "");
1035 void DeleteDesktopShortcuts(const base::FilePath& profile_path,
1036 const std::string& extension_id) {
1037 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
1039 base::FilePath shortcut_filename = GetExtensionShortcutFilename(
1040 profile_path, extension_id);
1041 DCHECK(!shortcut_filename.empty());
1043 DeleteShortcutOnDesktop(shortcut_filename);
1044 // Delete shortcuts from |kDirectoryFilename|.
1045 // Note that it is possible that shortcuts were not created in the Chrome Apps
1046 // directory. It doesn't matter: this will still delete the shortcut even if
1047 // it isn't in the directory.
1048 DeleteShortcutInApplicationsMenu(shortcut_filename,
1049 base::FilePath(kDirectoryFilename));
1052 void DeleteAllDesktopShortcuts(const base::FilePath& profile_path) {
1053 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
1055 scoped_ptr<base::Environment> env(base::Environment::Create());
1057 // Delete shortcuts from Desktop.
1058 base::FilePath desktop_path;
1059 if (PathService::Get(base::DIR_USER_DESKTOP, &desktop_path)) {
1060 std::vector<base::FilePath> shortcut_filenames_desktop =
1061 GetExistingProfileShortcutFilenames(profile_path, desktop_path);
1062 for (std::vector<base::FilePath>::const_iterator it =
1063 shortcut_filenames_desktop.begin();
1064 it != shortcut_filenames_desktop.end(); ++it) {
1065 DeleteShortcutOnDesktop(*it);
1069 // Delete shortcuts from |kDirectoryFilename|.
1070 base::FilePath applications_menu;
1071 if (GetDataWriteLocation(env.get(), &applications_menu)) {
1072 applications_menu = applications_menu.AppendASCII("applications");
1073 std::vector<base::FilePath> shortcut_filenames_app_menu =
1074 GetExistingProfileShortcutFilenames(profile_path, applications_menu);
1075 for (std::vector<base::FilePath>::const_iterator it =
1076 shortcut_filenames_app_menu.begin();
1077 it != shortcut_filenames_app_menu.end(); ++it) {
1078 DeleteShortcutInApplicationsMenu(*it,
1079 base::FilePath(kDirectoryFilename));
1084 } // namespace ShellIntegrationLinux