#!/bin/sh
# i3 and i3bar read the DPI (Xft.dpi in the X resources) once, when they
# start, and gsd-xsettings publishes it (regolith-desktop#900).
# regolith-x11.service starts after gsd-xsettings, but systemd counts
# gsd-xsettings as started once it owns its D-Bus name, a moment before it
# writes Xft.dpi. It answers D-Bus calls only after that, and
# regolith-session-x11 waits for one answer before it touches the resources
# or starts i3.
#
# Runs regolith-session-x11 under Xvfb with a stand-in for gsd-xsettings
# that owns its name, writes Xft.dpi a while later and answers only then,
# and checks that i3's bars and title bars are those of an i3 started at
# that DPI. Also checks that the session doesn't wait without gsd-xsettings
# and doesn't wait for long on one that never answers.
set -eu

tmp=${AUTOPKGTEST_TMP:-$(mktemp -d)}
export HOME="$tmp/home" XDG_RUNTIME_DIR="$tmp/xdg" XDG_SESSION_TYPE=x11
mkdir -p "$HOME/.config/regolith3/i3" "$HOME/.config/regolith3/flags" "$XDG_RUNTIME_DIR"
chmod 700 "$XDG_RUNTIME_DIR"
cat > "$HOME/.config/regolith3/i3/config" <<'EOF'
font pango:DejaVu Sans 10
default_border normal
bar {
    status_command echo bar
}
EOF

# Stand-in for gsd-xsettings: owns org.gnome.SettingsDaemon.XSettings, waits
# <delay> seconds, writes Xft.dpi <dpi>, then serves org.gtk.Settings.
cat > "$tmp/xsettings" <<'EOF'
import subprocess, sys, time
from gi.repository import Gio, GLib

delay, dpi = float(sys.argv[1]), sys.argv[2]
xml = """<node><interface name='org.gtk.Settings'>
<property name='Modules' type='s' access='read'/></interface></node>"""
bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
bus.register_object("/org/gtk/Settings", Gio.DBusNodeInfo.new_for_xml(xml).interfaces[0],
                    None, lambda *a: GLib.Variant("s", ""), None)
bus.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
              "RequestName", GLib.Variant("(su)", ("org.gnome.SettingsDaemon.XSettings", 4)),
              None, Gio.DBusCallFlags.NONE, -1, None)
print("owns the name", flush=True)
time.sleep(delay)
res = subprocess.run(["xrdb", "-query"], capture_output=True, text=True).stdout
res = "".join(l + "\n" for l in res.splitlines() if not l.startswith("Xft.dpi:"))
subprocess.run(["xrdb", "-nocpp", "-load"], input=res + "Xft.dpi:\t" + dpi + "\n", text=True)
print("wrote Xft.dpi", dpi, flush=True)
GLib.MainLoop().run()
EOF

Xvfb -displayfd 3 -screen 0 1920x1080x24 -dpi 96 -nolisten tcp -noreset \
    3>"$tmp/display" >"$tmp/xvfb.log" 2>&1 &
xvfb=$!
trap 'kill $xvfb 2>/dev/null || true' EXIT
for _ in 1 2 3 4 5 6 7 8 9 10; do [ -s "$tmp/display" ] && break; sleep 0.5; done
display=$(cat "$tmp/display")
export DISPLAY=":$display"

cat > "$tmp/run" <<'EOF'
#!/bin/bash
set -Eeu -o pipefail
t=$AUTOPKGTEST_TMP
fail=0
session=""
standin=""

check() { # check <what> <command...>
    local what=$1
    shift
    if "$@"; then echo "ok: $what"; else echo "FAIL: $what"; fail=1; fi
}
# The height of each bar and the title bar of the test window
looks() {
    local bars title
    bars=$(xwininfo -root -tree \
        | sed -n 's/.*"i3bar for output \([^"]*\)".* [0-9]*x\([0-9]*\)[-+][0-9]*[-+][0-9]* .*/\1=\2/p' \
        | sort | tr '\n' ' ')
    title=$(i3-msg -t get_tree | python3 -c '
import json, sys
def walk(n):
    if n.get("window_properties", {}).get("class") == "Xmessage":
        return n["deco_rect"]["height"]
    for c in n.get("nodes", []) + n.get("floating_nodes", []):
        h = walk(c)
        if h is not None:
            return h
print(walk(json.load(sys.stdin)))')
    echo "bars: ${bars}title bar: $title"
}
set_dpi() { # set_dpi [<dpi>]: Xft.dpi as gsd-xsettings writes it, or none
    xrdb -query | { grep -v '^Xft\.dpi:' || true; } > "$t/res"
    [ -z "${1-}" ] || printf 'Xft.dpi:\t%s\n' "$1" >> "$t/res"
    xrdb -nocpp -load "$t/res"
}
start_standin() { # start_standin <delay> <dpi>
    python3 "$t/xsettings" "$1" "$2" >"$t/standin.log" 2>&1 &
    standin=$!
    local end=$((SECONDS + 10))
    until grep -q 'owns the name' "$t/standin.log"; do
        [ "$SECONDS" -lt "$end" ] || { cat "$t/standin.log"; echo "FAIL: no stand-in"; exit 1; }
        sleep 0.1
    done
}
stop_standin() {
    [ -z "$standin" ] || kill "$standin" 2>/dev/null || true
    wait "$standin" 2>/dev/null || true
    standin=""
}
# start_session: run the session script as systemd runs it; prints the
# seconds until i3 answered
start_session() {
    local start=$SECONDS end=$((SECONDS + 30))
    NOTIFY_SOCKET="$t/notify" regolith-session-x11 >>"$t/session.log" 2>&1 &
    session=$!
    until i3-msg -q nop 2>/dev/null; do
        if [ "$SECONDS" -ge "$end" ]; then
            cat "$t/session.log"; echo "FAIL: i3 did not start"; exit 1
        fi
        sleep 0.1
    done
    started_after=$((SECONDS - start))
    xmessage -geometry +100+100 test >/dev/null 2>&1 &
    end=$((SECONDS + 15))
    until looks | grep -q '^bars: [^ ]*=[0-9].*title bar: [0-9]'; do
        [ "$SECONDS" -lt "$end" ] || { echo "FAIL: no bar or test window: $(looks)"; exit 1; }
        sleep 0.2
    done
    sleep 1
}
end_session() {
    pkill -u "$(id -u)" -x xmessage || true
    i3-msg -q exit || true
    local end=$((SECONDS + 10))
    while kill -0 "$session" 2>/dev/null && [ "$SECONDS" -lt "$end" ]; do sleep 0.2; done
    kill "$session" 2>/dev/null || true
    sleep 0.5
}

# How i3 looks when it starts at 96 and at 192 dpi
set_dpi 96; start_session; at96=$(looks); end_session
set_dpi 192; start_session; at192=$(looks); end_session
echo "started at 96 dpi: $at96"
echo "started at 192 dpi: $at192"
check "i3 looks different at 96 and 192 dpi" [ "$at96" != "$at192" ]

# gsd-xsettings owns its name (systemd starts i3), and writes Xft.dpi 192
# 3 seconds later
set_dpi
start_standin 3 192
start_session
login=$(looks)
echo "with gsd-xsettings writing Xft.dpi late: $login (i3 answered after ${started_after} s)"
check "i3 and its bars start at the DPI gsd-xsettings writes" [ "$login" = "$at192" ]
check "Xft.dpi is still 192" [ "$(xrdb -query | sed -n 's/^Xft\.dpi:\t//p')" = 192 ]
end_session
stop_standin

# No gsd-xsettings: no waiting
set_dpi 96
start_session
echo "without gsd-xsettings: i3 answered after ${started_after} s"
check "without gsd-xsettings the session doesn't wait" [ "$started_after" -lt 3 ]
end_session

# gsd-xsettings that never answers: the wait is bounded
start_standin 3600 192
start_session
echo "with gsd-xsettings not answering: i3 answered after ${started_after} s"
check "a gsd-xsettings that doesn't answer holds i3 back 5 s at most" [ "$started_after" -le 8 ]
check "i3 then starts at the DPI it finds" [ "$(looks)" = "$at96" ]
end_session
stop_standin

exit $fail
EOF
chmod +x "$tmp/run"

AUTOPKGTEST_TMP="$tmp" dbus-run-session -- "$tmp/run"
