как создать desktop файл linux
Desktop entries (Русский)
Существует примерно три типа ярлыков приложений:
Приложение ярлык приложения Ссылка ярлык на веб-ссылку Каталог контейнер метаданных в меню
В следующих разделах будет примерно показано, как они создаются и проверяются.
Contents
Ярлык приложения
/.local/share/applications для пользовательских приложений. Пользовательские ярлыки имеют приоритет над системными ярлыками.
Пример файла
Ниже приведен пример его структуры с дополнительными комментариями. Этот пример предназначен только для быстрого ознакомления и не показывает, как использовать все возможные ключи ввода. Полный список ключей можно найти в спецификация freedesktop.org.
Определение ключа
Все признанные Desktop ярлыки приложений можно найти на сайте freedesktop.org. Например, ключ Type определяет три типа ярлыков: Приложение (тип 1), Ссылка (тип 2) и Каталог (тип 3).
Этого следует избегать, поскольку это только будет запутывать пользователей. Ключ Name должен содержать только имя или хотя бы аббревиатуру/акроним, если они доступны.
Осуждение
Это даст вам очень подробные и полезные предупреждения и сообщения об ошибках.
Значки
Распространенные форматы изображений
Ниже приведен краткий обзор форматов изображений, обычно используемых для значков.
Расширение | Полное имя и/или описание | Тип графики | Формат контейнера | Поддерживаемый |
---|---|---|---|---|
.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, что по названию можно предположить одно изображение размером 48×48, но на самом деле оно содержит не менее 6 разных размеров, из которых один больше 48×48, а именно 128×128.
Кроме того, вы можете использовать icotool (из icoutils ) для извлечения png-изображений из контейнера ico:
Получение значков
Если разработчики приложения не включают значки в свои исходные пакеты, тогда следующим шагом будет поиск значков на их сайте. В некоторых проектах, например, tvbrowser, есть страница с изображением/логотипом, где могут быть найдены дополнительные значки. Если проект мультиплатформенный, может случиться так, что в пакете linux/unix отсутствует значок, тогда пакет Windows может предоставить его. Если в проекте используется система управления версиями, например CVS/SVN и т.д., и у вас есть некоторый опыт работы с ней, вы также можете рассмотреть возможность просмотра ее для значков. Если все не удастся, проект может просто не иметь значка/логотипа еще.
Инструменты
gendesk
Значки могут быть автоматически загружены из openiconlibrary, если они доступны. (Источник значков можно легко изменить в будущем).
Как использовать
lsdesktopf AUR может отображать доступные файлы .desktop или искать их содержимое.
Он также может выполнять поиск по типу MIME. Смотрите приложения по умолчанию#lsdesktopf.
fbrokendesktop
Советы и хитрости
Скрытие ярлыков приложений
Во-первых, скопируйте ярлык приложения в
Чтобы скрыть ярлык приложения на конкретной среде рабочего стола добавьте следующую строку в него: NotShowIn=desktop-name
Автозапуск
Если вы используете среду рабочего стола, совместимую с XDG, например GNOME или KDE, то она автоматически запускает файлы *.desktop, найденные в следующих каталогах:
/.config/autostart/ по умолчанию)
Пользователи могут переопределять общесистемные файлы *.desktop скопировав их в пользовательский каталог
Для более конкретного описания используемых каталогов смотрите спецификацию автозапуска ярлыков приложений.
Изменение переменных среды
Как добавить ярлык (.desktop) в док-станцию Ubuntu 18.10
Добавить ярлыки в Ubuntu 18.10
Разрешить запускать как программу
Добавить ярлык в док
Мы также можем создавать доступы для выполнения файлов
В красных квадратах у нас есть два доступа, которые у меня есть сейчас. Второй для конвертировать изображения в JPG и измените их размер до 830 пикселей в ширину, что лучше всего подходит для этого формата и размера здесь, в Ubunlog. Для этого второго доступа, сколько бы вы ни добавили в строку Exec Я не уловил две команды, поэтому я сделал ярлык, который запускал простой файл, содержащий обе команды. Если вам интересно, этот текстовый файл требует, чтобы мы только предоставили ему разрешения на запуск в качестве программы, и он имеет следующий текст:
Значение второй строки поясняется в ссылку: с ImageMagick установлен (по умолчанию в Ubuntu), это означает «для файлов, находящихся внутри папки в формате PNG, измените размер до 830 пикселей в ширину и преобразуйте файл в формат JPG.«. Я использую его несколько раз в день, поэтому стоит сохранить ваш ярлык в Dock.
Какие ярлыки у вас есть или вы добавите в док?
Содержание статьи соответствует нашим принципам редакционная этика. Чтобы сообщить об ошибке, нажмите здесь.
Полный путь к статье: Убунлог » Ubuntu » Как добавить ярлык (.desktop) в док-станцию Ubuntu 18.10
Ubuntu Documentation
Introduction
Unity Launchers are actually files stored in your computer, with a ‘.desktop’ extension. In earlier Ubuntu versions, these files were simply used so as to launch a specific application, but in Unity they are also used so as to create right-click menus for each application, which you can access from the Unity Launcher.
There are currently 2 ways of creating a desktop file. The 1st one is using a text editor, like Gedit, and the 2nd one is installing a program (gnome-panel) or using ‘alacarte’ that both do the job for you. The former lets you «control» your launcher more than the latter, but the latter way is easier. Please note that this section will cover only the basics, not how to add shortcuts to your launcher. For this, please head to Adding shortcuts to a launcher.
Using a text editor
Open your favourite text editor, like Gedit or nano, and type in (copy and paste):
These lines are enough for describing a simple launcher. Each launcher (.desktop file) consists of some basic fields.
Name is the name of the application, like ‘VLC media player’.
Comment is a phrase or two describing what this program does, like ‘Plays your music and videos files’.
Icon field is the icon that should be used by the launcher and represents the application. All icons that are under the directory /usr/share/pixmaps don’t need to have their full path specified, but their filename without the extension. For example, if the icon file is /usr/share/pixmaps/wallch.png, then the Icon field should be just ‘wallch’. All other icons should have their full path specified.
Terminal field specifies whether the application should run in a terminal window or not.
Type field specifies the type of the launcher file. The type can be Application, Link or Directory, but this article covers the ‘Application’ type.
Categories field specifies the category of the application. It is used by the Dash so as to categorize the applications. A launcher being a ‘Utility;Application;’ should be under the ‘Accessories’ section etc.
Same file with executable permissions:
Using gnome-panel/alacarte
It is important to install gnome-panel using the following command, so as not to install the recommended not-needed packets along with it. So open a terminal using Ctrl+Alt+T and give the following command:
It will ask you for your login password, which you have to fill (nothing will be shown, not even asterisks (*)) and press enter.
Without closing the terminal window, after the installation process is over, you have to type the following command:
/Desktop/’ is any directory you want your launcher to appear, after its creation process is over. After running this command, a familiar window will pop-up, which lets you fill the Name, the Command and the Comment for your launcher. Also, you can specify an icon for your launcher by clicking on the big icon of the window on the top left of it.
You can also use ‘alacarte’, which you can execute by searching in the Dash for ‘Main Menu’ and once the application launches, then you click on «New Item» on the section you want your application to be. Then a window similar to the one being shown using the gnome-panel method will be shown.
Editing an entry of the Unity Launcher
Editing its main characteristics
/.local/share/applications/ or under /usr/share/applications/. Usually, if you have made a desktop launcher, it is under
/.local/share/applications, but any other application launcher that belongs to an application you have installed to your computer should be under /usr/share/applications. So, in order to edit this launcher, open a terminal using Ctrl+Alt+T and give the following:
where ‘gedit’ you can use your favourite text editor. The following command will ask you for password. Type in your login password and gedit (or any other text editor) will open with the launcher file you wish to edit. To edit the launcher go to ‘Using a text editor’ where it says it clearly on how to create a launcher and the same applies on editing it.
Adding shortcuts to a launcher
Some applications become much more usable with a right-click menu. This is an example of shortcuts, being used by the application ‘Wallch’:
In this example, the program ‘audacious’, which is a music player available in the Ubuntu Software Center, will be used as an example of adding shortcuts.
After adding the main characteristics of a launcher, such as filling its ‘Name’ and ‘Exec’ fields, then you can add to it one or more shortcuts.
The part that has to do with the shortcuts is everything after ‘Actions=’ including this. Everything specified on the ‘Actions’ field has its own name, specified on the ‘Name’ field of each one. For example, action PlayPause has name Play-Pause, and thus Play-Pause will be displayed on the shortcut in the Unity Launcher once you right click the icon of ‘audacious’. Clicking on a shortcut will result on the corresponding action, which means it will execute anything specified in the corresponding ‘Exec’ field. Each action has its own ‘Exec’ field, aside from the ‘Exec’ field specified at the beginning of the file which refers to the action that will take place when you click on the launcher.
Making such shortcuts for applications is generally very easy, unless the application itself doesn’t provide enough command line arguments so as to do a corresponding action you would like to. The arguments and what each one does for every application are available through their man page. For example, the arguments ‘-t’, ‘-f’ and ‘-r’ of ‘audacious’, used on the above example were found though its manual page, using the command
A thread for discussion of this wiki can be found on the forum at http://ubuntuforums.org/showthread.php?t=2012385
UnityLaunchersAndDesktopFiles (последним исправлял пользователь vperetokin 2013-06-19 02:10:14)
The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details
Программа для создания desktop-файлов
Немного о desktop-файлах
Вот пример desktop-файла для консольной игры nsnake:
Тут и так все понятно, но я все-таки прокомментировал пару позиций. Самое главное, что нужно прописать это название приложения (Name), путь до исполняемого файла (Exec) и путь до иконки (Icon). Если иконки нет и нет желания ее искать или создавать, то некоторые окружения рабочего стола установят иконку по умолчанию.
Краткое описание
Исходники приложения находятся здесь. Программа довольно простая. Выглядит она вот так:
Нужно заполнить необходимые поля, отметить нужные чекбоксы и нажать кнопку CREATE. Программа запросит подтверждение и после согласия оповестит об успешном или неуспешном создании файла.
В хидербаре находится кнопка, при нажатии на которую в файловом менеджере откроется папка, находящаяся по пути /.local/share/applications. Именно там программа сохраняет созданные файлы.
Как работает
Приложение написано на языке Vala с помощью среды разработки GNOME Builder. Устанавливал самую свежую версию среды (40.0) из репозитория Flathub. Оказалось, что визуальный дизайнер в этой версии еще багованнее, чем в предыдущей, поэтому интерфейс делал в Glade.
После того как созданы значки в полях ввода и к ним, также как и к другим кнопкам, привязаны необходимые действия, записываем в переменную directory_path путь до папки с desktop-файлами. Также на всякий случай надо проверить наличие этой папки перед запуском приложения и если папка по каким-то причинам отсутствует, то вывести специальное сообщение и деактивировать кнопку CREATE, так как в этом случае в ней нет необходимости.
При нажатии на кнопку CREATE вызывается метод on_create_file:
Он предназначен для проверки ввода имени файла и проверки возможных совпадений с именами уже существующих в папке файлов, а также для вывода запроса подтверждения на создание файла. Если все проверки пройдены и пользователь подтвердил создание файла, то вызывается метод create_desktop_file:
Чтобы просмотреть готовые файлы существует метод on_open_directory. Он срабатывает при нажатии на кнопку в хидербаре.
Для выбора исполняемого файла используется следующий код:
А для выбора иконки код сложнее, так как данный диалог, помимо фильтра, содержит функционал предварительного просмотра изображения:
Метод для вывода сообщений пользователю:
Чтобы проверить введено ли какое-либо значение в текстовое поле используется такой метод:
На этом все! Надеюсь, что пост был для Вас полезен.
Дополнительная ссылка на SourceForge. До встречи в следующих постах!
How to create Desktop launchers
A “.desktop” file is basically a simple text file that holds information about a program. It is usually placed in “
/.local/share/applications” or “/usr/share/applications/” depending whether you want the launcher to be accessible only for local account or for everyone. If you navigate to either directory in your File manager, you will see quite a few “.desktop” files that correspond to the installed apps on your computer.
The only way to get the latest and greatest release is by downloading a tar archive, extracting it and executing a file which will launch the game.
You can follow along with whatever program you want to create a launcher for and it should work the same way.
Note: The following steps assume you have the archive for the program you want to create a launcher for in your “Downloads” folder.
1. Navigate to the directory where the archive is stored, right-click it and select “Extract here”.
2. Once the extraction is complete, Change to the newly created folder and find the executable. One you find it, right-click it click “Run” to launch the program, just to make sure it is working.
3. In some cases, you won’t see the “Run” option in the menu. This is often because the executable is a text file. You can get around this by executing it via the terminal or, if you use GNOME, click the Files menu in the top bar, and select “Preferences”.
4. Select the “Behavior” tab and choose the “Run them” option under “Executable Text Files”. Now the “Run” option should appear when you right-click the executable text file.
5. If you’ve confirmed that the application works when you launch it, you can exit it. Then launch your text editor and paste the following into the empty text file:
You need to change the “Exec” field to the path to the executable and “Name” field to the name of the application. Most programs would provide an icon somewhere in the archive so don’t forget to include that as well. In my case, the launcher file for Super Tux Kart looks like this:
6. Save the file in “
/.local/share/applications” folder as “application-name.desktop”. The “.local” folder is a hidden folder in your Home directory and you will have enable “Show Hidden Files” mode to view it. If you want it to be globally accessible, run the following command in the terminal:
7. Once done, just open the Applications menu on your desktop, and the application will be right there to use.
The method described here should work on all mainstream Linux based operating systems. Here’s another screenshot showing Super Tux Kart in elementary OS’s application launcher (slingshot)
Feel free to leave a comment below if you found this tutorial helpful.
Never Miss Out
Receive updates of our latest tutorials.
Ayo Isaiah is a freelance writer from Lagos who loves everything technology with a particular interest in open-source software. Follow him on Twitter.
One comment
I tried doing the “sudo mv
/.local… ” command but it says “No such directory”. When i tried doing manually using copy and paste option, it gives error message saying permission denied because it is not trusted program. Hope you have solution for this issue 🙂
Comments are closed.
Popular Posts
How to Mount a Windows Share Folder on Linux
How to Mount Your iPhone as an External Drive in Ubuntu
How to Reset the Root Password in Linux
15 of the Best Linux Games in 2021
How to Combine PDF Files on Windows and Linux
8 Useful and Interesting Bash Prompts
8 Reasons to Switch from Windows to Linux
The Ultimate Guide to Apt and Apt-Get Commands
4 Ways to Hide Desktop Icons in Ubuntu
Affiliate Disclosure: Make Tech Easier may earn commission on products purchased through our links, which supports the work we do for our readers.