#!/usr/bin/env 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 tempfile
import time
import msime_crash_capture


# 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
WATCH_RETRY_DELAY = 30
# 合成器不提供 data-control 协议时，wl-clipboard 的 `wl-paste --watch` 一启动就在 stderr 写下含这段文字的一行并以状态 1 退出（2.2 起是 "Watch mode requires a compositor that supports the data-control protocol"，更早是 "... wlroots data-control protocol"；编译时没带该协议的是 "wl-clipboard was built without support for the data-control protocol"）。
WAYLAND_NO_DATA_CONTROL = b"data-control protocol"
POLL_INTERVAL = 0.75


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():
    # 监视器自己读剪贴板只走 X11（Wayland 会话里即 XWayland），从不调用 `wl-paste`。Wayland 上的变化由 `wl-paste --watch` 推送，数据经标准输入交给 `--capture-event`，用不到这里；需要靠这里轮询的 Wayland 会话，恰恰是合成器不提供 data-control 协议（GNOME/Mutter）、`--watch` 起不来的那种，而在那里 `wl-paste` 只能临时建一个窗口抢走键盘焦点才读得到剪贴板，每读一次都会打断前台应用里输入法的预编辑，并让 gnome-shell 刷 `meta_window_set_stack_position_no_sync` 断言（#6514）。Mutter 会把 Wayland 剪贴板同步到 XWayland 的 CLIPBOARD，经 X11 读取不涉及焦点。
    commands = []
    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 wayland_lacks_data_control(returncode, errors):
    """已退出的 `wl-paste --watch` 是否是因为合成器不提供 data-control 而起不来。`errors` 是它的 stderr 所写的文件。崩溃、被信号杀掉（returncode 为负）、连不上合成器都不算，这些照旧过 WATCH_RETRY_DELAY 再试。"""
    if returncode <= 0:
        return False
    errors.seek(0)
    return WAYLAND_NO_DATA_CONTROL in errors.read(4096)


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")
    msime_crash_capture.start("clipboard-event" if args.capture_event else "clipboard-monitor",
                              options=args.options)
    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
    watcher_kind = None
    retry_watch = 0
    # `wl-paste --watch` 报告合成器不提供 data-control 协议（见 `wayland_lacks_data_control`）后，本轮不再起它，改用 X11 监听（Wayland 会话里即 XWayland）；关闭剪贴板历史时清除，重新开启后再试一次。别的退出不设它，照旧 30 秒后重起 `wl-paste --watch`。
    wayland_watch_failed = False
    # `wl-paste --watch` 的 stderr 写进这个文件，退出后据它判断原因；每次启动前清空。用文件而不用管道：它活着的时候没人读，`--watch` 起的子进程也继承这个 stderr，管道写满会把它们卡住。
    watch_errors = tempfile.TemporaryFile()
    try:
        while True:
            try:
                directory = history_directory(args.options)
                if directory is None:
                    stop_watch(watcher)
                    watcher = None
                    watcher_kind = None
                    last = None
                    wayland_watch_failed = False
                else:
                    if watcher is not None and watcher.poll() is not None:
                        failed = watcher_kind == "wayland" and wayland_lacks_data_control(watcher.returncode, watch_errors)
                        stop_watch(watcher)
                        watcher = None
                        watcher_kind = None
                        if failed and not wayland_watch_failed:
                            wayland_watch_failed = True
                            # 立即换 X11 监听，不等重试间隔。
                            retry_watch = 0
                            fallback = ("改经 XWayland 读取剪贴板" if os.environ.get("DISPLAY")
                                        else "且没有 X11 显示，暂停采集剪贴板")
                            print(f"msime-linux-clipboard-monitor: wl-paste --watch 不可用（合成器不支持 wlr-data-control），{fallback}",
                                  file=sys.stderr, flush=True)
                        else:
                            retry_watch = time.monotonic() + WATCH_RETRY_DELAY
                    wayland = bool(os.environ.get("WAYLAND_DISPLAY"))
                    x11_watch = Path(__file__).resolve().parent / "msime-linux-clipboard-watch-x11"
                    if watcher is None and time.monotonic() >= retry_watch:
                        if wayland and not wayland_watch_failed and shutil.which("wl-paste"):
                            watch_errors.seek(0)
                            watch_errors.truncate()
                            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=watch_errors, start_new_session=True)
                            watcher_kind = "wayland"
                        elif ((not wayland or wayland_watch_failed) 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)
                            watcher_kind = "x11"
                    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))
                    # 事件模式下再次复制相同文本也会采集；没有可用监听时退回有界轮询，轮询只经 X11 读取（见 `clipboard_text`）。
                    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
                watcher_kind = None
                retry_watch = time.monotonic() + WATCH_RETRY_DELAY
                last = None
            if watcher is not None and watcher.stdout is not None:
                select.select([watcher.stdout], [], [], POLL_INTERVAL)
            else:
                time.sleep(POLL_INTERVAL)
    finally:
        stop_watch(watcher)


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