#!/bin/bash
# Starchaser owns crash notices for this window.
export QS_DISABLE_CRASH_HANDLER=1 STARCHASER_QML_APP=capture
# summary: Capture the screen, an area, text, or a QR code.
# Screenshots for Starchaser (Print, Shift+Print, Super+Shift+S).
#
#   starchaser screenshot region [--copy-only]   pick an area of the screen as it was when the key was pressed
#   starchaser screenshot screen [--copy-only]   the whole screen (every monitor)
#   starchaser screenshot text             copy text from an area of the screen
#   starchaser screenshot qr               copy a QR code from an area of the screen
#
# Pictures are saved in ~/Pictures/Screenshots (YYYY-MM-DD_HH-MM-SS.png; a second one in the same second gets -2, -3
# and so on, never written over the first) AND copied to the clipboard, as other desktops do: a capture always leaves
# a file. --copy-only skips the file; --save is the default and is still accepted.
#
# The screen is captured FIRST, the moment the key is pressed, and the area is cut out of that capture afterward,
# so the picker cannot close quick settings or the notification list before the shot. While the area is being
# picked, the captured frame is shown over the screen, frozen, so what you see is what you get.
# Nothing here moves the pointer.
set -uo pipefail
usage() {
    echo "Usage: starchaser screenshot [region|screen] [--copy-only]"
    echo "       starchaser screenshot text|qr|color"
}
for a in "$@"; do
    case "$a" in
    -h|--help|help)
        usage; echo
        echo "Takes a screenshot, saves it in ~/Pictures/Screenshots and copies it (Print, Shift+Print, Super+Shift+S)."
        echo "  region    pick an area of the screen (the default)"
        echo "  screen    the whole screen, every monitor"
        echo "  text      pick an area and copy its text"
        echo "  color     pick a color and copy its hex value"
        echo "  qr        pick an area and copy a QR code (Open can open a web link)"
        echo "  --copy-only  copy a region or screen picture without saving a file"
        exit 0 ;;
    esac
done
# arguments are checked before anything is captured: a mistyped one never takes a picture or posts a notice
MODE=${1:-region}; SAVE=1
case "$MODE" in
    region|screen|text|qr|color) ;;
    -*) echo "starchaser screenshot: unknown option '$MODE'. Run 'starchaser screenshot --help' for more help." >&2; usage >&2; exit 2 ;;
    *)  echo "starchaser screenshot: unknown mode '$MODE' (use region, screen, text or qr). Run 'starchaser screenshot --help' for more help." >&2; usage >&2; exit 2 ;;
esac
case "${2:-}" in
    "") ;;
    --save|--copy-only)
        case "$MODE" in
            text|qr|color) echo "starchaser screenshot: $2 is only for region or screen" >&2; usage >&2; exit 2 ;;
        esac
        [ "$2" = --copy-only ] && SAVE= ;;
    *) echo "starchaser screenshot: unexpected argument '$2'" >&2; usage >&2; exit 2 ;;
esac
[ $# -le 2 ] || { echo "starchaser screenshot: too many arguments" >&2; usage >&2; exit 2; }
RUN=${XDG_RUNTIME_DIR:-/tmp}
D=$(mktemp -d "$RUN/starchaser-shot.XXXXXX") || exit 1
FREEZE=
cleanup() { [ -n "$FREEZE" ] && kill "$FREEZE" 2>/dev/null; rm -rf "$D"; }
trap cleanup EXIT
# a Starchaser tool the one command can run (the picker and the result helper; each has a fallback during repair)
has_tool() { starchaser "$@" --help >/dev/null 2>&1; }
fail() {
    local title="Screenshot not taken"
    case "$MODE" in
        text) title="Text not copied" ;;
        qr) title="QR code not copied" ;;
        color) title="Color not copied" ;;
    esac
    /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser -i dialog-error "$title" "$1" 2>/dev/null
    exit 1
}

# 1. the whole screen, now (PPM: no compression, so it is taken in a moment even on a big screen)
grim -t ppm "$D/full.ppm" 2>/dev/null || fail "The screen couldn't be captured."

# Copied (and saved), then a short notice that says so: with nothing to see, a new user couldn't tell the key had
# worked, or where the picture went. It comes after the capture, so it is never in the picture. Its picture is the
# saved file, never one in $D (deleted on exit, before the notice is drawn). Copying and saving don't depend on each
# other: a full or read-only Pictures folder still leaves the shot on the clipboard, and the notice says which failed.
finish() {      # $1: the finished PNG
    local f="" copied="" saved="" title body
    wl-copy --type image/png < "$1" && copied=1
    if [ -n "$SAVE" ]; then
        dir="$HOME/Pictures/Screenshots"
        local base n=1
        base="$dir/$(date +%Y-%m-%d_%H-%M-%S)"
        f="$base.png"
        # the name is claimed first (noclobber creates it only if it isn't there yet, in one step), so two saves in
        # the same second (Shift+Print twice) each get their own file instead of the second replacing the first
        if mkdir -p "$dir"; then
            while ! (set -C; : >"$f") 2>/dev/null; do
                n=$((n + 1))
                if [ ! -e "$f" ] || [ "$n" -gt 99 ]; then f=""; break; fi     # not a name clash: can't write there
                f="$base-$n.png"
            done
        else
            f=""
        fi
        if [ -n "$f" ] && cp "$1" "$f"; then saved=1; else [ -n "$f" ] && rm -f "$f"; f=""; fi
    fi
    # the card says where the picture went: the file's name and folder first, then the clipboard
    if [ -n "$copied" ] && [ -n "$saved" ]; then
        title="Screenshot saved and copied"; body="${f##*/} in Pictures/Screenshots. Paste it where you want it."
    elif [ -n "$copied" ]; then
        title="Screenshot copied"; body="Paste it where you want it."
        [ -n "$SAVE" ] && body="$body It couldn't be saved in Pictures/Screenshots."
    elif [ -n "$saved" ]; then
        title="Screenshot saved"; body="It's in Pictures/Screenshots. It couldn't be copied, so it can't be pasted."
    elif [ -n "$SAVE" ]; then
        fail "It couldn't be copied or saved in Pictures/Screenshots."
    else
        fail "It couldn't be copied."
    fi
    # Result actions: open=Open, edit=Edit, text=Copy text (the helper owns the action listener).
    if has_tool capture result; then
        if [ -z "$f" ]; then
            local cache="${XDG_CACHE_HOME:-$HOME/.cache}/starchaser/captures"
            mkdir -p "$cache" || fail "The capture preview couldn't be kept."
            f=$(mktemp "$cache/screenshot.XXXXXX.png") || fail "The capture preview couldn't be kept."
            cp "$1" "$f" || fail "The capture preview couldn't be kept."
        fi
        # A clipboard failure keeps its honest title instead of reporting a successful copy.
        if [ -n "$copied" ]; then
            starchaser capture result screenshot "$f" "$body" "$title" </dev/null >/dev/null 2>&1 &
            return
        fi
    fi
    /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser ${f:+-i "$f"} -t 4000 "$title" "$body" 2>/dev/null
}

if [ "$MODE" = screen ]; then
    magick "$D/full.ppm" "$D/shot.png" 2>/dev/null || fail "The capture couldn't be saved as a picture."
    finish "$D/shot.png"
    exit 0
fi

# The cockpit picker owns both the frozen frame and selection. The fallback keeps capture usable during repair.
if has_tool capture picker; then
    pick_args=(); [ "$MODE" = color ] && pick_args=(--color)
    geo=$(starchaser capture picker "$D/full.ppm" "${pick_args[@]}") || fail "The capture picker couldn't open. Try again."
    [ -n "$geo" ] || exit 0
else
# 2. the captured frame, frozen over every monitor while the area is picked (a small Quickshell overlay; each
#    monitor shows its own part of the capture). If it can't start, the picking happens over the live screen:
#    the shot still comes from the capture in step 1.
mkdir -p "$D/freeze"
cat > "$D/freeze/shell.qml" <<'QML'
import QtQuick
import Quickshell
import Quickshell.Wayland
Scope {
    // the layout's top left corner and size (logical pixels): the capture covers exactly this box
    readonly property real left: Math.min(...Quickshell.screens.map(s => s.x))
    readonly property real top: Math.min(...Quickshell.screens.map(s => s.y))
    readonly property real wide: Math.max(...Quickshell.screens.map(s => s.x + s.width)) - left
    readonly property real tall: Math.max(...Quickshell.screens.map(s => s.y + s.height)) - top
    id: root
    Variants {
        model: Quickshell.screens
        PanelWindow {
            required property var modelData
            screen: modelData
            anchors { top: true; bottom: true; left: true; right: true }
            exclusionMode: ExclusionMode.Ignore
            color: "black"
            WlrLayershell.layer: WlrLayer.Overlay
            WlrLayershell.namespace: "starchaser-screenshot-freeze"
            WlrLayershell.keyboardFocus: WlrKeyboardFocus.None
            Image {
                x: root.left - modelData.x; y: root.top - modelData.y
                width: root.wide; height: root.tall
                source: "file://" + Quickshell.env("STARCHASER_FREEZE")
                fillMode: Image.Stretch
                smooth: false; cache: false
            }
        }
    }
}
QML
if command -v qs >/dev/null; then
    STARCHASER_FREEZE="$D/full.ppm" qs -p "$D/freeze/shell.qml" >/dev/null 2>&1 &
    FREEZE=$!
    # wait (up to a second) until it is on screen, so the picker opens over it
    for _ in $(seq 20); do
        hyprctl layers -j 2>/dev/null | grep -q starchaser-screenshot-freeze && break
        kill -0 "$FREEZE" 2>/dev/null || break
        sleep 0.05
    done
fi

# 3. pick the area (Esc: no screenshot)
geo=$(slurp 2>/dev/null) || exit 0
[ -n "$FREEZE" ] && kill "$FREEZE" 2>/dev/null; FREEZE=

fi

# 4. cut it out of the capture. slurp gives "X,Y WxH" in the layout's logical pixels; the capture is the layout's
#    bounding box at grim's scale (the largest monitor scale), so scale by capture width / layout width.
read -r ox oy lw lh < <(hyprctl monitors -j | python3 -c '
import json, sys
ms = json.load(sys.stdin)
def size(m):                                     # logical size; a rotated monitor (transform 1, 3, 5, 7) swaps
    w, h = m["width"] / m["scale"], m["height"] / m["scale"]
    return (h, w) if m.get("transform", 0) % 2 else (w, h)
x0 = min(m["x"] for m in ms); y0 = min(m["y"] for m in ms)
print(x0, y0, max(m["x"] + size(m)[0] for m in ms) - x0, max(m["y"] + size(m)[1] for m in ms) - y0)')
read -r iw ih < <(magick identify -format '%w %h' "$D/full.ppm")
[ -n "${lh:-}" ] && [ -n "${ih:-}" ] || fail "The screen layout couldn't be read."
crop=$(python3 -c '
import sys, re
x, y, w, h = map(float, re.split(r"[ ,x]", sys.argv[1].strip()))
ox, oy, lw, lh, iw, ih = map(float, sys.argv[2:])
s = iw / lw
X, Y = round((x - ox) * s), round((y - oy) * s)
W, H = max(1, round(w * s)), max(1, round(h * s))
print(f"{W}x{H}+{X}+{Y}")' "$geo" "$ox" "$oy" "$lw" "$lh" "$iw" "$ih") || fail "The area couldn't be read."
magick "$D/full.ppm" -crop "$crop" +repage "$D/shot.png" 2>/dev/null || fail "The area couldn't be cut out."

case "$MODE" in
    color)
        color=$(magick "$D/shot.png" -gravity center -crop 1x1+0+0 +repage -depth 8 txt:- | python3 -c 'import re,sys; m=re.search(r"#[0-9A-Fa-f]{6}", sys.stdin.read()); print(m.group(0).lower() if m else "")')
        [ -n "$color" ] || fail "The color couldn't be read."
        printf '%s' "$color" | wl-copy --type text/plain || fail "The color couldn't be copied."
        /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser "Color copied" "$color" 2>/dev/null
        ;;
    text)
        command -v tesseract >/dev/null || fail "Tesseract is not installed. Install tesseract and tesseract-data-eng to copy text."
        read -r cw ch < <(magick identify -format '%w %h' "$D/shot.png")
        [ -n "${cw:-}" ] && [ -n "${ch:-}" ] || fail "The area's size couldn't be read."
        # Small letters are easier to read at twice their size; large selections already have enough pixels.
        resize=()
        if [ "$cw" -lt 1200 ] || [ "$ch" -lt 600 ]; then resize=(-resize 200%); fi
        magick "$D/shot.png" "${resize[@]}" -colorspace Gray "$D/read.png" 2>/dev/null || fail "The picture couldn't be prepared for reading."
        text=$(tesseract "$D/read.png" stdout -l eng 2>/dev/null) || fail "The text couldn't be read. Make sure Tesseract's English language data is installed."
        text=$(printf '%s' "$text" | python3 -c 'import sys; print(sys.stdin.read().strip(), end="")')
        if [ -z "$text" ]; then
            /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser -t 4000 "No text found" "Try selecting a larger area around the words." 2>/dev/null
            exit 0
        fi
        printf '%s' "$text" | wl-copy --type text/plain || fail "The text couldn't be copied."
        body=$(printf '%s' "$text" | python3 -c 'import html, sys; s = " ".join(sys.stdin.read().split()); print(html.escape(s[:60] + ("…" if len(s) > 60 else ""), quote=False))')
        /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser -t 4000 -- "Text copied" "$body" 2>/dev/null
        ;;
    qr)
        command -v zbarimg >/dev/null || fail "The QR code reader is not installed. Install zbar to read QR codes."
        text=$(zbarimg --quiet --raw -Sdisable -Sqrcode.enable "$D/shot.png" 2>/dev/null) || text=
        if [ -z "$text" ]; then
            # A code selected too tightly may be missing the blank margin the reader needs.
            magick "$D/shot.png" -bordercolor white -border 20 "$D/bordered.png" 2>/dev/null || fail "The picture couldn't be prepared for reading."
            text=$(zbarimg --quiet --raw -Sdisable -Sqrcode.enable "$D/bordered.png" 2>/dev/null) || text=
        fi
        if [ -z "$text" ]; then
            /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser -t 4000 "No QR code found" "Select the whole code, with a little blank margin around it." 2>/dev/null
            exit 0
        fi
        printf '%s' "$text" | wl-copy --type text/plain || fail "The QR code couldn't be copied."
        body=$(printf '%s' "$text" | python3 -c 'import html, sys; print(html.escape(sys.stdin.read(), quote=False), end="")')
        # Open is offered only for one web link (a crop with several codes, or a code with spaces, is just copied).
        link=
        case "$text" in
            *[[:space:]]*) ;;
            http://*|https://*) link=1 ;;
        esac
        case "${link:+open}" in
            open)
                # The key press returns now. Waiting for Open is bounded even if the notification stays visible.
                (
                    answer=$(timeout 15 /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser -t 15000 -w -A open=Open -- "QR code copied" "$body" 2>/dev/null) || exit 0
                    [ "$answer" = open ] && xdg-open "$text"
                ) </dev/null >/dev/null 2>&1 &
                ;;
            *) /bin/sh -c 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi' starchaser notify -a Starchaser -t 4000 -- "QR code copied" "$body" 2>/dev/null ;;
        esac
        ;;
    *) finish "$D/shot.png" ;;
esac
