side-cli 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.
side_cli/clients.py ADDED
@@ -0,0 +1,133 @@
1
+ """Async clients for framed output and line-framed input listeners."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ import socket
8
+ import struct
9
+ from collections.abc import AsyncIterator
10
+ from contextlib import suppress
11
+ from types import TracebackType
12
+
13
+ from .supervisor import CHUNK_SIZE, HOST, _FRAME_HEADER, _OUTPUT_STREAM_IDS, Ports, Stream
14
+
15
+ _OUTPUT_STREAMS = {identifier: stream for stream, identifier in _OUTPUT_STREAM_IDS.items()}
16
+ _ABORTIVE_LINGER = struct.pack("HH" if os.name == "nt" else "ii", 1, 0)
17
+
18
+
19
+ def _validate_port(port: int) -> None:
20
+ if type(port) is not int or not 1 <= port <= 65535:
21
+ raise ValueError("client port must be an integer between 1 and 65535")
22
+
23
+
24
+ class PanelClient:
25
+ """Connect to a local framed output port and iterate over (stream, bytes) pairs."""
26
+
27
+ def __init__(self, port: int = Ports().stdout) -> None:
28
+ _validate_port(port)
29
+ self.port = port
30
+ self._reader: asyncio.StreamReader | None = None
31
+ self._writer: asyncio.StreamWriter | None = None
32
+
33
+ async def __aenter__(self) -> PanelClient:
34
+ if self._writer is not None:
35
+ raise RuntimeError("panel client is already connected")
36
+ self._reader, self._writer = await asyncio.open_connection(HOST, self.port)
37
+ return self
38
+
39
+ async def __aexit__(
40
+ self,
41
+ exc_type: type[BaseException] | None,
42
+ exc_value: BaseException | None,
43
+ traceback: TracebackType | None,
44
+ ) -> None:
45
+ writer, self._writer = self._writer, None
46
+ self._reader = None
47
+ if writer is not None:
48
+ writer.close()
49
+ with suppress(OSError):
50
+ await writer.wait_closed()
51
+
52
+ async def __aiter__(self) -> AsyncIterator[tuple[Stream, bytes]]:
53
+ reader = self._reader
54
+ if reader is None:
55
+ raise RuntimeError("panel client is not connected")
56
+ while True:
57
+ try:
58
+ header = await reader.readexactly(_FRAME_HEADER.size)
59
+ except asyncio.IncompleteReadError as error:
60
+ if not error.partial:
61
+ return
62
+ raise ValueError("incomplete output frame header") from error
63
+
64
+ identifier, length = _FRAME_HEADER.unpack(header)
65
+ stream = _OUTPUT_STREAMS.get(identifier)
66
+ if stream is None or not 1 <= length <= CHUNK_SIZE:
67
+ raise ValueError("invalid output frame header")
68
+ try:
69
+ data = await reader.readexactly(length)
70
+ except asyncio.IncompleteReadError as error:
71
+ raise ValueError("incomplete output frame payload") from error
72
+ yield stream, data
73
+
74
+
75
+ class InputClient:
76
+ """Send LF-delimited bytes to stdin. Incomplete lines stay on this connection."""
77
+
78
+ def __init__(self, port: int = Ports().stdin) -> None:
79
+ _validate_port(port)
80
+ self.port = port
81
+ self._socket: socket.socket | None = None
82
+ self._send_lock = asyncio.Lock()
83
+
84
+ async def __aenter__(self) -> InputClient:
85
+ if self._socket is not None:
86
+ raise RuntimeError("input client is already connected")
87
+ connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
88
+ try:
89
+ connection.setblocking(False)
90
+ await asyncio.get_running_loop().sock_connect(connection, (HOST, self.port))
91
+ except BaseException:
92
+ connection.close()
93
+ raise
94
+ self._socket = connection
95
+ return self
96
+
97
+ async def __aexit__(
98
+ self,
99
+ exc_type: type[BaseException] | None,
100
+ exc_value: BaseException | None,
101
+ traceback: TracebackType | None,
102
+ ) -> None:
103
+ self.close(abort=exc_type is not None)
104
+
105
+ def close(self, *, abort: bool = False) -> None:
106
+ """Disconnect. Abort skips the orderly EOF that can close the child's stdin."""
107
+ connection, self._socket = self._socket, None
108
+ if connection is not None:
109
+ try:
110
+ if abort:
111
+ connection.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, _ABORTIVE_LINGER)
112
+ finally:
113
+ connection.close()
114
+
115
+ async def send(self, data: bytes) -> None:
116
+ """Send raw bytes without modifying them."""
117
+ async with self._send_lock:
118
+ await asyncio.get_running_loop().sock_sendall(self._connected_socket(), data)
119
+
120
+ async def send_line(self, data: bytes) -> None:
121
+ """Send bytes, adding a trailing LF if missing."""
122
+ await self.send(data if data.endswith(b"\n") else data + b"\n")
123
+
124
+ async def wait_for_disconnect(self) -> None:
125
+ """Wait for the server to close the connection; raise on a socket error."""
126
+ connection = self._connected_socket()
127
+ while await asyncio.get_running_loop().sock_recv(connection, CHUNK_SIZE):
128
+ pass
129
+
130
+ def _connected_socket(self) -> socket.socket:
131
+ if self._socket is None:
132
+ raise RuntimeError("input client is not connected")
133
+ return self._socket
side_cli/gui.py ADDED
@@ -0,0 +1,269 @@
1
+ """Tk desktop frontend for side-cli."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import codecs
8
+ import tkinter as tk
9
+ from contextlib import suppress
10
+ from io import IncrementalNewlineDecoder
11
+ from time import monotonic
12
+ from tkinter import ttk
13
+
14
+ from .ansi import AnsiColors, ColorRun
15
+ from .cli import ConsoleInterrupt, ConsoleOutput, _visible_input, show_ports
16
+ from .supervisor import INPUT_LINE_LIMIT, Ports, Stream, Supervisor
17
+
18
+
19
+ class Window:
20
+ def __init__(
21
+ self, root: tk.Tk, encoding: str, supervisor: Supervisor, console: ConsoleOutput | None = None,
22
+ ) -> None:
23
+ self.root = root
24
+ self.encoding = encoding
25
+ self.supervisor = supervisor
26
+ self.console = console
27
+ self.closed = False
28
+ self.send_task: asyncio.Task[None] | None = None
29
+ self._input_pending = ""
30
+ self._input_encoder = codecs.getincrementalencoder(encoding)()
31
+ self.decoders = {
32
+ stream: IncrementalNewlineDecoder(
33
+ codecs.getincrementaldecoder(encoding)("replace"), translate=True
34
+ )
35
+ for stream in (Stream.STDOUT, Stream.STDERR)
36
+ }
37
+ self.colors = {stream: AnsiColors() for stream in self.decoders}
38
+ self.pending: list[ColorRun] = []
39
+ self._color_tags: set[str] = set()
40
+ self.process_status = tk.StringVar(value="Starting listeners...")
41
+ self.input_status = tk.StringVar()
42
+ self.add_newline = tk.BooleanVar(value=True)
43
+ self.port_values = {
44
+ endpoint: tk.StringVar(value="Not listening") for endpoint in supervisor.status()
45
+ }
46
+
47
+ root.title("side-cli")
48
+ root.geometry("1040x590")
49
+ root.minsize(640, 360)
50
+ root.protocol("WM_DELETE_WINDOW", self.close)
51
+ panels = ttk.Panedwindow(root, orient=tk.HORIZONTAL)
52
+ panels.pack(fill=tk.BOTH, expand=True, padx=12, pady=12)
53
+ console = ttk.Frame(panels, padding=(0, 0, 8, 0))
54
+ sidebar = ttk.Frame(panels, padding=(8, 0, 0, 0), width=290)
55
+ panels.add(console, weight=3)
56
+ panels.add(sidebar, weight=1)
57
+
58
+ ttk.Label(console, text="Process output", font=("TkDefaultFont", 12, "bold")).pack(
59
+ anchor=tk.W, pady=(0, 6)
60
+ )
61
+ terminal = ttk.Frame(console)
62
+ terminal.pack(fill=tk.BOTH, expand=True)
63
+ self.output = tk.Text(
64
+ terminal, state=tk.DISABLED, wrap=tk.CHAR, font="TkFixedFont",
65
+ background="#151920", foreground="#e5e9f0", padx=10, pady=8,
66
+ selectbackground="#394f70", relief=tk.FLAT, borderwidth=0,
67
+ )
68
+ scrollbar = ttk.Scrollbar(terminal, orient=tk.VERTICAL, command=self.output.yview)
69
+ self.output.configure(yscrollcommand=scrollbar.set)
70
+ self.output.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
71
+ scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
72
+ self._caret = tk.Frame(self.output, background=self.output.cget("foreground"), takefocus=False)
73
+ self._caret_position: tuple[int, int, int] | None = None
74
+ self._caret_epoch = monotonic()
75
+
76
+ input_panel = ttk.LabelFrame(sidebar, text="Standard input", padding=10)
77
+ input_panel.pack(fill=tk.X)
78
+ input_panel.columnconfigure(0, weight=1)
79
+ self.entry = ttk.Entry(input_panel)
80
+ self.entry.grid(row=0, column=0, sticky="ew", padx=(0, 8))
81
+ self.entry.bind("<Return>", self.submit)
82
+ self.output.bind("<ButtonRelease-1>", self._focus_after_output_click)
83
+ self._caret.bind("<Button-1>", self._focus_after_output_click)
84
+ self.send_button = ttk.Button(input_panel, text="Send", command=self.submit, state=tk.DISABLED)
85
+ self.send_button.grid(row=0, column=1)
86
+ ttk.Checkbutton(input_panel, text="Append newline", variable=self.add_newline).grid(
87
+ row=1, column=0, columnspan=2, sticky="w", pady=(8, 0)
88
+ )
89
+ ttk.Label(input_panel, textvariable=self.input_status, wraplength=245).grid(
90
+ row=2, column=0, columnspan=2, sticky="w"
91
+ )
92
+
93
+ ports_panel = ttk.LabelFrame(sidebar, text="TCP ports", padding=10)
94
+ ports_panel.pack(fill=tk.X, pady=(12, 0))
95
+ for row, (endpoint, value) in enumerate(self.port_values.items()):
96
+ label = "STDOUT / STDERR" if endpoint == "output" else endpoint.upper()
97
+ ttk.Label(ports_panel, text=label).grid(
98
+ row=row, column=0, sticky="nw", padx=(0, 14), pady=(0, 8)
99
+ )
100
+ ttk.Label(ports_panel, textvariable=value).grid(
101
+ row=row, column=1, sticky="w", pady=(0, 8)
102
+ )
103
+ ttk.Label(sidebar, textvariable=self.process_status, wraplength=270).pack(
104
+ anchor=tk.W, pady=(12, 0)
105
+ )
106
+ self.entry.focus_set()
107
+
108
+ def _focus_after_output_click(self, event: tk.Event) -> None:
109
+ if event.widget is self.output and self.output.tag_ranges(tk.SEL):
110
+ self.output.focus_set()
111
+ else:
112
+ self.entry.focus_set()
113
+
114
+ def close(self) -> None:
115
+ self.closed = True
116
+ self.root.withdraw()
117
+
118
+ def receive(self, stream: Stream, data: bytes) -> None:
119
+ self.pending.extend(self.colors[stream].feed(self.decoders[stream].decode(data)))
120
+
121
+ async def echo_input(self, text: str) -> None:
122
+ if visible := _visible_input(text):
123
+ self.pending.append((visible, (None, None)))
124
+ if self.console is not None:
125
+ await self.console.echo_input(text)
126
+
127
+ def finish_output(self) -> None:
128
+ for stream, decoder in self.decoders.items():
129
+ self.pending.extend(self.colors[stream].feed(decoder.decode(b"", final=True), final=True))
130
+
131
+ def _color_tag(self, option: str, color: str) -> str:
132
+ tag = f"ansi-{option}-{color}"
133
+ if tag not in self._color_tags:
134
+ self.output.tag_configure(tag, **{option: color})
135
+ self._color_tags.add(tag)
136
+ return tag
137
+
138
+ def _refresh_caret(self) -> None:
139
+ position = None
140
+ if (monotonic() - self._caret_epoch) % 1.0 < 0.5:
141
+ if bounds := self.output.bbox("end-1c"):
142
+ left, top, _, height = bounds
143
+ position = left, top, height
144
+ if position == self._caret_position:
145
+ return
146
+ self._caret_position = position
147
+ if position is None:
148
+ self._caret.place_forget()
149
+ else:
150
+ left, top, height = position
151
+ self._caret.place(x=left, y=top, width=2, height=height, bordermode="outside")
152
+
153
+ def refresh(self) -> None:
154
+ if self.pending:
155
+ follow = self.output.yview()[1] >= 0.999
156
+ self.output.configure(state=tk.NORMAL)
157
+ for text, (foreground, background) in self.pending:
158
+ tags = tuple(
159
+ self._color_tag(option, color)
160
+ for option, color in (("foreground", foreground), ("background", background))
161
+ if color is not None
162
+ )
163
+ self.output.insert(tk.END, text, tags)
164
+ self.output.configure(state=tk.DISABLED)
165
+ self.pending.clear()
166
+ if follow:
167
+ self.output.see(tk.END)
168
+ self._caret_epoch = monotonic()
169
+ self._refresh_caret()
170
+ for port in self.supervisor.status().values():
171
+ state = "Listening" if port.listening else "Not listening"
172
+ clients = "client" if port.clients == 1 else "clients"
173
+ address = f"{port.host}:{port.port}" if port.port else "Automatic port"
174
+ value = f"{address}\n{state} | {port.clients} {clients}"
175
+ if self.port_values[port.stream].get() != value:
176
+ self.port_values[port.stream].set(value)
177
+ self.send_button.configure(
178
+ state=tk.NORMAL if self.supervisor.stdin_open and self.send_task is None else tk.DISABLED
179
+ )
180
+
181
+ def submit(self, *_: object) -> str:
182
+ if self.send_task is None and self.supervisor.stdin_open:
183
+ text = self.entry.get()
184
+ payload = text + ("\n" if self.add_newline.get() else "")
185
+ if payload:
186
+ self.send_task = asyncio.create_task(self.send(text, payload))
187
+ return "break"
188
+
189
+ async def send(self, text: str, payload: str) -> None:
190
+ try:
191
+ *lines, tail = (self._input_pending + payload).split("\n")
192
+ if len(tail.encode(self.encoding)) >= INPUT_LINE_LIMIT or any(
193
+ len((line + "\n").encode(self.encoding)) > INPUT_LINE_LIMIT for line in lines
194
+ ):
195
+ raise ValueError("input line exceeds 1 MiB")
196
+ await self.echo_input(payload)
197
+ for line in lines:
198
+ await self.supervisor.send(self._input_encoder.encode(line + "\n"))
199
+ self._input_pending = tail
200
+ except (OSError, ValueError) as error:
201
+ self.input_status.set(f"Send failed: {error}")
202
+ else:
203
+ if self.entry.get() == text:
204
+ self.entry.delete(0, tk.END)
205
+ self.input_status.set("Buffered until newline." if tail else "")
206
+ finally:
207
+ self.send_task = None
208
+
209
+ async def run_command(self, args: argparse.Namespace) -> int:
210
+ try:
211
+ with ConsoleInterrupt(self.supervisor) as interrupts:
212
+ async with self.supervisor:
213
+ if args.show_ports:
214
+ show_ports(self.supervisor)
215
+ if args.wait_for_output_clients:
216
+ if "output" in self.port_values:
217
+ self.process_status.set("Waiting for an output client...")
218
+ else:
219
+ self.process_status.set("Waiting for stdout and stderr clients...")
220
+ if not await interrupts.launch(args.wait_for_output_clients):
221
+ self.process_status.set("Launch interrupted.")
222
+ return 130
223
+ self.process_status.set(f"Running (PID {self.supervisor.pid})")
224
+ code = await self.supervisor.wait()
225
+ self.process_status.set(f"Process exited with code {code}.")
226
+ return code
227
+ except (OSError, RuntimeError, ValueError) as error:
228
+ self.process_status.set(f"side-cli: {error}")
229
+ return 1
230
+ finally:
231
+ self.finish_output()
232
+
233
+
234
+ async def run_gui(args: argparse.Namespace, ports: Ports) -> int:
235
+ try:
236
+ root = tk.Tk()
237
+ except tk.TclError as error:
238
+ raise RuntimeError(f"cannot open the Tk desktop window: {error}") from error
239
+ console = ConsoleOutput(args.encoding)
240
+
241
+ async def receive(stream: Stream, data: bytes) -> None:
242
+ window.receive(stream, data)
243
+ await console.write(stream, data)
244
+
245
+ supervisor = Supervisor(
246
+ args.command, ports=ports, on_output=receive,
247
+ on_input_echo=lambda text: window.echo_input(text), input_encoding=args.encoding,
248
+ close_stdin_on_eof=args.close_stdin_on_eof,
249
+ )
250
+ window = Window(root, args.encoding, supervisor, console)
251
+ command = asyncio.create_task(window.run_command(args))
252
+ try:
253
+ while not window.closed:
254
+ window.refresh()
255
+ root.update()
256
+ await asyncio.sleep(0.025)
257
+ return command.result() if command.done() else 0
258
+ finally:
259
+ if window.send_task is not None:
260
+ window.send_task.cancel()
261
+ with suppress(asyncio.CancelledError):
262
+ await window.send_task
263
+ command.cancel()
264
+ try:
265
+ with suppress(asyncio.CancelledError):
266
+ await command
267
+ await console.finish()
268
+ finally:
269
+ root.destroy()