Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / browser / shell_integration_linux.cc
blob923a30d250001a3e7f7d9a2187680d47e3862cc7
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>
8 #include <glib.h>
9 #include <stdlib.h>
10 #include <sys/stat.h>
11 #include <sys/types.h>
12 #include <unistd.h>
14 #include <string>
15 #include <vector>
17 #include "base/base_paths.h"
18 #include "base/command_line.h"
19 #include "base/environment.h"
20 #include "base/file_util.h"
21 #include "base/files/file_enumerator.h"
22 #include "base/files/file_path.h"
23 #include "base/files/scoped_temp_dir.h"
24 #include "base/i18n/file_util_icu.h"
25 #include "base/memory/ref_counted_memory.h"
26 #include "base/memory/scoped_ptr.h"
27 #include "base/message_loop/message_loop.h"
28 #include "base/path_service.h"
29 #include "base/posix/eintr_wrapper.h"
30 #include "base/process/kill.h"
31 #include "base/process/launch.h"
32 #include "base/strings/string_number_conversions.h"
33 #include "base/strings/string_tokenizer.h"
34 #include "base/strings/string_util.h"
35 #include "base/strings/utf_string_conversions.h"
36 #include "base/threading/thread.h"
37 #include "base/threading/thread_restrictions.h"
38 #include "build/build_config.h"
39 #include "chrome/browser/web_applications/web_app.h"
40 #include "chrome/common/chrome_constants.h"
41 #include "chrome/common/chrome_switches.h"
42 #include "chrome/common/chrome_version_info.h"
43 #include "content/public/browser/browser_thread.h"
44 #include "grit/chrome_unscaled_resources.h"
45 #include "ui/base/resource/resource_bundle.h"
46 #include "ui/gfx/image/image_family.h"
47 #include "url/gurl.h"
49 using content::BrowserThread;
51 namespace {
53 // Helper to launch xdg scripts. We don't want them to ask any questions on the
54 // terminal etc. The function returns true if the utility launches and exits
55 // cleanly, in which case |exit_code| returns the utility's exit code.
56 bool LaunchXdgUtility(const std::vector<std::string>& argv, int* exit_code) {
57 // xdg-settings internally runs xdg-mime, which uses mv to move newly-created
58 // files on top of originals after making changes to them. In the event that
59 // the original files are owned by another user (e.g. root, which can happen
60 // if they are updated within sudo), mv will prompt the user to confirm if
61 // standard input is a terminal (otherwise it just does it). So make sure it's
62 // not, to avoid locking everything up waiting for mv.
63 *exit_code = EXIT_FAILURE;
64 int devnull = open("/dev/null", O_RDONLY);
65 if (devnull < 0)
66 return false;
67 base::FileHandleMappingVector no_stdin;
68 no_stdin.push_back(std::make_pair(devnull, STDIN_FILENO));
70 base::ProcessHandle handle;
71 base::LaunchOptions options;
72 options.fds_to_remap = &no_stdin;
73 if (!base::LaunchProcess(argv, options, &handle)) {
74 close(devnull);
75 return false;
77 close(devnull);
79 return base::WaitForExitCode(handle, exit_code);
82 std::string CreateShortcutIcon(const gfx::ImageFamily& icon_images,
83 const base::FilePath& shortcut_filename) {
84 if (icon_images.empty())
85 return std::string();
87 // TODO(phajdan.jr): Report errors from this function, possibly as infobars.
88 base::ScopedTempDir temp_dir;
89 if (!temp_dir.CreateUniqueTempDir())
90 return std::string();
92 base::FilePath temp_file_path = temp_dir.path().Append(
93 shortcut_filename.ReplaceExtension("png"));
94 std::string icon_name = temp_file_path.BaseName().RemoveExtension().value();
96 for (gfx::ImageFamily::const_iterator it = icon_images.begin();
97 it != icon_images.end(); ++it) {
98 int width = it->Width();
99 scoped_refptr<base::RefCountedMemory> png_data = it->As1xPNGBytes();
100 if (png_data->size() == 0) {
101 // If the bitmap could not be encoded to PNG format, skip it.
102 LOG(WARNING) << "Could not encode icon " << icon_name << ".png at size "
103 << width << ".";
104 continue;
106 int bytes_written = file_util::WriteFile(temp_file_path,
107 reinterpret_cast<const char*>(png_data->front()), png_data->size());
109 if (bytes_written != static_cast<int>(png_data->size()))
110 return std::string();
112 std::vector<std::string> argv;
113 argv.push_back("xdg-icon-resource");
114 argv.push_back("install");
116 // Always install in user mode, even if someone runs the browser as root
117 // (people do that).
118 argv.push_back("--mode");
119 argv.push_back("user");
121 argv.push_back("--size");
122 argv.push_back(base::IntToString(width));
124 argv.push_back(temp_file_path.value());
125 argv.push_back(icon_name);
126 int exit_code;
127 if (!LaunchXdgUtility(argv, &exit_code) || exit_code) {
128 LOG(WARNING) << "Could not install icon " << icon_name << ".png at size "
129 << width << ".";
132 return icon_name;
135 bool CreateShortcutOnDesktop(const base::FilePath& shortcut_filename,
136 const std::string& contents) {
137 // Make sure that we will later call openat in a secure way.
138 DCHECK_EQ(shortcut_filename.BaseName().value(), shortcut_filename.value());
140 base::FilePath desktop_path;
141 if (!PathService::Get(base::DIR_USER_DESKTOP, &desktop_path))
142 return false;
144 int desktop_fd = open(desktop_path.value().c_str(), O_RDONLY | O_DIRECTORY);
145 if (desktop_fd < 0)
146 return false;
148 int fd = openat(desktop_fd, shortcut_filename.value().c_str(),
149 O_CREAT | O_EXCL | O_WRONLY,
150 S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
151 if (fd < 0) {
152 if (IGNORE_EINTR(close(desktop_fd)) < 0)
153 PLOG(ERROR) << "close";
154 return false;
157 ssize_t bytes_written = file_util::WriteFileDescriptor(fd, contents.data(),
158 contents.length());
159 if (IGNORE_EINTR(close(fd)) < 0)
160 PLOG(ERROR) << "close";
162 if (bytes_written != static_cast<ssize_t>(contents.length())) {
163 // Delete the file. No shortuct is better than corrupted one. Use unlinkat
164 // to make sure we're deleting the file in the directory we think we are.
165 // Even if an attacker manager to put something other at
166 // |shortcut_filename| we'll just undo his action.
167 unlinkat(desktop_fd, shortcut_filename.value().c_str(), 0);
170 if (IGNORE_EINTR(close(desktop_fd)) < 0)
171 PLOG(ERROR) << "close";
173 return true;
176 void DeleteShortcutOnDesktop(const base::FilePath& shortcut_filename) {
177 base::FilePath desktop_path;
178 if (PathService::Get(base::DIR_USER_DESKTOP, &desktop_path))
179 base::DeleteFile(desktop_path.Append(shortcut_filename), false);
182 // Creates a shortcut with |shortcut_filename| and |contents| in the system
183 // applications menu. If |directory_filename| is non-empty, creates a sub-menu
184 // with |directory_filename| and |directory_contents|, and stores the shortcut
185 // under the sub-menu.
186 bool CreateShortcutInApplicationsMenu(const base::FilePath& shortcut_filename,
187 const std::string& contents,
188 const base::FilePath& directory_filename,
189 const std::string& directory_contents) {
190 base::ScopedTempDir temp_dir;
191 if (!temp_dir.CreateUniqueTempDir())
192 return false;
194 base::FilePath temp_directory_path;
195 if (!directory_filename.empty()) {
196 temp_directory_path = temp_dir.path().Append(directory_filename);
198 int bytes_written = file_util::WriteFile(temp_directory_path,
199 directory_contents.data(),
200 directory_contents.length());
202 if (bytes_written != static_cast<int>(directory_contents.length()))
203 return false;
206 base::FilePath temp_file_path = temp_dir.path().Append(shortcut_filename);
208 int bytes_written = file_util::WriteFile(temp_file_path, contents.data(),
209 contents.length());
211 if (bytes_written != static_cast<int>(contents.length()))
212 return false;
214 std::vector<std::string> argv;
215 argv.push_back("xdg-desktop-menu");
216 argv.push_back("install");
218 // Always install in user mode, even if someone runs the browser as root
219 // (people do that).
220 argv.push_back("--mode");
221 argv.push_back("user");
223 // If provided, install the shortcut file inside the given directory.
224 if (!directory_filename.empty())
225 argv.push_back(temp_directory_path.value());
226 argv.push_back(temp_file_path.value());
227 int exit_code;
228 LaunchXdgUtility(argv, &exit_code);
229 return exit_code == 0;
232 void DeleteShortcutInApplicationsMenu(
233 const base::FilePath& shortcut_filename,
234 const base::FilePath& directory_filename) {
235 std::vector<std::string> argv;
236 argv.push_back("xdg-desktop-menu");
237 argv.push_back("uninstall");
239 // Uninstall in user mode, to match the install.
240 argv.push_back("--mode");
241 argv.push_back("user");
243 // The file does not need to exist anywhere - xdg-desktop-menu will uninstall
244 // items from the menu with a matching name.
245 // If |directory_filename| is supplied, this will also remove the item from
246 // the directory, and remove the directory if it is empty.
247 if (!directory_filename.empty())
248 argv.push_back(directory_filename.value());
249 argv.push_back(shortcut_filename.value());
250 int exit_code;
251 LaunchXdgUtility(argv, &exit_code);
254 // Quote a string such that it appears as one verbatim argument for the Exec
255 // key in a desktop file.
256 std::string QuoteArgForDesktopFileExec(const std::string& arg) {
257 // http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s06.html
259 // Quoting is only necessary if the argument has a reserved character.
260 if (arg.find_first_of(" \t\n\"'\\><~|&;$*?#()`") == std::string::npos)
261 return arg; // No quoting necessary.
263 std::string quoted = "\"";
264 for (size_t i = 0; i < arg.size(); ++i) {
265 // Note that the set of backslashed characters is smaller than the
266 // set of reserved characters.
267 switch (arg[i]) {
268 case '"':
269 case '`':
270 case '$':
271 case '\\':
272 quoted += '\\';
273 break;
275 quoted += arg[i];
277 quoted += '"';
279 return quoted;
282 const char kDesktopEntry[] = "Desktop Entry";
284 const char kXdgOpenShebang[] = "#!/usr/bin/env xdg-open";
286 const char kXdgSettings[] = "xdg-settings";
287 const char kXdgSettingsDefaultBrowser[] = "default-web-browser";
288 const char kXdgSettingsDefaultSchemeHandler[] = "default-url-scheme-handler";
290 const char kDirectoryFilename[] = "chrome-apps.directory";
292 #if defined(GOOGLE_CHROME_BUILD)
293 const char kAppListDesktopName[] = "chrome-app-list";
294 #else // CHROMIUM_BUILD
295 const char kAppListDesktopName[] = "chromium-app-list";
296 #endif
298 } // namespace
300 namespace {
302 // Utility function to get the path to the version of a script shipped with
303 // Chrome. |script| gives the name of the script. |chrome_version| returns the
304 // path to the Chrome version of the script, and the return value of the
305 // function is true if the function is successful and the Chrome version is
306 // not the script found on the PATH.
307 bool GetChromeVersionOfScript(const std::string& script,
308 std::string* chrome_version) {
309 // Get the path to the Chrome version.
310 base::FilePath chrome_dir;
311 if (!PathService::Get(base::DIR_EXE, &chrome_dir))
312 return false;
314 base::FilePath chrome_version_path = chrome_dir.Append(script);
315 *chrome_version = chrome_version_path.value();
317 // Check if this is different to the one on path.
318 std::vector<std::string> argv;
319 argv.push_back("which");
320 argv.push_back(script);
321 std::string path_version;
322 if (base::GetAppOutput(CommandLine(argv), &path_version)) {
323 // Remove trailing newline
324 path_version.erase(path_version.length() - 1, 1);
325 base::FilePath path_version_path(path_version);
326 return (chrome_version_path != path_version_path);
328 return false;
331 // Value returned by xdg-settings if it can't understand our request.
332 const int EXIT_XDG_SETTINGS_SYNTAX_ERROR = 1;
334 // We delegate the difficulty of setting the default browser and default url
335 // scheme handler in Linux desktop environments to an xdg utility, xdg-settings.
337 // When calling this script we first try to use the script on PATH. If that
338 // fails we then try to use the script that we have included. This gives
339 // scripts on the system priority over ours, as distribution vendors may have
340 // tweaked the script, but still allows our copy to be used if the script on the
341 // system fails, as the system copy may be missing capabilities of the Chrome
342 // copy.
344 // If |protocol| is empty this function sets Chrome as the default browser,
345 // otherwise it sets Chrome as the default handler application for |protocol|.
346 bool SetDefaultWebClient(const std::string& protocol) {
347 #if defined(OS_CHROMEOS)
348 return true;
349 #else
350 scoped_ptr<base::Environment> env(base::Environment::Create());
352 std::vector<std::string> argv;
353 argv.push_back(kXdgSettings);
354 argv.push_back("set");
355 if (protocol.empty()) {
356 argv.push_back(kXdgSettingsDefaultBrowser);
357 } else {
358 argv.push_back(kXdgSettingsDefaultSchemeHandler);
359 argv.push_back(protocol);
361 argv.push_back(ShellIntegrationLinux::GetDesktopName(env.get()));
363 int exit_code;
364 bool ran_ok = LaunchXdgUtility(argv, &exit_code);
365 if (ran_ok && exit_code == EXIT_XDG_SETTINGS_SYNTAX_ERROR) {
366 if (GetChromeVersionOfScript(kXdgSettings, &argv[0])) {
367 ran_ok = LaunchXdgUtility(argv, &exit_code);
371 return ran_ok && exit_code == EXIT_SUCCESS;
372 #endif
375 // If |protocol| is empty this function checks if Chrome is the default browser,
376 // otherwise it checks if Chrome is the default handler application for
377 // |protocol|.
378 ShellIntegration::DefaultWebClientState GetIsDefaultWebClient(
379 const std::string& protocol) {
380 #if defined(OS_CHROMEOS)
381 return ShellIntegration::UNKNOWN_DEFAULT;
382 #else
383 base::ThreadRestrictions::AssertIOAllowed();
385 scoped_ptr<base::Environment> env(base::Environment::Create());
387 std::vector<std::string> argv;
388 argv.push_back(kXdgSettings);
389 argv.push_back("check");
390 if (protocol.empty()) {
391 argv.push_back(kXdgSettingsDefaultBrowser);
392 } else {
393 argv.push_back(kXdgSettingsDefaultSchemeHandler);
394 argv.push_back(protocol);
396 argv.push_back(ShellIntegrationLinux::GetDesktopName(env.get()));
398 std::string reply;
399 int success_code;
400 bool ran_ok = base::GetAppOutputWithExitCode(CommandLine(argv), &reply,
401 &success_code);
402 if (ran_ok && success_code == EXIT_XDG_SETTINGS_SYNTAX_ERROR) {
403 if (GetChromeVersionOfScript(kXdgSettings, &argv[0])) {
404 ran_ok = base::GetAppOutputWithExitCode(CommandLine(argv), &reply,
405 &success_code);
409 if (!ran_ok || success_code != EXIT_SUCCESS) {
410 // xdg-settings failed: we can't determine or set the default browser.
411 return ShellIntegration::UNKNOWN_DEFAULT;
414 // Allow any reply that starts with "yes".
415 return (reply.find("yes") == 0) ? ShellIntegration::IS_DEFAULT :
416 ShellIntegration::NOT_DEFAULT;
417 #endif
420 // Get the value of NoDisplay from the [Desktop Entry] section of a .desktop
421 // file, given in |shortcut_contents|. If the key is not found, returns false.
422 bool GetNoDisplayFromDesktopFile(const std::string& shortcut_contents) {
423 // An empty file causes a crash with glib <= 2.32, so special case here.
424 if (shortcut_contents.empty())
425 return false;
427 GKeyFile* key_file = g_key_file_new();
428 GError* err = NULL;
429 if (!g_key_file_load_from_data(key_file, shortcut_contents.c_str(),
430 shortcut_contents.size(), G_KEY_FILE_NONE,
431 &err)) {
432 LOG(WARNING) << "Unable to read desktop file template: " << err->message;
433 g_error_free(err);
434 g_key_file_free(key_file);
435 return false;
438 bool nodisplay = false;
439 char* nodisplay_c_string = g_key_file_get_string(key_file, kDesktopEntry,
440 "NoDisplay", &err);
441 if (nodisplay_c_string) {
442 if (!g_strcmp0(nodisplay_c_string, "true"))
443 nodisplay = true;
444 g_free(nodisplay_c_string);
445 } else {
446 g_error_free(err);
449 g_key_file_free(key_file);
450 return nodisplay;
453 // Gets the path to the Chrome executable or wrapper script.
454 // Returns an empty path if the executable path could not be found.
455 base::FilePath GetChromeExePath() {
456 // Try to get the name of the wrapper script that launched Chrome.
457 scoped_ptr<base::Environment> environment(base::Environment::Create());
458 std::string wrapper_script;
459 if (environment->GetVar("CHROME_WRAPPER", &wrapper_script)) {
460 return base::FilePath(wrapper_script);
463 // Just return the name of the executable path for Chrome.
464 base::FilePath chrome_exe_path;
465 PathService::Get(base::FILE_EXE, &chrome_exe_path);
466 return chrome_exe_path;
469 } // namespace
471 // static
472 ShellIntegration::DefaultWebClientSetPermission
473 ShellIntegration::CanSetAsDefaultBrowser() {
474 return SET_DEFAULT_UNATTENDED;
477 // static
478 bool ShellIntegration::SetAsDefaultBrowser() {
479 return SetDefaultWebClient(std::string());
482 // static
483 bool ShellIntegration::SetAsDefaultProtocolClient(const std::string& protocol) {
484 return SetDefaultWebClient(protocol);
487 // static
488 ShellIntegration::DefaultWebClientState ShellIntegration::GetDefaultBrowser() {
489 return GetIsDefaultWebClient(std::string());
492 // static
493 std::string ShellIntegration::GetApplicationForProtocol(const GURL& url) {
494 return std::string("xdg-open");
497 // static
498 ShellIntegration::DefaultWebClientState
499 ShellIntegration::IsDefaultProtocolClient(const std::string& protocol) {
500 return GetIsDefaultWebClient(protocol);
503 // static
504 bool ShellIntegration::IsFirefoxDefaultBrowser() {
505 std::vector<std::string> argv;
506 argv.push_back(kXdgSettings);
507 argv.push_back("get");
508 argv.push_back(kXdgSettingsDefaultBrowser);
510 std::string browser;
511 // We don't care about the return value here.
512 base::GetAppOutput(CommandLine(argv), &browser);
513 return browser.find("irefox") != std::string::npos;
516 namespace ShellIntegrationLinux {
518 bool GetDataWriteLocation(base::Environment* env, base::FilePath* search_path) {
519 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
521 std::string xdg_data_home;
522 std::string home;
523 if (env->GetVar("XDG_DATA_HOME", &xdg_data_home) && !xdg_data_home.empty()) {
524 *search_path = base::FilePath(xdg_data_home);
525 return true;
526 } else if (env->GetVar("HOME", &home) && !home.empty()) {
527 *search_path = base::FilePath(home).Append(".local").Append("share");
528 return true;
530 return false;
533 std::vector<base::FilePath> GetDataSearchLocations(base::Environment* env) {
534 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
536 std::vector<base::FilePath> search_paths;
538 base::FilePath write_location;
539 if (GetDataWriteLocation(env, &write_location))
540 search_paths.push_back(write_location);
542 std::string xdg_data_dirs;
543 if (env->GetVar("XDG_DATA_DIRS", &xdg_data_dirs) && !xdg_data_dirs.empty()) {
544 base::StringTokenizer tokenizer(xdg_data_dirs, ":");
545 while (tokenizer.GetNext()) {
546 base::FilePath data_dir(tokenizer.token());
547 search_paths.push_back(data_dir);
549 } else {
550 search_paths.push_back(base::FilePath("/usr/local/share"));
551 search_paths.push_back(base::FilePath("/usr/share"));
554 return search_paths;
557 std::string GetProgramClassName() {
558 DCHECK(CommandLine::InitializedForCurrentProcess());
559 // Get the res_name component from argv[0].
560 const CommandLine* command_line = CommandLine::ForCurrentProcess();
561 std::string class_name = command_line->GetProgram().BaseName().value();
562 if (!class_name.empty())
563 class_name[0] = base::ToUpperASCII(class_name[0]);
564 return class_name;
567 std::string GetDesktopName(base::Environment* env) {
568 #if defined(GOOGLE_CHROME_BUILD)
569 return "google-chrome.desktop";
570 #else // CHROMIUM_BUILD
571 // Allow $CHROME_DESKTOP to override the built-in value, so that development
572 // versions can set themselves as the default without interfering with
573 // non-official, packaged versions using the built-in value.
574 std::string name;
575 if (env->GetVar("CHROME_DESKTOP", &name) && !name.empty())
576 return name;
577 return "chromium-browser.desktop";
578 #endif
581 std::string GetIconName() {
582 #if defined(GOOGLE_CHROME_BUILD)
583 return "google-chrome";
584 #else // CHROMIUM_BUILD
585 return "chromium-browser";
586 #endif
589 ShellIntegration::ShortcutLocations GetExistingShortcutLocations(
590 base::Environment* env,
591 const base::FilePath& profile_path,
592 const std::string& extension_id) {
593 base::FilePath desktop_path;
594 // If Get returns false, just leave desktop_path empty.
595 PathService::Get(base::DIR_USER_DESKTOP, &desktop_path);
596 return GetExistingShortcutLocations(env, profile_path, extension_id,
597 desktop_path);
600 ShellIntegration::ShortcutLocations GetExistingShortcutLocations(
601 base::Environment* env,
602 const base::FilePath& profile_path,
603 const std::string& extension_id,
604 const base::FilePath& desktop_path) {
605 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
607 base::FilePath shortcut_filename = GetExtensionShortcutFilename(
608 profile_path, extension_id);
609 DCHECK(!shortcut_filename.empty());
610 ShellIntegration::ShortcutLocations locations;
612 // Determine whether there is a shortcut on desktop.
613 if (!desktop_path.empty()) {
614 locations.on_desktop =
615 base::PathExists(desktop_path.Append(shortcut_filename));
618 // Determine whether there is a shortcut in the applications directory.
619 std::string shortcut_contents;
620 if (GetExistingShortcutContents(env, shortcut_filename, &shortcut_contents)) {
621 // Whether this counts as "hidden" or "APP_MENU_LOCATION_SUBDIR_CHROMEAPPS"
622 // depends on whether it contains NoDisplay=true. Since these shortcuts are
623 // for apps, they are always in the "Chrome Apps" directory.
624 if (GetNoDisplayFromDesktopFile(shortcut_contents)) {
625 locations.hidden = true;
626 } else {
627 locations.applications_menu_location =
628 ShellIntegration::APP_MENU_LOCATION_SUBDIR_CHROMEAPPS;
632 return locations;
635 bool GetExistingShortcutContents(base::Environment* env,
636 const base::FilePath& desktop_filename,
637 std::string* output) {
638 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
640 std::vector<base::FilePath> search_paths = GetDataSearchLocations(env);
642 for (std::vector<base::FilePath>::const_iterator i = search_paths.begin();
643 i != search_paths.end(); ++i) {
644 base::FilePath path = i->Append("applications").Append(desktop_filename);
645 VLOG(1) << "Looking for desktop file in " << path.value();
646 if (base::PathExists(path)) {
647 VLOG(1) << "Found desktop file at " << path.value();
648 return base::ReadFileToString(path, output);
652 return false;
655 base::FilePath GetWebShortcutFilename(const GURL& url) {
656 // Use a prefix, because xdg-desktop-menu requires it.
657 std::string filename =
658 std::string(chrome::kBrowserProcessExecutableName) + "-" + url.spec();
659 file_util::ReplaceIllegalCharactersInPath(&filename, '_');
661 base::FilePath desktop_path;
662 if (!PathService::Get(base::DIR_USER_DESKTOP, &desktop_path))
663 return base::FilePath();
665 base::FilePath filepath = desktop_path.Append(filename);
666 base::FilePath alternative_filepath(filepath.value() + ".desktop");
667 for (size_t i = 1; i < 100; ++i) {
668 if (base::PathExists(base::FilePath(alternative_filepath))) {
669 alternative_filepath = base::FilePath(
670 filepath.value() + "_" + base::IntToString(i) + ".desktop");
671 } else {
672 return base::FilePath(alternative_filepath).BaseName();
676 return base::FilePath();
679 base::FilePath GetExtensionShortcutFilename(const base::FilePath& profile_path,
680 const std::string& extension_id) {
681 DCHECK(!extension_id.empty());
683 // Use a prefix, because xdg-desktop-menu requires it.
684 std::string filename(chrome::kBrowserProcessExecutableName);
685 filename.append("-")
686 .append(extension_id)
687 .append("-")
688 .append(profile_path.BaseName().value());
689 file_util::ReplaceIllegalCharactersInPath(&filename, '_');
690 // Spaces in filenames break xdg-desktop-menu
691 // (see https://bugs.freedesktop.org/show_bug.cgi?id=66605).
692 base::ReplaceChars(filename, " ", "_", &filename);
693 return base::FilePath(filename.append(".desktop"));
696 std::vector<base::FilePath> GetExistingProfileShortcutFilenames(
697 const base::FilePath& profile_path,
698 const base::FilePath& directory) {
699 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
700 // Use a prefix, because xdg-desktop-menu requires it.
701 std::string prefix(chrome::kBrowserProcessExecutableName);
702 prefix.append("-");
703 std::string suffix("-");
704 suffix.append(profile_path.BaseName().value());
705 file_util::ReplaceIllegalCharactersInPath(&suffix, '_');
706 // Spaces in filenames break xdg-desktop-menu
707 // (see https://bugs.freedesktop.org/show_bug.cgi?id=66605).
708 base::ReplaceChars(suffix, " ", "_", &suffix);
709 std::string glob = prefix + "*" + suffix + ".desktop";
711 base::FileEnumerator files(directory, false, base::FileEnumerator::FILES,
712 glob);
713 base::FilePath shortcut_file = files.Next();
714 std::vector<base::FilePath> shortcut_paths;
715 while (!shortcut_file.empty()) {
716 shortcut_paths.push_back(shortcut_file.BaseName());
717 shortcut_file = files.Next();
719 return shortcut_paths;
722 std::string GetDesktopFileContents(
723 const base::FilePath& chrome_exe_path,
724 const std::string& app_name,
725 const GURL& url,
726 const std::string& extension_id,
727 const base::FilePath& extension_path,
728 const base::string16& title,
729 const std::string& icon_name,
730 const base::FilePath& profile_path,
731 bool no_display,
732 bool show_app_list) {
733 // Although not required by the spec, Nautilus on Ubuntu Karmic creates its
734 // launchers with an xdg-open shebang. Follow that convention.
735 std::string output_buffer = std::string(kXdgOpenShebang) + "\n";
737 // See http://standards.freedesktop.org/desktop-entry-spec/latest/
738 GKeyFile* key_file = g_key_file_new();
740 // Set keys with fixed values.
741 g_key_file_set_string(key_file, kDesktopEntry, "Version", "1.0");
742 g_key_file_set_string(key_file, kDesktopEntry, "Terminal", "false");
743 g_key_file_set_string(key_file, kDesktopEntry, "Type", "Application");
745 // Set the "Name" key.
746 std::string final_title = base::UTF16ToUTF8(title);
747 // Make sure no endline characters can slip in and possibly introduce
748 // additional lines (like Exec, which makes it a security risk). Also
749 // use the URL as a default when the title is empty.
750 if (final_title.empty() ||
751 final_title.find("\n") != std::string::npos ||
752 final_title.find("\r") != std::string::npos) {
753 final_title = url.spec();
755 g_key_file_set_string(key_file, kDesktopEntry, "Name", final_title.c_str());
757 // Set the "Exec" key.
758 std::string final_path = chrome_exe_path.value();
759 CommandLine cmd_line(CommandLine::NO_PROGRAM);
760 if (show_app_list) {
761 cmd_line.AppendSwitch(switches::kShowAppList);
762 } else {
763 cmd_line = ShellIntegration::CommandLineArgsForLauncher(
764 url, extension_id, profile_path);
766 const CommandLine::SwitchMap& switch_map = cmd_line.GetSwitches();
767 for (CommandLine::SwitchMap::const_iterator i = switch_map.begin();
768 i != switch_map.end(); ++i) {
769 if (i->second.empty()) {
770 final_path += " --" + i->first;
771 } else {
772 final_path += " " + QuoteArgForDesktopFileExec("--" + i->first +
773 "=" + i->second);
777 g_key_file_set_string(key_file, kDesktopEntry, "Exec", final_path.c_str());
779 // Set the "Icon" key.
780 if (!icon_name.empty()) {
781 g_key_file_set_string(key_file, kDesktopEntry, "Icon", icon_name.c_str());
782 } else {
783 g_key_file_set_string(key_file, kDesktopEntry, "Icon",
784 GetIconName().c_str());
787 // Set the "NoDisplay" key.
788 if (no_display)
789 g_key_file_set_string(key_file, kDesktopEntry, "NoDisplay", "true");
791 std::string wmclass = web_app::GetWMClassFromAppName(app_name);
792 g_key_file_set_string(key_file, kDesktopEntry, "StartupWMClass",
793 wmclass.c_str());
795 gsize length = 0;
796 gchar* data_dump = g_key_file_to_data(key_file, &length, NULL);
797 if (data_dump) {
798 // If strlen(data_dump[0]) == 0, this check will fail.
799 if (data_dump[0] == '\n') {
800 // Older versions of glib produce a leading newline. If this is the case,
801 // remove it to avoid double-newline after the shebang.
802 output_buffer += (data_dump + 1);
803 } else {
804 output_buffer += data_dump;
806 g_free(data_dump);
809 g_key_file_free(key_file);
810 return output_buffer;
813 std::string GetDirectoryFileContents(const base::string16& title,
814 const std::string& icon_name) {
815 // See http://standards.freedesktop.org/desktop-entry-spec/latest/
816 GKeyFile* key_file = g_key_file_new();
818 g_key_file_set_string(key_file, kDesktopEntry, "Version", "1.0");
819 g_key_file_set_string(key_file, kDesktopEntry, "Type", "Directory");
820 std::string final_title = base::UTF16ToUTF8(title);
821 g_key_file_set_string(key_file, kDesktopEntry, "Name", final_title.c_str());
822 if (!icon_name.empty()) {
823 g_key_file_set_string(key_file, kDesktopEntry, "Icon", icon_name.c_str());
824 } else {
825 g_key_file_set_string(key_file, kDesktopEntry, "Icon",
826 GetIconName().c_str());
829 gsize length = 0;
830 gchar* data_dump = g_key_file_to_data(key_file, &length, NULL);
831 std::string output_buffer;
832 if (data_dump) {
833 // If strlen(data_dump[0]) == 0, this check will fail.
834 if (data_dump[0] == '\n') {
835 // Older versions of glib produce a leading newline. If this is the case,
836 // remove it to avoid double-newline after the shebang.
837 output_buffer += (data_dump + 1);
838 } else {
839 output_buffer += data_dump;
841 g_free(data_dump);
844 g_key_file_free(key_file);
845 return output_buffer;
848 bool CreateDesktopShortcut(
849 const ShellIntegration::ShortcutInfo& shortcut_info,
850 const ShellIntegration::ShortcutLocations& creation_locations) {
851 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
853 base::FilePath shortcut_filename;
854 if (!shortcut_info.extension_id.empty()) {
855 shortcut_filename = GetExtensionShortcutFilename(
856 shortcut_info.profile_path, shortcut_info.extension_id);
857 // For extensions we do not want duplicate shortcuts. So, delete any that
858 // already exist and replace them.
859 if (creation_locations.on_desktop)
860 DeleteShortcutOnDesktop(shortcut_filename);
861 // The 'applications_menu_location' and 'hidden' locations are actually the
862 // same place ('applications').
863 if (creation_locations.applications_menu_location !=
864 ShellIntegration::APP_MENU_LOCATION_NONE ||
865 creation_locations.hidden)
866 DeleteShortcutInApplicationsMenu(shortcut_filename, base::FilePath());
867 } else {
868 shortcut_filename = GetWebShortcutFilename(shortcut_info.url);
870 if (shortcut_filename.empty())
871 return false;
873 std::string icon_name =
874 CreateShortcutIcon(shortcut_info.favicon, shortcut_filename);
876 std::string app_name =
877 web_app::GenerateApplicationNameFromInfo(shortcut_info);
879 bool success = true;
881 base::FilePath chrome_exe_path = GetChromeExePath();
882 if (chrome_exe_path.empty()) {
883 LOG(WARNING) << "Could not get executable path.";
884 return false;
887 if (creation_locations.on_desktop) {
888 std::string contents = ShellIntegrationLinux::GetDesktopFileContents(
889 chrome_exe_path,
890 app_name,
891 shortcut_info.url,
892 shortcut_info.extension_id,
893 shortcut_info.extension_path,
894 shortcut_info.title,
895 icon_name,
896 shortcut_info.profile_path,
897 false,
898 false);
899 success = CreateShortcutOnDesktop(shortcut_filename, contents);
902 if (creation_locations.applications_menu_location !=
903 ShellIntegration::APP_MENU_LOCATION_NONE ||
904 creation_locations.hidden) {
905 base::FilePath directory_filename;
906 std::string directory_contents;
907 switch (creation_locations.applications_menu_location) {
908 case ShellIntegration::APP_MENU_LOCATION_NONE:
909 case ShellIntegration::APP_MENU_LOCATION_ROOT:
910 break;
911 case ShellIntegration::APP_MENU_LOCATION_SUBDIR_CHROMEAPPS:
912 directory_filename = base::FilePath(kDirectoryFilename);
913 directory_contents = ShellIntegrationLinux::GetDirectoryFileContents(
914 ShellIntegration::GetAppShortcutsSubdirName(), "");
915 break;
916 default:
917 NOTREACHED();
918 break;
920 // Set NoDisplay=true if hidden but not in the applications menu. This will
921 // hide the application from user-facing menus.
922 std::string contents = ShellIntegrationLinux::GetDesktopFileContents(
923 chrome_exe_path,
924 app_name,
925 shortcut_info.url,
926 shortcut_info.extension_id,
927 shortcut_info.extension_path,
928 shortcut_info.title,
929 icon_name,
930 shortcut_info.profile_path,
931 creation_locations.applications_menu_location ==
932 ShellIntegration::APP_MENU_LOCATION_NONE,
933 false);
934 success = CreateShortcutInApplicationsMenu(
935 shortcut_filename, contents, directory_filename, directory_contents) &&
936 success;
939 return success;
942 bool CreateAppListDesktopShortcut(
943 const std::string& wm_class,
944 const std::string& title) {
945 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
947 base::FilePath desktop_name(kAppListDesktopName);
948 base::FilePath shortcut_filename = desktop_name.AddExtension("desktop");
950 // We do not want duplicate shortcuts. Delete any that already exist and
951 // replace them.
952 DeleteShortcutInApplicationsMenu(shortcut_filename, base::FilePath());
954 base::FilePath chrome_exe_path = GetChromeExePath();
955 if (chrome_exe_path.empty()) {
956 LOG(WARNING) << "Could not get executable path.";
957 return false;
960 gfx::ImageFamily icon_images;
961 ResourceBundle& resource_bundle = ResourceBundle::GetSharedInstance();
962 icon_images.Add(*resource_bundle.GetImageSkiaNamed(IDR_APP_LIST_16));
963 icon_images.Add(*resource_bundle.GetImageSkiaNamed(IDR_APP_LIST_32));
964 icon_images.Add(*resource_bundle.GetImageSkiaNamed(IDR_APP_LIST_48));
965 icon_images.Add(*resource_bundle.GetImageSkiaNamed(IDR_APP_LIST_256));
966 std::string icon_name = CreateShortcutIcon(icon_images, desktop_name);
968 std::string contents = ShellIntegrationLinux::GetDesktopFileContents(
969 chrome_exe_path,
970 wm_class,
971 GURL(),
973 base::FilePath(),
974 base::UTF8ToUTF16(title),
975 icon_name,
976 base::FilePath(),
977 false,
978 true);
979 return CreateShortcutInApplicationsMenu(
980 shortcut_filename, contents, base::FilePath(), "");
983 void DeleteDesktopShortcuts(const base::FilePath& profile_path,
984 const std::string& extension_id) {
985 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
987 base::FilePath shortcut_filename = GetExtensionShortcutFilename(
988 profile_path, extension_id);
989 DCHECK(!shortcut_filename.empty());
991 DeleteShortcutOnDesktop(shortcut_filename);
992 // Delete shortcuts from |kDirectoryFilename|.
993 // Note that it is possible that shortcuts were not created in the Chrome Apps
994 // directory. It doesn't matter: this will still delete the shortcut even if
995 // it isn't in the directory.
996 DeleteShortcutInApplicationsMenu(shortcut_filename,
997 base::FilePath(kDirectoryFilename));
1000 void DeleteAllDesktopShortcuts(const base::FilePath& profile_path) {
1001 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
1003 scoped_ptr<base::Environment> env(base::Environment::Create());
1005 // Delete shortcuts from Desktop.
1006 base::FilePath desktop_path;
1007 if (PathService::Get(base::DIR_USER_DESKTOP, &desktop_path)) {
1008 std::vector<base::FilePath> shortcut_filenames_desktop =
1009 GetExistingProfileShortcutFilenames(profile_path, desktop_path);
1010 for (std::vector<base::FilePath>::const_iterator it =
1011 shortcut_filenames_desktop.begin();
1012 it != shortcut_filenames_desktop.end(); ++it) {
1013 DeleteShortcutOnDesktop(*it);
1017 // Delete shortcuts from |kDirectoryFilename|.
1018 base::FilePath applications_menu;
1019 if (GetDataWriteLocation(env.get(), &applications_menu)) {
1020 applications_menu = applications_menu.AppendASCII("applications");
1021 std::vector<base::FilePath> shortcut_filenames_app_menu =
1022 GetExistingProfileShortcutFilenames(profile_path, applications_menu);
1023 for (std::vector<base::FilePath>::const_iterator it =
1024 shortcut_filenames_app_menu.begin();
1025 it != shortcut_filenames_app_menu.end(); ++it) {
1026 DeleteShortcutInApplicationsMenu(*it,
1027 base::FilePath(kDirectoryFilename));
1032 } // namespace ShellIntegrationLinux