fix: improve tui ui/ux

This commit is contained in:
fufsob committed 2026-09-14 15:43:03 +00:00
1 parent 00b27e94ce
commit 8ed4ab9a8d
2 files changed
+357 -82

No files matched your search

+296 -79
View File
@@ -6,6 +6,7 @@ die() cannot take the TUI down.
"""
import os
import re
import shlex
import signal
import subprocess
@@ -15,14 +16,16 @@ from dataclasses import dataclass, field
from typing import Callable
from rich.text import Text
from textual import work
from textual import events, work
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Vertical
from textual.containers import Container, Vertical
from textual.content import Content
from textual.markup import escape
from textual.coordinate import Coordinate
from textual.screen import ModalScreen, Screen
from textual.widgets import DataTable, Footer, Input, Label, OptionList, RichLog, Static, TabbedContent, TabPane
from textual.theme import Theme
from textual.widgets import DataTable, Input, Label, OptionList, RichLog, Static, TabbedContent, TabPane
from textual.widgets.option_list import Option
import proxy_ctl as ctl
@@ -134,7 +137,7 @@ def toggle_argv(row, *_):
def service_rows(states):
return [{"key": u, "unit": u, "state": s} for u, s in states.items()]
return [{"key": u, "unit": u, "name": u.removeprefix("proxy-suite-"), "state": s} for u, s in states.items()]
def route_rows(_):
@@ -262,11 +265,40 @@ def status_text(states):
if zapret := ctl._status_zapret():
parts.append(("zapret ", f"{zapret} learned"))
failed = sum(1 for s in states.values() if s == "failed")
return (
"[b $accent]proxy-suite[/]"
+ "".join(f" [$text-muted]{label}[/][b]{escape(value)}[/]" for label, value in parts)
+ (f" [b $error]{failed} failed[/]" if failed else "")
)
return [
"[b ansi_cyan]proxy-suite[/]",
*(f"[dim]{label}[/][b]{escape(value)}[/]" for label, value in parts),
*([f"[b ansi_red]{failed} failed[/]"] if failed else []),
]
def pack(items, width, gap=" "):
"""Status items joined into lines no wider than width; an item never splits across lines."""
lines = []
for item in items:
if lines and Content.from_markup(lines[-1] + gap + item).cell_length <= width:
lines[-1] += gap + item
else:
lines.append(item)
return "\n".join(lines)
def filter_rows(rows, columns, text):
"""Every word must match: column:value in that column (by heading or field), anything else in any column."""
names = {k.lower(): name for name, heading in columns for k in (name, heading) if k}
def matches(row, term):
column, sep, value = term.lower().partition(":")
if sep and column in names:
return value in str(row.get(names[column], "")).lower()
return any(term.lower() in str(row.get(name, "")).lower() for name, _ in columns)
return [r for r in rows if all(matches(r, t) for t in text.split())]
def _natural(value):
# "port 443" before "port 2053": digit runs compare as numbers.
return [int(p) if p.isdigit() else p for p in re.split(r"(\d+)", str(value or "").lower())]
def _link(row, *extra):
@@ -294,7 +326,7 @@ TABS = [
"services",
"Services",
lambda _: True,
[("unit", "Unit"), ("state", "State")],
[("name", "Unit"), ("state", "State")],
service_rows,
actions=[
Action(
@@ -420,7 +452,8 @@ TABS = [
GLOBAL_KEYS = [
("enter", "actions for the selected row (or click it)"),
("← → ⇥", "switch tab; 1-8 jump to one"),
("/", "filter the rows; esc clears the filter"),
("/", "filter the rows (list:learned for one column); esc clears"),
("click", "a column heading sorts by it, again reverses, a third time unsorts"),
("w", "how is a domain routed"),
("L", "follow all logs"),
("o", "output of the last command"),
@@ -429,22 +462,66 @@ GLOBAL_KEYS = [
("q", "quit"),
]
HINT = "enter: actions for the selected row · ←/→: tabs · /: filter · ?: keys"
KEY_LINE = [("menu", "⏎", "actions"), ("filter", "/", "filter"), ("help", "?", "keys"), ("quit", "q", "quit")]
FEEDBACK_SECONDS = 10
STATE_STYLES = {"active": "green", "inactive": "dim", "failed": "red", "activating": "yellow", "deactivating": "yellow"}
# Terminal colors only, so the terminal's own background and palette show through, light or dark.
# Cyan is what you can press or click; green, yellow and red say how things are, and only where that matters.
THEME = Theme(
name="proxy-tui",
ansi=True,
primary="ansi_cyan",
secondary="ansi_cyan",
accent="ansi_cyan",
warning="ansi_yellow",
error="ansi_red",
success="ansi_green",
foreground="ansi_default",
background="ansi_default",
surface="ansi_default",
panel="ansi_default",
boost="ansi_default",
variables={
# The cursor reverses the row: readable on any background, and the same with or without focus.
**{f"block-cursor{blur}-{part}": "ansi_default" for blur in ("", "-blurred") for part in ("foreground", "background")},
"block-cursor-text-style": "reverse",
"block-cursor-blurred-text-style": "reverse",
"ansi-background": "ansi_black",
"ansi-foreground": "ansi_white",
"block-hover-background": "ansi_bright_black",
# Links (key hints) read as text, and hovering one lights it up the way hovering a row does.
"link-color": "ansi_default",
"link-background": "ansi_default",
"link-style": "none",
"link-color-hover": "ansi_default",
"link-background-hover": "ansi_bright_black",
"link-style-hover": "bold not dim",
"border": "ansi_cyan",
"border-blurred": "ansi_bright_black",
"input-cursor-background": "ansi_default",
"input-cursor-foreground": "ansi_default",
"input-cursor-text-style": "reverse",
"input-selection-background": "ansi_bright_black",
"scrollbar": "ansi_bright_black",
"scrollbar-hover": "ansi_white",
"scrollbar-active": "ansi_cyan",
"scrollbar-background": "ansi_default",
"scrollbar-corner-color": "ansi_default",
},
)
ACCENT = "bold cyan"
STATE_STYLES = {"active": "green", "inactive": "dim", "failed": "bold red", "activating": "yellow", "deactivating": "yellow"}
STATE_ICONS = {"active": "●", "inactive": "○", "failed": "✗", "activating": "◐", "deactivating": "◐"}
CELL_STYLES = {
"ok": "green",
"bad": "red",
"★": "bold yellow",
"▸": "bold cyan",
"▸": "bold green",
"●": "bold green",
"runtime": "cyan",
"learned": "yellow",
"pinned": "cyan",
"excluded": "magenta",
"routed": "green",
"excluded": "dim",
"queued": "yellow",
}
@@ -456,6 +533,29 @@ def cell(name, value):
return Text(value, style=CELL_STYLES.get(value, ""))
def detail(tab, row, actions):
"""The selected row in full, and what can be done with it: beside or below the table when there is room."""
text = Text()
if row:
for name, heading in tab.columns:
if heading and (value := row.get(name)):
text.append(f"{heading:<11}", style="dim")
text.append_text(cell(name, value))
text.append("\n")
text.append("\n")
text.append("Actions\n" if actions else "No actions here.\n", style="bold")
for a in actions:
text.append(f" {a.key:<7}", style=ACCENT)
text.append(f"{a.label}\n")
return text
def _update(widget, content):
# Only a change repaints: the refresh tick rewrites everything every few seconds.
if widget.content != content:
widget.update(content)
def _capture(argv):
try:
p = subprocess.run([CTL, *argv], capture_output=True, text=True, stdin=subprocess.DEVNULL)
@@ -478,7 +578,20 @@ def _read_states():
# --- dialogs ------------------------------------------------------------------
class Prompt(ModalScreen):
class Dialog(ModalScreen):
def on_click(self, event):
if event.widget is self: # the backdrop around the dialog
self.dismiss()
def hint(*parts):
"""A dialog's key hint; a (text, action) part is also clickable."""
return Label(
" · ".join(p if isinstance(p, str) else f"[@click=screen.{p[1]}]{p[0]}[/]" for p in parts), classes="dialog-hint"
)
class Prompt(Dialog):
BINDINGS = [Binding("escape", "dismiss", "cancel")]
def __init__(self, title, placeholder, value=""):
@@ -489,13 +602,16 @@ class Prompt(ModalScreen):
with Vertical(classes="dialog"):
yield Label(self.heading, classes="dialog-title")
yield Input(self.value, placeholder=self.placeholder)
yield Label("enter run · esc cancel", classes="dialog-hint")
yield hint(("enter run", "submit"), ("esc cancel", "dismiss"))
def on_input_submitted(self, event):
self.dismiss(event.value.strip())
def action_submit(self):
self.dismiss(self.query_one(Input).value.strip())
class Confirm(ModalScreen):
class Confirm(Dialog):
BINDINGS = [Binding("y,enter", "dismiss(True)", "yes"), Binding("n,escape", "dismiss(False)", "no")]
def __init__(self, command):
@@ -506,10 +622,17 @@ class Confirm(ModalScreen):
with Vertical(classes="dialog"):
yield Label("Run this?", classes="dialog-title")
yield Label(self.command, markup=False)
yield Label("y/enter run · n/esc cancel", classes="dialog-hint")
yield hint(("y/enter run", "dismiss(True)"), ("n/esc cancel", "dismiss(False)"))
class Menu(ModalScreen):
class Choices(OptionList):
def watch__mouse_hovering_over(self, index):
# One cursor for mouse and keys: otherwise the highlighted option looks the same hovered or not.
if index is not None:
self.highlighted = index
class Menu(Dialog):
"""The selected row's actions, picked with the arrows."""
BINDINGS = [Binding("escape,q", "dismiss", "close")]
@@ -521,16 +644,16 @@ class Menu(ModalScreen):
def compose(self) -> ComposeResult:
with Vertical(classes="dialog menu"):
yield Label(self.heading, classes="dialog-title", markup=False)
yield OptionList(
*(Option(Text.assemble((f"{a.key:<7}", "bold cyan"), a.label), id=str(i)) for i, a in enumerate(self.actions))
yield Choices(
*(Option(Text.assemble((f"{a.key:<7}", ACCENT), a.label), id=str(i)) for i, a in enumerate(self.actions))
)
yield Label("↑↓ choose · enter run · esc close", classes="dialog-hint")
yield hint("↑↓ or click to choose", ("esc close", "dismiss"))
def on_option_list_option_selected(self, event):
self.dismiss(self.actions[int(event.option.id)])
class Output(ModalScreen):
class Output(Dialog):
BINDINGS = [Binding("escape,q", "dismiss", "close"), Binding("c", "copy", "copy")]
def __init__(self, title, text=None):
@@ -543,13 +666,13 @@ class Output(ModalScreen):
with Vertical(classes="dialog output"):
yield Label(self.heading, classes="dialog-title", markup=False)
# Follow a streaming command; show finished text from its top.
log = RichLog(wrap=False, markup=False, auto_scroll=self.initial is None)
log = RichLog(wrap=True, min_width=1, markup=False, auto_scroll=self.initial is None)
if self.initial is not None:
text = self.initial if isinstance(self.initial, Text) else Text.from_ansi(self.initial)
self.text.append(text.plain)
log.write(text)
yield log
yield Label("↑↓ scroll · c copy · esc close", classes="dialog-hint")
yield hint(("c copy", "copy"), ("esc close", "dismiss"))
def write(self, line):
if self.is_attached:
@@ -569,26 +692,43 @@ class Output(ModalScreen):
# --- main screen --------------------------------------------------------------
def _short(label):
return label.split(" (")[0].removesuffix("…")
class Table(DataTable):
def _on_mouse_move(self, event):
event.prevent_default() # Textual would run DataTable's own handler again after this one.
super()._on_mouse_move(event)
if self.hover_row < 0: # the header row: hovering it changes nothing
self._set_hover_cursor(False)
def _pane(tab):
"""A pane whose bindings are its tab's action keys, so the footer shows them."""
bindings = [Binding(a.key, f"app.act({i})", a.label.removesuffix("…"), show=False) for i, a in enumerate(tab.actions)]
"""A pane whose bindings are its tab's action keys, live while its table has focus."""
bindings = [Binding(a.key, f"app.act({i})") for i, a in enumerate(tab.actions)]
return type(f"{tab.id.title()}Pane", (TabPane,), {"BINDINGS": bindings})
WIDE, TALL = 130, 40 # from here on the detail panel shows beside, or below, the table
class MainScreen(Screen):
HORIZONTAL_BREAKPOINTS = [(0, "-narrow"), (WIDE, "-wide")]
VERTICAL_BREAKPOINTS = [(0, "-short"), (TALL, "-tall")]
BINDINGS = [
Binding("left,shift+tab", "app.tab(-1)", "tabs", key_display="←→", priority=True),
Binding("right,tab", "app.tab(1)", "next tab", show=False, priority=True),
*(Binding(str(n), f"app.jump({n - 1})", show=False) for n in range(1, 9)),
Binding("enter", "app.menu", "actions", priority=True),
Binding("question_mark", "app.help", "keys"),
Binding("slash", "app.filter", "filter"),
Binding("escape", "app.clear_filter", "clear filter", show=False),
Binding("w", "app.where", "where", show=False),
Binding("L", "app.logs", "all logs", show=False),
Binding("o", "app.last_output", "last output", show=False),
Binding("r", "app.reload", "refresh", show=False),
Binding("q", "app.quit", "quit"),
Binding("left,shift+tab", "app.tab(-1)", priority=True),
Binding("right,tab", "app.tab(1)", priority=True),
*(Binding(str(n), f"app.jump({n - 1})") for n in range(1, 9)),
Binding("enter", "app.menu", priority=True),
Binding("question_mark", "app.help"),
Binding("slash", "app.filter"),
Binding("escape", "app.clear_filter"),
Binding("w", "app.where"),
Binding("L", "app.logs"),
Binding("o", "app.last_output"),
Binding("r", "app.reload"),
Binding("q", "app.quit"),
]
def __init__(self, tabs):
@@ -601,16 +741,23 @@ class MainScreen(Screen):
for tab in self.tabs.values():
with _pane(tab)(tab.title, id=tab.id):
yield Static(id=f"{tab.id}-summary", classes="summary")
table = DataTable(id=f"{tab.id}-table", cursor_type="row")
for name, heading in tab.columns:
table.add_column(heading, key=name)
yield table
yield Static(HINT, id="feedback")
yield Footer(show_command_palette=False)
with Container(classes="body"):
table = Table(id=f"{tab.id}-table", cursor_type="row")
for name, heading in tab.columns:
table.add_column(f"{heading} ", key=name) # room for the sort arrow
yield table
yield Static(id=f"{tab.id}-detail", classes="detail")
yield Static(id="feedback")
yield Static(id="keys")
def on_mount(self):
self.app.start()
def on_resize(self, _):
if self.app.rows: # the first load has filled the tables
self.app.selection_changed()
self.app.show_status()
def on_screen_resume(self):
# Refreshes pause under dialogs; catch up once one closes.
if self.app.rows:
@@ -620,21 +767,35 @@ class MainScreen(Screen):
class ProxyTui(App):
TITLE = "proxy-tui"
CSS = """
#status { height: 1; background: $panel; }
#status { height: auto; padding: 0 1; }
Underline > .underline--bar { color: $accent; background: $border-blurred; }
#tabs { height: 1fr; }
#tabs ContentSwitcher { height: 1fr; }
#tabs TabPane { height: 1fr; padding: 0; }
.summary { display: none; height: auto; padding: 0 1; color: $text-muted; }
.summary { display: none; height: auto; padding: 0 1; text-style: dim; }
DataTable { background: $background; }
#tabs DataTable { height: 1fr; }
#feedback { height: 1; padding: 0 1; background: $panel; }
DataTable > .datatable--header { background: $background; color: $accent; text-style: bold; }
.body { height: 1fr; }
.detail { display: none; padding: 0 1; }
.-tall #tabs DataTable { height: auto; max-height: 70%; }
.-tall .detail { display: block; height: 1fr; border-top: solid $border-blurred; }
.-wide .body { layout: horizontal; }
.-wide #tabs DataTable { width: auto; max-width: 70%; height: 1fr; max-height: 100%; }
.-wide .detail { display: block; width: 1fr; min-width: 40; border-top: none; border-left: solid $border-blurred; }
#feedback { display: none; height: 1; padding: 0 1; }
#keys { dock: bottom; height: auto; padding: 0 1; }
ModalScreen { align: center middle; }
.dialog { width: 76; max-width: 95%; height: auto; max-height: 90%; border: round $accent; background: $surface; padding: 0 1; }
.dialog { width: 76; max-width: 95%; height: auto; max-height: 90%; border: round $border; background: $background; padding: 0 1; }
.dialog-title { text-style: bold; color: $accent; margin-bottom: 1; }
.dialog-hint { color: $text-muted; margin-top: 1; }
.dialog Input { width: 1fr; }
.menu OptionList { height: auto; max-height: 20; border: none; padding: 0; }
.dialog-hint { text-style: dim; margin-top: 1; }
.dialog Input { width: 1fr; border: tall $border-blurred; }
.dialog Input:focus { border: tall $border; }
.menu OptionList { height: auto; max-height: 20; border: none; padding: 0; background: $background; }
/* An option list drops reverse video: the selected option gets the hover gray instead. */
.menu OptionList > .option-list--option-highlighted { color: $foreground; background: $block-hover-background; text-style: bold; }
.output { width: 95%; height: 90%; }
.output RichLog { height: 1fr; }
.output RichLog { height: 1fr; background: $background; }
"""
def __init__(self):
@@ -644,9 +805,19 @@ class ProxyTui(App):
self.shown = self.available_tabs(self.states)
self.rows = {} # tab id -> {row key: row}
self.filters = {} # tab id -> text
self.sorts = {} # tab id -> (column, descending)
self.loaded = {} # tab id -> the last load, refilled at once when sorting or filtering changes
self.status = []
self.typed = {} # prompt title -> what was last typed there
self.feedback_timer = None
self.last_output = None # (title, text)
self.animation_level = "none" # tab switches land at once
self.register_theme(THEME)
self.theme = THEME.name
def on_app_blur(self, event):
# Textual drops focus when the terminal loses it, and the table's cursor and footer change with it.
event.prevent_default()
def available_tabs(self, states):
return [t.id for t in TABS if _safe(t.available, states, fallback=False)]
@@ -657,10 +828,7 @@ class ProxyTui(App):
def start(self):
"""Once the main screen is up: it owns every widget read here."""
self.focus_table()
tabs = self.main.query_one("#tabs", TabbedContent)
for tab_id in self.tabs:
if tab_id not in self.shown:
tabs.hide_tab(tab_id)
self.show_tabs(self.shown)
self.action_reload()
self.set_interval(REFRESH_SECONDS, self.tick)
@@ -694,8 +862,23 @@ class ProxyTui(App):
def on_tabbed_content_tab_activated(self, _):
self.focus_table()
self.selection_changed()
self.action_reload()
def on_data_table_row_highlighted(self, _):
self.selection_changed()
def selection_changed(self):
tab_id, row = self.active_tab(), self.selected_row()
tab, actions = self.tabs[tab_id], self.applicable(row)
_update(self.main.query_one(f"#{tab_id}-detail", Static), detail(tab, row, actions))
width, height = self.size
# The detail panel lists the row's actions when it shows; the key line need not repeat them.
shown = [] if width >= WIDE or height >= TALL else [(f"act({tab.actions.index(a)})", a.key, _short(a.label)) for a in actions]
# The key keeps its color outside the link: a link's own color would cover it.
items = [f"[b ansi_cyan]{escape(k)}[/] [@click=app.{action}]{escape(label)}[/]" for action, k, label in shown + KEY_LINE]
_update(self.main.query_one("#keys", Static), pack(items, width - 2))
# --- reading --------------------------------------------------------------
def action_reload(self):
@@ -707,28 +890,41 @@ class ProxyTui(App):
tab = self.tabs[tab_id]
states = _read_states()
visible = self.available_tabs(states)
status = _safe(status_text, states, fallback="status unavailable")
status = _safe(status_text, states, fallback=["status unavailable"])
summary = (_safe(tab.summary, fallback="") or "") if tab.summary else ""
try:
rows = tab.rows(states)
except (Exception, SystemExit) as e:
rows = []
summary = f"✗ {str(e) or type(e).__name__}" + (f"\n{summary}" if summary else "")
else:
if not rows:
hints = " ".join(f"{a.key}: {_short(a.label)}" for a in tab.actions if a.prompt)
summary = "Nothing here yet." + (f" {hints}" if hints else "") + (f"\n{summary}" if summary else "")
self.call_from_thread(self.fill, tab_id, states, visible, status, rows, summary)
def show_status(self):
_update(self.main.query_one("#status", Static), pack(self.status, self.size.width - 2))
def refill(self, tab_id):
if tab_id in self.loaded:
self.fill(tab_id, *self.loaded[tab_id])
def fill(self, tab_id, states, visible, status, rows, summary):
self.states = states
self.main.query_one("#status", Static).update(status)
self.loaded[tab_id] = (states, visible, status, rows, summary)
self.states, self.status = states, status
self.show_status()
if visible != self.shown:
self.show_tabs(visible)
if tab_id not in visible:
return # show_tabs moved to another tab, which loads itself
if text := self.filters.get(tab_id):
needle = text.lower()
rows = [r for r in rows if any(needle in str(r.get(name, "")).lower() for name, _ in self.tabs[tab_id].columns)]
rows = filter_rows(rows, self.tabs[tab_id].columns, text)
summary = f"filter: {text} ({len(rows)} rows) · esc clears" + (f"\n{summary}" if summary else "")
if sort := self.sorts.get(tab_id):
rows = sorted(rows, key=lambda r: _natural(r.get(sort[0])), reverse=sort[1])
widget = self.main.query_one(f"#{tab_id}-summary", Static)
widget.update(Text(summary))
_update(widget, Text(summary))
widget.display = bool(summary)
self.rows[tab_id] = {r["key"]: r for r in rows}
tab, table = self.tabs[tab_id], self.table(tab_id)
@@ -740,6 +936,7 @@ class ProxyTui(App):
value = cell(name, r.get(name))
if table.get_cell(r["key"], name) != value:
table.update_cell(r["key"], name, value)
self.selection_changed()
return
selected = self.selected_key(tab_id)
table.clear()
@@ -747,11 +944,14 @@ class ProxyTui(App):
table.add_row(*(cell(name, r.get(name)) for name, _ in tab.columns), key=r["key"])
if selected in keys:
table.move_cursor(row=keys.index(selected), animate=False)
self.selection_changed()
def show_tabs(self, visible):
tabs = self.main.query_one("#tabs", TabbedContent)
for tab_id in self.tabs:
(tabs.show_tab if tab_id in visible else tabs.hide_tab)(tab_id)
for n, tab_id in enumerate(visible, 1):
tabs.get_tab(tab_id).label = f"{n} {self.tabs[tab_id].title}"
self.shown = visible
if tabs.active not in visible and visible:
tabs.active = visible[0]
@@ -771,6 +971,12 @@ class ProxyTui(App):
def applicable(self, row):
return [a for a in self.tabs[self.active_tab()].actions if a.when is None or (row is not None and a.when(row))]
def check_action(self, action, parameters):
# A row action that does not apply: its key does nothing.
if action != "act" or self.screen is not self.main:
return True
return self.tabs[self.active_tab()].actions[parameters[0]] in self.applicable(self.selected_row())
def action_menu(self):
row = self.selected_row()
title = row["key"] if row else self.tabs[self.active_tab()].title
@@ -785,17 +991,26 @@ class ProxyTui(App):
self.action_menu()
def action_act(self, index):
action = self.tabs[self.active_tab()].actions[index]
row = self.selected_row()
if action.when is not None and (row is None or not action.when(row)):
target = row["key"] if row else "an empty list"
self.feedback(f"'{action.label.removesuffix('…')}' does not apply to {target}", ok=False)
return
self.perform(action, row)
self.perform(self.tabs[self.active_tab()].actions[index], self.selected_row())
def action_where(self):
self.perform(Action("w", "How is a domain routed", lambda r, t, _: ["where", t], prompt="<domain>", mode="dialog"), None)
def on_data_table_header_selected(self, event):
tab_id, name = self.active_tab(), event.column_key.value
sort = self.sorts.pop(tab_id, None)
if not sort or sort[0] != name:
self.sorts[tab_id] = (name, False)
elif not sort[1]:
self.sorts[tab_id] = (name, True)
table = self.table(tab_id)
for column, heading in self.tabs[tab_id].columns:
arrow = ("▼" if self.sorts[tab_id][1] else "▲") if self.sorts.get(tab_id, ("",))[0] == column else " "
table.columns[column].label = Text(f"{heading} {arrow}")
table._clear_caches() # the header is cached with its old labels
table.refresh()
self.refill(tab_id)
def action_filter(self):
tab_id = self.active_tab()
@@ -803,13 +1018,13 @@ class ProxyTui(App):
if text is None:
return
self.filters[tab_id] = text
self.action_reload()
self.refill(tab_id)
self.push_screen(Prompt("Filter rows", "text in any column; empty clears", self.filters.get(tab_id, "")), apply)
self.push_screen(Prompt("Filter rows", "words in any column, or column:value (list:learned); empty clears", self.filters.get(tab_id, "")), apply)
def action_clear_filter(self):
if self.filters.pop(self.active_tab(), ""):
self.action_reload()
self.refill(self.active_tab())
def action_logs(self):
self.run_argv("suspend", ["logs"])
@@ -826,7 +1041,7 @@ class ProxyTui(App):
for heading, keys in ((tab.title, [(a.key, a.label) for a in tab.actions]), ("Everywhere", GLOBAL_KEYS)):
text.append(f"{heading}\n", style="bold")
for key, label in keys:
text.append(f" {key:<9}", style="bold cyan")
text.append(f" {key:<9}", style=ACCENT)
text.append(f"{label}\n")
text.append("\n")
self.push_screen(Output("Keys", text))
@@ -906,11 +1121,13 @@ class ProxyTui(App):
def feedback(self, message, ok=None):
icon, style = {True: ("✓ ", "green"), False: ("✗ ", "red"), None: ("", "")}[ok]
self.main.query_one("#feedback", Static).update(Text(icon + message, style=style, no_wrap=True, overflow="ellipsis"))
bar = self.main.query_one("#feedback", Static)
bar.update(Text(icon + message, style=style, no_wrap=True, overflow="ellipsis"))
bar.display = True
if self.feedback_timer:
self.feedback_timer.stop()
if ok is not None:
self.feedback_timer = self.set_timer(FEEDBACK_SECONDS, lambda: self.feedback(HINT))
self.feedback_timer = self.set_timer(FEEDBACK_SECONDS, lambda: setattr(bar, "display", False))
if __name__ == "__main__":
+61 -3
View File
@@ -38,6 +38,8 @@ class TuiTest(unittest.TestCase):
(ctl, "_status_zapret", lambda: ""),
(ctl, "svc_state", lambda unit: ""),
(ctl, "_inbound_links", lambda: [{"tag": "vless", "user": "alice", "type": "vless", "port": 443}]),
# No refresh ticks: a tick's load landing mid-test would read everything again.
(tui, "REFRESH_SECONDS", 3600),
]:
patcher = mock.patch.object(target, name, value)
patcher.start()
@@ -56,6 +58,17 @@ class TuiTest(unittest.TestCase):
):
self.assertEqual(tui.subscription_rows({})[0]["updated"], "0m ago")
def test_filter_sort_pack(self):
rows = [{"key": "a", "host": "a.example", "kind": "learned"}, {"key": "b", "host": "learned.org", "kind": "pinned"}]
columns = [("host", "Host"), ("kind", "List")]
keys = lambda text: [r["key"] for r in tui.filter_rows(rows, columns, text)]
self.assertEqual(keys("learned"), ["a", "b"])
self.assertEqual(keys("list:learned"), ["a"]) # by heading
self.assertEqual(keys("kind:pinned LEARNED"), ["b"]) # by field, and every word must match
self.assertEqual(sorted(["port 2053", "port 443"], key=tui._natural), ["port 443", "port 2053"])
# Items never split across lines.
self.assertEqual(tui.pack(["[b]aaa[/]", "bbb", "ccc"], 9), "[b]aaa[/] bbb\nccc")
def test_ui(self):
# Not IsolatedAsyncioTestCase: its asyncio debug mode makes Textual crawl.
asyncio.run(self.ui())
@@ -77,6 +90,17 @@ class TuiTest(unittest.TestCase):
self.assertEqual(app.shown, ["services", "zapret"])
self.assertEqual(app.focused.id, "services-table")
# The terminal losing focus leaves the TUI as it is.
app.post_message(tui.events.AppBlur())
await pilot.pause()
self.assertEqual((app.app_focus, app.focused.id), (True, "services-table"))
# Hovering the header, even past its last column, does not highlight it.
await pilot.hover("#services-table", offset=(90, 0))
self.assertFalse(app.table()._show_hover_cursor)
await pilot.hover("#services-table", offset=(90, 1))
self.assertTrue(app.table()._show_hover_cursor)
# Tabs follow what runs: socks starting brings its tabs in.
self.units = {"proxy-suite-socks": "active", **self.units}
app.action_reload()
@@ -108,7 +132,7 @@ class TuiTest(unittest.TestCase):
self.units["proxy-suite-ssh-proxy"] = "failed"
app.action_reload()
await self.settle(app, pilot)
self.assertIn("1 failed", tui.status_text(app.states))
self.assertIn("1 failed", tui.pack(tui.status_text(app.states), 100))
app.table().move_cursor(row=list(app.rows["services"]).index(tui.AWG_PREFIX + "p"))
await pilot.press("ctrl+r")
self.assertEqual(self.ran.pop(), ["awg", "restart", "p"])
@@ -136,15 +160,23 @@ class TuiTest(unittest.TestCase):
app.action_reload()
await self.settle(app, pilot)
self.assertEqual(self.current.call_count, 1)
# The footer offers only what applies to the selected row.
self.assertIn("p", app.screen.active_bindings)
self.assertNotIn("u", app.screen.active_bindings)
await pilot.press("p", "t", "u")
self.assertEqual(self.ran, [["proxy", "pin", "a"], ["proxy", "outbounds", "test", "a"]])
await pilot.press("down", "p", "d", "u")
await pilot.press("down")
self.assertNotIn("p", app.screen.active_bindings)
await pilot.press("p", "d", "u")
self.assertEqual(self.ran.pop(), ["proxy", "unpin"])
self.ran.clear()
await pilot.press("enter")
await pilot.pause()
self.assertNotIn("pin it", self.menu_labels(app))
self.assertNotIn("remove it", self.menu_labels(app))
# Hovering an option selects it: one cursor for mouse and keys.
await pilot.hover(tui.Choices, offset=(3, 1))
self.assertEqual(app.screen.query_one(tui.Choices).highlighted, 1)
await pilot.press("escape")
# Prompts: add takes "<tag> <url>".
@@ -157,6 +189,11 @@ class TuiTest(unittest.TestCase):
self.assertEqual(app.screen.query_one(tui.Input).value, "x vless://h")
await pilot.press("escape")
# An empty tab says how to fill it.
await pilot.press("4")
await self.settle(app, pilot)
self.assertIn("Nothing here yet. n: add a runtime subscription", str(app.main.query_one("#subs-summary").content))
# zapret: an excluded host can be included again, not forgotten.
# Brackets in a summary are text, not markup.
self.env["ZAPRET_CUTOFF_ENABLED"] = "1"
@@ -173,7 +210,12 @@ class TuiTest(unittest.TestCase):
await pilot.press("escape", "i")
self.assertEqual(self.ran.pop(), ["zapret", "auto", "include", "kept.example"])
# Confirmed actions run only on yes.
# Confirmed actions run only on yes; a click beside a dialog closes it.
await pilot.press("C")
await pilot.pause()
await pilot.click(offset=(0, 0))
await pilot.pause()
self.assertIs(app.screen, app.main)
await pilot.press("C", "n")
await pilot.pause()
self.assertEqual(self.ran, [])
@@ -189,6 +231,22 @@ class TuiTest(unittest.TestCase):
await self.settle(app, pilot)
self.assertEqual(len(app.rows["zapret"]), 2)
# A narrow terminal lists the row's actions on the key line; wider ones in the detail panel instead.
self.assertIn("forget it", str(app.main.query_one("#keys").content))
# Clicking a heading sorts by it, again reverses, a third time restores the order.
order = lambda: [str(app.table().get_row_at(i)[0]) for i in range(app.table().row_count)]
self.assertEqual(order(), ["learned.example", "kept.example"])
await pilot.click("#zapret-table", offset=(2, 0))
self.assertEqual(order(), ["kept.example", "learned.example"])
self.assertEqual(str(app.table().columns["host"].label), "Host ▲")
await pilot.click("#zapret-table", offset=(2, 0))
self.assertEqual(order(), ["learned.example", "kept.example"])
self.assertEqual(str(app.table().columns["host"].label), "Host ▼")
await pilot.click("#zapret-table", offset=(2, 0))
self.assertEqual(order(), ["learned.example", "kept.example"])
self.assertEqual(str(app.table().columns["host"].label), "Host ")
# Inbounds appears once enabled; c copies the share link.
self.env["INBOUNDS_ENABLED"] = "1"
app.action_reload()