Tomáš Faikl
~rampaq

Tomáš Faikl ~rampaq

Linux programming electronics mathematics

My PGP key.

© 2023

Feed

Simple lock and more (sxidle)

I have recently became mad about such a simple thing as a screen lock. So here is my try at very simple lock for minimal desktops.

Quite a standard program for managing screen locker (on minimal desktops) is xautolock. But I have noticed that sometimes it just won’t lock the screen when it should (time delay) or when I tell it to. It throws some weird error like it can’t find a running xautolock process or it is just silent and doesn’t do anything.

So I wrote this very simple (almost nothing-to-break) shell script I call sxidle (simple X idle) to do this trivial task right. Full code and more info is on my gitlab.

It goes like this:

#!/bin/sh
run_periodic () {
	while true; do
		sh -c "$pcmd"  # periodically executed command while locked
		sleep $period
	done
}
main () {
	[ $period -gt 0 ] && { run_periodic & PID=$!; }
	sh -c "$cmd"  # locker command
	[ $period -gt 0 ] && kill $PID
}

trap main USR1  # SIGUSR1 to lock immedieately

while true; do
	idle=$(($(xssstate -i) / 1000))
	if [ $idle -ge $time ] && sh -c "$cond_cmd"; then
		main
	else
		sleep 10 & wait $!
	fi
done

It uses a suckless utility xssstate, which prints general info about screensaver in X, I was mainly interested in the ability to print X server’s idle time - how long there was no user activity.

Just start it on boot and don’t care!

Example:

# after boot, for ex. in .xinitrc
# lock after 10 minutes and suspend every 5 minutes while locked
sxidle 10 slock 5 "systemctl suspend"

# to lock immedieately
pkill -SIGUSR1 sxidle

Unix philosophy is to build small scripts that you can compose together. As you can see, slock was used, another really simple suckless program to just do as it says - “simple lock” your screen and unlock when you enter password.

To spice it up, two little things were added

  • a fullscreen checker. One doesn’t want to interrupt watching a lecture or a movie with a lockscreen.
  • a smart suspend. When laptop is not connected to power source, suspend it.

So it looks like

sxidle -c "! isfullscreen" 10 slock 5 smartsuspend

Sadly, the condition cannot be inserted like sxidle 10 "isfullscreen || slock" 5 smartsuspend, because it would cause suspend to run every loop when in fullscreen after idle.

Alternatively, it could be stated like sxidle "isfullscreen || slock '{ while true; do; smartsuspend; sleep 5m; done; }'", but it is a little wordy and specific to slock (it runs whatever command supplied as argument as long as the slock itself is running).

Whole setup can be found again on my gitlab.