opticflow 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
opticflow/capture.py ADDED
@@ -0,0 +1,329 @@
1
+ """-log NAME: the two files, and a capture of one device with dumpcap.
2
+
3
+ dumpcap writes the capture to a pipe (``-w -``) and a thread copies it into
4
+ NAME.pcap, which opticflow creates itself so an existing file is never
5
+ overwritten. If opticflow is killed outright, dumpcap's next write to the pipe
6
+ fails and it exits, so a capture is never left running on its own.
7
+
8
+ dumpcap's messages do not prove a capture started (it prints "Capturing on"
9
+ even for an interface that does not exist). What does: the 24-byte pcap file
10
+ header arrives, and dumpcap is still running.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import contextlib
16
+ import os
17
+ import re
18
+ import select
19
+ import shutil
20
+ import signal
21
+ import socket
22
+ import subprocess
23
+ import threading
24
+ import time
25
+ from dataclasses import dataclass
26
+ from pathlib import Path
27
+
28
+ HEADER_SIZE = 24
29
+ START_TIMEOUT = 3.0
30
+ STOP_TIMEOUT = 5.0
31
+ FILE_MODE = 0o600
32
+ SETUP_HINT = 'In flowspool: sudo scripts/setup.sh --capture-user "$USER", then log in again.'
33
+ # dumpcap lines that are progress or noise, not an explanation of a failure.
34
+ _NOISE = re.compile(r"^(Capturing on |File: |Packets|dumpcap: '-P' is deprecated)")
35
+ _CAPTURED = re.compile(r"Packets captured: (\d+)")
36
+ _DROPPED = re.compile(r"Packets received/dropped on interface .*?: (\d+)/(\d+)")
37
+ _INTERFACE_NAME = re.compile(r"^[A-Za-z0-9._:-]+$")
38
+
39
+
40
+ class CaptureError(Exception):
41
+ """The capture cannot start. The message says why."""
42
+
43
+
44
+ def capture_filter(address: str) -> str:
45
+ return f"host {address}"
46
+
47
+
48
+ def local_interfaces() -> set[str]:
49
+ try:
50
+ return {name for _, name in socket.if_nameindex()}
51
+ except OSError: # pragma: no cover - only without any interfaces
52
+ return set()
53
+
54
+
55
+ def check_interface(name: str, known: set[str] | None = None) -> None:
56
+ """Refuse names dumpcap would treat specially, and names not on this machine."""
57
+ if not name or not _INTERFACE_NAME.match(name) or name.startswith("-") or name.isdigit():
58
+ raise CaptureError(
59
+ f"the interface name {name!r} cannot be used for a capture. Give one with --interface."
60
+ )
61
+ known = local_interfaces() if known is None else known
62
+ if name not in known:
63
+ raise CaptureError(
64
+ f"there is no interface {name!r} on this machine. If the engine runs elsewhere, "
65
+ "run opticflow there, or give a local interface with --interface."
66
+ )
67
+
68
+
69
+ @dataclass
70
+ class LogFiles:
71
+ """NAME.txt and NAME.pcap, created by opticflow and never overwritten."""
72
+
73
+ text_path: Path
74
+ pcap_path: Path
75
+ text: object | None = None
76
+ pcap_fd: int | None = None
77
+
78
+ @classmethod
79
+ def for_name(cls, name: str) -> LogFiles:
80
+ return cls(Path(f"{name}.txt"), Path(f"{name}.pcap"))
81
+
82
+ def check_free(self) -> None:
83
+ for path in (self.text_path, self.pcap_path):
84
+ if path.exists() or path.is_symlink():
85
+ raise CaptureError(f"{path} already exists; opticflow does not overwrite files")
86
+ for path in (self.text_path, self.pcap_path):
87
+ folder = path.parent if str(path.parent) else Path(".")
88
+ if not folder.is_dir():
89
+ raise CaptureError(f"the folder for {path} does not exist")
90
+
91
+ def create(self) -> None:
92
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
93
+ try:
94
+ text_fd = os.open(self.text_path, flags, FILE_MODE)
95
+ except FileExistsError:
96
+ raise CaptureError(f"{self.text_path} already exists") from None
97
+ except OSError as error:
98
+ raise CaptureError(f"cannot create {self.text_path}: {error.strerror}") from None
99
+ try:
100
+ self.pcap_fd = os.open(self.pcap_path, flags, FILE_MODE)
101
+ except OSError as error:
102
+ os.close(text_fd)
103
+ os.unlink(self.text_path)
104
+ if isinstance(error, FileExistsError):
105
+ raise CaptureError(f"{self.pcap_path} already exists") from None
106
+ raise CaptureError(f"cannot create {self.pcap_path}: {error.strerror}") from None
107
+ self.text = open(text_fd, "w", encoding="utf-8", newline="\n") # noqa: SIM115
108
+
109
+ def write_text(self, lines: list[str]) -> None:
110
+ if self.text is not None:
111
+ self.text.write("".join(line + "\n" for line in lines))
112
+ self.text.flush()
113
+
114
+ def remove(self) -> None:
115
+ """Remove both files again: used only when the capture failed to start."""
116
+ self.close()
117
+ for path in (self.text_path, self.pcap_path):
118
+ with contextlib.suppress(FileNotFoundError):
119
+ path.unlink()
120
+
121
+ def close(self) -> None:
122
+ if self.text is not None:
123
+ with contextlib.suppress(OSError):
124
+ self.text.close()
125
+ self.text = None
126
+ if self.pcap_fd is not None:
127
+ with contextlib.suppress(OSError):
128
+ os.fsync(self.pcap_fd)
129
+ with contextlib.suppress(OSError):
130
+ os.close(self.pcap_fd)
131
+ self.pcap_fd = None
132
+
133
+
134
+ @dataclass(frozen=True)
135
+ class Summary:
136
+ captured: int | None
137
+ dropped: int | None
138
+ problem: str | None
139
+
140
+
141
+ class Capture:
142
+ """One dumpcap process writing one device's packets into an open file."""
143
+
144
+ def __init__(
145
+ self,
146
+ pcap_fd: int,
147
+ interface: str,
148
+ address: str,
149
+ dumpcap: str | None = None,
150
+ start_timeout: float = START_TIMEOUT,
151
+ stop_timeout: float = STOP_TIMEOUT,
152
+ ) -> None:
153
+ self.pcap_fd = pcap_fd
154
+ self.interface = interface
155
+ self.address = address
156
+ self.dumpcap = dumpcap or os.environ.get("OPTICFLOW_DUMPCAP") or "dumpcap"
157
+ self.start_timeout = start_timeout
158
+ self.stop_timeout = stop_timeout
159
+ self.process: subprocess.Popen | None = None
160
+ self._errors: list[str] = []
161
+ self._threads: list[threading.Thread] = []
162
+ self._write_problem: str | None = None
163
+ self._reported = False
164
+
165
+ @property
166
+ def command(self) -> list[str]:
167
+ return [
168
+ self.dumpcap,
169
+ "-q",
170
+ "-i",
171
+ self.interface,
172
+ "-f",
173
+ capture_filter(self.address),
174
+ "-F",
175
+ "pcap",
176
+ "-w",
177
+ "-",
178
+ ]
179
+
180
+ def start(self) -> None:
181
+ program = shutil.which(self.dumpcap)
182
+ if program is None:
183
+ raise CaptureError(
184
+ f"{self.dumpcap} is not installed, or not runnable by your user. {SETUP_HINT}"
185
+ )
186
+ command = [program, *self.command[1:]]
187
+ try:
188
+ self.process = subprocess.Popen(
189
+ command,
190
+ stdin=subprocess.DEVNULL,
191
+ stdout=subprocess.PIPE,
192
+ stderr=subprocess.PIPE,
193
+ start_new_session=True, # Ctrl-C reaches opticflow only
194
+ )
195
+ except PermissionError:
196
+ raise CaptureError(
197
+ f"not allowed to run {program}: your user is not in the wireshark group "
198
+ f"yet. {SETUP_HINT}"
199
+ ) from None
200
+ except OSError as error:
201
+ raise CaptureError(f"cannot start {program}: {error.strerror}") from None
202
+ self._start_thread(self._collect_errors)
203
+ header = self._read_header()
204
+ if len(header) < HEADER_SIZE or self.process.poll() is not None:
205
+ self._kill()
206
+ raise CaptureError(self._failure_message())
207
+ os.write(self.pcap_fd, header)
208
+ self._start_thread(self._copy)
209
+
210
+ def _start_thread(self, target) -> None:
211
+ thread = threading.Thread(target=target, daemon=True)
212
+ thread.start()
213
+ self._threads.append(thread)
214
+
215
+ def _read_header(self) -> bytes:
216
+ assert self.process is not None and self.process.stdout is not None
217
+ descriptor = self.process.stdout.fileno()
218
+ header = b""
219
+ deadline = time.monotonic() + self.start_timeout
220
+ while len(header) < HEADER_SIZE:
221
+ left = deadline - time.monotonic()
222
+ if left <= 0:
223
+ break
224
+ ready, _, _ = select.select([descriptor], [], [], left)
225
+ if not ready:
226
+ break
227
+ chunk = os.read(descriptor, HEADER_SIZE - len(header))
228
+ if not chunk:
229
+ break
230
+ header += chunk
231
+ if len(header) == HEADER_SIZE:
232
+ # Still running a moment later? A start that fails after the header
233
+ # (rare) is caught here rather than after tables have been printed.
234
+ time.sleep(0.2)
235
+ return header
236
+
237
+ def _collect_errors(self) -> None:
238
+ assert self.process is not None and self.process.stderr is not None
239
+ for raw in self.process.stderr:
240
+ line = raw.decode("utf-8", "replace").rstrip()
241
+ if line:
242
+ self._errors.append(line)
243
+
244
+ def _copy(self) -> None:
245
+ assert self.process is not None and self.process.stdout is not None
246
+ descriptor = self.process.stdout.fileno()
247
+ while True:
248
+ try:
249
+ chunk = os.read(descriptor, 65536)
250
+ except OSError as error:
251
+ self._write_problem = self._write_problem or f"reading the capture: {error}"
252
+ return
253
+ if not chunk:
254
+ return
255
+ if self._write_problem:
256
+ continue # keep draining so dumpcap does not stall
257
+ try:
258
+ view = memoryview(chunk)
259
+ while view:
260
+ written = os.write(self.pcap_fd, view)
261
+ view = view[written:]
262
+ except OSError as error:
263
+ self._write_problem = f"writing the capture file failed: {error.strerror}"
264
+
265
+ def _failure_message(self) -> str:
266
+ reasons = [line for line in self._wait_for_errors() if not _NOISE.match(line)]
267
+ reasons = [line.removeprefix("dumpcap: ") for line in reasons]
268
+ if not reasons:
269
+ return (
270
+ f"the capture did not start within {self.start_timeout:g} s "
271
+ f"(dumpcap on {self.interface})"
272
+ )
273
+ return "the capture could not start: " + " ".join(reasons)
274
+
275
+ def _wait_for_errors(self) -> list[str]:
276
+ for thread in self._threads[:1]:
277
+ thread.join(timeout=2.0)
278
+ return list(self._errors)
279
+
280
+ def _kill(self) -> None:
281
+ if self.process is None:
282
+ return
283
+ if self.process.poll() is None:
284
+ with contextlib.suppress(ProcessLookupError):
285
+ self.process.kill()
286
+ with contextlib.suppress(subprocess.TimeoutExpired):
287
+ self.process.wait(timeout=2.0)
288
+
289
+ def problem(self) -> str | None:
290
+ """A problem to report once while running: dumpcap exited, or writing failed."""
291
+ if self._reported or self.process is None:
292
+ return None
293
+ message = None
294
+ if self._write_problem:
295
+ message = self._write_problem
296
+ elif self.process.poll() is not None:
297
+ reasons = [line for line in self._errors if not _NOISE.match(line)]
298
+ message = "the capture stopped early" + (": " + " ".join(reasons) if reasons else "")
299
+ if message:
300
+ self._reported = True
301
+ return message
302
+
303
+ def stop(self) -> Summary:
304
+ """Stop dumpcap (SIGTERM, then SIGKILL), copy the rest, and summarise."""
305
+ problem = None
306
+ if self.process is None:
307
+ return Summary(None, None, None)
308
+ early = self.process.poll() is not None
309
+ if not early:
310
+ with contextlib.suppress(ProcessLookupError):
311
+ self.process.send_signal(signal.SIGTERM)
312
+ try:
313
+ self.process.wait(timeout=self.stop_timeout)
314
+ except subprocess.TimeoutExpired:
315
+ problem = f"dumpcap did not stop within {self.stop_timeout:g} s and was killed"
316
+ self._kill()
317
+ for thread in self._threads:
318
+ thread.join(timeout=5.0)
319
+ text = "\n".join(self._errors)
320
+ captured = _CAPTURED.findall(text)
321
+ dropped = _DROPPED.findall(text)
322
+ if early and not self._reported:
323
+ problem = problem or "the capture stopped early"
324
+ problem = problem or self._write_problem
325
+ return Summary(
326
+ captured=int(captured[-1]) if captured else None,
327
+ dropped=sum(int(d) for _, d in dropped) if dropped else None,
328
+ problem=problem,
329
+ )
opticflow/cli.py ADDED
@@ -0,0 +1,90 @@
1
+ """Command line: opticflow -i ADDRESS [-log NAME] [--interface IFACE] [--color] [SOURCE]."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from opticflow import __version__
9
+ from opticflow.filters import parse_address
10
+ from opticflow.sources import DEFAULT_SOCKET
11
+
12
+ DESCRIPTION = (
13
+ "Watch one device's network flows live: a table per flow snapshot, appended "
14
+ "below the last. Keys: f filter, a max age, c clear, ? help, q quit."
15
+ )
16
+ EPILOG = f"""\
17
+ sources:
18
+ (none) the engine's socket, {DEFAULT_SOCKET}
19
+ PATH a socket, a named pipe, or a file of snapshot lines
20
+ - standard input: flowspool watch | opticflow -i ADDRESS -
21
+
22
+ -log NAME writes NAME.txt (what is printed, without colour) and NAME.pcap
23
+ (every packet to or from the device, captured with dumpcap) until opticflow
24
+ exits. Neither file is ever overwritten.
25
+ """
26
+
27
+
28
+ def build_parser() -> argparse.ArgumentParser:
29
+ parser = argparse.ArgumentParser(
30
+ prog="opticflow",
31
+ description=DESCRIPTION,
32
+ epilog=EPILOG,
33
+ formatter_class=argparse.RawDescriptionHelpFormatter,
34
+ )
35
+ parser.add_argument(
36
+ "-i",
37
+ dest="address",
38
+ metavar="ADDRESS",
39
+ required=True,
40
+ help="the device to show (required): its IPv4 or IPv6 address",
41
+ )
42
+ parser.add_argument(
43
+ "-log",
44
+ dest="log",
45
+ metavar="NAME",
46
+ help="write NAME.txt and NAME.pcap (that device's packets) until exit",
47
+ )
48
+ parser.add_argument(
49
+ "--interface",
50
+ metavar="IFACE",
51
+ help="interface for the -log capture, when the snapshots name none",
52
+ )
53
+ parser.add_argument(
54
+ "--color",
55
+ choices=("auto", "always", "never"),
56
+ default="auto",
57
+ help="colour in a terminal unless NO_COLOR is set (default: auto)",
58
+ )
59
+ parser.add_argument("--version", action="version", version=f"opticflow {__version__}")
60
+ parser.add_argument("source", nargs="?", metavar="SOURCE", help="where snapshots come from")
61
+ return parser
62
+
63
+
64
+ def main(argv: list[str] | None = None) -> int:
65
+ parser = build_parser()
66
+ arguments = parser.parse_args(argv)
67
+ try:
68
+ address = parse_address(arguments.address)
69
+ except ValueError as problem:
70
+ parser.error(f"-i: {problem}")
71
+ if arguments.log is not None and not arguments.log.strip():
72
+ parser.error("-log: give a name, such as -log phone")
73
+ if arguments.interface is not None and arguments.log is None:
74
+ parser.error("--interface is only used with -log")
75
+
76
+ from opticflow.app import Options, run
77
+
78
+ return run(
79
+ Options(
80
+ address=address,
81
+ source=arguments.source,
82
+ log=arguments.log,
83
+ interface=arguments.interface,
84
+ color=arguments.color,
85
+ )
86
+ )
87
+
88
+
89
+ if __name__ == "__main__": # pragma: no cover
90
+ sys.exit(main())
opticflow/filters.py ADDED
@@ -0,0 +1,85 @@
1
+ """Which flows are shown: the device, then the two filters set with keys."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ipaddress
6
+ from dataclasses import dataclass
7
+
8
+ from opticflow.formatting import cells, seconds
9
+ from opticflow.snapshot import Flow
10
+
11
+ Address = ipaddress.IPv4Address | ipaddress.IPv6Address
12
+
13
+
14
+ def parse_address(text: str) -> Address:
15
+ """The device address given with -i. Raises ValueError with a readable message."""
16
+ try:
17
+ return ipaddress.ip_address(text.strip())
18
+ except ValueError:
19
+ raise ValueError(f"{text!r} is not an IPv4 or IPv6 address") from None
20
+
21
+
22
+ def _same(address: Address, text: str) -> bool:
23
+ try:
24
+ return ipaddress.ip_address(text) == address
25
+ except ValueError:
26
+ return False
27
+
28
+
29
+ def involves(flow: Flow, address: Address) -> bool:
30
+ """True if the device is the flow's client or server."""
31
+ return _same(address, flow.client.ip) or _same(address, flow.server.ip)
32
+
33
+
34
+ def parse_terms(text: str) -> tuple[str, ...]:
35
+ """'google.com, UDP,, tls ' -> ('google.com', 'udp', 'tls')."""
36
+ return tuple(term.strip().lower() for term in text.split(",") if term.strip())
37
+
38
+
39
+ def parse_age(text: str) -> float | None:
40
+ """'30' -> 30.0, '' -> None (no limit). Raises ValueError for anything else."""
41
+ text = text.strip()
42
+ if not text:
43
+ return None
44
+ try:
45
+ value = float(text)
46
+ except ValueError:
47
+ raise ValueError(f"{text!r} is not a number of seconds") from None
48
+ if value != value or value < 0 or value == float("inf"):
49
+ raise ValueError(f"{text!r} is not a number of seconds of 0 or more")
50
+ return value
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class Filters:
55
+ """The f and a filters. Both must pass; either may be unset."""
56
+
57
+ terms: tuple[str, ...] = ()
58
+ max_age: float | None = None
59
+
60
+ @property
61
+ def active(self) -> bool:
62
+ return bool(self.terms) or self.max_age is not None
63
+
64
+ def passes(self, flow: Flow) -> bool:
65
+ if self.max_age is not None and flow.age > self.max_age:
66
+ return False
67
+ if self.terms:
68
+ text = "\n".join(cells(flow)).lower()
69
+ return any(term.lower() in text for term in self.terms)
70
+ return True
71
+
72
+ def describe(self, unicode: bool = True) -> str:
73
+ """'filter: tls, udp · age ≤ 600 s', or '' when nothing is set."""
74
+ parts = []
75
+ if self.terms:
76
+ parts.append("filter: " + ", ".join(self.terms))
77
+ if self.max_age is not None:
78
+ parts.append(f"age {'≤' if unicode else '<='} {seconds(self.max_age)} s")
79
+ return (" · " if unicode else " - ").join(parts)
80
+
81
+ def terms_text(self) -> str:
82
+ return ", ".join(self.terms)
83
+
84
+ def age_text(self) -> str:
85
+ return "" if self.max_age is None else seconds(self.max_age)
@@ -0,0 +1,80 @@
1
+ """Text for each table column, shared by the table and the filters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time as _time
6
+
7
+ from opticflow.snapshot import Flow
8
+
9
+ # Column titles of the full layout, in order. PORT appears twice.
10
+ TITLES = (
11
+ "AGE",
12
+ "CLIENT IP",
13
+ "PORT",
14
+ "SERVER IP",
15
+ "PORT",
16
+ "L4",
17
+ "APPLICATION",
18
+ "UP",
19
+ "DOWN",
20
+ "TOTAL",
21
+ "DOMAIN",
22
+ )
23
+
24
+ BYTE_UNITS = {
25
+ "frame": "whole frames",
26
+ "ip": "IP packets",
27
+ "payload": "transport payload",
28
+ }
29
+
30
+
31
+ def human_bytes(count: int) -> str:
32
+ """1536 -> '1.5 KB', as in flowreel."""
33
+ value = float(count)
34
+ for unit in ("B", "KB", "MB", "GB"):
35
+ if value < 1024 or unit == "GB":
36
+ return f"{int(value)} B" if unit == "B" else f"{value:.1f} {unit}"
37
+ value /= 1024
38
+ return f"{value:.1f} GB" # pragma: no cover - the loop always returns
39
+
40
+
41
+ def age(seconds: float) -> str:
42
+ """Whole seconds, or whole days past 99999: 30.7 -> '30', 132075369 -> '1528d'."""
43
+ whole = int(max(0.0, seconds))
44
+ return str(whole) if whole < 100000 else f"{whole // 86400}d"
45
+
46
+
47
+ def cells(flow: Flow) -> list[str]:
48
+ """The text of every column of the full layout, for one flow."""
49
+ return [
50
+ age(flow.age),
51
+ flow.client.ip,
52
+ str(flow.client.port) if flow.client.port else "",
53
+ flow.server.ip,
54
+ str(flow.server.port) if flow.server.port else "",
55
+ flow.transport.upper(),
56
+ flow.app,
57
+ human_bytes(flow.bytes_up),
58
+ human_bytes(flow.bytes_down),
59
+ human_bytes(flow.bytes_total),
60
+ flow.domain,
61
+ ]
62
+
63
+
64
+ def clock(timestamp: float, with_date: bool) -> str:
65
+ """Local time of a snapshot: '14:03:20', or '2026-12-03 14:03:20'."""
66
+ moment = _time.localtime(timestamp)
67
+ return _time.strftime("%Y-%m-%d %H:%M:%S" if with_date else "%H:%M:%S", moment)
68
+
69
+
70
+ def day(timestamp: float) -> str:
71
+ return _time.strftime("%Y-%m-%d", _time.localtime(timestamp))
72
+
73
+
74
+ def byte_unit(name: str) -> str:
75
+ return BYTE_UNITS.get(name, name)
76
+
77
+
78
+ def seconds(value: float) -> str:
79
+ """30.0 -> '30', 2.5 -> '2.5'."""
80
+ return f"{value:g}"
opticflow/prompt.py ADDED
@@ -0,0 +1,92 @@
1
+ """Keys from the terminal: single-key commands, and a one-line editor for prompts.
2
+
3
+ Both work on raw bytes as they arrive from a terminal in cbreak mode, so they
4
+ can be tested by feeding bytes, without a terminal.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import codecs
10
+
11
+ ESC = "\x1b"
12
+ APPLY = "apply"
13
+ CANCEL = "cancel"
14
+ CHANGED = "changed"
15
+
16
+
17
+ class KeyReader:
18
+ """Turns bytes into keys, skipping escape sequences such as arrow keys.
19
+
20
+ An Esc that ends a read, or is followed by an ordinary character, is the
21
+ Esc key itself. ``ESC [`` starts a sequence that ends at a byte from ``@``
22
+ to ``~``; ``ESC O`` is followed by one more character.
23
+ """
24
+
25
+ NORMAL, CSI, SS3 = range(3)
26
+
27
+ def __init__(self) -> None:
28
+ self._decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
29
+ self._state = self.NORMAL
30
+
31
+ def feed(self, data: bytes) -> list[str]:
32
+ text = self._decoder.decode(data)
33
+ keys: list[str] = []
34
+ index = 0
35
+ while index < len(text):
36
+ char = text[index]
37
+ index += 1
38
+ if self._state == self.CSI:
39
+ if "@" <= char <= "~":
40
+ self._state = self.NORMAL
41
+ continue
42
+ if self._state == self.SS3:
43
+ self._state = self.NORMAL
44
+ continue
45
+ if char == ESC and index < len(text) and text[index] in "[O":
46
+ self._state = self.CSI if text[index] == "[" else self.SS3
47
+ index += 1
48
+ continue
49
+ keys.append(char)
50
+ return keys
51
+
52
+
53
+ class LineEditor:
54
+ """The text typed after f or a, with the usual editing keys.
55
+
56
+ Enter applies, Esc cancels, Backspace deletes a character, Ctrl-U clears.
57
+ Other control characters are ignored.
58
+ """
59
+
60
+ def __init__(self, label: str, text: str = "") -> None:
61
+ self.label = label
62
+ self.text = text
63
+
64
+ def key(self, char: str) -> str | None:
65
+ """Handle one key. Returns APPLY, CANCEL, CHANGED or None."""
66
+ if char in ("\r", "\n"):
67
+ return APPLY
68
+ if char == ESC:
69
+ return CANCEL
70
+ if char in ("\x7f", "\b"):
71
+ if self.text:
72
+ self.text = self.text[:-1]
73
+ return CHANGED
74
+ return None
75
+ if char == "\x15": # Ctrl-U
76
+ if self.text:
77
+ self.text = ""
78
+ return CHANGED
79
+ return None
80
+ if char < " " or char == "\x7f":
81
+ return None
82
+ self.text += char
83
+ return CHANGED
84
+
85
+ def display(self, width: int | None) -> str:
86
+ """The prompt line, showing only the end of the text if it is too long."""
87
+ line = f"{self.label}{self.text}_"
88
+ if width is None or len(line) <= width - 1:
89
+ return line
90
+ room = width - 1 - len(self.label) - 2 # "<" before, "_" after
91
+ tail = self.text[-room:] if room > 0 else ""
92
+ return f"{self.label}<{tail}_"[: max(1, width - 1)]