Skip to content
Sam Mason edited this page Nov 14, 2023 · 2 revisions

swayidle and swaylock recipes

basic usage

As described in swayidle's man page, running the following command will ensure swaylock is run to lock the screen with a password.

swayidle -w \
  timeout 300 'swaylock -f -c 000000' \
  timeout 600 'swaymsg "output * dpms off"' \
       resume 'swaymsg "output * dpms on"' \
  before-sleep 'swaylock -f -c 000000'

This will cause the screen to be blacked out (-c 000000) after 5 minutes, and uses DPMS to turn attached displays off after 10 minutes. The before-sleep section says that it should additionally listen for, e.g., your laptop being closed, and this should also immediately lock the display.

shell script

Creating the following in a shell script (~/.local/bin/swayidle.sh) so it's easier to kill/restart swayidle when you want to disable the screensaver, e.g., for a presentation. A simple line exec swayidle.sh in my ~/.config/sway/config can be used to start it after login.

#!/bin/bash
set -eufo pipefail
lock='swaylock -f -c 000000'
exec swayidle -w \
   timeout 300 "$lock" \
   timeout 600 'swaymsg "output * dpms off"' \
        resume 'swaymsg "output * dpms on"' \
   before-sleep "$lock" \
   lock "$lock"

the lock section allows me to set up a binding for quickly locking a systemd session:

bindsym $mod+Escape exec loginctl lock-session

gentle fade

swaylock just does a hard transition when locking, without giving the user any grace-period to react and cancel the lock. The tiny chayang utility fills this gap with a configurable fade-out. Creating a script to run swaylock after chayang makes this easy, e.g., in ~/.local/bin/swaylock.sh:

#!/bin/bash
set -eufo pipefail
case "${1:-}" in
  # minimal screen fadeout, https://git.sr.ht/~emersion/chayang
  slow) chayang -d 10;;
  fast) chayang -d 0.3;;
esac
exec swaylock -f -F -c 000000

then changing swayidle.sh to pass slow or fast as appropriate:

#!/bin/bash
set -eufo pipefail
lock=swaylock.sh
exec swayidle -w \
     timeout 300 "$lock slow" \
     timeout 600 'swaymsg "output * dpms off"' \
          resume 'swaymsg "output * dpms on"' \
     before-sleep "$lock" \
     lock "$lock fast"

This will give you a 10 seconds while the display fades out to cancel the lock due to inactivity, while using a sub-second fade when explicitly locked.

Clone this wiki locally