Skip to content

Instantly share code, notes, and snippets.

@XenGi
Last active September 18, 2021 02:11
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save XenGi/5499771 to your computer and use it in GitHub Desktop.
Save XenGi/5499771 to your computer and use it in GitHub Desktop.
display magic
#/etc/udev/rules.d/99-displaymagic.rules
# enable LVDS on HDMI disconnect
SUBSYSTEM=="drm", ACTION=="change", RUN+="/usr/local/bin/displaymagic.sh"
#!/bin/bash
#
# display magic v0.1.0
#
# The following script toggles between the internal monitor and an external
# monitor.
#
# by XenGi
##### edit config #####
EXTERNAL="HDMI1"
#TODO: EXTERNAL2="VGA1"
INTERNAL="LVDS1"
export DISPLAY=":0.0"
USER="bob"
#USER=$(who | grep $DISPLAY\) | head -1 | cut -f 1 -d ' ')
##### end config #####
# Check if we are root
if [[ $EUID -ne 0 ]] ; then
echo "This script must be run as root"
exit 1
fi
# check for udev rule
if [[ ! -f /etc/udev/rules.d/99-displaymagic.rules ]] ; then
echo "No udev rule found. Put '99-displaymagic.rules' in '/etc/udev/rules.d' and execute 'udevadm control --reload' as root."
exit
fi
# the script
export XAUTHORITY="/home/$USER/.Xauthority"
# just wait a second so that things run smooth
sleep 1
STATUS=$(su $USER -c "xrandr --current | grep $EXTERNAL | cut -d \ -f 2")
if [[ "$STATUS" == "disconnected" ]] ; then
# switch HDMI on and LVDS off
su $USER -c "xrandr --output $INTERNAL --off"
su $USER -c "xrandr --output $EXTERNAL --auto"
# set HDMI output as primary audio
su $USER -c "pactl set-card-profile 0 output:hdmi-surround"
fi
#TODO: add the same funcionality for the VGA port.
#STATUS="`su $USER -c "xrandr --current | grep $EXTERNAL2 | cut -d \ -f 2"`"
#if [[ "$STATUS" == "disconnected" ]] ; then
# # switch VGA on and LVDS off
# su $USER -c "xrandr --output $INTERNAL --off"
# su $USER -c "xrandr --output $EXTERNAL2 --auto"
# # set internal speakers and mic as primary audio
# su $USER -c "pactl set-card-profile 0 output:analog-stereo+input:analog-stereo"
#fi
if [[ "$STATUS" == "connected" ]] ; then
# switch HDMI off and LVDS on
su $USER -c "xrandr --output $EXTERNAL --off"
su $USER -c "xrandr --output $INTERNAL --auto"
# set internal speakers and mic as primary audio
su $USER -c "pactl set-card-profile 0 output:analog-stereo+input:analog-stereo"
fi
@amituttam
Copy link

Are the behaviors opposite in the connected/disconnected case? For example, in connected, the external is turned off.

@XenGi
Copy link
Author

XenGi commented Dec 12, 2013

yes, it's the oppisite. I've no idea why, but it only works this way. Seems like if you fire the xrandr command on an udev rule you only get the last state, not the currently active.

@rdenham
Copy link

rdenham commented Feb 25, 2016

XenGi, that was really useful to me. Thanks. Might be a missing quote on line 39.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment