Electron🔗
Due to the nature of Electron, building Electron applications as Flatpaks requires a few extra steps compared with other applications. Thankfully, several tools and resources are available which make this much easier.
В этом руководстве представлена информация о том, чем создание приложений Electron отличается от других приложений. Он также включает информацию об инструментах для создания приложений Electron и о том, как их использовать.
The guide walks through the manifest file of the sample Electron Flatpak application. Before you start, it is a good idea to take a look at this, either online or by downloading the application.
Сборка образца приложения🔗
Хотя в этом нет строгой необходимости, вы можете попробовать создать и запустить образец приложения самостоятельно.
To get setup for the build, download or clone the sample app from GitHub, and navigate to the project directory in the terminal. Then to build:
$ flatpak-builder build org.flathub.electron-sample-app.yml --install-deps-from=flathub --force-clean --user --install
Наконец, приложение можно запустить с:
$ flatpak run org.flathub.electron-sample-app
Базовая конфигурация🔗
В первой части манифеста демонстрационного приложения указывается идентификатор приложения. Он также настраивает среду выполнения и SDK:
id: org.flathub.electron-sample-app
runtime: org.freedesktop.Platform
runtime-version: '24.08'
sdk: org.freedesktop.Sdk
Среда выполнения Freedesktop, как правило, является лучшей средой выполнения для использования с приложениями Electron, поскольку это минимальная среда выполнения, а другие зависимости будут специфичными для самого Electron.
The Electron BaseApp🔗
Next, the manifest specifies that the Electron BaseApp should be used, by
specifying the base and base-version properties in the application
manifest:
base: org.electronjs.Electron2.BaseApp
base-version: '24.08'
BaseApps are described in Зависимости. Using the Electron base app is much faster and more convenient than manually building Electron dependencies. It also has the advantage of reducing the amount of duplication on users“ machines, since it means that Electron is only saved once on disk.
Расширение SDK для Node.js🔗
Чтобы создавать приложения на основе Electron, вам понадобится Node.js, доступный во время сборки. Flathub предоставляет версии LTS для Node.js в качестве расширений для SDK, поэтому вы можете установить одну из них и добавить ее в манифест приложений:
sdk-extensions:
- org.freedesktop.Sdk.Extension.node18
Включите расширение, добавив его в «PATH»:
build-options:
append-path: /usr/lib/sdk/node18/bin
Обратите внимание, что имя расширения (последняя часть нотации обратного DNS, «node18» в этом примере) должно быть одинаковым в «sdk-extensions» и «append-path».
Command🔗
Свойство command указывает, что для запуска приложения должен быть выполнен сценарий с именем run.sh. Это будет объяснено более подробно позже.
command: run.sh
Разрешения песочницы🔗
The standard sandbox Рекомендации по разрешениям also apply to Electron applications. However, Electron’s Wayland support is still experimental. So for display access, only X11 should be used as the default configuration. This will make Electron use Xwayland in a Wayland session and nothing else is required.
The sample app also configures PulseAudio for sound and enables network access:
finish-args:
- --share=ipc
- --device=dri
- --socket=x11
- --socket=pulseaudio
- --share=network
- --env=ELECTRON_TRASH=gio
To allow experimental native Wayland support in Electron>=20, the
--ozone-platform-hint=auto flag can be passed to the program. auto
will choose Wayland when the current session is running under Wayland and
Xwayland or X11 otherwise.
It’s recommended to leave actually enabling Wayland up to the user for now,
i.e. set --socket=x11 in the manifest. Wayland can then be tested with:
flatpak run --socket=wayland org.flathub.electron-sample-app
Enable native Wayland support by default🔗
Примечание
Native Wayland support in Electron is still experimental and often unstable. It is advised to stick with the X11/Xwayland configuration above as the default.
To make native Wayland the default for users, --socket=fallback-x11
and --socket=wayland must be used in the manifest.
For Electron versions between 17 and 27, client-side window decorations under
native Wayland can be enabled by passing
--enable-features=WaylandWindowDecorations to the program. For newer
versions of Electron , this isn’t necessary anymore.
Electron uses libnotify on Linux to provide desktop notifications.
Since version 0.8.0 libnotify
automatically uses the notification portal
when inside a sandboxed environment and --talk-name=org.freedesktop.Notifications
is not required anymore. org.electronjs.Electron2.BaseApp includes
libnotify>=0.8.0 since branch/23.08.
To ensure proper mouse cursor scaling on HiDPI displays under Wayland, the
XCURSOR_PATH environment variable must be set to the host’s corresponding
directories:
finish-args:
- --env=XCURSOR_PATH=/run/host/user-share/icons:/run/host/share/icons
Using correct desktop file name🔗
It’s important for Linux applications to set the correct desktop file name. If not, it can lead to problems like missing the window icon under Wayland.
By default Electron uses {appname}.desktop as desktop file name. In Flatpak the name of the desktop file must be the id of the Flatpak.
To tell Electron to use another name you need to set the desktopName key in your package.json e.g. "desktopName": "com.example.MyApp.desktop".
In case you repack a binary, you can use the patch-electron-desktop-filename tool included in the BaseApp.
Each Electron binary ships with resources/app.asar file.
You need to call patch-desktop-filename with this file as argument.
If your application is installed under ${FLATPAK_DEST}/my-app you need to run patch-desktop-filename ${FLATPAK_DEST}/my-app/resources/app.asar.
Варианты сборки🔗
Эти параметры сборки не являются обязательными, но могут быть полезны, если что-то пойдет не так. env позволяет установить массив переменных среды, в этом случае мы устанавливаем NPM_CONFIG_LOGLEVEL на info, чтобы npm давал нам более подробные сообщения об ошибках.
build-options:
cflags: -O2 -g
cxxflags: -O2 -g
env:
NPM_CONFIG_LOGLEVEL: info
Модуль приложения🔗
Последний раздел манифеста определяет, как должен быть построен модуль приложения. Здесь можно найти дополнительную логику для Electron и Node.js.
По умолчанию flatpak-builder не разрешает инструментам сборки доступ к сети. Это означает, что инструменты, которые полагаются на источники загрузки, не будут работать. Поэтому пакеты Node.js необходимо загрузить до запуска сборки. Установка переменной окружения electronic_config_cache означает, что они будут найдены при сборке.
Следующая часть манифеста описывает, как должно быть создано приложение. Используется опция simple buildsystem, которая позволяет указать последовательность команд, используемых для сборки. Также указывается место загрузки и хеш приложения.
name: electron-sample-app
buildsystem: simple
build-options:
env:
XDG_CACHE_HOME: /run/build/electron-sample-app/flatpak-node/cache
npm_config_cache: /run/build/electron-sample-app/flatpak-node/npm-cache
npm_config_nodedir: /usr/lib/sdk/node18
npm_config_offline: 'true'
subdir: main
sources:
- type: archive
url: https://github.com/flathub/electron-sample-app/archive/1.0.1.tar.gz
sha256: a2feb3f1cf002a2e4e8900f718cc5c54db4ad174e48bfcfbddcd588c7b716d5b
dest: main
Объединение пакетов NPM🔗
В следующей строке показано, как модули NPM объединяются как часть Flatpaks:
- generated-sources.json
Поскольку даже простые приложения Node.js зависят от десятков пакетов, было бы нецелесообразно указывать их все как часть файла манифеста. Поэтому был разработан скрипт Python для загрузки пакетов Node.js с помощью NPM или Yarn и включения их в исходный код приложения.
Для скрипта Python требуется файл package-lock.json (или yarn.lock). Этот файл содержит информацию о пакетах, от которых зависит приложение, и может быть сгенерирован запуском npm install --package-lock-only из корневого каталога приложения. Затем скрипт запускается следующим образом:
$ flatpak-node-generator npm package-lock.json
Это генерирует манифест JSON, необходимый для сборки пакетов NPM/Yarn для приложения, которые выводятся в файл с именем generated-sources.json. Содержимое этого файла можно скопировать в манифест приложения, но, поскольку он часто очень длинный, часто лучше сделать ссылку на него из основного манифеста, что делается путем добавления generated-source.json в качестве строка в разделе манифеста, как показано выше.
Запуск приложения🔗
The Electron app is run through a simple shell script that wraps
zypak. This script can be given any name
but must be specified in the manifest’s command property. See below for a
sample wrapper to launch the app:
- type: script
dest-filename: run.sh
commands:
- zypak-wrapper /app/main/electron-sample-app "$@"
Команды сборки🔗
Last but not least, since the simple buildsystem is being used, a list of
build commands must be provided. As can be seen, npm is run with the
npm_config_offline=true environment variable, installing dependencies from
packages that have already been cached. These are copied to /app/main/.
Finally the run.sh script is installed to /app/bin/ so that it will be
on $PATH:
build-commands:
# Install npm dependencies
- npm install --offline
# Build the app; in this example the `dist` script
# in package.json runs electron-builder
- |
. ../flatpak-node/electron-builder-arch-args.sh
npm run dist -- $ELECTRON_BUILDER_ARCH_ARGS --linux --dir
# Bundle app and dependencies
- cp -a dist/linux*unpacked /app/main
# Install app wrapper
- install -Dm755 -t /app/bin/ ../run.sh
Обратите внимание: если приложение, которое вы пытаетесь упаковать, содержит блок build в package.json с инструкциями для Linux, это может привести к тому, что electron-builder попытается получить дополнительные двоичные файлыво время сборки. (Даже если используется опция –dir). В следующем примере показана конфигурация, которая попытается загрузить двоичные файлы AppImage:
"build": {
"linux": {
"target": "AppImage",
}
}
Предпочтительный способ исправить это - не патч, а редактирование во время сборки с использованием jq. Следующая команда заменит "target": "AppImage" на "target": "dir":
jq '.build.linux.target="dir"' <<<$(<package.json) > package.json
Make setProgressBar and setBadgeCount work🔗
The setProgressBar and setBadgeCount functions allow showing a progress bar and a badge count in the window icon. It is implemented under Linux using the UnityLauncherAPI. This API is not implemented on every desktop environment. A known desktop environment which implements this is KDE. It is also implemented by the popular Dash to Dock GNOME extension and Plank.
To make it work in Flatpak, the app needs to use the correct desktop filename in its embedded package.json file. The Flatpak also needs the --talk-name=com.canonical.Unity permission. Electron versions earlier than v32 checks checks if it’s running on Unity or KDE before using the UnityLauncherAPI.