#!/usr/bin/env bash
# Draw the sway background from the regolith.wallpaper.* resources, the way
# the X11 session draws them through org.gnome.desktop.background:
#
#   - regolith.wallpaper.file: an image, a GNOME wallpaper XML file, or a
#     folder of pictures;
#   - regolith.wallpaper.interval: for a folder, how many seconds each picture
#     stays (a positive whole number); otherwise one picture for the session;
#   - regolith.wallpaper.color.primary, .color.secondary and
#     .color.shading.type (solid, vertical or horizontal): the background when
#     there is no image. Colours can be anything GNOME accepts: #RGB, #RRGGBB,
#     #RRRGGGBBB, #RRRRGGGGBBBB, rgb(), rgba() or a colour name;
#   - regolith.wallpaper.mode (a swaybg mode), or else
#     regolith.wallpaper.options (a GNOME picture-options value).
#
# When neither the file nor the primary colour has a value, the background is
# left alone, as in X11.
#
# A wallpaper chosen in Settings > Background can be a pair of pictures, one
# for the Default style and one for Dark (picture-uri and picture-uri-dark of
# org.gnome.desktop.background); X11 shows the one for the current style.
# When regolith.wallpaper.file is one picture of that pair, the one for the
# current style is drawn. With --follow-style, the script keeps running and
# draws the background again whenever the style changes.
#
# Folders and GNOME slideshows keep moving after this script returns:
# regolith-wallpaper-cycle draws their pictures in turn, through this script
# run with --picture <mode> <colour> <secondary colour> <shading type>
# <folder or slideshow>, which reads the pictures from its standard input,
# each followed by a NUL byte, and writes a newline once each one is drawn.

set -uo pipefail

RGB_TXT=${REGOLITH_SWAYBG_RGB_TXT:-/usr/share/X11/rgb.txt}
GRADIENT_DIR=${XDG_RUNTIME_DIR:-/tmp}/regolith-swaybg

warn() {
  echo "regolith-set-swaybg: $*" >&2
}

resource() {
  trawlcat "$1" ""
}

# sway_path <file>: set sway_name to the file name as sway's background
# command reads it, which expands it like a shell word: ASCII characters
# other than letters, digits and /._- are escaped
sway_path() {
  local LC_ALL=C name=$1 c i n
  sway_name=
  for (( i = 0; i < ${#name}; i++ )); do
    c=${name:i:1}
    printf -v n '%d' "'$c"
    if [[ $c == [A-Za-z0-9/._-] ]] || (( n > 127 )); then
      sway_name+=$c
    else
      sway_name+="\\$c"
    fi
  done
}

# cycle <regolith-wallpaper-cycle arguments...>: the copy next to this script
# is preferred, as when it runs from the source tree
cycle() {
  local helper=${BASH_SOURCE[0]%/*}/regolith-wallpaper-cycle
  if [[ ${BASH_SOURCE[0]} != */* || ! -f $helper ]]; then
    helper=$(command -v regolith-wallpaper-cycle) || {
      warn "regolith-wallpaper-cycle is not installed"
      return 1
    }
  fi
  "$BASH" "$helper" "$@"
}

# start_cycle <folder|slideshow> [<interval>]: hand the wallpaper over to
# regolith-wallpaper-cycle, which draws its pictures with --picture
start_cycle() {
  local self=${BASH_SOURCE[0]} settings
  [[ $self == /* ]] || self=$PWD/$self
  printf -v settings '%s\n' "$mode" "$color" "$secondary" "$shading"
  local draw=("$BASH" "$self" --picture "$mode" "$color" "$secondary" "$shading" "$wallpaper")
  if [[ $1 == folder ]]; then
    cycle folder sway "$wallpaper" "$2" "$settings" "${draw[@]}"
  else
    cycle slideshow sway "$wallpaper" "$settings" "${draw[@]}"
  fi
  exit
}

# to_hex <colour>: print the colour as #rrggbb, or fail
to_hex() {
  local c=$1 n r g b
  c=${c#"${c%%[![:space:]]*}"}
  c=${c%"${c##*[![:space:]]}"}

  if [[ $c =~ ^#([[:xdigit:]]+)$ ]]; then
    local hex=${BASH_REMATCH[1],,}
    n=$(( ${#hex} / 3 ))
    if (( ${#hex} % 3 != 0 || n < 1 || n > 4 )); then
      return 1
    fi
    r=${hex:0:n}; g=${hex:n:n}; b=${hex:2*n:n}
    if (( n == 1 )); then
      printf '#%02x%02x%02x\n' $((16#$r * 17)) $((16#$g * 17)) $((16#$b * 17))
    else
      printf '#%s%s%s\n' "${r:0:2}" "${g:0:2}" "${b:0:2}"
    fi
    return 0
  fi

  local num='[[:space:]]*([0-9]+(\.[0-9]+)?%?)[[:space:]]*'
  if [[ ${c,,} =~ ^rgba?\($num,$num,$num(,[^\)]*)?\)$ ]]; then
    local out=() v
    for v in "${BASH_REMATCH[1]}" "${BASH_REMATCH[3]}" "${BASH_REMATCH[5]}"; do
      if [[ $v == *% ]]; then
        v=$(awk -v p="${v%\%}" 'BEGIN { v = p * 255 / 100; if (v > 255) v = 255; printf "%d", v + 0.5 }')
      else
        v=${v%%.*}
      fi
      (( v > 255 )) && v=255
      out+=("$v")
    done
    printf '#%02x%02x%02x\n' "${out[@]}"
    return 0
  fi

  # Colour names: GNOME (Pango) uses the X11 colour names, without regard to
  # case or spaces
  local name=${c,,}
  name=${name//[[:space:]]/}
  [[ -n $name && -r $RGB_TXT ]] || return 1
  awk -v want="$name" '
    /^[[:space:]]*!/ { next }
    NF >= 4 {
      n = ""
      for (i = 4; i <= NF; i++) n = n $i
      if (tolower(n) == want) { printf "#%02x%02x%02x\n", $1, $2, $3; found = 1; exit }
    }
    END { exit !found }' "$RGB_TXT"
}

# background_path <key>: print the file of org.gnome.desktop.background's
# <key> (a file:// URI), or nothing
background_path() {
  local uri
  uri=$(gsettings get org.gnome.desktop.background "$1" 2> /dev/null) || return 0
  python3 -c '
import ast, sys, urllib.parse
try:
    uri = ast.literal_eval(sys.argv[1])
except (ValueError, SyntaxError):
    sys.exit()
if isinstance(uri, str) and uri.startswith("file://"):
    print(urllib.parse.unquote(urllib.parse.urlsplit(uri).path))
' "$uri"
}

# style_wallpaper <file>: print the picture to draw for the wallpaper file:
# the one for the current style when the file is one picture of the Default
# and Dark pair set in GNOME, the file itself otherwise
style_wallpaper() {
  local light dark
  light=$(background_path picture-uri)
  dark=$(background_path picture-uri-dark)
  if [[ -z $light || -z $dark || $light == "$dark" ]] ||
     [[ $1 != "$light" && $1 != "$dark" ]]; then
    printf '%s
' "$1"
  elif [[ $(gsettings get org.gnome.desktop.interface color-scheme 2> /dev/null) == "'prefer-dark'" ]]; then
    printf '%s
' "$dark"
  else
    printf '%s
' "$light"
  fi
}

# gradient <file> <width> <height> <vertical|horizontal> <#rrggbb> <#rrggbb>:
# write a PNG going from the first colour (top or left) to the second, as
# GNOME draws color-shading-type
gradient() {
  python3 - "$@" <<'EOF'
import os, struct, sys, zlib

path, width, height, kind, first, second = sys.argv[1:]
width, height = max(1, int(width)), max(1, int(height))
a = [int(first[i:i + 2], 16) for i in (1, 3, 5)]
b = [int(second[i:i + 2], 16) for i in (1, 3, 5)]

def colour(i, n):
    t = i / (n - 1) if n > 1 else 0
    return bytes(round(x + (y - x) * t) for x, y in zip(a, b))

z = zlib.compressobj(6)
data = []
if kind == "vertical":
    for y in range(height):
        data.append(z.compress(b"\0" + colour(y, height) * width))
else:
    row = b"\0" + b"".join(colour(x, width) for x in range(width))
    for _ in range(height):
        data.append(z.compress(row))
data.append(z.flush())

def chunk(tag, body):
    return struct.pack(">I", len(body)) + tag + body + struct.pack(">I", zlib.crc32(tag + body))

tmp = path + ".tmp"
with open(tmp, "wb") as f:
    f.write(b"\x89PNG\r\n\x1a\n")
    f.write(chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)))
    f.write(chunk(b"IDAT", b"".join(data)))
    f.write(chunk(b"IEND", b""))
os.replace(tmp, path)
EOF
}

# draw_colours: the background without an image: the gradient between the
# primary and secondary colours, or else the primary colour
draw_colours() {
  local second
  if [[ -n $secondary && ( $shading == vertical || $shading == horizontal ) ]]; then
    if second=$(to_hex "$secondary"); then
      draw_gradient "$shading" "$color" "$second" && exit 0
    else
      warn "regolith.wallpaper.color.secondary: not a colour: '$secondary'"
    fi
  fi
  rm -f "$GRADIENT_DIR"/gradient-*.png
  exec swaymsg output "*" background "$color" solid_color
}

# draw_gradient <vertical|horizontal> <#rrggbb> <#rrggbb>: give each active
# output a gradient image of its own size; fail if there is no output
draw_gradient() {
  local dir=$GRADIENT_DIR name width height file
  local cmds=() keep=()
  mkdir -p "$dir" || return 1
  while read -r name width height; do
    file="$dir/gradient-$1-${2#\#}-${3#\#}-${width}x$height.png"
    if [[ ! -f $file ]]; then
      gradient "$file" "$width" "$height" "$1" "$2" "$3" || continue
    fi
    if (( ${#cmds[@]} == 0 )); then
      # Outputs that are connected later get the first output's image
      cmds+=("output * background $file fill $2")
    fi
    cmds+=("output \"$name\" background $file fill $2")
    keep+=("$file")
  done < <(swaymsg -t get_outputs | jq -r '.[] | select(.active) |
    "\(.name) \(.rect.width * (.scale // 1) | round) \(.rect.height * (.scale // 1) | round)"')
  (( ${#cmds[@]} > 0 )) || return 1

  swaymsg "$(IFS=';'; echo "${cmds[*]}")" > /dev/null || return 1
  # Drop the images of earlier colours and output sizes
  local old kept
  for old in "$dir"/gradient-*.png; do
    for kept in "${keep[@]}"; do
      [[ $old == "$kept" ]] && continue 2
    done
    rm -f "$old"
  done
}

# draw_picture <picture>: one picture of a folder or slideshow
draw_picture() {
  if [[ -n $1 ]]; then
    rm -f "$GRADIENT_DIR"/gradient-*.png
    sway_path "$1"
    exec swaymsg output "*" background "$sway_name" "$mode" "$color"
  fi
  # A folder without pictures: the colours, as for a missing file
  warn "regolith.wallpaper.file: no pictures in '$source'"
  draw_colours
}

if [[ ${1-} == --picture ]]; then
  # The pictures of a folder or slideshow, from regolith-wallpaper-cycle
  mode=${2-} color=${3-} secondary=${4-} shading=${5-} source=${6-}
  while IFS= read -r -d '' picture; do
    ( draw_picture "$picture" ) > /dev/null
    echo
  done
  exit 0
fi

if [[ ${1-} == --follow-style ]]; then
  # Draw the background again on each change of the Default/Dark style
  gsettings monitor org.gnome.desktop.interface color-scheme |
    while read -r _; do
      "${BASH_SOURCE[0]}"
    done
  exit 0
fi

wallpaper=$(resource regolith.wallpaper.file)
options=$(resource regolith.wallpaper.options)
mode=$(resource regolith.wallpaper.mode)
primary=$(resource regolith.wallpaper.color.primary)
secondary=$(resource regolith.wallpaper.color.secondary)
shading=$(resource regolith.wallpaper.color.shading.type)

if [[ -z $wallpaper && -z $primary ]]; then
  # Nothing is set: the background is the user's to manage
  cycle stop sway
  exit 0
fi

if [[ -z $mode ]]; then
  case $options in
    wallpaper) mode=tile ;;
    centered) mode=center ;;
    scaled) mode=fit ;;
    stretched) mode=stretch ;;
    none) mode=fill; wallpaper= ;;
    *) mode=fill ;;
  esac
fi

color="#000000"
if [[ -n $primary ]] && ! color=$(to_hex "$primary"); then
  warn "regolith.wallpaper.color.primary: not a colour: '$primary'"
  color="#000000"
fi

if [[ -n $wallpaper ]]; then
  wallpaper=${wallpaper/#\~/$HOME}
  wallpaper=$(style_wallpaper "$wallpaper")
  if [[ -d $wallpaper ]]; then
    # A folder: its pictures in turn
    start_cycle folder "$(resource regolith.wallpaper.interval)"
  elif [[ ! -f $wallpaper ]]; then
    warn "regolith.wallpaper.file: no such file: '$wallpaper'"
    wallpaper=
  fi
fi

# A GNOME wallpaper XML file (a slideshow, root element <background>, or a
# wallpaper list, <wallpapers>) names the images to draw. Any other file is
# an image; SVG images are XML too, so the root element decides.
xml=
if [[ -n $wallpaper ]] && file -b "$wallpaper" | grep -q text; then
  xml=$(xmllint --xpath "name(/*)" "$wallpaper" 2> /dev/null)
fi
if [[ $xml == background ]]; then
  entries=$(xmllint --xpath "count(/background/static | /background/transition)" "$wallpaper" 2> /dev/null)
  if [[ $entries =~ ^[1-9] ]]; then
    # A slideshow: the picture of the moment, on the slideshow's own clock
    start_cycle slideshow
  fi
fi

# From here on the background is drawn once: no folder or slideshow moves it
cycle stop sway

if [[ -z $wallpaper ]]; then
  draw_colours
fi

rm -f "$GRADIENT_DIR"/gradient-*.png
if [[ $xml == background || $xml == wallpapers ]]; then
  # The largest size of a wallpaper list, if there is an image at all
  image_path=$(xmllint "$wallpaper" --xpath "string(*//size[last()]/text())")
  [[ -n $image_path ]] || image_path=$(xmllint "$wallpaper" --xpath "normalize-space((//static/file)[1])")
  if [[ -z $image_path ]]; then
    warn "regolith.wallpaper.file: no image in '$wallpaper'"
    exec swaymsg output "*" background "$color" solid_color
  fi
  sway_path "$image_path"
  swaymsg output "*" background "$sway_name" "$mode" "$color"
  while read -r name width height; do
    wallpaper_file=$(xmllint "$wallpaper" --xpath "string(*//size[@width=$width][@height=$height]/text())")

    if [[ -n "$wallpaper_file" ]]; then
      sway_path "$wallpaper_file"
      swaymsg output "\"$name\"" background "$sway_name" "$mode" "$color"
    fi
  done < <(swaymsg -t get_outputs | jq -r '.[] | select(.active) | "\(.name) \(.current_mode.width) \(.current_mode.height)"')
else
  sway_path "$wallpaper"
  exec swaymsg output "*" background "$sway_name" "$mode" "$color"
fi
