Automatically switch screen configuration when a new monitor is connected in Sabayon Linux

Posted by

Category : guides

Using often my laptop for presentations, I really got bored of manual switching the graphics every time a new monitor is connected. Thou KDE offers a functional utility in its control panel for that, I prefer my computer to switch automagically as soon as a screen connector is plugged in or removed. The following instructions will work for both Sabayon and Gentoo, and possibly under other Linux distributions like Ubuntu, Mint, SUSE, depending on where the configuration files are placed.

To see if you can trigger udev events related to monitor connected, run:

udevadm monitor --property

Now, if you try to plug and unplug a new monitor, you should see some events on your console, something like:

KERNEL[1303765357.560848] change /devices/pci0000:00/0000:00:02.0/drm/card0 (drm)

If you can see that, you will be able to configure your monitor for the automatic switch. First:

cd /etc/udev/rules.d/

here are stored the udev rules. Let’s create a new one. I will use nano, but every editor is ok.

nano 80-vga.rules

in the file, write the following, to intercept the monitor events:

ACTION=="change", SUBSYSTEM=="drm", HOTPLUG=="1", RUN+="/root/"

The RUN variable will contain the path to a script which will be run when a new event is detected. I placed it in /root/, but you may want to place it somewhere else. Now, the script. I will quote mine, then explain:

read STATUS < /sys/class/drm/card0-VGA-1/status
export DISPLAY=:0
export XAUTHORITY=/home/danysk/.Xauthority
if [ "$STATUS" = "connected" ]
    xrandr --output VGA1 --right-of LVDS1 --auto --screen 0
    xrandr --output VGA1 --off --screen 0

So, this is what this simple script does: read the current status of the VGA connector (can be either "connected" or "disconnected"); export the variables required in order to access the current running X (remember to change danysk to your user name!); verify the current status of the VGA connector and use xrandr to properly set it (i like to the right of my main screen, but you may set clone or whatever you like.

That’s it. If you did it well, now your system reacts to plug and unplug operations automatically switching to the right configuration. Have fun :)

About Danilo Pianini

Fixed-term Post-doc researcher at the University of Bologna. Software engineer, designer and developer of the Protelis programming language, the Alchemist simulator, and several other libraries and tools. Proficient in Java, Kotlin, Scala, Python, Xtend. Can also write in Groovy, Bash, Ruby, C, Rust, Prolog, Javascript. Build automation and continuous integration zealot.

Star DanySK on GitHub
Useful Links