Debian Codegraph @

src/fenrirscreenreader/utils/x_clipboard.py

raw
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 # Fenrir TTY screen reader
5 # By Chrys, Storm Dragon, and contributors.
6
7 import os
8 import shutil
9 import subprocess
10 import threading
11
12
13 _display_lock = threading.RLock()
14 _CLIPBOARD_TIMEOUT = 2.0
15 _ENCODING = "utf-8"
16
17
18 def _command_exists(command):
19 return shutil.which(command) is not None
20
21
22 def _env_for_display(display):
23 env = os.environ.copy()
24 if display:
25 env["DISPLAY"] = display
26 return env
27
28
29 def _display_candidates(display="", scan_displays=False):
30 if display:
31 return [display]
32 current_display = os.environ.get("DISPLAY", "")
33 candidates = []
34 if current_display:
35 candidates.append(current_display)
36 if scan_displays:
37 candidates.extend(f":{index}" for index in range(10))
38 if not candidates:
39 candidates.append("")
40 return list(dict.fromkeys(candidates))
41
42
43 def _read_commands(display):
44 commands = []
45 if display:
46 if _command_exists("xclip"):
47 commands.append(["xclip", "-selection", "clipboard", "-o"])
48 if _command_exists("xsel"):
49 commands.append(["xsel", "-b", "-o"])
50 elif os.environ.get("WAYLAND_DISPLAY") and _command_exists("wl-paste"):
51 commands.append(["wl-paste", "-n", "-t", "text"])
52 return commands
53
54
55 def _write_commands(display):
56 commands = []
57 if display:
58 if _command_exists("xclip"):
59 commands.append(["xclip", "-selection", "clipboard"])
60 if _command_exists("xsel"):
61 commands.append(["xsel", "-b", "-i"])
62 elif os.environ.get("WAYLAND_DISPLAY") and _command_exists("wl-copy"):
63 commands.append(["wl-copy"])
64 return commands
65
66
67 def _run_command(command, display, input_text=None):
68 input_bytes = None
69 if input_text is not None:
70 input_bytes = input_text.encode(_ENCODING)
71 output_target = (
72 subprocess.PIPE if input_text is None else subprocess.DEVNULL
73 )
74 return subprocess.run(
75 command,
76 input=input_bytes,
77 stdout=output_target,
78 stderr=output_target,
79 env=_env_for_display(display),
80 timeout=_CLIPBOARD_TIMEOUT,
81 check=False,
82 )
83
84
85 def _command_error(command, result):
86 stderr = (result.stderr or b"").decode(
87 _ENCODING, errors="replace"
88 ).strip()
89 if stderr:
90 return RuntimeError(stderr)
91 return RuntimeError(
92 "clipboard command failed: "
93 + " ".join(command)
94 + " exited with "
95 + str(result.returncode)
96 )
97
98
99 def read_text(display="", scan_displays=False):
100 last_error = None
101 command_succeeded = False
102 with _display_lock:
103 for candidate in _display_candidates(display, scan_displays):
104 commands = _read_commands(candidate)
105 if not commands:
106 last_error = RuntimeError("no supported clipboard reader found")
107 for command in commands:
108 try:
109 result = _run_command(command, candidate)
110 if result.returncode != 0:
111 last_error = _command_error(command, result)
112 continue
113 command_succeeded = True
114 text = result.stdout.decode(_ENCODING)
115 if text:
116 return text
117 except Exception as error:
118 last_error = error
119 if last_error:
120 if command_succeeded:
121 return None
122 raise last_error
123 return None
124
125
126 def write_text(text, display="", scan_displays=False):
127 if not isinstance(text, str) or not text:
128 return False
129 last_error = None
130 with _display_lock:
131 for candidate in _display_candidates(display, scan_displays):
132 commands = _write_commands(candidate)
133 if not commands:
134 last_error = RuntimeError("no supported clipboard writer found")
135 for command in commands:
136 try:
137 result = _run_command(command, candidate, text)
138 if result.returncode == 0:
139 return True
140 last_error = _command_error(command, result)
141 except Exception as error:
142 last_error = error
143 if last_error:
144 raise last_error
145 return False