User:Soyuz2012/Sway (Русский)

From ArchWiki
Jump to navigation Jump to search

sway - i3-совместимый композитор Wayland.


Установите пакет sway. Чтобы получить версию для разработчиков, установите пакеты wlroots-gitAUR и sway-gitAUR. Крайне рекомендуется обновлять wlroots при обновлении sway из-за жестких зависимостей.

Примечание: Пропиетарные драйвера не поддерживаются

Опционально можно установить swaylock и swayidle для возможности блокировки экрана и настройки менеджера простоя.

По умолчанию в качестве средства запуска приложений используется dmenu (по умолчанию вызывается комбинацией Win+d), в качестве эмулятора терминала используется alacritty (по умолчанию вызывается комбинацией Win+Enter). Перед запуском sway рекомендуется заранее установить dmenu и alacritty, или же сменить значения по умолчанию в конфигурационном файле.



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

Автоматически при входе в TTY

Sway можно запускать автоматически без использования экранных менеджеров, с помощью добавления следующих строк в файл иницилизации оболочки ~/.bash_profile для bash, ~/.zlogin или ~/.zprofile для zsh:

if [ "$(tty)" = "/dev/tty1" ]; then
	exec sway

Если используется оболочка fish, создайте файл ~/.config/fish/conf.d/

set TTY1 (tty)
if test -z "$DISPLAY"; and test $TTY1 = "/dev/tty1"
  exec sway

Для подробностей см. Command-line shell#Login shell и Xinit#Autostart X at login.

С помощью экранного менеджера

Примечание: Sway оффициально не поддерживает экранные менеджеры [1]

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

Также возможно запустить sway в качестве пользовательского сервиса systemd без использования дисплейного менеджера, но этот способ не поддерживается разработчиками и не рекомендуется.

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


Вы можете скопировать пример конфигурационного файла sway или свой существующий конфигурационный файл i3 в ~/.config/sway/config. Пример конфигурационного файла находится в /etc/sway/config, если не установлен флаг DFALLBACK_CONFIG_DIR. См. sway(5) для получения информации о конфигурации.


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

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).

The keymap can also be configured using environment variables (XKB_DEFAULT_LAYOUT, XKB_DEFAULT_VARIANT, etc.) when starting sway, with config options taking precedence over environment variables.

Typematic delay and rate

To change typematic delay and rate, you can add the following lines to your input section:

input <identifier> repeat_delay 300
input <identifier> repeat_rate 30


sway ships with a default status bar in the form of swaybar which runs in a pure Wayland environment. swaybar can call a shell script or other program to show information in the status bar. See sway-bar(5) and swaybar-protocol(7) for details.

Installing the program i3status is an option to obtain a practical, default status bar under Wayland. All you have to do is add the following snippet at the end of your sway config:

bar {
    status_command i3status

If you want to achieve colored output of i3status, you can adjust following part in the i3status configuration:

general {
    colors = true
    interval = 5

In both examples, the system-wide installed configuration files have been copied over to the user directory and then modified.

Совет: waybar is an alternative to the bar included with sway (swaybar).

Обои рабочего стола

Since release 1.1.1 the wallpaper part of the SwayWM project was moved to swaybg, which is needed in order to run the output command.

This line, which can be appended at the end of your sway configuration, sets a background image on all displays (output matches all with name "*"):

output "*" bg /path/to/image fill

Of course you have to replace the file name and path according to your wallpaper.

You may use azoteAUR as the GTK3 frontend to swaybg.

Solid colors may be set as follows:

output * bg #000000 solid_color

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

It is possible to tweak specific input device configurations. For example, to enable tap-to-click and natural scrolling for all touchpads:

input type:touchpad {
    tap enabled
    natural_scroll enabled

To set configuration for a particular touchpad, use swaymsg -t get_inputs to obtain a device identifier and use it instead of type:touchpad. For example, to set pointer acceleration:

input "2:14:ETPS/2_Elantech_Touchpad" pointer_accel 0.2
Примечание: The output from the swaymsg -t get_inputs command may contain "\" to escape symbols like "/" (e.g. "2:14:ETPS\/2_Elantech_Touchpad") and it needs to be removed.

More documentation and options like acceleration profiles can be found in sway-input(5).


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

output <name> scale <factor>

You can find your display name with the following command:

$ swaymsg -t get_outputs

Custom keybindings

Special keys on your keyboard can be used to execute commands, for example to control volume, monitor brightness or media players:

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

See PulseAudio#Keyboard volume control, Advanced Linux Sound Architecture#Keyboard volume control, Backlight#Backlight utilities and MPRIS for details and alternative utilities.

To allow a keybinding to be executed while the lockscreen is active add the --locked parameter to bindsym.

bindsym --locked XF86AudioPlay exec playerctl play-pause
Совет: wevAUR is a tool which provides functionality similar to that of xorg-xev, but on Wayland.

Graphical indicator bars

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.

Плавающие окна

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.

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.


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


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

XWayland включен по умолчанию.

Если хотите полностью выключить XWayland и запустить "чистую" сессию Wayland, добавьте следующую строку в ~/.config/sway/config для выключения XWayland:

xwayland disable
Примечание: 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.

Tips and tricks

Enable CapsLock/NumLock

Enable the capslock and/or numlock by adding the following lines to your sway config

input * xkb_capslock enable
input * xkb_numlock enable
Примечание: Enabling these options may cause Firefox to crash upon reloading your sway config file: Bugzilla 1652820

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'

Backlight toggle

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

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

Снимки и демонстарция экрана

См. Screen capture#Wayland.

Регулировка цветовой температуры

См. 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:

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.

Изменение темы и размера курсора

To set the cursor theme and size:

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.

Примечание: Wayland uses client-side cursors. It's possible that applications do not evaluate the values of $XCURSOR_SIZE and $XCURSOR_THEME.

Решение проблем

Application launchers

Совет: 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.


Sway works with both VirtualBox and VMware ESXi.

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 and Optimus.

No visible cursor

When using the VMSVGA graphics controller, the cursor is invisible. This can be fixed by using software cursors as discussed in [2]:


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

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, 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 Intellij editor. 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-amd64/. [3]

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.

См. также