3 # Automatically select a display configuration based on connected devices
5 # Copyright (c) 2013 Stefan Tomanek <stefan.tomanek@wertarbyte.de>
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
24 # Save your current display configuration and setup with:
25 # $ autorandr --save mobile
27 # Connect an additional display, configure your setup and save it:
28 # $ autorandr --save docked
30 # Now autorandr can detect which hardware setup is active:
35 # To automatically reload your setup, just append --change to the command line
37 # To manually load a profile, you can use the --load <profile> option.
39 # autorandr tries to avoid reloading an identical configuration. To force the
40 # (re)configuration, apply --force.
42 # To prevent a profile from being loaded, place a script call "block" in its
43 # directory. The script is evaluated before the screen setup is inspected, and
44 # in case of it returning a value of 0 the profile is skipped. This can be used
45 # to query the status of a docking station you are about to leave.
47 # If no suitable profile can be identified, the current configuration is kept.
48 # To change this behaviour and switch to a fallback configuration, specify
51 # Another script called "postswitch "can be placed in the directory
52 # ~/.autorandr as well as in all profile directories: The scripts are executed
53 # after a mode switch has taken place and can notify window managers or other
54 # applications about it.
57 # While the script uses xrandr by default, calling it by the name "autodisper"
58 # or "auto-disper" forces it to use the "disper" utility, which is useful for
59 # controlling nvidia chipsets. The formats for fingerprinting the current setup
60 # and saving/loading the current configuration are adjusted accordingly.
62 XRANDR=/usr/bin/xrandr
63 DISPER=/usr/bin/disper
64 XDPYINFO=/usr/bin/xdpyinfo
66 CONFIG=~/.autorandr.conf
67 RESERVED_PROFILE_NAMES=`cat <<EOF
68 common Clone all connected outputs at the largest common resolution
69 horizontal Stack all connected outputs horizontally at their largest resolution
70 vertical Stack all connected outputs vertically at their largest resolution
78 FP_METHODS="setup_fp_xrandr_edid setup_fp_sysfs_edid"
79 CURRENT_CFG_METHOD="current_cfg_xrandr"
80 LOAD_METHOD="load_cfg_xrandr"
82 SCRIPTNAME="$(basename $0)"
83 # when called as autodisper/auto-disper, we assume different defaults
84 if [ "$SCRIPTNAME" = "auto-disper" ] || [ "$SCRIPTNAME" = "autodisper" ]; then
85 echo "Assuming disper defaults..." >&2
86 FP_METHODS="setup_fp_disper"
87 CURRENT_CFG_METHOD="current_cfg_disper"
88 LOAD_METHOD="load_cfg_disper"
91 if [ -f $CONFIG ]; then
92 echo "Loading configuration from '$CONFIG'" >&2
96 if ! which xxd 2>&1 >/dev/null; then
98 # xxd replacement for systems without vim. Ugly, but the only simple
99 # version that both Python 2 and 3 understand that I could come up with.
100 # awk can only do one direction, it has no ord() function.
101 if [ "$1" = "-r" ]; then
102 python -c "import binascii, sys; getattr(sys.stdout, 'buffer', sys.stdout).write(binascii.unhexlify(getattr(sys.stdin, 'buffer', sys.stdin).read()))"
104 python -c "import binascii, sys; getattr(sys.stdout, 'buffer', sys.stdout).write(binascii.hexlify(getattr(sys.stdin, 'buffer', sys.stdin).read()))"
110 setup_fp_xrandr_edid() {
111 $XRANDR -q --verbose | awk '
113 / (dis)?connected/ { DEVICE=gensub("-([A-Z]-)?", "", "g", $1) " "; }
114 /^[[:blank:]]+EDID:/ {
117 for(getline; /^[[:blank:]]+[0-9a-f]+$/; getline) {
128 setup_fp_sysfs_edid() {
129 $XRANDR -q > /dev/null
130 for DEVICE in /sys/class/drm/card*-*; do
131 [ -e "${DEVICE}/status" ] && grep -q "^connected$" "${DEVICE}/status" || continue
132 echo -n "$(echo "${DEVICE}/edid" | sed -re 's#^.+card[0-9]+-([^/]+).+#\1#; s#-([A-Z]-)?##') "
133 cat "${DEVICE}/edid" | xxd -c 256 -ps | awk 'ORS=""; /.+/ { print; }'
139 $DISPER -l | grep '^display '
144 for M in $FP_METHODS; do
146 if [ -n "$FP" ]; then
150 if [ -z "$FP" ]; then
151 echo "Unable to fingerprint display configuration" >&2
157 current_cfg_xrandr() {
158 local PRIMARY_SETUP="";
159 if [ -x "$XDPYINFO" ]; then
160 PRIMARY_SETUP="$($XDPYINFO -ext XINERAMA | awk '/^ head #0:/ {printf $3 $5}')"
162 $XRANDR -q | awk -v primary_setup="${PRIMARY_SETUP}" '
163 # display is connected and has a mode
164 /^[^ ]+ connected [^(]/ {
166 if ($3 == "primary") {
173 if (A[1] A[2] "," A[3] == primary_setup)
176 if (($4 == "left") || ($4 == "right")) {
181 print "pos "A[2]"x"A[3];
186 print "rotate normal";
190 # disconnected or disabled displays
191 /^[^ ]+ (dis)?connected / ||
192 /^[^ ]+ unknown connection / {
199 current_cfg_disper() {
203 common_cfg_xrandr() {
206 # output: current output
207 # outputlist: space sep list of all outputs
208 # outputarr: array of all connected outputs
209 # outputarrsize: number of connected outputs
210 # modelist[800x600]: space sep list of outputs supporting mode
211 # display is connected
212 /^[^ ]+ connected / {
214 outputlist=outputlist " " output
215 outputarr[outputarrsize++]=output
217 # disconnected or disabled displays
218 /^[^ ]+ disconnected / ||
219 /^[^ ]+ unknown connection / {
223 # modes available on a screen
225 modelist[$1]=modelist[$1] " " output
228 # find common mode with largest screen area
229 for (m in modelist) {
230 if (modelist[m] == outputlist) {
231 # calculate area of resolution
233 if (wh[1]*wh[2] >= maxdim) {
240 for (i in outputarr) {
241 print "output " outputarr[i];
242 print "mode " maxmode;
245 print "same-as " outputarr[0]
254 $XRANDR -q | awk -v stack="${STACK}" '
256 # stack: "horizontal" (anything except vertical) or "vertical"
257 # output: current output
258 # firstmode: pick first mode after output
259 # posX,posY: position of the next output
263 # display is connected
264 /^[^ ]+ connected / {
269 # disconnected or disabled displays
270 /^[^ ]+ disconnected / ||
271 /^[^ ]+ unknown connection / {
275 # modes available on a screen, but pick only the first
277 if (!firstmode) next;
279 # output mode at current virtual desktop pos
281 print "pos " posX "x" posY;
282 # calculate position of next output
284 if (stack == "vertical")
298 [ ! -x "$PROFILES/$PROFILE/block" ] && return 1
300 "$PROFILES/$PROFILE/block" "$PROFILE"
305 if [ "$(cat "$PROFILES/$PROFILE/config")" = "$(current_cfg)" ]; then
306 echo "Config already loaded"
314 # sed 1: Prefix arguments with "--"
315 # sed 2: Merge arguments into one line per output
316 # sed 3: * Merge all --off outputs into the first line
317 # * Place the output with --pos 0x0 on the second line
318 # * Remaining outputs are appended as they appear
319 # * Keep everything in hold buffer until the last line
320 # sed 4: Remove empty lines caused by G and H on empty hold buffer
321 # sed 5: Join lines enabling screens in pairs of two (See https://github.com/phillipberndt/autorandr/pull/6)
322 sed 's/^/--/' "$1" | sed -e '
329 # Merge with next line if it contains --off
330 s/\n\([^\n]* --off\)/ \1/
336 # Swap lines 1 and 2 if --off is found
337 / --off/ s/^\([^\n]*\)\n\([^\n]*\)/\2\n\1/
345 /--mode/{ N; s/\n/ /; }
346 ' | xargs -L 1 $XRANDR
355 local CONF="$PROFILES/$PROFILE/config"
356 local IS_VIRTUAL_PROFILE=`echo "$RESERVED_PROFILE_NAMES" | grep -c "^ $PROFILE "`
358 if [ ! -f "$CONF" -a $IS_VIRTUAL_PROFILE -eq 0 ]; then
359 echo " -> Error: Profile '$PROFILE' does not exist." >&2
363 if [ -x "$PROFILES/preswitch" ]; then
364 "$PROFILES/preswitch" "$PROFILE"
366 if [ -x "$PROFILES/$PROFILE/preswitch" ]; then
367 "$PROFILES/$PROFILE/preswitch" "$PROFILE"
370 if [ -f "$CONF" ]; then
371 echo " -> loading profile $PROFILE"
372 if [ $IS_VIRTUAL_PROFILE -ne 0 ]; then
373 echo " -> Warning: Existing profile overrides virtual profile with same name" >&2
378 if [ $PROFILE = "common" ]; then
379 echo " -> setting largest common mode in cloned mode"
381 elif [ $PROFILE = "horizontal" ]; then
382 echo " -> stacking all outputs horizontally at their largest modes"
383 STACK="horizontal" stack_cfg_xrandr
384 elif [ $PROFILE = "vertical" ]; then
385 echo " -> stacking all outputs vertically at their largest modes"
386 STACK="vertical" stack_cfg_xrandr
390 if [ -x "$PROFILES/$PROFILE/postswitch" ]; then
391 "$PROFILES/$PROFILE/postswitch" "$PROFILE"
393 if [ -x "$PROFILES/postswitch" ]; then
394 "$PROFILES/postswitch" "$PROFILE"
400 Usage: $SCRIPTNAME [options]
402 -h, --help get this small help
403 -c, --change reload current setup
404 -s, --save <profile> save your current setup to profile <profile>
405 -l, --load <profile> load profile <profile>
406 -d, --default <profile> make profile <profile> the default profile
407 --force force (re)loading of a profile
408 --fingerprint fingerprint your current hardware setup
409 --config dump your current xrandr setup
411 To prevent a profile from being loaded, place a script call "block" in its
412 directory. The script is evaluated before the screen setup is inspected, and
413 in case of it returning a value of 0 the profile is skipped. This can be used
414 to query the status of a docking station you are about to leave.
416 If no suitable profile can be identified, the current configuration is kept.
417 To change this behaviour and switch to a fallback configuration, specify
420 Another script called "postswitch "can be placed in the directory
421 ~/.autorandr as well as in any profile directories: The scripts are executed
422 after a mode switch has taken place and can notify window managers.
424 When called by the name "autodisper" or "auto-disper", the script uses "disper"
425 instead of "xrandr" to detect, configure and save the display configuration.
427 If xrandr is used, the following virtual configurations are available:
428 ${RESERVED_PROFILE_NAMES}
434 OPTS=$(getopt -n autorandr -o s:l:d:cfh --long change,default:,save:,load:,force,fingerprint,config,help -- "$@")
435 if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
440 -c|--change) CHANGE_PROFILE=1; shift ;;
441 -d|--default) DEFAULT_PROFILE="$2"; shift 2 ;;
442 -s|--save) SAVE_PROFILE="$2"; shift 2 ;;
443 -l|--load) LOAD_PROFILE="$2"; shift 2 ;;
445 --force) FORCE_LOAD=1; shift ;;
446 --fingerprint) setup_fp; exit 0;;
447 --config) current_cfg; exit 0;;
449 *) echo "Error: $1"; exit 1;;
453 CURRENT_SETUP="$(setup_fp)"
455 if [ -n "$SAVE_PROFILE" ]; then
456 if echo "$RESERVED_PROFILE_NAMES" | grep -q "^ $SAVE_PROFILE "; then
457 echo "Cannot save current configuration as profile '${SAVE_PROFILE}': This configuration name is a reserved virtual configuration."
460 echo "Saving current configuration as profile '${SAVE_PROFILE}'"
461 mkdir -p "$PROFILES/$SAVE_PROFILE"
462 echo "$CURRENT_SETUP" > "$PROFILES/$SAVE_PROFILE/setup"
463 $CURRENT_CFG_METHOD > "$PROFILES/$SAVE_PROFILE/config"
467 if [ -n "$LOAD_PROFILE" ]; then
468 CHANGE_PROFILE=1 FORCE_LOAD=1 load "$LOAD_PROFILE"
472 for SETUP_FILE in $PROFILES/*/setup; do
473 if ! [ -e $SETUP_FILE ]; then
476 PROFILE="$(basename $(dirname "$SETUP_FILE"))"
479 if blocked "$PROFILE"; then
484 # This sed command is for compatibility with old versions that did not try
485 # to normalize device names
486 FILE_SETUP="$(sed -re 's#-([A-Z]-)?##g; s#card[0-9]##;' "$PROFILES/$PROFILE/setup")"
487 # Detect the md5sum in fingerprint files created using the old sysfs fingerprinting
488 # If it is detected, output a warning and calculate the legacy variant of the current
490 if echo "$FILE_SETUP" | grep -Eq "^[^ ]+ [0-9a-f]{32}$"; then
491 echo -n " (Obsolete fingerprint format. Please update using --save.) "
493 if [ -z "$LEGACY_CURRENT_SETUP" ]; then
494 LEGACY_CURRENT_SETUP="$(echo "$CURRENT_SETUP" | while read DEVICE EDID; do
496 echo -n "${EDID}" | xxd -r -ps | md5sum - | awk '{print $1}'
499 FILE_SETUP="$(echo "$FILE_SETUP" | sort)"
500 if [ "$LEGACY_CURRENT_SETUP" = "$FILE_SETUP" ]; then
501 CURRENT_SETUP="$LEGACY_CURRENT_SETUP"
505 if [ "$CURRENT_SETUP" = "$FILE_SETUP" ]; then
507 if [ "$CHANGE_PROFILE" -eq 1 ]; then
508 if [ "$FORCE_LOAD" -eq 1 ] || ! config_equal "$PROFILE"; then
512 # found the profile, exit with success
519 # we did not find the profile, load default
520 if [ -n "$DEFAULT_PROFILE" ]; then
521 echo "No suitable profile detected, falling back to $DEFAULT_PROFILE"
522 load "$DEFAULT_PROFILE"
530 # indent-tabs-mode: t