Desktop entry linux categories

Desktop entries (Русский)

Спецификация freedesktop ярлык приложения предусматривает стандарт для приложений для интеграции в среду рабочего стола. Ярлыки приложений — это файлы конфигурации, описывающие, как запускается приложение, и какие данные оно может обрабатывать. Они также настраивают, как появляются приложения в меню со значком, на который распространяется соответствующий стандарт спецификации меню.

Наиболее распространенные ярлыки приложений представлены файлами .desktop и .directory . В этой статье кратко объясняется, как создавать полезные и соответствующие стандарту ярлыки приложений. Она в основном предназначена для разработчиков и сопровождающих пакетов(ы), но может также быть полезна разработчикам программного обеспечения и другим.

Существует примерно три типа ярлыков приложений:

Приложение ярлык приложения Ссылка ярлык на веб-ссылку Каталог контейнер метаданных в меню

В следующих разделах будет примерно показано, как они создаются и проверяются.

Связанное с этим материалом, а также определенные в файлах .desktop , являются ассоциациями типа MIME для файлов данных. Приложения по умолчанию описывают, как они настроены.

Contents

Ярлык приложения

Ярлыки для приложений или файлов .desktop , как правило, представляют собой комбинацию метаинформационных ресурсов и ярлыков приложений. Эти файлы обычно находятся в /usr/share/applications или /usr/local/share/applications для приложений, установленных в системе, или

/.local/share/applications для пользовательских приложений. Пользовательские ярлыки имеют приоритет над системными ярлыками.

Пример файла

Ниже приведен пример его структуры с дополнительными комментариями. Этот пример предназначен только для быстрого ознакомления и не показывает, как использовать все возможные ключи ввода. Полный список ключей можно найти в спецификация freedesktop.org.

Определение ключа

Все признанные Desktop ярлыки приложений можно найти на сайте freedesktop.org. Например, ключ Type определяет три типа ярлыков: Приложение (тип 1), Ссылка (тип 2) и Каталог (тип 3).

  • Ключ Version обозначает версию спецификации ярлыка приложения, которая соответствует этому файлу, но не как не версию приложения.
  • Name , GenericName и Comment часто содержат избыточные значения в виде комбинаций из них, например:

Этого следует избегать, поскольку это только будет запутывать пользователей. Ключ Name должен содержать только имя или хотя бы аббревиатуру/акроним, если они доступны.

  • GenericName должен указывать на категорию приложения, которая обозначает особый признак этого конкретного приложения (например Firefox является «веб-браузером»).
  • Comment должен содержать любую полезную дополнительную информацию.

Осуждение

Существует много ключей, которые стали устаревшими с течением времени по мере созревания стандарта. Лучший/самый простой способ — использовать инструмент desktop-file-validate , который является частью пакета desktop-file-utils . Чтобы проверить, выполните

Это даст вам очень подробные и полезные предупреждения и сообщения об ошибках.

Значки

Распространенные форматы изображений

Ниже приведен краткий обзор форматов изображений, обычно используемых для значков.

Поддержка форматов изображений для значков, указанных в стандарте freedesktop.org.

Расширение Полное имя и/или описание Тип графики Формат контейнера Поддерживаемый
.png Portable Network Graphics Raster Нет Да
.svg(z) Scalable Vector Graphics Vector Нет Да (опционально)
.xpm X PixMap Raster Нет Да (устаревший)
.gif Graphics Interchange Format Raster Нет Нет
.ico MS Windows Icon Format Raster Да Нет
.icns Apple Icon Image Raster Да Нет

Преобразование значков

Если вы наткнулись на значок, который находится в формате, который не поддерживается стандартом freedesktop.org (например, gif или ico ), вы можете использовать инструмент преобразования (который является частью пакета imagemagick ), чтобы преобразовать его в поддерживаемый/рекомендованный формат, например:

Если вы преобразуете из формата контейнера, такого как ico , вы получите все изображения, которые были инкапсулированы в файл ico в форме — .png . Если вы хотите узнать размер изображения или количество изображений в файле контейнера, например ico , вы можете использовать инструмент идентификации (также часть пакета imagemagick ):

Читайте также:  Transmission для windows portable

Как вы можете видеть, на примере файла ico, что по названию можно предположить одно изображение размером 48×48, но на самом деле оно содержит не менее 6 разных размеров, из которых один больше 48×48, а именно 128×128.

Кроме того, вы можете использовать icotool (из icoutils ) для извлечения png-изображений из контейнера ico:

Для извлечения изображений из контейнера .icns вы можете использовать icns2png (предоставленный libicns ):

Получение значков

Хотя пакеты, которые уже поставляются с файлом .desktop, наверняка содержат значок или набор значков, иногда бывает, что разработчик не создал файл .desktop, но тем не менее может отправить значки. Поэтому неплохо начать поиск значков в исходном пакете. Вы можете, например, сначала фильтровать расширение с помощью find, а затем использовать grep для дальнейшей фильтрации по определенным ключевым словам, таких как имя пакета, «значок», «логотип» и т.д., если изображений достаточно много в исходном пакете.

Если разработчики приложения не включают значки в свои исходные пакеты, тогда следующим шагом будет поиск значков на их сайте. В некоторых проектах, например, tvbrowser, есть страница с изображением/логотипом, где могут быть найдены дополнительные значки. Если проект мультиплатформенный, может случиться так, что в пакете linux/unix отсутствует значок, тогда пакет Windows может предоставить его. Если в проекте используется система управления версиями, например CVS/SVN и т.д., и у вас есть некоторый опыт работы с ней, вы также можете рассмотреть возможность просмотра ее для значков. Если все не удастся, проект может просто не иметь значка/логотипа еще.

Инструменты

gendesk

gendesk стартовал как инструмент, специально предназначенный для Arch Linux для генерации файлов .desktop, путем сбора необходимой информации непосредственно из файлов PKGBUILD. Теперь это общий инструмент, который принимает аргументы командной строки.

Значки могут быть автоматически загружены из openiconlibrary, если они доступны. (Источник значков можно легко изменить в будущем).

Как использовать

  • Добавьте gendesk в makedepends
  • Запустите функцию prepare() с:
  • Альтернативно, если значок уже предоставлен (например, $pkgname.png). Флаг -n предназначен для не загрузки значка или использования значка по умолчанию. Пример:
  • $srcdir/$pkgname.desktop будет создан и может быть установлен в функции package() с:
  • Значок можно установить с помощью:
  • Используйте —name=’Program Name’ для выбора имени для входа в меню..
  • Для установки поля exec используйте —exec=’/opt/some_app/elf —with-ponies’ .
  • Смотрите проект gendesk для получения дополнительной информации.

Список или поиск в файлах .desktop

lsdesktopf AUR может отображать доступные файлы .desktop или искать их содержимое.

Он также может выполнять поиск по типу MIME. Смотрите приложения по умолчанию#lsdesktopf.

fbrokendesktop

Скрипт fbrokendesktop AUR с использованием команды which для обнаружения сломанного Exec , который указывает на не существующий путь. Без каких-либо параметров он использует предварительно установленные каталоги в массиве DskPath . Он показывает только сломанный .desktop с полным отсутствием пути и имени файла.

Советы и хитрости

Скрытие ярлыков приложений

Во-первых, скопируйте ярлык приложения в

/.local/share/applications , чтобы ваши изменения не были перезаписаны.

Затем, чтобы скрыть ярлык приложения во всех средах, откройте его в текстовом редакторе и добавьте следующую строку: NoDisplay=true .

Чтобы скрыть ярлык приложения на конкретной среде рабочего стола добавьте следующую строку в него: NotShowIn=desktop-name

где desktop-name может быть таким, как GNOME, Xfce, KDE и т.д. Ярлык приложения может быть скрытым более, чем в одной среде рабочего стола сразу — просто разделяйте имена сред рабочего стола точкой с запятой.

Автозапуск

Если вы используете среду рабочего стола, совместимую с XDG, например GNOME или KDE, то она автоматически запускает файлы *.desktop, найденные в следующих каталогах:

  • Общесистемный: $XDG_CONFIG_DIRS/autostart/ ( /etc/xdg/autostart/ по умолчанию)
  • GNOME также запускает файлы, найденные в /usr/share/gnome/autostart/
  • Пользовательский: $XDG_CONFIG_HOME/autostart/ (

    /.config/autostart/ по умолчанию)

Пользователи могут переопределять общесистемные файлы *.desktop скопировав их в пользовательский каталог

Для более конкретного описания используемых каталогов смотрите спецификацию автозапуска ярлыков приложений.

Изменение переменных среды

Отредактируйте команду Exec , добавив env, чтобы задать переменные окружения. Например:

/.local/share/applications/ вместо изменения его в /usr/share/applications/ .

Источник

Desktop entries

The XDG Desktop Entry specification defines a standard for applications to integrate into application menus of desktop environments implementing the XDG Desktop Menu specification.

Contents

Basics

Each desktop entry must have a Type and a Name key and can optionally define its appearance in the application menu.

The three available types are:

Application Defines how to launch an application and what MIME types it supports (used by XDG MIME Applications). With XDG Autostart Application entries can be started automatically by placing them in specific directories. Application entries use the .desktop file extension. See #Application entry. Link Defines a shortcut to a URL . Link entries use the .desktop file extension. Directory Defines the appearance of a submenu in the application menu. Directory entries use the .directory file extension.

The following sections will roughly explain how these are created and validated.

Application entry

Desktop entries for applications, or .desktop files, are generally a combination of meta information resources and a shortcut of an application. These files usually reside in /usr/share/applications/ or /usr/local/share/applications/ for applications installed system-wide, or

/.local/share/applications/ for user-specific applications. User entries take precedence over system entries.

File example

Following is an example of its structure with additional comments. The example is only meant to give a quick impression, and does not show how to utilize all possible entry keys. The complete list of keys can be found in the freedesktop specification.

Key definition

All recognized entries can be found on the freedesktop site. For example, the Type key defines three types of desktop entries: Application (type 1), Link (type 2) and Directory (type 3).

  • Version key does not stand for the version of the application, but for the version of the desktop entry specification to which this file complies.
  • Name , GenericName and Comment often contain redundant values in the form of combinations of them, like:

This should be avoided, as it will only be confusing to users. The Name key should only contain the name, or maybe an abbreviation/acronym if available.

  • GenericName should state what you would generally call an application that does what this specific application offers (i.e. Firefox is a «Web Browser»).
  • Comment is intended to contain any useful additional information.

Validation

As some keys have become deprecated over time, you may want to validate your desktop entries using desktop-file-validate(1) which is part of the desktop-file-utils package. To validate, run:

This will give you very verbose and useful warnings and error messages.

Installation

Use desktop-file-install(1) to install desktop file into target directory. For example:

Update database of desktop entries

To make desktop entries defined in

/.local/share/applications work, run the following command:

Icons

Common image formats

Here is a short overview of image formats commonly used for icons.

Support for image formats for icons as specified by the freedesktop.org standard.

Extension Full Name and/or Description Graphics Type Container Format Supported
.png Portable Network Graphics Raster No Yes
.svg(z) Scalable Vector Graphics Vector No Yes (optional)
.xpm X PixMap Raster No Yes (deprecated)
.gif Graphics Interchange Format Raster No No
.ico MS Windows Icon Format Raster Yes No
.icns Apple Icon Image Raster Yes No

Converting icons

This article or section is a candidate for merging with ImageMagick#Usage.

If you stumble across an icon which is in a format that is not supported by the freedesktop.org standard (like gif or ico ), you can use the convert tool (which is part of the imagemagick package) to convert it to a supported/recommended format, e.g.:

If you convert from a container format like ico , you will get all images that were encapsulated in the ico file in the form — .png . If you want to know the size of the image, or the number of images in a container file like ico you can use the identify tool (also part of the imagemagick package):

As you can see, the example ico file, although its name might suggest a single image of size 48×48, contains no less than 6 different sizes, of which one is even greater than 48×48, namely 128×128.

Alternatively, you can use icotool (from icoutils ) to extract png images from ico container:

For extracting images from .icns container, you can use icns2png (provided by libicns ):

Obtaining icons

Although packages that already ship with a .desktop file most certainly contain an icon or a set of icons, there is sometimes the case when a developer has not created a .desktop file, but may ship icons, nonetheless. So a good start is to look for icons in the source package. You can i.e. first filter for the extension with find and then use grep to filter further for certain buzzwords like the package name, «icon», «logo», etc, if there are quite a lot of images in the source package.

If the developers of an application do not include icons in their source packages, the next step would be to search on their web sites. Some projects, like i.e. tvbrowser AUR have an artwork/logo page where additional icons may be found. If a project is multi-platform, there may be the case that even if the linux/unix package does not come with an icon, the Windows package might provide one. If the project uses a Version control system like CVS/SVN/etc. and you have some experience with it, you also might consider browsing it for icons. If everything fails, the project might simply have no icon/logo yet.

Icon path

The freedesktop.org standard specifies in which order and directories programs should look for icons:

  1. $HOME/.icons (for backwards compatibility)
  2. $XDG_DATA_DIRS/icons
  3. /usr/share/pixmaps

Tools

gendesk

gendesk started as an Arch Linux-specific tool for generating .desktop files by fetching the needed information directly from PKGBUILD files. Now it is a general tool that takes command-line arguments.

Icons can be automatically downloaded from openiconlibrary, if available. (The source for icons is configurable).

How to use

  • Add gendesk to makedepends
  • Start the prepare() function with:
  • Alternatively, if an icon is already provided ($pkgname.png, for instance). The -n flag is for not downloading an icon or using the default icon. Example:
  • $srcdir/$pkgname.desktop will be created and can be installed in the package() function with:
  • The icon can be installed with:
  • Use —name=’Program Name’ for choosing a name for the menu entry.
  • Use —exec=’/opt/some_app/elf —some-arg —other-arg’ for setting the exec field.
  • See the gendesk project for more information.

lsdesktopf

lsdesktopf AUR can list available .desktop files or search their contents.

It can also perform MIME-type-related searches. See XDG MIME Applications#lsdesktopf.

fbrokendesktop

The fbrokendesktop AUR Bash script detects broken Exec values pointing to non-existent paths. Without any arguments it uses preset directories in the DskPath array. It shows only broken .desktop with full path and filename that is missing.

Tips and tricks

Run a desktop file from a terminal

If gtk3 is installed, run gtk-launch application.desktop .

Or install the dex package and run dex /path/to/application.desktop .

Hide desktop entries

Firstly, copy the desktop entry file in question to

/.local/share/applications to avoid your changes being overwritten.

Then, to hide the entry in all environments, open the desktop entry file in a text editor and add the following line: NoDisplay=true .

To hide the entry in a specific desktop, add the following line to the desktop entry file: NotShowIn=desktop-name

where desktop-name can be option such as GNOME, Xfce, KDE etc. A desktop entry can be hidden in more than desktop at once — simply separate the desktop names with a semi-colon.

Modify environment variables

To set environment variables, copy the .desktop file from /usr/share/applications/ to $XDG_DATA_HOME/ (

/.local/share/applications/ ) and edit the Exec= command line by prepending env. For example:

Источник

Читайте также:  Предпочитаемые языки windows 10
Оцените статью