tuihost 0.2.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.
tuihost/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """TUI Host - runs any TUI as a child process on a PTY."""
2
+
3
+ __version__ = "0.2.0"
4
+
5
+ from .config import HostConfig # noqa: E402
6
+
7
+
8
+ def run(config: HostConfig, backend: str = "gui") -> int:
9
+ from .app import run as _run
10
+
11
+ return _run(config, backend)
12
+
13
+
14
+ __all__ = ["HostConfig", "run", "__version__"]
tuihost/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
tuihost/_terminal.py ADDED
@@ -0,0 +1,69 @@
1
+ """TerminalView with terminal size reports.
2
+
3
+ PuiKit (1.36) does not set libghostty-vt's size callback, so the terminal
4
+ never answers XTWINOPS size queries (CSI 14/16/18 t) or sends the in-band
5
+ size report (mode 2048). Textual still sees mode 2048 as supported, turns on
6
+ SGR-pixel mouse reporting (1016) and waits for the report to learn the
7
+ pixel-to-cell ratio; without it every mouse coordinate is read as a cell
8
+ number far off-screen, so no mouse input works.
9
+
10
+ The callback reports PuiKit's mouse-encoder cell size (``_MCELL_W`` x
11
+ ``_MCELL_H``), so pixel positions and the reported size share one scale.
12
+ Remove once PuiKit sets the callback itself.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import ctypes as C
18
+
19
+ from puikit import _ghostty as G
20
+ from puikit.widgets.terminal_view import TerminalView
21
+
22
+ # libghostty-vt 1.0.1 include/ghostty/vt/terminal.h
23
+ OPT_SIZE = 7 # GHOSTTY_TERMINAL_OPT_SIZE
24
+ DATA_COLS = 1 # GHOSTTY_TERMINAL_DATA_COLS (uint16_t)
25
+ DATA_ROWS = 2 # GHOSTTY_TERMINAL_DATA_ROWS (uint16_t)
26
+
27
+
28
+ class SizeReportSize(C.Structure):
29
+ """GhosttySizeReportSize (frozen by libghostty-vt)."""
30
+
31
+ _fields_ = [("rows", C.c_uint16), ("columns", C.c_uint16),
32
+ ("cell_width", C.c_uint32), ("cell_height", C.c_uint32)]
33
+
34
+
35
+ SizeFn = C.CFUNCTYPE(C.c_bool, C.c_void_p, C.c_void_p, C.POINTER(SizeReportSize))
36
+
37
+
38
+ def install_size_reports(term: G.Terminal) -> None:
39
+ """Make ``term`` answer size queries; no-op if a callback is already set."""
40
+ if getattr(term, "_cb_size", None) is not None:
41
+ return
42
+ lib = term._lib
43
+
44
+ def _size(handle, _userdata, out) -> bool:
45
+ if not out:
46
+ return False
47
+ cols, rows = C.c_uint16(), C.c_uint16()
48
+ # Read the live size: during a resize the report is sent before
49
+ # G.Terminal updates its own cols/rows.
50
+ if (lib.ghostty_terminal_get(handle, DATA_COLS, C.byref(cols)) != G.SUCCESS
51
+ or lib.ghostty_terminal_get(handle, DATA_ROWS, C.byref(rows)) != G.SUCCESS):
52
+ cols.value, rows.value = term.cols, term.rows
53
+ size = out.contents
54
+ size.columns, size.rows = cols.value, rows.value
55
+ size.cell_width, size.cell_height = G._MCELL_W, G._MCELL_H
56
+ return True
57
+
58
+ # The CFUNCTYPE object must outlive the terminal.
59
+ term._cb_size = SizeFn(_size)
60
+ lib.ghostty_terminal_set(term._h, OPT_SIZE, C.cast(term._cb_size, C.c_void_p))
61
+
62
+
63
+ class HostTerminalView(TerminalView):
64
+ def _start_on(self, panel, theme, cols, rows) -> None:
65
+ # The child is already running when super() returns, but its output
66
+ # is fed to the terminal later on the UI thread, so no query is missed.
67
+ super()._start_on(panel, theme, cols, rows)
68
+ if self._term is not None:
69
+ install_size_reports(self._term)
tuihost/app.py ADDED
@@ -0,0 +1,448 @@
1
+ """The host app: native windows, each a full-window TerminalView running a
2
+ session (the hosted program or a shell), in one process with one Dock icon."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import dataclasses
7
+ import os
8
+ import sys
9
+ from typing import Any
10
+
11
+ from puikit import SEPARATOR, EventType, Font, Item, Menu, MenuItem, Panel, VSplit
12
+ from puikit.backends import create_backend
13
+
14
+ from . import __version__, state, window
15
+ from .config import DEFAULT_FONT_SIZE, MAX_FONT_SIZE, MIN_FONT_SIZE, HostConfig
16
+
17
+ #: Backends that open a native window sized in base units (one cell each).
18
+ GUI_BACKENDS = frozenset({"gui", "macos", "windows", "win32"})
19
+ #: Backends whose base grid font size can be set.
20
+ FONT_BACKENDS = GUI_BACKENDS | {"web", "webbrowser", "browser"}
21
+
22
+ IS_MAC = sys.platform == "darwin"
23
+
24
+ #: Host shortcuts, checked before the terminal sees the key. Zoom: Cmd (macOS)
25
+ #: or Ctrl (elsewhere, as Windows Terminal) + = - 0. Windows: Cmd+N/T/W (macOS)
26
+ #: or Ctrl+Shift+N/T/W (elsewhere, so plain Ctrl+letter stays the program's).
27
+ _ZOOM_KEYS = {"=": "bigger", "+": "bigger", "-": "smaller", "0": "reset"}
28
+ _WINDOW_KEYS = {"n": "new_window", "t": "new_shell", "w": "close_window"}
29
+
30
+
31
+ def host_action(event: Any, mac: bool | None = None) -> str | None:
32
+ """The host command a KEY event triggers, or None if it is the program's."""
33
+ mac = IS_MAC if mac is None else mac
34
+ if event.type is not EventType.KEY:
35
+ return None
36
+ mods = frozenset(event.modifiers)
37
+ primary = "cmd" if mac else "ctrl"
38
+ if event.key in _ZOOM_KEYS and mods - {"shift"} == {primary}:
39
+ return _ZOOM_KEYS[event.key]
40
+ if mac and mods == {"cmd"}:
41
+ return "quit" if event.key == "q" else _WINDOW_KEYS.get(event.key)
42
+ if not mac and mods == {"ctrl", "shift"}:
43
+ return _WINDOW_KEYS.get(event.key)
44
+ return None
45
+
46
+
47
+ def backend_kwargs(backend: str, config: HostConfig) -> dict[str, Any]:
48
+ kwargs: dict[str, Any] = {}
49
+ if backend in GUI_BACKENDS:
50
+ kwargs.update(width=config.cols, height=config.rows, title=config.title)
51
+ if config.frame_autosave_name:
52
+ kwargs["frame_autosave_name"] = config.frame_autosave_name
53
+ elif backend == "memory":
54
+ kwargs.update(width=config.cols, height=config.rows)
55
+ if config.font_size is not None and backend in FONT_BACKENDS:
56
+ kwargs["base_font"] = Font(size=config.font_size, monospace=True)
57
+ return kwargs
58
+
59
+
60
+ def resolve_font_size(config: HostConfig, state_directory: str | None = None) -> float | None:
61
+ """Explicit --font-size, else the remembered one, else None (backend default)."""
62
+ if config.font_size is not None:
63
+ return config.font_size
64
+ if config.remember_window:
65
+ saved = state.load(config.app_id, state_directory).get("font_size")
66
+ if isinstance(saved, (int, float)) and MIN_FONT_SIZE <= saved <= MAX_FONT_SIZE:
67
+ return float(saved)
68
+ return None
69
+
70
+
71
+ def child_env(config: HostConfig) -> dict[str, str] | None:
72
+ """Environment for the child; None inherits ours (PuiKit then adds TERM,
73
+ COLORTERM, LANG and TERM_PROGRAM)."""
74
+ if not config.env:
75
+ return None
76
+ return {**os.environ, **config.env}
77
+
78
+
79
+ def build_menu(config: HostConfig, actions: dict[str, Any], mac: bool | None = None) -> Menu:
80
+ """The app menu bar. Shortcuts are display hints; the keys themselves are
81
+ handled by host_action (windows, zoom) and TerminalView (clipboard)."""
82
+ mac = IS_MAC if mac is None else mac
83
+ mod = "Cmd" if mac else "Ctrl"
84
+ win = "Cmd" if mac else "Ctrl+Shift"
85
+ clip = "Cmd" if mac else "Ctrl+Shift"
86
+ file_items = [MenuItem("New Window", on_select=actions["new_window"], shortcut=f"{win}+N")]
87
+ if config.shell_windows and config.argv:
88
+ file_items.append(MenuItem("New Shell Window", on_select=actions["new_shell"],
89
+ shortcut=f"{win}+T"))
90
+ file_items += [SEPARATOR,
91
+ MenuItem("Close Window", on_select=actions["close_window"], shortcut=f"{win}+W")]
92
+ if not mac:
93
+ file_items += [SEPARATOR, MenuItem("Exit", on_select=actions["quit"])]
94
+ return Menu(
95
+ MenuItem("File", submenu=Menu(*file_items)),
96
+ MenuItem("Edit", submenu=Menu(
97
+ MenuItem("Copy", on_select=actions["copy"], shortcut=f"{clip}+C"),
98
+ MenuItem("Paste", on_select=actions["paste"], shortcut=f"{clip}+V"),
99
+ )),
100
+ MenuItem("View", submenu=Menu(
101
+ MenuItem("Bigger Text", on_select=actions["bigger"], shortcut=f"{mod}+="),
102
+ MenuItem("Smaller Text", on_select=actions["smaller"], shortcut=f"{mod}+-"),
103
+ SEPARATOR,
104
+ MenuItem("Actual Size", on_select=actions["reset"], shortcut=f"{mod}+0"),
105
+ )),
106
+ MenuItem("Help", submenu=Menu(
107
+ MenuItem(f"About {config.title}", on_select=actions["about"]),
108
+ )),
109
+ )
110
+
111
+
112
+ def about_text(config: HostConfig) -> str:
113
+ import puikit
114
+
115
+ command = " ".join(config.argv) if config.argv else "login shell"
116
+ return (f"{config.title}\n\nRunning: {command}\n\n"
117
+ f"tuihost {__version__} · PuiKit {puikit.__version__}")
118
+
119
+
120
+ class TerminalUnavailable(RuntimeError):
121
+ """The embedded terminal cannot run here (libghostty-vt or a pty missing)."""
122
+
123
+
124
+ class Session:
125
+ """One window and the program running in it. ``handle`` None is the
126
+ backend's main window."""
127
+
128
+ def __init__(self, kind: str, handle: Any, panel: Panel, term: Any) -> None:
129
+ self.kind = kind # "app" or "shell"
130
+ self.handle = handle
131
+ self.panel = panel
132
+ self.term = term
133
+ self.closed = False
134
+
135
+ @property
136
+ def is_main(self) -> bool:
137
+ return self.handle is None
138
+
139
+ @property
140
+ def running(self) -> bool:
141
+ term = self.term
142
+ return (getattr(term, "_proc", None) is not None
143
+ and getattr(term, "_exited", False) is False)
144
+
145
+ def needs_confirm(self) -> bool:
146
+ """Closing would end something the user may care about: a hosted
147
+ program that still runs, or a shell busy with a command (a shell idle
148
+ at its prompt is not asked about; Windows can't tell, so it asks)."""
149
+ if not self.running:
150
+ return False
151
+ if self.kind == "app":
152
+ return True
153
+ return getattr(self.term, "child_in_foreground", None) is not True
154
+
155
+ def is_active(self, backend: Any) -> bool:
156
+ if self.handle is None:
157
+ return bool(backend.is_main_window_active())
158
+ return bool(self.handle.is_active())
159
+
160
+
161
+ class HostApp:
162
+ def __init__(self, config: HostConfig, backend_name: str) -> None:
163
+ self.config = config
164
+ self.backend_name = backend_name
165
+ self.be: Any = None
166
+ self.sessions: list[Session] = []
167
+ self.front: Session | None = None
168
+ self.font_size = config.font_size
169
+ self.result = 0
170
+ self.first: Session | None = None
171
+ self._quitting = False
172
+ self._asking = False
173
+
174
+ # --- sessions -------------------------------------------------------------
175
+
176
+ def _argv_env(self, kind: str) -> tuple[list[str] | None, dict[str, str] | None]:
177
+ if kind == "app":
178
+ return (self.config.argv or None), child_env(self.config)
179
+ return None, None # the user's login shell, our own environment
180
+
181
+ def _make_term(self, session_ref: list, kind: str) -> Any:
182
+ from . import _terminal
183
+
184
+ argv, env = self._argv_env(kind)
185
+ cwd = self.config.cwd if kind == "app" else (self.config.cwd or os.path.expanduser("~"))
186
+ return _terminal.HostTerminalView(
187
+ argv, cwd=cwd, env=env,
188
+ on_exit=lambda code: self._on_exit(session_ref[0], code),
189
+ on_title=(lambda title: self._on_title(session_ref[0], title))
190
+ if self.config.follow_title else None,
191
+ padding_px=self.config.padding_px,
192
+ term_program=("tuihost", __version__),
193
+ )
194
+
195
+ def _base_title(self, kind: str) -> str:
196
+ return self.config.title if kind == "app" else f"{self.config.title} — Shell"
197
+
198
+ def _attach(self, kind: str, handle: Any, panel: Panel) -> Session:
199
+ ref: list = [None]
200
+ term = self._make_term(ref, kind)
201
+ session = Session(kind, handle, panel, term)
202
+ ref[0] = session
203
+ panel.set_layout(VSplit(Item(term, weight=1, hints={"surface": "content"})))
204
+ panel.focus(term)
205
+ self.sessions.append(session)
206
+ self.front = session
207
+ return session
208
+
209
+ def new_window(self, kind: str = "app") -> Session:
210
+ be = self.be
211
+ main_free = not any(s.is_main for s in self.sessions)
212
+ if main_free:
213
+ # Reuse the main window (hidden when its session closed): it keeps
214
+ # its remembered frame.
215
+ session = self._attach(kind, None, self.main_panel)
216
+ window.set_title(be, None, self._base_title(kind))
217
+ be.show_main_window()
218
+ else:
219
+ front = self.front if self.front in self.sessions else None
220
+ cols, rows = (front.panel.backend.size_units if front is None or front.is_main
221
+ else front.handle.size_units)
222
+ handle = be.create_window(int(cols), int(rows), title=self._base_title(kind))
223
+ session_box: list = [None]
224
+ handle.on_event = lambda event: self._on_event(session_box[0], event)
225
+ handle.on_close = lambda: self._on_closed(session_box[0])
226
+ panel = Panel(be, window=handle)
227
+ session = self._attach(kind, handle, panel)
228
+ session_box[0] = session
229
+ window.install_close_guard(be, handle, lambda: self.request_close(session))
230
+ window.cascade(be, None if front is None else front.handle, handle)
231
+ handle.show()
232
+ session.panel.render()
233
+ return session
234
+
235
+ def front_session(self) -> Session | None:
236
+ for session in self.sessions:
237
+ if session.is_active(self.be):
238
+ return session
239
+ return self.front if self.front in self.sessions else (
240
+ self.sessions[-1] if self.sessions else None)
241
+
242
+ # --- closing --------------------------------------------------------------
243
+
244
+ def _confirm(self, session: Session, message: str, button: str, then) -> None:
245
+ from puikit.widgets import show_message_box
246
+
247
+ if self._asking:
248
+ return
249
+ self._asking = True
250
+
251
+ def done(choice: str) -> None:
252
+ self._asking = False
253
+ session.panel.focus(session.term)
254
+ if choice == button:
255
+ then()
256
+ else:
257
+ session.panel.render()
258
+
259
+ show_message_box(session.panel, message, title=self.config.title,
260
+ buttons=(button, "Cancel"), icon="warning",
261
+ default=1, cancel=1, on_result=done)
262
+ session.panel.render()
263
+
264
+ def request_close(self, session: Session | None) -> None:
265
+ """The user asked to close a window: ask first if something runs."""
266
+ if session is None or session.closed:
267
+ return
268
+ if self.config.confirm_close and session.needs_confirm():
269
+ what = ("A program is still running" if session.kind == "shell"
270
+ else f"{self.config.title} is still running")
271
+ self._confirm(session, f"{what} in this window.\n\nClose it?", "Close",
272
+ lambda: self.close_session(session))
273
+ else:
274
+ self.close_session(session)
275
+
276
+ def close_session(self, session: Session) -> None:
277
+ if session.closed:
278
+ return
279
+ session.closed = True
280
+ session.term.close()
281
+ if session in self.sessions:
282
+ self.sessions.remove(session)
283
+ if self.front is session:
284
+ self.front = self.sessions[-1] if self.sessions else None
285
+ if not self.sessions:
286
+ self.be.quit()
287
+ return
288
+ if session.is_main:
289
+ self.be.hide_main_window()
290
+ else:
291
+ window.release_close_guard(self.be, session.handle)
292
+ if not getattr(session.handle, "closed", False):
293
+ session.handle.close()
294
+
295
+ def _on_closed(self, session: Session | None) -> None:
296
+ """A secondary window closed without asking us (no close guard)."""
297
+ if session is not None and not session.closed:
298
+ self.close_session(session)
299
+
300
+ def request_quit(self) -> None:
301
+ if self._quitting:
302
+ return
303
+ busy = [s for s in self.sessions if s.needs_confirm()] if self.config.confirm_close else []
304
+ if not busy:
305
+ self.quit()
306
+ return
307
+ front = self.front_session() or busy[0]
308
+ n = len(busy)
309
+ message = (f"{n} sessions are still running.\n\nQuit {self.config.title}?" if n > 1
310
+ else f"A session is still running.\n\nQuit {self.config.title}?")
311
+ self._confirm(front, message, "Quit", self.quit)
312
+
313
+ def quit(self) -> None:
314
+ self._quitting = True
315
+ self.be.quit()
316
+
317
+ # --- events ---------------------------------------------------------------
318
+
319
+ def _on_exit(self, session: Session | None, code: int | None) -> None:
320
+ if session is None:
321
+ return
322
+ if session is self.first:
323
+ self.result = 1 if code is None else code
324
+ # A shell window closes whatever the shell's status (a bare ``exit``
325
+ # returns the last command's); --keep-open is for the hosted program.
326
+ if session.kind == "shell" or self.config.should_close(code):
327
+ self.close_session(session)
328
+
329
+ def _on_title(self, session: Session | None, title: str) -> None:
330
+ if session is None or session.closed:
331
+ return
332
+ window.set_title(self.be, session.handle, self._window_title(session, title))
333
+
334
+ def _window_title(self, session: Session, program_title: str) -> str:
335
+ base = self._base_title(session.kind)
336
+ if not program_title or program_title == base:
337
+ return base
338
+ return f"{base} — {program_title}"
339
+
340
+ def _on_event(self, session: Session | None, event: Any) -> None:
341
+ if session is None or session.closed:
342
+ return
343
+ if event.type in (EventType.KEY, EventType.MOUSE_DOWN, EventType.MOUSE_CLICK):
344
+ self.front = session
345
+ action = host_action(event)
346
+ if action is not None:
347
+ self.actions[action]()
348
+ return
349
+ if session.panel.dispatch_event(event) or event.type is EventType.RESIZE:
350
+ session.panel.render()
351
+
352
+ def _main_event(self, event: Any) -> None:
353
+ main = next((s for s in self.sessions if s.is_main), None)
354
+ if main is not None:
355
+ self._on_event(main, event)
356
+ elif event.type is EventType.RESIZE:
357
+ self.main_panel.render()
358
+
359
+ # --- zoom, clipboard, about -----------------------------------------------
360
+
361
+ def set_font_size(self, size: float | None) -> None:
362
+ if size is not None:
363
+ size = min(MAX_FONT_SIZE, max(MIN_FONT_SIZE, size))
364
+ if size == self.font_size:
365
+ return
366
+ self.font_size = size
367
+ # App-wide: windows share the backend's base font. Each keeps its pixel
368
+ # size, so its grid gains or loses cells and its program gets a resize.
369
+ self.be.set_base_font(Font(size=size or DEFAULT_FONT_SIZE, monospace=True))
370
+ if self.config.remember_window:
371
+ state.save(self.config.app_id, font_size=size)
372
+ for session in self.sessions:
373
+ session.panel.render()
374
+
375
+ def zoom(self, step: float) -> None:
376
+ self.set_font_size((self.font_size or DEFAULT_FONT_SIZE) + step)
377
+
378
+ def about(self) -> None:
379
+ from puikit.widgets import show_message_box
380
+
381
+ session = self.front_session()
382
+ if session is None:
383
+ return
384
+ show_message_box(session.panel, about_text(self.config), title="About",
385
+ on_result=lambda _b: session.panel.focus(session.term))
386
+ session.panel.render()
387
+
388
+ def _with_front(self, fn):
389
+ def run() -> None:
390
+ session = self.front_session()
391
+ if session is not None:
392
+ fn(session)
393
+ return run
394
+
395
+ # --- run ------------------------------------------------------------------
396
+
397
+ def run(self) -> int:
398
+ from puikit.widgets.terminal_view import available
399
+
400
+ why = available()
401
+ if why is not None:
402
+ raise TerminalUnavailable(f"embedded terminal unavailable: {why}")
403
+
404
+ config = self.config
405
+ self.be = be = create_backend(self.backend_name, **backend_kwargs(self.backend_name, config))
406
+ self.actions = {
407
+ "new_window": lambda: self.new_window("app"),
408
+ "new_shell": lambda: self.new_window("shell" if config.shell_windows else "app"),
409
+ "close_window": self._with_front(self.request_close),
410
+ "copy": self._with_front(lambda s: s.term.copy_selection()),
411
+ "paste": self._with_front(lambda s: s.term.paste()),
412
+ "bigger": lambda: self.zoom(1),
413
+ "smaller": lambda: self.zoom(-1),
414
+ "reset": lambda: self.set_font_size(None),
415
+ "about": self.about,
416
+ "quit": self.request_quit,
417
+ }
418
+ with be:
419
+ window.route_text_input_to_key_window(be)
420
+ self.main_panel = Panel(be)
421
+ main = self.first = self.new_window("app")
422
+ if IS_MAC:
423
+ # macOS: the main window's close button comes to the guard;
424
+ # Quit (menu, Cmd+Q, Dock) to the quit handler.
425
+ window.install_close_guard(be, None, lambda: self.request_close(
426
+ next((s for s in self.sessions if s.is_main), None)))
427
+ be.set_quit_handler(self.request_quit, shortcut="Cmd+Q")
428
+ else:
429
+ # Windows: the main window's close button is the quit request.
430
+ be.set_quit_handler(lambda: self.request_close(
431
+ next((s for s in self.sessions if s.is_main), None)))
432
+ self.main_panel.set_menu_bar(build_menu(config, self.actions))
433
+ try:
434
+ main.panel.render()
435
+ be.run_event_loop(self._main_event)
436
+ finally:
437
+ for session in list(self.sessions):
438
+ session.closed = True
439
+ session.term.close()
440
+ return self.result
441
+
442
+
443
+ def run(config: HostConfig, backend: str = "gui") -> int:
444
+ """Open the host window and run until the last window closes. Returns the
445
+ first window's program's exit code (0 if it was still running, 1 if it was
446
+ killed by a signal)."""
447
+ config = dataclasses.replace(config, font_size=resolve_font_size(config))
448
+ return HostApp(config, backend).run()