#!/usr/bin/python3
"""Observe text clipboard changes while the configured history preference is enabled."""
import argparse
import codecs
import json
import os
from pathlib import Path
import select
import shutil
import signal
import stat
import sys
import subprocess
import time


# Full preferences include custom prompts and dictionaries, not just clipboard settings.
MAX_CONFIGURATION_BYTES = 1024 * 1024
# 4000 UTF-16 units occupy at most 12000 UTF-8 bytes.
MAX_TEXT_BYTES = 12000


def history_text(data, complete):
    text = codecs.getincrementaldecoder("utf-8")().decode(data, final=complete)
    text = text.rstrip("\0\r")
    text = text.encode("utf-16-le")[:8000].decode("utf-16-le", errors="ignore")
    return text if text and "\0" not in text else None


def document(path):
    descriptor = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_CLOEXEC | os.O_NOFOLLOW)
    with os.fdopen(descriptor, "rb") as source:
        before = os.fstat(source.fileno())
        if not stat.S_ISREG(before.st_mode) or before.st_size > MAX_CONFIGURATION_BYTES:
            raise ValueError()
        raw = source.read(MAX_CONFIGURATION_BYTES + 1)
        after = os.fstat(source.fileno())
        identity = lambda info: (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
        if len(raw) > MAX_CONFIGURATION_BYTES or identity(before) != identity(after):
            raise ValueError()
    value = json.loads(raw)
    if not isinstance(value, dict):
        raise ValueError()
    return value


def history_directory(options):
    config = document(options)
    directory = Path(config["preferences_directory"])
    if not directory.is_absolute():
        raise ValueError()
    history = config.get("clipboard_history_path")
    if history and Path(history) != directory / "clipboard_history.json":
        raise ValueError()
    preferences = document(directory / "preferences.json")
    if preferences.get("format_version") != 1 or not isinstance(preferences.get("preferences"), dict):
        raise ValueError()
    return directory if preferences["preferences"].get("clipboard_history") is True else None


def read_command(args):
    process = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
                               stderr=subprocess.DEVNULL)
    data = bytearray()
    deadline = time.monotonic() + 1
    try:
        while time.monotonic() < deadline:
            if not select.select([process.stdout], [], [], max(0, deadline - time.monotonic()))[0]:
                return None
            chunk = os.read(process.stdout.fileno(), MAX_TEXT_BYTES - len(data))
            if not chunk:
                if process.wait(timeout=max(0.01, deadline - time.monotonic())) != 0:
                    return None
                # Preserve source line endings; wl-paste already suppresses
                # its own added newline and X11 tools return the raw selection.
                return history_text(data, complete=True)
            data.extend(chunk)
            if len(data) == MAX_TEXT_BYTES:
                return history_text(data, complete=False)
    finally:
        if process.poll() is None:
            process.kill()
        process.wait()
        process.stdout.close()
    return None


def clipboard_text():
    commands = []
    if os.environ.get("WAYLAND_DISPLAY"):
        commands.append(["wl-paste", "--no-newline", "--type", "text"])
    if os.environ.get("DISPLAY"):
        native = Path(__file__).resolve().parent / "msime-linux-clipboard-watch-x11"
        if native.is_file():
            commands.append([str(native), "--read"])
        commands.extend([["xclip", "-selection", "clipboard", "-o"],
                         ["xsel", "--clipboard", "--output"]])
    for args in commands:
        if shutil.which(args[0]):
            try:
                text = read_command(args)
                if text is not None:
                    return text
            except (OSError, ValueError, subprocess.SubprocessError):
                pass
    return None


def capture_event(options, capture):
    # Watch mode passes selection data over stdin, never in argv or logs.
    if os.environ.get("CLIPBOARD_STATE", "data") != "data":
        return
    directory = history_directory(options)
    if directory is None:
        return
    data = bytearray()
    deadline = time.monotonic() + 1
    while time.monotonic() < deadline:
        if not select.select([sys.stdin.buffer], [], [], max(0, deadline - time.monotonic()))[0]:
            return
        chunk = os.read(sys.stdin.fileno(), MAX_TEXT_BYTES - len(data))
        data.extend(chunk)
        if not chunk or len(data) == MAX_TEXT_BYTES:
            text = history_text(data, complete=not chunk)
            if text and history_directory(options) == directory:
                subprocess.run([str(capture), str(directory)], input=text.encode("utf-8"),
                               stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=2)
            return


def stop_watch(process):
    if process is None:
        return
    # A watch child can outlive wl-paste. Always stop the owned process group,
    # including when the leader has already exited or exits on SIGTERM first.
    try:
        os.killpg(process.pid, signal.SIGTERM)
    except ProcessLookupError:
        pass
    try:
        process.wait(timeout=1)
    except subprocess.TimeoutExpired:
        pass
    finally:
        try:
            os.killpg(process.pid, signal.SIGKILL)
        except ProcessLookupError:
            pass
    process.wait()
    if process.stdout is not None:
        process.stdout.close()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("options", type=Path)
    parser.add_argument("--capture-event", action="store_true", help=argparse.SUPPRESS)
    args = parser.parse_args()
    if not args.options.is_absolute():
        parser.error("runtime options path must be absolute")
    capture = Path(__file__).resolve().parent / "msime-linux-clipboard-capture"
    if args.capture_event:
        try:
            capture_event(args.options, capture)
        except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError):
            pass
        return
    def terminate(signum, frame):
        raise KeyboardInterrupt()
    signal.signal(signal.SIGTERM, terminate)
    last = None
    watcher = None
    retry_watch = 0
    try:
        while True:
            try:
                directory = history_directory(args.options)
                if directory is None:
                    stop_watch(watcher)
                    watcher = None
                    last = None
                else:
                    if watcher is not None and watcher.poll() is not None:
                        stop_watch(watcher)
                        watcher = None
                        retry_watch = time.monotonic() + 30
                    if (watcher is None and time.monotonic() >= retry_watch and
                            os.environ.get("WAYLAND_DISPLAY") and shutil.which("wl-paste")):
                        watcher = subprocess.Popen(
                            ["wl-paste", "--type", "text", "--watch", sys.executable,
                             str(Path(__file__).resolve()), "--capture-event", str(args.options)],
                            stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
                            stderr=subprocess.DEVNULL, start_new_session=True)
                    x11_watch = Path(__file__).resolve().parent / "msime-linux-clipboard-watch-x11"
                    if (watcher is None and time.monotonic() >= retry_watch and
                            not os.environ.get("WAYLAND_DISPLAY") and os.environ.get("DISPLAY") and
                            x11_watch.is_file()):
                        watcher = subprocess.Popen([str(x11_watch)], stdin=subprocess.DEVNULL,
                                                   stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
                                                   start_new_session=True)
                    changed = False
                    if watcher is not None and watcher.stdout is not None:
                        if select.select([watcher.stdout], [], [], 0)[0]:
                            changed = bool(os.read(watcher.stdout.fileno(), 4096))
                    # Event mode also captures an explicit copy of identical text.
                    # Systems without a usable watcher retain bounded polling.
                    if watcher is None or changed:
                        text = clipboard_text()
                        identity = (str(directory), text)
                        # Reading the selection can block while runtime options
                        # or preferences change. Match watch-mode revalidation
                        # before delivering text to the capture process.
                        if (text is not None and (changed or identity != last) and
                                history_directory(args.options) == directory):
                            result = subprocess.run([str(capture), str(directory)], input=text.encode(),
                                                    stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                                                    timeout=2)
                            if result.returncode == 0:
                                last = identity
                        elif text is None:
                            last = None
            except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError):
                stop_watch(watcher)
                watcher = None
                retry_watch = time.monotonic() + 30
                last = None
            if watcher is not None and watcher.stdout is not None:
                select.select([watcher.stdout], [], [], 0.75)
            else:
                time.sleep(0.75)
    finally:
        stop_watch(watcher)


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        pass
