aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/dot_config/sway/executable_display-toggle.sh
blob: 08481dc1da1318a5a861d316b2aa130ac5adfb54 (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
#!/bin/sh
# Display mode manager: laptop-off ↔ side-by-side.
#   (no arg)  toggle between modes (F7 / Super+x d).
#   apply     re-apply whatever is in the state file. Used by sway's
#             exec_always at startup and on every config reload (sway
#             reload re-enables all outputs side-by-side by default;
#             this restores the user's chosen layout). First boot
#             defaults to laptop-off when no state file exists.
#   init      force laptop-off; used by the hotplug watcher when a
#             newly-plugged external should preempt whatever was saved.

STATE_FILE="${XDG_RUNTIME_DIR:-/tmp}/display-mode"

OUTPUTS=$(swaymsg -t get_outputs -r)
LAPTOP=$(echo "$OUTPUTS" | jq -r '[.[] | select(.name | test("^eDP")) | .name] | first // empty')
EXTERNAL=$(echo "$OUTPUTS" | jq -r '[.[] | select(.name | test("^eDP") | not) | .name] | first // empty')

if [ -z "$EXTERNAL" ]; then
  # No external connected: make sure the laptop screen is on. This recovers
  # from an earlier "laptop-off" state after the external was unplugged.
  if [ -n "$LAPTOP" ]; then
    swaymsg output "$LAPTOP" enable pos 0 0 || true
    echo "laptop-only" >"$STATE_FILE"
  fi
  [ -z "${1:-}" ] && notify-send "Display" "No external display connected"
  exit 0
fi

[ -z "$LAPTOP" ] && exit 0

LAPTOP_WIDTH=$(echo "$OUTPUTS" | jq -r ".[] | select(.name == \"$LAPTOP\") | .current_mode.width // .modes[0].width")
[ -z "$LAPTOP_WIDTH" ] && LAPTOP_WIDTH=1920

if [ "${1:-}" = "apply" ]; then
  NEXT=$(cat "$STATE_FILE" 2>/dev/null || echo "laptop-off")
elif [ "${1:-}" = "init" ]; then
  NEXT="laptop-off"
else
  CURRENT=$(cat "$STATE_FILE" 2>/dev/null || echo "laptop-off")
  case "$CURRENT" in
    laptop-off) NEXT="side-by-side" ;;
    *) NEXT="laptop-off" ;;
  esac
fi

case "$NEXT" in
  laptop-off)
    swaymsg output "$LAPTOP" disable || true
    swaymsg output "$EXTERNAL" enable || true
    swaymsg workspace number 1 || true
    echo "laptop-off" >"$STATE_FILE"
    [ -z "${1:-}" ] && notify-send "Display" "Laptop screen off"
    ;;
  side-by-side)
    swaymsg output "$LAPTOP" enable pos 0 0 || true
    swaymsg output "$EXTERNAL" enable pos "$LAPTOP_WIDTH" 0 || true
    echo "side-by-side" >"$STATE_FILE"
    [ -z "${1:-}" ] && notify-send "Display" "Side by side"
    ;;
esac