#!/usr/bin/env python3
# XUI designer live capture: a LEAP plugin the viewer runs (Python 3, standard library only).
#
# Add to the viewer's command line (shortcut target, or Visual Studio debugging arguments):
#     --leap "python C:/path/to/xui-capture.py"
# with forward slashes: LEAP's command parser reads backslashes as escapes and drops them.
# then start the viewer. The designer's Capture button calls http://127.0.0.1:47823/capture:
# the whole live view tree (paths, classes, rects, visibility, control values), the UI scale,
# skin, theme and language, and a snapshot of the window with its UI (/snapshot.bmp).
# Optional: --port N.
#
# stdout belongs to the LEAP protocol: never print there. stderr lines go to the viewer log.
#
# This file is part of the XUI designer, LGPL 2.1-only.

import base64
import http.server
import json
import os
import struct
import sys
import tempfile
import threading
import time
import urllib.parse
import uuid

VERSION = 4 # the designer's LIVE_VERSION: raise both when the reply changes
PORT = 47823
SETTINGS = ['UIScaleFactor', 'SkinCurrent', 'SkinCurrentTheme', 'Language', 'InstallLanguage']


def log(msg):
    sys.stderr.write(f'xui-capture: {msg}\n')
    sys.stderr.flush()


# ---- LLSD: binary in (viewer -> plugin), notation out (plugin -> viewer), as llleap.cpp does ----

def parse_binary(buf):
    """LLSDBinaryParser: the '<? LLSD/Binary ?>' header line, then one value."""
    pos = 0
    if buf.startswith(b'<?'):
        pos = buf.index(b'\n') + 1

    def u32():
        nonlocal pos
        (n,) = struct.unpack_from('>I', buf, pos)
        pos += 4
        return n

    def raw(n):
        nonlocal pos
        b = buf[pos:pos + n]
        pos += n
        return b

    def value():
        nonlocal pos
        c = buf[pos:pos + 1]
        pos += 1
        if c == b'!':
            return None
        if c == b'1':
            return True
        if c == b'0':
            return False
        if c == b'i':
            (n,) = struct.unpack_from('>i', buf, pos)
            pos += 4
            return n
        if c == b'r':
            (f,) = struct.unpack_from('>d', buf, pos)
            pos += 8
            return f
        if c == b'd':
            (f,) = struct.unpack_from('<d', buf, pos)  # dates are written in host order
            pos += 8
            return {'date': f}
        if c == b'u':
            return str(uuid.UUID(bytes=raw(16)))
        if c in (b's', b'l'):
            return raw(u32()).decode('utf-8', 'replace')
        if c == b'b':
            return {'binary': base64.b64encode(raw(u32())).decode('ascii')}
        if c == b'[':
            out = [value() for _ in range(u32())]
            pos += 1  # ']'
            return out
        if c == b'{':
            out = {}
            for _ in range(u32()):
                kc = buf[pos:pos + 1]
                pos += 1
                if kc != b'k':
                    raise ValueError(f'binary LLSD: map key marker {kc!r}')
                k = raw(u32()).decode('utf-8', 'replace')
                out[k] = value()
            pos += 1  # '}'
            return out
        raise ValueError(f'binary LLSD: unknown marker {c!r} at {pos - 1}')

    return value()


def notation(v):
    """LLSDNotationFormatter output for the values this plugin sends."""
    if v is None:
        return '!'
    if v is True:
        return 'true'
    if v is False:
        return 'false'
    if isinstance(v, int):
        return f'i{v}'
    if isinstance(v, float):
        return f'r{v!r}'
    if isinstance(v, str):
        return "'" + v.replace('\\', '\\\\').replace("'", "\\'") + "'"
    if isinstance(v, (list, tuple)):
        return '[' + ','.join(notation(x) for x in v) + ']'
    if isinstance(v, dict):
        return '{' + ','.join(notation(str(k)) + ':' + notation(x) for k, x in v.items()) + '}'
    raise TypeError(f'notation: {type(v).__name__}')


# ---- LEAP ----

class Leap:
    def __init__(self):
        self.stdin = sys.stdin.buffer
        self.stdout = sys.stdout.buffer
        self.out_lock = threading.Lock()
        self.reply_pump = None
        self.features = {}
        self.next_id = 0
        self.waiting = {}  # reqid -> [Event, reply]
        self.wait_lock = threading.Lock()

    def read(self):
        """One '<length>:<LLSD>' message, or None at end of input (the viewer quit)."""
        n = b''
        while True:
            c = self.stdin.read(1)
            if not c:
                return None
            if c == b':':
                break
            if not c.isspace():
                n += c
        data = self.stdin.read(int(n))
        if len(data) < int(n):
            return None
        return parse_binary(data)

    def send(self, pump, data):
        body = notation({'pump': pump, 'data': data}).encode('utf-8')
        with self.out_lock:
            self.stdout.write(str(len(body)).encode('ascii') + b':' + body)
            self.stdout.flush()

    def request(self, pump, data, timeout=60.0):
        """Posts data to an event API pump and waits for the reply that carries its reqid."""
        with self.wait_lock:
            self.next_id += 1
            rid = self.next_id
            slot = [threading.Event(), None]
            self.waiting[rid] = slot
        self.send(pump, {**data, 'reply': self.reply_pump, 'reqid': rid})
        if not slot[0].wait(timeout):
            with self.wait_lock:
                self.waiting.pop(rid, None)
            raise TimeoutError(f'{pump} {data.get("op")}: no reply in {timeout:.0f} s')
        reply = slot[1]
        if isinstance(reply, dict):
            reply.pop('reqid', None)
            if reply.get('error'):
                raise RuntimeError(f'{pump} {data.get("op")}: {reply["error"]}')
        return reply

    def run(self, on_end):
        """Reader loop: the first message names our reply pump; later ones are replies."""
        try:
            while True:
                msg = self.read()
                if msg is None:
                    break
                data = msg.get('data') if isinstance(msg, dict) else None
                if self.reply_pump is None:
                    self.reply_pump = msg.get('pump')
                    self.features = (data or {}).get('features') or {}
                    log(f'connected, reply pump {self.reply_pump}')
                    continue
                rid = data.get('reqid') if isinstance(data, dict) else None
                with self.wait_lock:
                    slot = self.waiting.pop(rid, None)
                if slot:
                    slot[1] = data
                    slot[0].set()
        except Exception as e:  # a protocol error ends the plugin; say why in the viewer log
            log(f'reader stopped: {e!r}')
        finally:
            on_end()


leap = Leap()
capture_lock = threading.Lock()
snapshot = {'bytes': b''}


def capture(under):
    """under: an LLUI path; '//name' finds the view of that name anywhere (LLUI::resolvePath).
    The whole UI tree is hundreds of MB of LLSD: always capture one floater or panel."""
    with capture_lock:
        t0 = time.time()
        tree = leap.request('LLWindow', {'op': 'getSubtree', 'under': under})
        # The root view's rect in UI px: snapshot width / its width = OS display scale x UIScaleFactor.
        root = leap.request('LLWindow', {'op': 'getInfo', 'path': '/main_view'})
        settings = {}
        for key in SETTINGS:
            try:
                settings[key] = leap.request('LLViewerControl', {'op': 'get', 'group': 'Global', 'key': key}).get('value')
            except Exception as e:
                settings[key] = None
                log(f'setting {key}: {e}')
        path = os.path.join(tempfile.gettempdir(), 'xui-capture-snapshot.bmp')
        shot = leap.request('LLViewerWindow', {'op': 'saveSnapshot', 'filename': path,
                                               'showui': True, 'showhud': False, 'rebuild': False})
        ok = bool(shot and shot.get('ok'))
        snapshot['bytes'] = b''
        size = None
        if ok:
            with open(path, 'rb') as f:
                snapshot['bytes'] = f.read()
            os.remove(path)
            # BITMAPINFOHEADER width, height (raw window px): with root_rect, the display scale.
            w, h = struct.unpack_from('<ii', snapshot['bytes'], 18)
            size = [w, abs(h)]
        return {
            'version': VERSION,
            'under': under,
            'time': time.time(),
            'ms': round((time.time() - t0) * 1000),
            'features': leap.features,
            'settings': settings,
            'root_rect': root.get('rect'),
            'snapshot': '/snapshot.bmp' if ok else None,
            'snapshot_size': size,
            'tree': tree,
        }


class Handler(http.server.BaseHTTPRequestHandler):
    def cors(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', '*')
        # Chrome's Private Network Access preflight: an https page calling 127.0.0.1.
        self.send_header('Access-Control-Allow-Private-Network', 'true')

    def reply(self, code, body, ctype):
        self.send_response(code)
        self.cors()
        self.send_header('Content-Type', ctype)
        self.send_header('Content-Length', str(len(body)))
        self.send_header('Cache-Control', 'no-store')
        self.end_headers()
        self.wfile.write(body)

    def json(self, code, obj):
        self.reply(code, json.dumps(obj).encode('utf-8'), 'application/json')

    def do_OPTIONS(self):
        self.send_response(204)
        self.cors()
        self.end_headers()

    def do_GET(self):
        route, _, qs = self.path.partition('?')
        query = urllib.parse.parse_qs(qs)
        try:
            if route == '/ping':
                self.json(200, {'version': VERSION, 'connected': leap.reply_pump is not None, 'features': leap.features})
            elif route == '/capture':
                if leap.reply_pump is None:
                    return self.json(503, {'error': 'the viewer has not connected to the plugin yet'})
                # A floater by name: under 'Floater View' (main_view.xml), since '//name' alone finds
                # the first view of that name depth-first (the phototools toolbar button, say).
                floater = query.get('floater', [''])[0]
                under = f'//Floater View/{floater}' if floater else query.get('under', [''])[0]
                if not under:
                    return self.json(400, {'error': 'give ?floater=<name> (the floater XML root name) or ?under=<LLUI path>'})
                self.json(200, capture(under))
            elif route == '/find':
                # The full path of one view, e.g. path=//Floater View//imcontacts (a recursive
                # search, LLUI::resolvePath): the designer finds the open file's view this way, also
                # inside a hosting floater. One small reply: listing every path (getPaths) is
                # tens of MB once hidden floaters such as the inventory are built.
                if leap.reply_pump is None:
                    return self.json(503, {'error': 'the viewer has not connected to the plugin yet'})
                path = query.get('path', [''])[0]
                try:
                    info = leap.request('LLWindow', {'op': 'getInfo', 'path': path})
                except RuntimeError:
                    return self.json(404, {'error': f'no view at {path}'})
                self.json(200, {'path': info.get('path'), 'visible_chain': info.get('visible_chain')})
            elif route == '/snapshot.bmp':
                if not snapshot['bytes']:
                    return self.json(404, {'error': 'no snapshot: capture first'})
                self.reply(200, snapshot['bytes'], 'image/bmp')
            else:
                self.json(404, {'error': f'unknown route {route}'})
        except Exception as e:
            log(f'{route}: {e!r}')
            self.json(500, {'error': str(e)})

    def log_message(self, fmt, *args):
        pass  # one line per request would flood the viewer log


def main():
    port = PORT
    if '--port' in sys.argv:
        port = int(sys.argv[sys.argv.index('--port') + 1])
    server = http.server.ThreadingHTTPServer(('127.0.0.1', port), Handler)
    server.daemon_threads = True
    threading.Thread(target=leap.run, args=(server.shutdown,), daemon=True).start()
    log(f'version {VERSION}, serving http://127.0.0.1:{port}')
    server.serve_forever()
    log('viewer closed the pipe: exiting')


if __name__ == '__main__':
    main()
