#!/usr/bin/env python3
# rikkiti-msg — send a command, or run a query, against the Rikkiti compositor IPC
# (the socket at $RIKKITISOCK; i3-ipc framing). Like swaymsg.
#
#   rikkiti-msg output HDMI-A-1 scale 1.5     # run a compositor command
#   rikkiti-msg workspace 3
#   rikkiti-msg seat click left 640 360       # synthesise input (see the comp)
#   rikkiti-msg seat grab resize 1130 375     # start an edge resize, then `seat move` drags it
#   rikkiti-msg seat grab end                 # …and let go (what a real release does)
#     The point has to be on the window's edge grab: up to 8 px OUTSIDE its left, right or bottom edge, or
#     3 px inside (8 inside a side at the screens' edge, where outside can't be reached). Those edges are
#     the rect `get-windows` reports; a decorated window's title bar sits above it, and the grab beside it
#     reaches up past the title bar too (`rikkiti-msg geom <app_id> --frame` gives the whole frame).
#   rikkiti-msg get-outputs                   # query → prints the JSON reply
#   rikkiti-msg get-workspaces
#   rikkiti-msg get-windows
#
# Agent conveniences (built on get-windows; no protocol change):
#   rikkiti-msg get-window <app_id>|--focused          # the matching window object(s)
#   rikkiti-msg geom <app_id>|--focused [--frame]      # a `grim -g` geometry string
#                                                      # --frame includes the SSD titlebar
#   rikkiti-msg wait-window <app_id>|--focused [secs]  # block until it appears → rect
#   rikkiti-msg capture window <app_id>|--focused [--max N] [-o PATH]
#                                                      # comp-native window capture → PNG.
#                                                      # Reliable + NON-INTRUSIVE: grabs the
#                                                      # window even when occluded (no raise/focus).
#   rikkiti-msg capture output <name>|--focused [--max N] [-o PATH]  # one monitor (full scene)
#   rikkiti-msg capture region <x,y wxh>            [--max N] [-o PATH]  # a rectangle (may span outputs)
#   rikkiti-msg capture all                         [--max N] [-o PATH]  # the whole desktop
#   rikkiti-msg seat click-in <app_id> [button] <rx> <ry>   # click at window-relative px
#   rikkiti-msg seat move-in/dblclick-in/drag-in <app_id> … # (same, other ops)
#   rikkiti-msg seat scroll <dx> <dy>                       # wheel notches at the pointer (fractions too)
#   rikkiti-msg seat scroll-in <app_id> <rx> <ry> <dx> <dy> # …at a window-relative point
#   rikkiti-msg seat swipe-begin <fingers> | swipe-update <dx> <dy> | swipe-end [cancel]
#                                                      # a touchpad swipe, as libinput gives it (3 fingers: the
#                                                      # desktop's own — across moves the workspaces with it)
#     A click holds the button 40 ms, as a finger does (--hold MS for another); a double-click's two are 80 ms apart.
#   rikkiti-msg seat type-in <app_id> <text…> [--delay MS] # type into that window: focused and typed in one go by the
#                                                      # compositor, so the text can't land in another window
#   rikkiti-msg seat key-in <app_id> <combo>…            # keys to that window: ctrl+s, shift+Tab, Return, Next
#   rikkiti-msg wait-frame <app_id> [secs]               # until the window draws its next frame
#   rikkiti-msg wait-idle <app_id> [quiet_ms] [secs]     # until it has drawn nothing for quiet_ms (300), from now
#   rikkiti-msg resize <app_id> <w> <h>                  # a floating window's size (as get-windows' rect)
#   rikkiti-msg position <app_id> <x> <y>                # …and where its top left goes
#   rikkiti-msg capture window <app_id> --opaque …       # as seen: over what's behind it, even where covered
#   rikkiti-msg tree <app_id>|pid:N [--showing] [--json] # its elements: role, name, place in the window, states;
#                                                      # --showing: only what's in view, not scrolled out of it
#   rikkiti-msg seat click-el <app_id> <element id>      # press one (its own action: no pointer moves)
#   rikkiti-msg help [--json]                            # this, or every command as data (args, returns, needs)
#   rikkiti-msg capabilities                             # what the running compositor can do (it may be older)
#   rikkiti-msg menu show [--at X Y] [--title T] [--section FILE|-]  # the menu (at the pointer); waits for it to
#                                                      # close: {"chosen": id of a --section item, or null}
#   rikkiti-msg menu open [X Y] | menu close             # the menu, nobody waiting for its answer
#   rikkiti-msg menu-state                               # the menu as it is: levels, where, items, which is lit
#   rikkiti-msg get-pointer                              # where the pointer is, the cursor it shows, whether a drag is on
# A command the compositor refuses prints why and exits 1; one the running compositor is too old for is refused here.
import socket, struct, sys, os, json, time, glob, mmap, zlib

QUERIES = {"get-workspaces": 1, "get-windows": 2, "get-outputs": 3}
CAPTURE = 6  # RIK_MSG_CAPTURE — full-res window capture, reply = JSON + 1 memfd (docs/38)

def _candidate_socks():
    """Comp IPC sockets to try, newest first. RIKKITISOCK wins when exported; else
    every rikkiti-ipc-*.sock in the runtime dir. The comp normally exports RIKKITISOCK
    to its children, but tools launched outside that env would otherwise fail silently
    (→ black screen). request() tries each candidate, so a STALE socket left by a
    crashed/nested comp (newer mtime, nothing listening) falls through to the live one
    instead of hard-failing. mtime is read defensively (a socket can be unlinked between
    glob and stat)."""
    env = os.environ.get("RIKKITISOCK")
    if env:
        return [env]
    rt = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
    dated = []
    for p in glob.glob(os.path.join(rt, "rikkiti-ipc-*.sock")):
        try:
            dated.append((os.path.getmtime(p), p))
        except OSError:
            pass  # vanished between glob and stat — skip
    dated.sort(reverse=True)
    return [p for _, p in dated]
SUBSCRIBE = 4
TITLEBAR_H = 30  # mirrors rikkiti-comp.c TITLEBAR_H (SSD titlebar, for --frame)

def _recv_exact(s, n):
    buf = b""
    while len(buf) < n:
        c = s.recv(n - len(buf))
        if not c:
            break
        buf += c
    return buf

def request(typ, payload=b"", retries=3, timeout=3.0):
    """Send one framed message and return the reply payload bytes. Retries the
    whole exchange on a timeout / short reply (the comp can be briefly busy under
    load); raises on a hard failure."""
    candidates = _candidate_socks()
    if not candidates:
        sys.exit("rikkiti-msg: RIKKITISOCK not set and no comp socket found (run inside a Rikkiti session)")
    last = None
    for _ in range(max(1, retries)):
        for sock in candidates:  # a dead newest socket (crashed comp) falls through to the live one
            try:
                s = socket.socket(socket.AF_UNIX)
                s.settimeout(timeout)
                s.connect(sock)
                s.sendall(b"i3-ipc" + struct.pack("=II", len(payload), typ) + payload)
                hdr = _recv_exact(s, 14)
                if len(hdr) < 14:
                    last = f"{sock}: short header"; s.close(); continue
                ln = struct.unpack("=I", hdr[6:10])[0]
                data = _recv_exact(s, ln)
                s.close()
                if len(data) < ln:
                    last = f"{sock}: short body"; continue
                return data
            except (socket.timeout, OSError) as e:
                last = f"{sock}: {e}"
    sys.exit(f"rikkiti-msg: no reply from compositor ({last})")

def request_fd(typ, payload=b"", timeout=5.0):
    """Like request() but also receives ONE fd via SCM_RIGHTS — the comp's
    capture/thumbnail replies pass a memfd alongside the JSON. Returns
    (reply_bytes, fd); fd is -1 if none was attached. The caller owns the fd."""
    candidates = _candidate_socks()
    if not candidates:
        sys.exit("rikkiti-msg: no comp socket found (run inside a Rikkiti session)")
    fdsize = struct.calcsize("i")
    last = None
    for sock in candidates:
        s = None
        try:
            s = socket.socket(socket.AF_UNIX)
            s.settimeout(timeout)
            s.connect(sock)
            s.sendall(b"i3-ipc" + struct.pack("=II", len(payload), typ) + payload)
            # The fd rides the sendmsg, so the FIRST recvmsg carries it — read a
            # generous chunk (header + small JSON) with an ancillary fd buffer.
            chunk, ancdata, _flags, _addr = s.recvmsg(65536, socket.CMSG_LEN(fdsize))
            passed = -1
            for level, ctype, cdata in ancdata:
                if level == socket.SOL_SOCKET and ctype == socket.SCM_RIGHTS:
                    n = len(cdata) // fdsize
                    fds = struct.unpack("=%di" % n, cdata[:n * fdsize])
                    passed = fds[0]
                    for extra in fds[1:]:
                        os.close(extra)  # only one expected; close any surplus
            buf = bytearray(chunk)
            while len(buf) < 14:
                more = s.recv(14 - len(buf))
                if not more:
                    break
                buf += more
            if len(buf) < 14:
                last = f"{sock}: short header"
                if passed >= 0:
                    os.close(passed)
                s.close()
                continue
            ln = struct.unpack("=I", bytes(buf[6:10]))[0]
            while len(buf) - 14 < ln:
                more = s.recv(ln - (len(buf) - 14))
                if not more:
                    break
                buf += more
            s.close()
            return bytes(buf[14:14 + ln]), passed
        except (socket.timeout, OSError) as e:
            last = f"{sock}: {e}"
            if s is not None:
                try:
                    s.close()
                except OSError:
                    pass
    sys.exit(f"rikkiti-msg: no reply from compositor ({last})")


def write_png_rgba(path, w, h, stride, raw):
    """Write RGBA8 bytes (R,G,B,A per pixel; each row `stride` bytes, first w*4
    used) as a PNG using only stdlib zlib — no image-library dependency, so the
    compositor never has to encode in its event loop."""
    def _chunk(typ, data):
        return (struct.pack(">I", len(data)) + typ + data +
                struct.pack(">I", zlib.crc32(typ + data) & 0xffffffff))
    rowbytes = w * 4
    scan = bytearray()
    for y in range(h):
        off = y * stride
        scan.append(0)                       # filter type 0 (none)
        scan += raw[off:off + rowbytes]
    ihdr = struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)  # 8-bit, colour type 6 (RGBA)
    with open(path, "wb") as f:
        f.write(b"\x89PNG\r\n\x1a\n")
        f.write(_chunk(b"IHDR", ihdr))
        f.write(_chunk(b"IDAT", zlib.compress(bytes(scan), 6)))
        f.write(_chunk(b"IEND", b""))


def _emit_capture(payload, out_path, default_name):
    """Send a CAPTURE request (payload bytes), mmap the returned memfd, write it as
    a PNG to out_path (or `default_name` under /tmp), and print the path. Shared by
    every capture shape — the comp hands back the same raw-RGBA+metadata reply."""
    meta_bytes, fd = request_fd(CAPTURE, payload)
    try:
        meta = json.loads(meta_bytes.decode("utf-8", "replace") or "{}")
    except ValueError:
        meta = {}
    if not meta.get("ok") or fd < 0:
        if fd >= 0:
            os.close(fd)
        sys.exit(f"rikkiti-msg: capture failed ({payload.decode('ascii', 'replace')}: {meta})")
    w, h, stride = int(meta["w"]), int(meta["h"]), int(meta["stride"])
    try:
        mm = mmap.mmap(fd, stride * h, access=mmap.ACCESS_READ)
        raw = mm.read(stride * h)
        mm.close()
    finally:
        os.close(fd)
    write_png_rgba(out_path or default_name, w, h, stride, raw)
    print(out_path or default_name)


def _parse_region(pos):
    """Accept 'x,y wxh' (slurp/grim style) or 'x y w h' → (x, y, w, h) ints."""
    parts = " ".join(pos).replace(",", " ").replace("x", " ").split()
    if len(parts) != 4:
        sys.exit("rikkiti-msg: capture region needs 'x,y wxh' or 'x y w h'")
    try:
        x, y, w, h = (int(p) for p in parts)
    except ValueError:
        sys.exit("rikkiti-msg: region coords must be integers")
    if w <= 0 or h <= 0:
        sys.exit("rikkiti-msg: region width/height must be positive")
    return x, y, w, h


def do_capture(rest):
    """rikkiti-msg capture <window|output|region|all> … — compositor-native,
    reliable, NON-INTRUSIVE capture (docs/38); prints the PNG path.
      capture window <id|app_id|--focused> [--max N] [-o PATH]  window content
      capture output <name|--focused>      [--max N] [-o PATH]  one monitor
      capture region <x,y wxh>|<x y w h>   [--max N] [-o PATH]  a rectangle
      capture all                          [--max N] [-o PATH]  whole desktop"""
    shape = "window"
    if rest and rest[0] in ("window", "output", "region", "all"):
        shape = rest[0]; rest = rest[1:]
    # Peel common flags; the remainder is the shape's positional target.
    out_path, max_dim, pos, opaque = None, 0, [], False
    i = 0
    while i < len(rest):
        a = rest[i]
        if a == "--opaque":
            opaque = True; i += 1; continue
        if a in ("-o", "--out") and i + 1 < len(rest):
            out_path = rest[i + 1]; i += 2; continue
        if a == "--max" and i + 1 < len(rest):
            try:
                max_dim = max(0, int(rest[i + 1]))
            except ValueError:
                sys.exit("rikkiti-msg: --max needs an integer")
            i += 2; continue
        pos.append(a); i += 1

    if shape == "window":
        if not pos:
            sys.exit("rikkiti-msg: capture window needs <id>|<app_id>|--focused")
        target = pos[0]
        if target.isdigit():
            wid = int(target)
        else:
            m = pick(target)
            if not m:
                sys.exit(f"rikkiti-msg: no window matching {target!r}")
            wid = int(m[0].get("id", 0))
        if opaque:
            require("opaque_capture", "capture --opaque")
        shape = "wopq" if opaque else "win" # --opaque: composited over what's behind it (boc-r08)
        _emit_capture(f"{shape} {wid} {max_dim}".encode(), out_path,
                      f"/tmp/rikkiti-capture-{wid}.png")
    elif shape == "output":
        name = pos[0] if pos else "--focused"
        name = "@focused" if name in ("--focused", "focused") else name
        _emit_capture(f"out {name} {max_dim}".encode(), out_path,
                      "/tmp/rikkiti-capture-output.png")
    elif shape == "region":
        x, y, w, h = _parse_region(pos)
        _emit_capture(f"reg {x} {y} {w} {h} {max_dim}".encode(), out_path,
                      "/tmp/rikkiti-capture-region.png")
    elif shape == "all":
        _emit_capture(f"all {max_dim}".encode(), out_path,
                      "/tmp/rikkiti-capture-all.png")


def windows():
    return json.loads(request(QUERIES["get-windows"]).decode("utf-8", "replace"))

def pick(target):
    """Return the windows matching `target`: '--focused'/'focused' → the focused
    one; 'id:N' → that window; otherwise an exact app_id (or title) match. Empty list if none."""
    ws = windows()
    if target in ("--focused", "focused"):
        return [w for w in ws if w.get("focused")]
    if target.startswith("id:") and target[3:].isdigit(): # one window, by the id get-windows gives it
        return [w for w in ws if w.get("id") == int(target[3:])]
    return ([w for w in ws if w.get("app_id") == target] or
            [w for w in ws if w.get("title") == target] or
            [w for w in ws if target.lower() in (w.get("title") or "").lower()])

def command(text):
    """Run a compositor command. A refusal ({"success":false,"error":…}) says why and exits 1."""
    reply = request(0, text.encode())
    try:
        r = json.loads(reply.decode("utf-8", "replace"))
    except ValueError:
        r = {}
    if isinstance(r, dict) and r.get("success") is False:
        sys.exit(f"rikkiti-msg: {r.get('error') or 'refused'}")
    return reply

def window_of(target):
    """The one window `target` names (exits when none): its get-windows object."""
    m = pick(target)
    if not m:
        sys.exit(f"rikkiti-msg: no window matching {target!r}")
    return m[0]

def window_now(wid):
    for w in windows():
        if w.get("id") == wid:
            return w
    sys.exit(f"rikkiti-msg: window {wid} has gone")

def take_opt(args, name, default):
    """Remove `name VALUE` from args; its value as a float (or `default`)."""
    if name in args:
        i = args.index(name)
        if i + 1 >= len(args):
            sys.exit(f"rikkiti-msg: {name} needs a number")
        try:
            v = float(args[i + 1])
        except ValueError:
            sys.exit(f"rikkiti-msg: {name} needs a number")
        del args[i:i + 2]
        return v
    return default

HOLD_MS, DOUBLE_GAP_MS = 40, 80

def seat_click(button, xy, times, hold_ms):
    """A click as a hand makes one: to the point, press, hold, release (boc-r04: back to back, with one timestamp, a
    click had acted as two). A double-click's two clicks DOUBLE_GAP_MS apart."""
    if xy:
        command(f"seat move {xy[0]} {xy[1]}")
    for i in range(times):
        command(f"seat press {button}")
        time.sleep(hold_ms / 1000)
        command(f"seat release {button}")
        if i + 1 < times:
            time.sleep(DOUBLE_GAP_MS / 1000)

TYPE_CHUNK = 100 # code points a call: the compositor takes 200 different keys at once

def seat_type_in(target, text, delay_ms):
    """Typed into the window by the compositor: focused and typed in one go, so nothing lands elsewhere (boc-r02).
    With a delay, a key a call (each call focuses again, so a focus move in between is undone, not typed into)."""
    wid = window_of(target)["id"]
    step = 1 if delay_ms > 0 else TYPE_CHUNK
    for i in range(0, len(text), step):
        command(f"seat type-in id:{wid} {text[i:i + step].encode().hex()}")
        if delay_ms > 0:
            time.sleep(delay_ms / 1000)

def wait_frame(target, timeout):
    w = window_of(target)
    wid, start = w["id"], w.get("commits", 0)
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        if window_now(wid).get("commits", 0) > start:
            return True
        time.sleep(0.01)
    return False

def wait_idle(target, quiet_ms, timeout):
    """Settled: nothing drawn for quiet_ms, counted from now — a redraw an action starts just after this is called
    is waited for, not missed."""
    wid = window_of(target)["id"]
    begun = time.monotonic()
    deadline = begun + timeout
    while time.monotonic() < deadline:
        idle = window_now(wid).get("idle_ms", -1)
        if (idle < 0 or idle >= quiet_ms) and (time.monotonic() - begun) * 1000 >= quiet_ms:
            return True
        time.sleep(0.02)
    return False

# ---- what's in a window, as data (boc-r03) ----
# Read from the accessibility bus (AT-SPI), where Baldr apps put their tree whenever the desktop has one (as GTK and Qt
# apps do): each element's role, name, states and place in the window, found by the window's process. An element is
# pressed through its own action — no pointer moves, and it works where the window is covered.

A11Y_STATES = { # AT-SPI's StateType numbers (the ones a window can be in that an agent would ask about)
    1: "active", 2: "armed", 3: "busy", 4: "checked", 5: "collapsed", 6: "defunct", 7: "editable", 8: "enabled",
    9: "expandable", 10: "expanded", 11: "focusable", 12: "focused", 13: "has-tooltip", 16: "modal", 17: "multi-line",
    18: "multiselectable", 20: "pressed", 21: "resizable", 22: "selectable", 23: "selected", 24: "sensitive",
    25: "showing", 26: "single-line", 30: "visible", 32: "indeterminate", 33: "required", 36: "invalid-entry",
    38: "selectable-text", 39: "default", 41: "checkable", 42: "has-popup", 43: "read-only"}

def _a11y():
    try:
        import dbus
    except ImportError:
        sys.exit("rikkiti-msg: tree needs python3-dbus")
    try:
        addr = dbus.SessionBus().get_object("org.a11y.Bus", "/org/a11y/bus").GetAddress(dbus_interface="org.a11y.Bus")
        return dbus, dbus.bus.BusConnection(str(addr))
    except dbus.DBusException as e:
        sys.exit(f"rikkiti-msg: no accessibility bus ({e.get_dbus_name()})")

def _a11y_app(dbus, bus, pid):
    """The (bus name, path) of the application on the accessibility bus that is process `pid`."""
    root = bus.get_object("org.a11y.atspi.Registry", "/org/a11y/atspi/accessible/root")
    for name, path in root.GetChildren(dbus_interface="org.a11y.atspi.Accessible"):
        try:
            if int(bus.get_object("org.freedesktop.DBus", "/org/freedesktop/DBus").GetConnectionUnixProcessID(
                    name, dbus_interface="org.freedesktop.DBus")) == pid:
                return str(name), str(path)
        except dbus.DBusException:
            continue
    return None

def a11y_tree(target):
    """The window's elements: [{id, role, name, rect: [x, y, w, h] in the window, states, depth}]. 'pid:N' reads that
    process (a layer surface — the desktop, the shell — has no window to find it by); its window is then {}."""
    if target.startswith("pid:") and target[4:].isdigit():
        w, pid = {}, int(target[4:])
    else:
        w = window_of(target)
        pid = int(w.get("pid", 0))
    dbus, bus = _a11y()
    app = _a11y_app(dbus, bus, pid)
    if app is None:
        sys.exit(f"rikkiti-msg: {target!r} (pid {pid}) isn't on the accessibility bus")
    name, root = app
    out = []
    def walk(path, depth):
        o = bus.get_object(name, path)
        acc = dbus.Interface(o, "org.a11y.atspi.Accessible")
        try:
            role = str(acc.GetRoleName())
            label = str(o.Get("org.a11y.atspi.Accessible", "Name", dbus_interface="org.freedesktop.DBus.Properties"))
            st = [int(v) for v in acc.GetState()]
            bits = st[0] | (st[1] << 32) if len(st) > 1 else st[0]
            states = [n for b, n in sorted(A11Y_STATES.items()) if bits & (1 << b)]
            try:
                x, y, cw, ch = (int(v) for v in o.GetExtents(dbus.UInt32(1), dbus_interface="org.a11y.atspi.Component"))
            except dbus.DBusException:
                x = y = cw = ch = -1
            text = ""
            if not label: # a text with no name of its own (a book's page): its words, as a screen reader hears them
                try:
                    text = str(o.GetText(dbus.Int32(0), dbus.Int32(-1), dbus_interface="org.a11y.atspi.Text"))[:300]
                except dbus.DBusException:
                    text = ""
            if depth > 0: # the application itself isn't an element
                el = {"id": f"{path}", "role": role, "name": label, "rect": [x, y, cw, ch], "states": states, "depth": depth - 1}
                if text:
                    el["text"] = text
                out.append(el)
            for _, child in acc.GetChildren():
                walk(str(child), depth + 1)
        except dbus.DBusException:
            return
    walk(root, 0)
    return w, name, out

def a11y_press(target, element):
    w, name, els = a11y_tree(target)
    if not any(e["id"] == element for e in els):
        sys.exit(f"rikkiti-msg: no element {element!r} in {target!r}")
    dbus, bus = _a11y()
    try:
        ok = bus.get_object(name, element).DoAction(dbus.Int32(0), dbus_interface="org.a11y.atspi.Action")
    except dbus.DBusException as e:
        sys.exit(f"rikkiti-msg: it can't be pressed ({e.get_dbus_name()})")
    if not ok:
        sys.exit("rikkiti-msg: it didn't take the press")

# The commands as data, for `help --json` (boc-r10): each with its arguments, what it gives back, and what it needs —
# "client" (this script alone, any compositor), "compositor" (any Rikkiti compositor), or "compositor:<feature>" (one
# whose `capabilities` lists that feature). A `window` is an app_id, `id:N`, a title, or --focused.
W = {"name": "window", "type": "window", "optional": False}
def _a(name, typ, optional=False): return {"name": name, "type": typ, "optional": optional}
COMMANDS = [
    {"command": "help", "args": [_a("--json", "flag", True)], "returns": "this list", "needs": "client"},
    {"command": "capabilities", "args": [], "returns": "JSON: compositor version, verbs, seat subcommands, features; client features", "needs": "client"},
    {"command": "get-windows", "args": [], "returns": "JSON array: id, app_id, title, pid, rect, focused, commits, idle_ms…", "needs": "compositor"},
    {"command": "get-outputs", "args": [], "returns": "JSON array of screens", "needs": "compositor"},
    {"command": "get-workspaces", "args": [], "returns": "JSON array", "needs": "compositor"},
    {"command": "get-pointer", "args": [], "returns": "JSON: x, y, cursor (theme name, \"\" for an app's own picture), dragging", "needs": "compositor:pointer"},
    {"command": "get-window", "args": [W], "returns": "JSON: the window", "needs": "client"},
    {"command": "geom", "args": [W, _a("--frame", "flag", True)], "returns": "'x,y wxh'", "needs": "client"},
    {"command": "wait-window", "args": [W, _a("secs", "number", True)], "returns": "JSON rect once it exists; exit 1 on time-out", "needs": "client"},
    {"command": "wait-frame", "args": [W, _a("secs", "number", True)], "returns": "exit 0 once it draws a frame, 1 on time-out", "needs": "compositor:wait_idle"},
    {"command": "wait-idle", "args": [W, _a("quiet_ms", "number", True), _a("secs", "number", True)], "returns": "exit 0 once nothing drawn for quiet_ms (from the call), 1 on time-out", "needs": "compositor:wait_idle"},
    {"command": "tree", "args": [W, _a("--showing", "flag", True), _a("--json", "flag", True)], "returns": "its elements: role, name, rect in the window, states, the words of a text with no name, id (AT-SPI); --showing: only those in view", "needs": "client"},
    {"command": "seat click-el", "args": [W, _a("element", "id from tree")], "returns": "pressed by its own action; no pointer moves", "needs": "client"},
    {"command": "seat type-in", "args": [W, _a("text", "text"), _a("--delay", "ms", True)], "returns": "typed into that window only", "needs": "compositor:type_in"},
    {"command": "seat key-in", "args": [W, _a("combo", "key, e.g. ctrl+s, Return")], "returns": "sent to that window only", "needs": "compositor:key_in"},
    {"command": "seat click-in", "args": [W, _a("button", "left|right|middle", True), _a("rx", "number"), _a("ry", "number"), _a("--hold", "ms", True)], "returns": "a click at a window-relative point", "needs": "compositor"},
    {"command": "seat dblclick-in", "args": [W, _a("button", "left|right|middle", True), _a("rx", "number"), _a("ry", "number")], "returns": "a double-click there", "needs": "compositor"},
    {"command": "seat move-in", "args": [W, _a("rx", "number"), _a("ry", "number")], "returns": "the pointer there", "needs": "compositor"},
    {"command": "seat drag-in", "args": [W, _a("rx1", "number"), _a("ry1", "number"), _a("rx2", "number"), _a("ry2", "number"), _a("button", "left|right|middle", True)], "returns": "a drag", "needs": "compositor"},
    {"command": "seat scroll-in", "args": [W, _a("rx", "number"), _a("ry", "number"), _a("dx", "notches"), _a("dy", "notches")], "returns": "the wheel there", "needs": "compositor"},
    {"command": "seat swipe-begin", "args": [_a("fingers", "number")], "returns": "a touchpad swipe starts (3 fingers: the desktop's)", "needs": "compositor:swipe"},
    {"command": "seat swipe-update", "args": [_a("dx", "touchpad units"), _a("dy", "touchpad units")], "returns": "the fingers move", "needs": "compositor:swipe"},
    {"command": "seat swipe-end", "args": [_a("cancel", "flag", True)], "returns": "the fingers lift", "needs": "compositor:swipe"},
    {"command": "seat click", "args": [_a("button", "left|right|middle", True), _a("x", "number", True), _a("y", "number", True), _a("--hold", "ms", True)], "returns": "a click (desktop coordinates)", "needs": "compositor"},
    {"command": "seat scroll", "args": [_a("dx", "notches"), _a("dy", "notches")], "returns": "the wheel at the pointer", "needs": "compositor"},
    {"command": "resize", "args": [W, _a("w", "number"), _a("h", "number")], "returns": "a floating window's size; refused for tiled/maximized/full screen", "needs": "compositor:resize"},
    {"command": "position", "args": [W, _a("x", "number"), _a("y", "number")], "returns": "where its top left goes", "needs": "compositor:resize"},
    {"command": "capture window", "args": [W, _a("--opaque", "flag", True), _a("--max", "pixels", True), _a("-o", "path", True)], "returns": "PNG path; --opaque: as seen, even where covered", "needs": "compositor (--opaque: compositor:opaque_capture)"},
    {"command": "capture region", "args": [_a("x,y wxh", "rect"), _a("--max", "pixels", True), _a("-o", "path", True)], "returns": "PNG path", "needs": "compositor"},
    {"command": "capture output", "args": [_a("name", "screen | --focused"), _a("-o", "path", True)], "returns": "PNG path", "needs": "compositor"},
    {"command": "menu show", "args": [_a("--at", "x y", True), _a("--title", "text", True), _a("--section", "file of items (- = stdin)", True)], "returns": "waits for the menu to close: {\"chosen\": the id of a --section item (\"Label<TAB>:id\"), or null}", "needs": "compositor:menu"},
    {"command": "menu open", "args": [_a("x", "number", True), _a("y", "number", True)], "returns": "the menu, at the pointer without x y", "needs": "compositor:menu"},
    {"command": "menu close", "args": [], "returns": "the menu closed, nothing chosen", "needs": "compositor:menu"},
    {"command": "menu-state", "args": [], "returns": "JSON: open, levels (x y w h hover from, items: label y h hint submenu disabled check)", "needs": "compositor:menu"},
    {"command": "<verb> …", "args": [], "returns": "any compositor verb `capabilities` lists; a refusal says why and exits 1", "needs": "compositor"},
]

def capabilities():
    """The running compositor's own answer, with what this script can do: they can be different builds."""
    try:
        comp = json.loads(request(10).decode("utf-8", "replace")) # RIK_MSG_GET_CAPABILITIES
    except (ValueError, OSError):
        comp = {}
    if not isinstance(comp, dict) or "version" not in comp: # a compositor from before the question existed
        comp = {"version": None, "predates_capabilities": True, "verbs": [], "seat": [],
                "features": {"type_in": False, "key_in": False, "wait_idle": False, "resize": False,
                             "opaque_capture": False, "errors": False, "agent_seat": False, "swipe": False}}
    try:
        import dbus # noqa: F401
        a11y = True
    except ImportError:
        a11y = False
    comp["client"] = {"tree": a11y, "click_el": a11y, "scroll_in": True, "click_hold": True, "help_json": True}
    return comp

def require(feature, what):
    """Refuse a command the running compositor can't do, rather than send it: one from before a feature ignores the
    command and replies success, so an agent would think it had typed. (One extra request: cheap.)"""
    if not capabilities().get("features", {}).get(feature):
        sys.exit(f"rikkiti-msg: the running compositor can't do {what} yet — it's older than this rikkiti-msg "
                 "(`rikkiti-msg capabilities`); the next Rikkiti package brings it")

def usage():
    """The commands: this script's own header, so the help can't drift from it."""
    lines = []
    with open(os.path.realpath(__file__), encoding="utf-8") as f:
        for line in f.read().splitlines()[1:]: # past the #! line
            if not line.startswith("#"):
                break
            lines.append(line[2:] if line.startswith("# ") else line[1:])
    return "\n".join(lines)

def main():
    args = sys.argv[1:]
    if args and args[0] in ("help", "--help", "-h"):
        print(json.dumps(COMMANDS, indent=1) if "--json" in args[1:] else usage())
        return
    if args and args[0] == "capabilities":
        print(json.dumps(capabilities(), indent=1))
        return
    if not args:
        sys.exit("usage: rikkiti-msg <command…> | get-outputs|get-workspaces|get-windows | "
                 "get-window <app_id>|--focused | geom <app_id>|--focused [--frame] | "
                 "wait-window <app_id> [secs] | "
                 "capture window|output|region|all [target] [--max N] [-o PATH] | "
                 "seat click-in|move-in|drag-in|scroll-in|type-in|key-in <app_id> … | "
                 "wait-frame|wait-idle <app_id> … | resize|position <app_id> a b")

    if args[0] in ("get-window", "geom"):
        if len(args) < 2:
            sys.exit(f"rikkiti-msg: {args[0]} needs <app_id> or --focused")
        matches = pick(args[1])
        if not matches:
            sys.exit(f"rikkiti-msg: no window matching {args[1]!r}")
        if args[0] == "get-window":
            print(json.dumps(matches[0] if len(matches) == 1 else matches, indent=1))
            return
        # geom → a grim geometry "x,y WxH"
        frame = "--frame" in args[2:]
        r = matches[0].get("rect") or {}
        x, y, w, h = r.get("x", 0), r.get("y", 0), r.get("width", 0), r.get("height", 0)
        if frame and matches[0].get("ssd"):
            y -= TITLEBAR_H; h += TITLEBAR_H  # the SSD titlebar sits above the content rect
        print(f"{x},{y} {w}x{h}")
        return

    if args[0] == "capture":
        do_capture(args[1:])
        return

    if args[0] == "wait-window":
        if len(args) < 2:
            sys.exit("rikkiti-msg: wait-window needs <app_id> or --focused")
        timeout = float(args[2]) if len(args) > 2 else 10.0
        deadline = time.monotonic() + timeout
        while True:
            m = pick(args[1])
            if m:
                print(json.dumps(m[0].get("rect") or {}))
                return
            if time.monotonic() >= deadline:
                sys.exit(f"rikkiti-msg: timed out after {timeout:g}s waiting for {args[1]!r}")
            time.sleep(0.2)

    if args[0] in ("wait-frame", "wait-idle"):
        if len(args) < 2:
            sys.exit(f"rikkiti-msg: {args[0]} needs <app_id>")
        require("wait_idle", args[0])
        if args[0] == "wait-frame":
            ok = wait_frame(args[1], float(args[2]) if len(args) > 2 else 5.0)
        else:
            ok = wait_idle(args[1], float(args[2]) if len(args) > 2 else 300.0, float(args[3]) if len(args) > 3 else 10.0)
        if not ok:
            sys.exit(f"rikkiti-msg: {args[0]} timed out on {args[1]!r}")
        return

    if args[0] == "tree":
        if len(args) < 2:
            sys.exit("rikkiti-msg: tree needs <app_id>")
        _, _, els = a11y_tree(args[1])
        if "--showing" in args[2:]: # only what's on screen now, not scrolled out of its view (Baldr 169)
            els = [e for e in els if "showing" in e["states"]]
        if "--json" in args[2:]:
            print(json.dumps(els, indent=1))
        else: # one line each, indented by depth: role "name" x,y wxh [states] [text "words"] id
            for e in els:
                x, y, w, h = e["rect"]
                words = f" text {json.dumps(e['text'])}" if e.get("text") else ""
                print(f"{'  ' * e['depth']}{e['role']} {json.dumps(e['name'])} {x},{y} {w}x{h} [{' '.join(e['states'])}]{words} {e['id']}")
        return

    if args[0] == "seat" and len(args) >= 2 and args[1] == "click-el":
        if len(args) != 4:
            sys.exit("rikkiti-msg: seat click-el needs <app_id> <element id> (from `rikkiti-msg tree`)")
        a11y_press(args[2], args[3])
        sys.stdout.write('{"success":true}\n')
        return

    if args[0] in ("resize", "position"):
        if len(args) != 4:
            sys.exit(f"rikkiti-msg: {args[0]} needs <app_id> and two numbers")
        require("resize", args[0])
        command(f"{args[0]} id:{window_of(args[1])['id']} {args[2]} {args[3]}")
        return

    if args[0] == "seat" and len(args) >= 2 and args[1].startswith("swipe-"):
        require("swipe", f"seat {args[1]}") # an older compositor would say yes and do nothing
        command(" ".join(args))
        return

    if args[0] == "seat" and len(args) >= 2 and args[1] in ("type-in", "key-in"):
        rest = args[2:]
        delay = take_opt(rest, "--delay", 0)
        if len(rest) < 2:
            sys.exit(f"rikkiti-msg: seat {args[1]} needs <app_id> and {'text' if args[1] == 'type-in' else 'a key'}")
        require("type_in" if args[1] == "type-in" else "key_in", f"seat {args[1]}")
        if args[1] == "type-in":
            seat_type_in(rest[0], " ".join(rest[1:]), delay)
        else:
            wid = window_of(rest[0])["id"]
            for combo in rest[1:]:
                command(f"seat key-in id:{wid} {combo}")
                if delay > 0:
                    time.sleep(delay / 1000)
        return

    if args[0] == "seat" and len(args) >= 2 and args[1] == "scroll-in":
        if len(args) != 7:
            sys.exit("rikkiti-msg: seat scroll-in needs <app_id> <rx> <ry> <dx> <dy>")
        r = window_of(args[2]).get("rect") or {}
        try:
            rx, ry, dx, dy = (float(v) for v in args[3:7])
        except ValueError:
            sys.exit("rikkiti-msg: seat scroll-in's numbers aren't numbers")
        command(f"seat move {round(r.get('x', 0) + rx)} {round(r.get('y', 0) + ry)}")
        command(f"seat scroll {dx:g} {dy:g}")
        return

    # Window-relative pointer input: resolve <app_id> → its rect origin and offset
    # the coordinate PAIRS, then forward the absolute `seat <op>` command. Mirrors
    # the absolute grammar (button leads click/dblclick, trails drag):
    #   seat click-in|dblclick-in <app_id> [button] <rx> <ry>
    #   seat move-in              <app_id> <rx> <ry>
    #   seat drag-in              <app_id> <rx1> <ry1> <rx2> <ry2> [button]
    SEAT_IN = {"click-in": "click", "dblclick-in": "dblclick", "move-in": "move", "drag-in": "drag"}
    if args[0] == "seat" and len(args) >= 2 and args[1] in SEAT_IN:
        op = SEAT_IN[args[1]]
        rest = args[2:]
        hold = take_opt(rest, "--hold", HOLD_MS)
        if not rest:
            sys.exit(f"rikkiti-msg: seat {args[1]} needs <app_id> and coordinates")
        matches = pick(rest[0])
        if not matches:
            sys.exit(f"rikkiti-msg: no window matching {rest[0]!r}")
        r = matches[0].get("rect") or {}
        ox, oy = int(r.get("x", 0)), int(r.get("y", 0))
        rest = rest[1:]
        BTN = ("left", "right", "middle", "back", "forward")
        lead, trail = [], []
        if op in ("click", "dblclick") and rest and rest[0] in BTN:
            lead = [rest[0]]; rest = rest[1:]
        if op == "drag" and rest and rest[-1] in BTN:
            trail = [rest[-1]]; rest = rest[:-1]
        try:
            nums = [float(x) for x in rest]
        except ValueError:
            sys.exit(f"rikkiti-msg: seat {args[1]} coordinates must be numbers")
        if not nums or len(nums) % 2 != 0:
            sys.exit(f"rikkiti-msg: seat {args[1]} needs x y coordinate pair(s)")
        absxy = []
        for i in range(0, len(nums), 2):
            absxy += [str(round(nums[i] + ox)), str(round(nums[i + 1] + oy))]
        args = ["seat", op] + lead + absxy + trail  # forward the absolute command
        if op in ("click", "dblclick"):
            args += ["--hold", f"{hold:g}"]

    if args[0] in QUERIES:
        sys.stdout.write(request(QUERIES[args[0]]).decode("utf-8", "replace").rstrip("\n") + "\n")
        return

    if args[0] == "get-pointer":
        require("pointer", "the pointer's state")
        sys.stdout.write(request(13).decode("utf-8", "replace").rstrip("\n") + "\n") # RIK_MSG_GET_POINTER
        return
    if args[0] == "menu-state":
        require("menu", "the menu")
        sys.stdout.write(request(12).decode("utf-8", "replace").rstrip("\n") + "\n") # RIK_MSG_MENU_STATE
        return
    if args[0] == "menu" and len(args) >= 2 and args[1] == "show":
        require("menu", "the menu")
        rest = args[2:]
        opts = []
        def text_opt(name):
            if name not in rest:
                return None
            i = rest.index(name)
            if i + 1 >= len(rest):
                sys.exit(f"rikkiti-msg: menu show {name} needs a value")
            v = rest[i + 1]
            del rest[i:i + 2]
            return v
        if "--at" in rest:
            i = rest.index("--at")
            try:
                opts.append(f"!at {float(rest[i + 1]):g} {float(rest[i + 2]):g}")
            except (IndexError, ValueError):
                sys.exit("rikkiti-msg: menu show --at takes X Y")
            del rest[i:i + 3]
        title = text_opt("--title")
        if title:
            opts.append(f"!title {title}")
        section = text_opt("--section")
        body = ""
        if section == "-":
            body = sys.stdin.read()
        elif section:
            with open(section, encoding="utf-8") as f:
                body = f.read()
        payload = ("\n".join(opts) + ("\n" if opts else "") + body).encode()
        sys.stdout.write(request(11, payload, retries=1, timeout=None).decode("utf-8", "replace").rstrip("\n") + "\n")
        return

    # seat click / dblclick [button] [x y] [--hold MS]: pressed and released with a hold between (boc-r04).
    if args[0] == "seat" and len(args) >= 2 and args[1] in ("click", "dblclick"):
        rest = args[2:]
        hold = take_opt(rest, "--hold", HOLD_MS)
        button = "left"
        if rest and rest[0] in ("left", "right", "middle", "back", "forward"):
            button = rest[0]; rest = rest[1:]
        if len(rest) not in (0, 2):
            sys.exit(f"rikkiti-msg: seat {args[1]} takes [button] [x y]")
        seat_click(button, rest, 2 if args[1] == "dblclick" else 1, hold)
        sys.stdout.write('{"success":true}\n')
        return

    # Anything else is a compositor COMMAND (type 0). The comp replies {"success":…}; a refusal exits 1.
    reply = command(" ".join(args))
    sys.stdout.write(reply.decode("utf-8", "replace").rstrip("\n") + "\n")

if __name__ == "__main__":
    main()
