|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import os |
| 4 | +import platform |
| 5 | +import shutil |
| 6 | +import subprocess |
| 7 | + |
| 8 | + |
| 9 | +class ClipboardError(Exception): |
| 10 | + pass |
| 11 | + |
| 12 | + |
| 13 | +def detect_clipboard_command() -> list[str] | None: |
| 14 | + system = platform.system() |
| 15 | + if system == "Darwin": |
| 16 | + # pbcopy uses locale env vars for encoding; UTF-8 recommended |
| 17 | + if shutil.which("pbcopy"): |
| 18 | + return ["pbcopy"] |
| 19 | + return None |
| 20 | + if system == "Windows": |
| 21 | + if shutil.which("clip"): |
| 22 | + return ["clip"] |
| 23 | + return None |
| 24 | + if system in ("Linux", "FreeBSD"): |
| 25 | + if os.environ.get("WAYLAND_DISPLAY") and shutil.which("wl-copy"): |
| 26 | + # Force text/plain to avoid xdg-mime inference issues in minimal/headless setups |
| 27 | + return ["wl-copy", "--type", "text/plain"] |
| 28 | + if os.environ.get("DISPLAY"): |
| 29 | + if shutil.which("xclip"): |
| 30 | + return ["xclip", "-selection", "clipboard"] |
| 31 | + if shutil.which("xsel"): |
| 32 | + return ["xsel", "--clipboard", "--input"] |
| 33 | + return None |
| 34 | + return None |
| 35 | + |
| 36 | + |
| 37 | +def copy_to_clipboard(text: str) -> int: |
| 38 | + cmd = detect_clipboard_command() |
| 39 | + if cmd is None: |
| 40 | + raise ClipboardError("No clipboard tool found") |
| 41 | + |
| 42 | + # Windows clip.exe requires UTF-16LE without BOM for proper Unicode support |
| 43 | + encoding = "utf-16le" if platform.system() == "Windows" else "utf-8" |
| 44 | + encoded = text.encode(encoding) |
| 45 | + |
| 46 | + try: |
| 47 | + subprocess.run( |
| 48 | + cmd, |
| 49 | + input=encoded, |
| 50 | + stdout=subprocess.DEVNULL, |
| 51 | + stderr=subprocess.PIPE, |
| 52 | + timeout=5, |
| 53 | + check=True, |
| 54 | + ) |
| 55 | + except subprocess.TimeoutExpired as e: |
| 56 | + raise ClipboardError("Clipboard operation timed out") from e |
| 57 | + except subprocess.CalledProcessError as e: |
| 58 | + stderr_msg = e.stderr.decode(errors="replace").strip() if e.stderr else "" |
| 59 | + raise ClipboardError(stderr_msg or f"Command failed with code {e.returncode}") from e |
| 60 | + except OSError as e: |
| 61 | + raise ClipboardError(f"Failed to execute clipboard command: {e}") from e |
| 62 | + |
| 63 | + return len(encoded) |
| 64 | + |
| 65 | + |
| 66 | +def clipboard_available() -> bool: |
| 67 | + return detect_clipboard_command() is not None |
0 commit comments