aboutsummaryrefslogtreecommitdiff
path: root/misc/bin/display_toggle.sh
blob: b2c7e5c4430a1d9aa73682a376f29def4450e1bf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/bin/bash

# Assuming there are two displays. A small one (e.g. laptop) and a big
# one (e.g. monitor). Identify the displays, and toggle between 3
# states: small one only -> both with the big one to the left of the
# small one -> big one only
# small one: <20 inch
# big one: >20 inch

# Make sure the variables from pipe can be assigned
# https://stackoverflow.com/questions/42963395/bash-assign-variable-from-pipe
shopt -s lastpipe
i=0
regex="^([^ ]+).* .*$"

# Read the output of xrandr for connected display names and sizes
xrandr | grep " connected " | while IFS=$'\n' read -r line; do
  if [[ $line =~ $regex ]]; then
    name["$i"]="${BASH_REMATCH[1]}"
    (( i++ ))
  fi
done

if (( i == 1 )); then
  echo "Only one connected display"
  exit 1
fi

regex="^.*/([0-9]+)x.*/([0-9]+).* ([^ ]+)$"
xrandr --listactivemonitors | while IFS=$'\n' read -r line; do
  if [[ $line =~ $regex ]]; then
    if (( "${BASH_REMATCH[1]}" > 500 )); then
      bigger="${BASH_REMATCH[3]}"
      if [[ $bigger == "${name[0]}" ]]; then
        smaller=${name[1]}
      else
        smaller=${name[0]}
      fi
    else
      smaller="${BASH_REMATCH[3]}"
      if [[ $smaller == "${name[0]}" ]]; then
        bigger=${name[1]}
      else
        bigger=${name[0]}
      fi
    fi
  fi
done

# If only smaller on, then have both on
if ! xrandr --listactivemonitors | grep -q "$bigger"; then
  xrandr --output "$bigger" --primary --auto --output "$smaller" --right-of "$bigger" --auto
  # if only bigger on, then only smaller on
elif ! xrandr --listactivemonitors | grep -q "$smaller"; then
  xrandr --output "$bigger" --auto --left-of "$smaller" --output "$smaller" --primary --auto
  xrandr --output "$bigger" --off
  # if both are on, then only bigger on
else
  xrandr --output "$bigger" --primary --auto --left-of "$smaller" --output "$smaller" --auto
  xrandr --output "$smaller" --off
fi