User:Wannacry/Sway

From ArchWiki

Sway (сокращенно от SirCmpwn's Wayland compositor [1]) совместимый с i3 Wayland композитор. В соответствии с официальным сайтом:

Sway is a tiling Wayland compositor and a drop-in replacement for the i3 window manager for X11. It works with your existing i3 configuration and supports most of i3's features, plus a few extras.
Sway - это тайловый Wayland композитор и замена оконному менеджеру i3. Sway совместим с конфигурациоонным файлом i3 и поддерживает большинство функций i3, а также добавляет несколько дополнительных.

Установка

Установите пакет sway. Разрабатываемая версия может быть установлена с помощью sway-gitAUR. Рекомендуется всегда обновлять wlroots перед обновлением sway.

Примечание: Любые проприетарные драйвера, включая NVIDIA, не поддерживаются. Sway может работать с драйвером NVIDIA 495 версии и выше, если Вы включите kernel mode setting и добавите параметр запуска --unsupported-gpu.

Вы также можете установить swaylock и swayidle для блокировки экрана.

Sway использует по умолчанию dmenu в качестве лаунчера, и foot как дефолтный эмулятор терминала. Рекомендуется установить эти пакеты перед запуском sway или изменить дефолтные лаунчер и терминал в конфигурационном файле.

Запуск

Для запуска Sway ему требуется доступ к клавиатуре, мыши и видеокарте. Набор этих устройств называется seat, как указано в sd-login(3).

В Arch Linux, Sway может получить доступ к seat при помощи

Если polkit установлен, Sway автоматически получит доступ к seat. Если polkit не установлен и Вы хотите использовать seatd вместо него, добавьте своего пользователя в группу seat и включите/запустите seatd.service, перелогинтесь и запустите Sway одним из указанных ниже способов.

Вручную

Для запуска просто напишите sway в консоли.

Автоматически после логина в TTY

Добавьте следующие строки в файл инициализации. (смотрите Command-line shell#Login shell):

if [ -z $DISPLAY ] && [ "$(tty)" = "/dev/tty1" ]; then
  exec sway
fi

Подробнее можно узнать здесь Xinit#Autostart X at login

При помощи экранного менеджера

Примечание: Sway официально не поддерживает запуск при помощи экранного менеджера.[2]

Файл сессии Sway расположен в /usr/share/wayland-sessions/sway.desktop. Он автоматически распознается современными экранными менеджерами, такими как GDM и SDDM.

Также возможен запуск Sway как пользовательского сервиса systemd с помощью экранного менеджера.

Также Вы можете использовать текстовый менеджер сессий, смотрите Display manager#Console.

Настройка

Если Вы уже используете i3, Вы можете скопировать конфигурационный файл i3 в ~/.config/sway/config. Также можно скопировать образец конфигурационного файла из /etc/sway/config в ~/.config/sway/config. Подробности настройки описаны в sway(5).

Раскладка клавиатуры

По умолчанию sway запускается с раскладкой US QWERTY. Для настройки раскладки используйте:

~/.config/sway/config
input * {
    xkb_layout "us,de,ru"
    xkb_variant "colemak,,typewriter"
    xkb_options "grp:win_space_toggle"
}

input <identifier> xkb_model "pc101"

Детальное описание доступно в xkeyboard-config(7) и sway-input(5).

Также раскладка может быть указана при помощи переменных окружения (XKB_DEFAULT_LAYOUT, XKB_DEFAULT_VARIANT, и т.д) при запуске sway. Параметры, указанные в конфигурационном файле имеют приоритет над переменными окружения.

Задержка ввода

Для изменения задержки ввода добавьте следующие строки в секцию input:

~/.config/sway/config
input <identifier> repeat_delay 300
input <identifier> repeat_rate 30

Статусбар

Sway поставляется с swaybar по умолчанию, который запускается в чистом Wayland окружении. Для отображения информации swaybar может вызывать скрипт командной оболочки или другую программу. Смотрите sway-bar(5) и swaybar-protocol(7).


Совет: В качестве альтернативы swaybar можно использовать waybar.

Вместе с swaybar также можно использовать i3status. Для этого добавьте следующий фрагмент в конец конфигурационного файла sway:

~/.config/sway/config
bar {
    status_command i3status
}

Чтобы включить цветной вывод в i3status, необходимо настроить указанные параметры конфигурации i3status:

~/.config/i3status/config
general {
    colors = true
    interval = 5
}

Обои

Отображение обоев в sway обрабатывается программой, которая поставляется в отдельном пакете swaybg. Она необходима для запуска команды output.

Строка, указанная ниже, устанавливает обои на все экраны:

~/.config/sway/config
output "*" bg /path/to/image fill

Не забудьте заменить путь к изображению на реальный.

Также в качестве фона может использоваться сплошной цвет:

output * bg #000000 solid_color

Вы можете использовать azoteAUR в качестве фронтенда для swaybg.

Устройства ввода

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

~/.config/sway/config
input type:touchpad {
    tap enabled
    natural_scroll enabled
}

Для настройки конкретного тачпада, вместо type:touchpad используйте идентификатор устройства, который можно узнать с помощью swaymsg -t get_inputs.

Примечание: Вывод команды swaymsg -t get_inputs может содержать "\" для экранирования таких символов как "/" (т.е "2:14:ETPS\/2_Elantech_Touchpad"). Их необходимо удалить.

Дополнительную документацию а также такие опции как ускорение или отключение ввода можно найти в sway-input(5).

HiDPI

Set your displays scale factor with the output command in your configuration file. The scale factor can be fractional, but it is usually 2 for HiDPI screens.

~/.config/sway/config
output <name> scale <factor>

You can find your display name with the following command:

$ swaymsg -t get_outputs

Сочетания клавиш

Специальные клавиши on your keyboard can be used to execute commands, for example to control volume, monitor brightness or media players: Специальные клавиши могут использоваться для запуска команд, например для регулировки громкости, яркости монитора или управления медиа плеером:

~/.config/sway/config
bindsym XF86AudioRaiseVolume exec pactl set-sink-volume @DEFAULT_SINK@ +5%
bindsym XF86AudioLowerVolume exec pactl set-sink-volume @DEFAULT_SINK@ -5%
bindsym XF86AudioMute exec pactl set-sink-mute @DEFAULT_SINK@ toggle
bindsym XF86AudioMicMute exec pactl set-source-mute @DEFAULT_SOURCE@ toggle
bindsym XF86MonBrightnessDown exec brightnessctl set 5%-
bindsym XF86MonBrightnessUp exec brightnessctl set 5%+
bindsym XF86AudioPlay exec playerctl play-pause
bindsym XF86AudioNext exec playerctl next
bindsym XF86AudioPrev exec playerctl previous
bindsym XF86Search exec bemenu-run

Подробнее смотрите PulseAudio#Keyboard volume control, Advanced Linux Sound Architecture#Keyboard volume control, Backlight#Backlight utilities и MPRIS.

Чтобы сочетание клавиш работало когда экран заблокирован, добавьте параметр --locked к bindsym.

bindsym --locked XF86AudioPlay exec playerctl play-pause
Совет: wevAUR аналог программы xorg-xev для Wayland.
Note: Systemd handles some special keys like the power key and lid open as well as close events. These may interfere with the ones configured in sway. See loginctl(1) and logind.conf(5) for details on how to configure them in systemd.
Примечание: Systemd обрабатывает некоторые специальные клавиши, такие как кнопка питания и события открытия и закрытия крышки ноутбука. Они могут мешать тем, что настроены в sway. Смотрите loginctl(1) и logind.conf(5) для настройки их с помощью systemd.

Графическая панель индикаторов

It is often desirable to have the current level of some percentage-valued setting, such as brightness or volume, be indicated by a graphical bar when it is adjusted. A good option for providing this facility in Sway is wobAUR (alternatively wob-gitAUR), which provides a subset of the functionality of the popular X tool xobAUR but as a native Wayland utility implementing the layer-shell protocol. See the project website for usage examples. Часто желательно, чтобы текущий уровень какого-либо параметра, выраженного в процентах, например яркость или громкость, отображался на графической панели. Хорошим вариантом, предоставляющим такую возможность в Sway является wobAUR, который предоставляет функциональность популярной программы xobAUR. Смотрите примеры использования на сайте проекта.

Обзор рабочих пространств

sovAUR будет полезен тем, кто использует много рабочих пространств. Он предоставляет оверлей, отображающий схему всех рабочих пространств, что облегчает навигацию. Он показывает имена програм, заголовки окон, а также поддерживает несколько мониторов. Подробнее о нем смотрите на странице проекта.

Режим ожидания

Sway предоставляет демон swayidle для управления режимом ожидания. Есть несколько способов запустить и настроить демон. Самый простой - использовать конфигурационный файл sway. swayidle принимает множество аргументов для настройки таких событий как timeout (режим ожидания), resume (пробуждение из режима ожидания), before-sleep и т.д. Смотрите swayidle(1) чтобы узнать подробности. Каждому событию может быть назначено действие.

The following instructs swayidle to lock the screen after 30 minutes and turn it off five seconds after: Строки ниже настраивают swayidle на блокировку экрана после 30 минут и его отключение спустя 5 секунд после этого.

~/.config/sway/config
exec swayidle -w \
	timeout 1800 'swaylock -f' \
	timeout 1805 'swaymsg "output * dpms off"' \
	resume 'swaymsg "output * dpms on"'

Чтобы отключить заблокированный экран намного раньше, например, после 10 секунд, используйте swaymsg "output * dpms off", заменив swaylock на ваш менеджер блокировки:

timeout 10 'if pgrep -x swaylock; then swaymsg "output * dpms off"; fi'

In order to lock the screen before suspending and pause any playing media, amend the following instructions to the swayidle command:

before-sleep 'playerctl pause'
before-sleep 'swaylock'
Note: Systemd too handles some idle events which may conflict with the ones configured in sway. See loginctl(1) and logind.conf(5) for details on how to configure them.

Floating windows

To enable floating windows or window assignments, open the application and then use the app_id, the class, the instance and the title attributes to enable floating windows/window assignments. The following command will list the properties of all the open windows.

$ swaymsg -t get_tree

To get only the app_id's of all open windows use:

$ swaymsg -t get_tree | grep "app_id"

To get the app_id of the focused window use:

$ swaymsg -t get_tree | jq -r '..|try select(.focused == true)'

If the app_id happens to be null for some windows, you might have to use the class and/or the instance attributes to enable floating mode/window assignments. You can search the output and create fine grained rules for your windows.

~/.config/sway/config
for_window [app_id="galculator"] floating enable
assign [class="firefox"] -> 3
assign [class="^Urxvt$" instance="^htop$"] -> 9

This is similar to using xorg-xprop to find the class or wm_name attributes in X11.

When using multiple monitors, the floating scratchpad window can get too large, covering more than one monitor. This command centers and resizes the floating window to 80% of the current monitor's size:

$ swaymsg move position center; swaymsg resize set 80ppt 80ppt

Clipboard

This article or section is a candidate for merging with Clipboard.

Notes: Not specific to Sway. (Discuss in User talk:Wannacry/Sway)

By default, the clipboard is emptied whenever a window is closed. This can be a surprising default behaviour.

A "clipboard manager" must be installed to make the clipboard's content shared amongst windows.

One example of a clipboard manager, designed for Wayland, is clipman, which can be installed from clipmanAUR or clipman-gitAUR.

To start clipman with Sway, add the following line to your configuration file:

~/.config/sway/config
exec wl-paste -t text --watch clipman store --no-persist

Xresources

Copy ~/.Xresources to ~/.Xdefaults to use them in Sway.

XWayland

See Wayland#XWayland for details and an overview of available packages.

The use of XWayland is enabled by default.

If you would like to disable XWayland entirely and run a "pure" Wayland session, set the following to deactivate the use of XWayland:

~/.config/sway/config
xwayland disable
Note: Some programs need special environment variables or configuration options to run natively under Wayland, and other programs (including most proprietary applications) do not support Wayland at all. Currently it is recommended to keep XWayland on so that legacy applications can be used.

Use another wlroots renderer

You can use another wlroots renderer by specifying the WLR_RENDERER environment variable. The list of available ones is on the wlroots documentation.

Tips and tricks

Initially enable CapsLock/NumLock

By default, sway initially disables the CapsLock and NumLock keys on startup. To instead enable them on startup, set the xkb_capslock and/or xkb_numlock input configurations to enable for your keyboards. For example, to do so on all keyboards, add the following lines to your sway configuration:

~/.config/sway/config
input * xkb_capslock enable
input * xkb_numlock enable

In either case, the CapsLock and NumLock keys may be toggled by pressing the relevant keys on a keyboard.

Note: Enabling these using the wildcard identifier may cause Firefox to crash upon reloading your sway configuration file: Bugzilla 1652820. Try specifying the keyboard instead.

Current keyboard layout

The current keyboard layout can be retrieved as follows, where kbd_identifier needs to be replaced with your keyboard's identifier:

$ swaymsg -t get_inputs | jq -r '.[] | select(.identifier == "kbd_identifier") | .xkb_active_layout_name'

Compose key

To set up PrintScreen as the compose key:

$ swaymsg 'input * xkb_options compose:prsc'

The combinations for the compose key can also be configured in the XCompose file. Applications need to be restarted for this change to take effect.

This article or section needs expansion.

Reason: Explain what the following tip means (why is it useful). (Discuss in User talk:Wannacry/Sway)

You can look up key names in /usr/include/X11/keysymdef.h, or use the xev(1)-like debugger: xkbcli-interactive-wayland(1) (in /usr/lib/xkbcommon/).

Backlight toggle

To turn off (and on) your displays with a key (e.g. Pause) bind the following script in your Sway config:

#!/bin/sh
read lcd < /tmp/lcd
    if [ "$lcd" -eq "0" ]; then
        swaymsg "output * dpms on"
        echo 1 > /tmp/lcd
    else
        swaymsg "output * dpms off"
        echo 0 > /tmp/lcd
    fi

Screen capture and screen sharing

See Screen capture#Wayland.

Color temperature adjustment

See Backlight#Wayland.

Control swaynag with the keyboard

Swaynag, the default warning/prompt program shipped with sway, only supports user interaction with the mouse. A helper program such as swaynagmodeAUR may be used to enable interaction via keyboard shortcuts.

Swaynagmode works by first launching swaynag, then listening for signals which trigger actions such as selecting the next button, dismissing the prompt, or accepting the selected button. These signals are sent by launching another instance of the swaynagmode script itself with a control argument, such as swaynagmode --select right or swaynagmode --confirm.

Swaynagmode by default triggers the sway mode nag upon initialization, followed by default on exit. This makes it easy to define keybindings in your sway configuration:

~/.config/sway/config
set $nag exec swaynagmode
mode "nag" {
  bindsym {
    Ctrl+d    mode "default"

    Ctrl+c    $nag --exit
    q         $nag --exit
    Escape    $nag --exit

    Return    $nag --confirm

    Tab       $nag --select prev
    Shift+Tab $nag --select next

    Left      $nag --select next
    Right     $nag --select prev

    Up        $nag --select next
    Down      $nag --select prev
  }
}

Note that, beginning in sway version 1.2, mode names are case-sensitive.

You can configure sway to use swaynagmode with the configuration command swaynag_command swaynagmode.

Change cursor theme and size

To set the cursor theme and size:

~/.config/sway/config
seat seat0 xcursor_theme my_cursor_theme my_cursor_size

Where my_cursor_theme can be set to or replaced by a specific value like default, Adwaita or Simple-and-Soft, and my_cursor_size a value like 48.

You can inspect their values with echo $XCURSOR_SIZE and echo $XCURSOR_THEME.

Note that you need to restart the application to see the changes.

Note: Wayland uses client-side cursors. It is possible that applications do not evaluate the values of $XCURSOR_SIZE and $XCURSOR_THEME.

Manage Sway-specific daemons with systemd

Systemd provides a graphical-session.target which is a user unit which is active whenever any graphical session is running, whether Xorg or Wayland. User services which should run in all graphical environments can be bound to that target. It also allows for a window-manager-specific target to be bound to graphical-session.target to start and stop services which should run only under that window manager. See systemd.special(7)

Users may want to start some services/daemons (such as swayidle or kanshi) only when the current window manager is Sway, and they may also want these services to stop when Sway stops. Additionally, users who are running systemd-oomd.service(8) may want to have the services be in separate cgroups so that a single memory-hungry service does not take down the whole Sway session (see the Fedora bug report).

Some or all of this functionality is provided by Arch Sway packages. For example, the sway package in community provides the sway-session.target file and both sway and sway-gitAUR provide a 50-systemd-user.conf drop-in file for the /etc/sway/config.d/ directory. This file imports required environment variables into the systemd user session and dbus if the Sway config file contains include /etc/sway/config.d/*.

If you intend to provide functionality using the roll-your-own method described below or by using a specialist package such as sway-systemd-gitAUR or sway-services-gitAUR you should consider removing files that provide the same functionality.

This functionality can be provided on a roll-your-own basis by creating a sway-session.target and let those daemons/services wanted by sway-session.target. This systemd target should be a user target (see systemd/User). For example:

~/.config/systemd/user/sway-session.target
[Unit]
Description=Sway compositor session
Documentation=man:systemd.special
BindsTo=graphical-session.target
Wants=graphical-session-pre.target
After=graphical-session-pre.target

Then, add the following line to Sway's configuration file (for example, append the line to ~/.config/sway/config, or add a new file to /etc/sway/config.d/):

~/.config/sway/config
...
...
...
exec_always "systemctl --user import-environment; systemctl --user start sway-session.target"

With the above line in the configuration file, whenever Sway starts, it also activates sway-session.target.

Finally, link the desired services to sway-session.target. For example, adding a kanshi (or kanshi-gitAUR) service:

~/.config/systemd/user/kanshi.service
[Unit]
Description=Dynamic output configuration for Wayland compositors
Documentation=https://sr.ht/~emersion/kanshi
BindsTo=sway-session.target

[Service]
Type=simple
ExecStart=/usr/bin/kanshi

[Install]
WantedBy=sway-session.target

When this user unit is enabled, it is only activated when Sway is running and deactivated when Sway stops.

The creation of the sway-session.target file and the importing of the environment can also be accomplished by installing sway-systemd-gitAUR. In addition to separating services into cgroups, sway-systemd also places each GUI application in its own cgroup. This enables imposition of per-cgroup resource constraints on individual application. See the sway-systemd README.

Change screen resolution after start

You can use the graphical program wdisplaysAUR or the terminal program wlr-randrAUR to change the resolution, rotate and arrange displays.

Create headless outputs

Create outputs not related to a physical video interface, HEADLESS-1, HEADLESS-2, etc.:

$ swaymsg create_output

Print a description of the new output:

$ swaymsg -pt get_outputs | grep -A 10 HEADLESS

Configure the new output with the output command, for example:

~/.config/sway/config
output HEADLESS-1 {
pos 1920,0
mode 1280x720@75Hz
}

Troubleshooting

Application launchers

Tip: Sway's wiki also has a list of known application launchers.

i3-dmenu-desktop, dmenu, and rofi all function relatively well in Sway, but all run under XWayland and suffer from the same issue where they can become unresponsive if the cursor is moved to a native Wayland window. The reason for this issue is that Wayland clients/windows do not have access to input devices unless they have focus of the screen. The XWayland server is itself a client to the Wayland compositor, so one of its XWayland clients must have focus for it to access user input. However, once one of its clients has focus, it can gather input and make it available to all XWayland clients through the X11 protocol. Hence, moving the cursor to an XWayland window and pressing Escape should fix the issue, and sometimes running pkill does too.

bemenu is a native Wayland dmenu replacement which can optionally be combined with j4-dmenu-desktopAUR to provide a Wayland-native combination for launching desktop files (as i3-dmenu-desktop does):

j4-dmenu-desktop --dmenu='bemenu -i --nb "#3f3f3f" --nf "#dcdccc" --fn "pango:DejaVu Sans Mono 12"' --term='termite'

You may need to set BEMENU_BACKEND environment variable to "wayland" if you choose not to disable XWayland.

You can also build your own with a floating terminal and fzf as discussed in a GitHub issue.

Also krunner binary provided by plasma-workspace package can serve as launcher, offering both XWayland and native Wayland support.

rofi-lbonn-wayland-gitAUR is a fork of rofi that works in Wayland and also has an -x11 flag if you need to launch it in an X11 session.

wofi is a command launcher, that provides some of the same features as rofi but running under Wayland. wofi lacks some features from rofi like an SSH mode and a window-switching mode. It is based on wlroots library and use GTK3 for rendering. It works pretty well with sway.

Virtualization

Sway works with both VirtualBox and VMware ESXi.

For Sway to work in QEMU, QEMU must be started with -vga qxl. See also QEMU#qxl.

Unable to start Sway from tty

For ESXi, you need to enable 3D support under the Hardware Configuration > Video card settings. See also VMware#Enable 3D graphics on Intel, Optimus and AMD.

No visible cursor

When using certain graphics drivers (e.g. the VMSVGA graphics controller or the proprietary NVIDIA driver), the cursor is invisible. This can be fixed by using software cursors as discussed in [3]:

$ export WLR_NO_HARDWARE_CURSORS=1

Sway socket not detected

Using a swaymsg argument, such as swaymsg -t get_outputs, will sometimes return the message:

sway socket not detected.
ERROR: Unable to connect to

when run inside a terminal multiplexer (such as gnu screen or tmux). This means swaymsg could not connect to the socket provided in your SWAYSOCK.

To view what the current value of SWAYSOCK is, type:

$ env | fgrep SWAYSOCK
SWAYSOCK=/run/user/1000/sway-ipc.1000.4981.sock

To work around this problem, you may try attaching to a socket based on the running sway process:

$ export SWAYSOCK=/run/user/$(id -u)/sway-ipc.$(id -u).$(pgrep -x sway).sock

To avoid this error, run the command outside of a multiplexer.

Unable to retrieve socket path

Requesting messages from swaymsg -t on a tty may return the following message:

Unable to retrieve socket path

SWAYSOCK environment variable is set after launching Sway, therefore a workaround to this error is to request swaymsg -t [message] in a terminal inside Sway.

Keybindings and keyboard layouts

By default, if you are using more than one keyboard layout, e.g. input * xkb_layout "us,ru", bindings may become broken when you switch on some secondary layout.

Thanks to https://github.com/swaywm/sway/pull/3058, all you need is to add --to-code key to sensitive bindsym lines like this:

bindsym --to-code {
  $mod+$left focus left
  $mod+$down focus down
  $mod+$up focus up
  $mod+$right focus right
}

Alternatively you can create a variable set $mybind bindsym --to-code and then replace all instances of bindsym with $mybind like so: $mybind $mod+w thing

Java applications

Some Java-based applications will display blank screen when opened, for example any JetBrains editor such as IntelliJ, CLion, or PyCharm. To mitigate this, the application can be started with the _JAVA_AWT_WM_NONREPARENTING environment variable set to 1.

If you start the application from a launcher like rofi or dmenu, you might want to modify the application desktop entry as shown in Desktop entries#Modify environment variables.

Some issues with Java applications have been fixed in OpenJDK 11 and Sway 1.5. However, certain applications require additional configuration to use newer versions of OpenJDK, in the case of Android Studio you must set STUDIO_JDK=/usr/lib/jvm/java-11-openjdk/. [4]

Scroll on border

If using the mouse scroll wheel on an application's border crashes sway, you could use border none for the app_id (e.g. Firefox).

Program cannot open display

If a program crashes on start with the error message "cannot open display", it is likely that the program you are using is an X11 program. You can use the XWayland compatibility layer to run X11 programs under Wayland, see #XWayland for details.

See also