Jump to content

# Dunst (Русский)

3 languages

- English
- 日本語
- Polski

From ArchWiki
Состояние перевода: На этой странице представлен перевод статьи Dunst. Дата последней синхронизации: 4 июля 2023. Вы можете помочь синхронизировать перевод, если в английской версии произошли изменения.

Ссылки по теме

- Desktop notifications

Dunst — это легковесная альтернатива для демонов уведомлений, предоставляемых большинством сред рабочего стола.

## Установка

Установите пакет dunst.

Пример конфигурационного файла включен в `/etc/dunst/dunstrc`. Скопируйте этот файл в `~/.config/dunst/dunstrc` и отредактируйте его соответствующим образом.

Запустите `/usr/bin/dunst` и убедитесь, что ваш оконный менеджер или среда рабочего стола запускает его при запуске/входе в систему.

Примечание: Может показаться, что нет необходимости вручную запускать dunst, поскольку он может быть автозапущен dbus-daemon, когда программы отправляют уведомления через D-Bus. Однако, служба уведомлений часто имеет несколько демонов, и нет способа узнать, какой демон будет автозапущен. Сопровождающие dbus-daemon предупреждают, что не стоит полагаться на автозапуск для служб с несколькими провайдерами.

## Оформление

Тексту в уведомлениях можно придать определенный стиль. Некоторые примеры: жирный шрифт, курсив, зачеркивание и подчеркивание. Полное описание см. в Разметка Pango. Pango может быть удален из уведомлений, если `markup` установлен в `none`.

Можно задать форматирование уведомления следующими параметрами:

    %a  (application) приложение
    %s  (summary) заголовок
    %b  (body) основное тело
    %i  (iconname) имя иконки, включая путь
    %I  (iconname) имя иконки, исключая путь
    %p  (progress) прогресс (если установлен от [  0%] до [100%]) или ничего

Их можно использовать в сочетании с HTML-разметкой. Например, `format` можно задать как `<b>%s</b>\n%b` для выделения жирным шрифтом заголовка уведомления, переноса строки и неформатированного основного тела.

### Наборы иконок

Наборы иконки задаются параметром `icon_path` в разделе `global` конфигурационного файла. Используются `status`, `devices` и `legacy`. По умолчанию Dunst использует gnome-icon-themeAUR. Например, переключение на adwaita-icon-theme (который наследует gnome-icon-themeAUR) следует указать так:

    icon_path = /usr/share/icons/Adwaita/16x16/status/:/usr/share/icons/Adwaita/16x16/devices/:/usr/share/icons/Adwaita/16x16/legacy/

В разделе `global` вместо указания пути к директории с набором иконок можно использовать название темы. В этом случае необходимо установить `enable_recursive_icon_lookup=true`, чтобы включить поиск во вложенных директориях темы:

    icon_theme = Papirus
    enable_recursive_icon_lookup = true

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

Dunst можно управлять с помощью dunstctl. Вы можете изменить сочетания клавиш для вызова dunstctl.

Например, для закрытия всех оповещений:

    $ dunstctl close-all

Для показа истории:

    $ dunstctl history-pop

## Rules

Эта статья или раздел нуждается в переводе

Примечания: Перевод этот статьи только начат (обсуждение: Talk:Dunst (Русский)#)

You can create rules in your dunstrc file which match certain notifications and then perform an action on it such as executing a script.

### Filtering

To create a new rule, create a new section with a custom name in your configuration file. In that section you can now use the attributes appname, summary, body, icon, category, match_transient and msg_urgency to match the notification. Globbing is supported. See Scripting for an example. Start dunst with the `-print` option to find out useful information about a notification to write proper rules.

### Modifying

When a notification is matched you can perform certain actions on it like modifying the format string, which is especially useful if you want to completely ignore certain notifications. In that case simply add the line `format=""` to your rule.

Another useful feature is if you want to keep certain notifications out of your history for example if you use dunst as a Volume indicator. To achieve this simply add `history_ignore=yes` to your rule.

### Scripting

Dunst can be configured to run scripts based on certain notification content. Here is an example using Dunst to run a script when someone from pidgin signs on:

    [signed_on]
       appname = Pidgin
       summary = "*signed on*"
       urgency = low
       script = do_something.sh

The specified script will be passed the following parameters in that order: appname, summary, body, icon, urgency.

## Disable dunst temporarily

To disable dunst temporarily there are two options.

Use `dunstctl`
  You can use `dunstctl set-paused true/false/toggle` to disable/reenable or toggle pausing notifications. Use `dunstctl is-paused` to check if dunst is currently running or paused.

Use `killall`
  Use `killall -SIGUSR1 dunst` to disable and `killall -SIGUSR2 dunst` to reenable

Once paused dunst will hold back all notifications. After enabling dunst again all held back notifications will be displayed.

## Dunstify

Dunstify is an alternative to the notify-send command which is completely compatible to notify-send and can be used alongside it, but offers some more features. Dunstify works only with the Dunst notification daemon.

Additionally to the options available in notify-send, dunstify offers some more features like IDs and actions.

### Replacing notifications

You can assign an ID to a notification by calling dunstify with the `-r ID` option, where `ID` must be an integer. If a notification with that ID already exists it will be replaced with the new one. You may also close a notification with `dunstify -C ID`.

However, for most use cases, implementing tags is preferred over micromanaging IDs because the latter option has many hidden pitfalls [1]. Replacing IDs may be considered for debugging and for very complex notification senders instead of common practice [2].

Notifications with the same tag ("test" in this example) are replaced without having to care for IDs.

    $ dunstify -h string:x-dunst-stack-tag:test Test -A 'tested,default'
    $ dunstify -h string:x-dunst-stack-tag:test Testing

### Actions

You can define actions which can be invoked directly from the notification by specifying one or more `--action=action,label` parameters. For instance:

    dunstify --action="replyAction,reply" "Message received"

The user can then access the specified actions via Dunst's context menu. The call to dunstify will block until either the notification disappears or an action is selected. In the former case dunstify will return 1 if the notification timed out and 2 if it was dismissed manually [3]. In the latter case it returns the action which was selected by the Dunst context menu.

In addition to invoking actions with the context menu, you may also define how mouse events invoke actions [4]. This allows Dunst to be used interactively, as was suggested in [5]. When a notification has only one action, or when an action is named "default", that action may be invoked by middle-clicking the notification (by default or when `dunstrc` defines `mouse_middle_click = do_action`).

    reply_action () {}
    forward_action () {}
    handle_dismiss () {}

    ACTION=$(dunstify --action="default,Reply" --action="forwardAction,Forward" "Message Received")

    case "$ACTION" in
    "default")
        reply_action
        ;;
    "forwardAction")
        forward_action
        ;;
    "2")
        handle_dismiss
        ;;
    esac

## Tips and tricks

### Using dunstify as volume/brightness level indicator

You can use the replace id feature to implement a simple volume or brightness indicator notification like in this picture [6].

To realize that volume indicator place the following script somewhere on your `PATH`.

    #!/bin/bash
    # changeVolume

    # Arbitrary but unique message tag
    msgTag="myvolume"

    # Change the volume using alsa(might differ if you use pulseaudio)
    amixer -c 0 set Master "$@" > /dev/null

    # Query amixer for the current volume and whether or not the speaker is muted
    volume="$(amixer -c 0 get Master | tail -1 | awk '{print $4}' | sed 's/[^0-9]*//g')"
    mute="$(amixer -c 0 get Master | tail -1 | awk '{print $6}' | sed 's/[^a-z]*//g')"
    if [[ $volume == 0 || "$mute" == "off" ]]; then
        # Show the sound muted notification
        dunstify -a "changeVolume" -u low -i audio-volume-muted -h string:x-dunst-stack-tag:$msgTag "Volume muted"
    else
        # Show the volume notification
        dunstify -a "changeVolume" -u low -i audio-volume-high -h string:x-dunst-stack-tag:$msgTag \
        -h int:value:"$volume" "Volume: ${volume}%"
    fi

    # Play the volume changed sound
    canberra-gtk-play -i audio-volume-change -d "changeVolume"

Now simply bind `changeVolume 2dB+ unmute` etc. to some hotkey and you are done. You might also want to make dunst ignore these type of notifications in its history. See #Modifying.

### Overwrite previous notification

For some notifications (for example sound or brightness), you might want to overwrite the previous notification. You can either use the Dunst method in #Replacing notifications or refer to Desktop notifications#Replace previous notification for a more general example.

## Troubleshooting

### Dunst fails to start via systemd

When using dunst without a Display Manager, the `DISPLAY` environment variable might not be correctly set.[7]

To fix this, add the following to your `.xinitrc`:

    systemctl --user import-environment DISPLAY

Tip: This is done automatically as part of `/etc/X11/xinit/xinitrc.d/50-systemd-user.sh` that comes with recent versions of systemd.

### Non-matching font sizes (Emojis much larger than text)

This is caused by fontconfig not rescaling bitmap fonts. This is usually only noticed with certain emoji fonts (e.g. noto-fonts-emoji)

To solve, simply run:

    # ln -s /etc/fonts/conf.avail/10-scale-bitmap-fonts.conf /etc/fonts/conf.d/

and restart Dunst.

### Notifications from some applications don't obey timeout rules

You have set my timeouts to 30 for all urgencies.

However, notifications from some applications, for example discord, mattermost, gitlab, disappear very quickly. approximately after just 3 seconds. See issue #276.

This happens because it comes push to close. A special parameter was introduced to ignore this - ignore_dbusclose.

    ignore_dbusclose (default: false)

        Ignore the dbus closeNotification message. This is useful to enforce the timeout set by dunst configuration. Without this parameter, an application may close the notification sent before the user defined timeout.

Category:

- X server (Русский)

Hidden category:

- Pages or sections flagged with Template:Translateme (Русский)