refactor: better binds in tui/gui

This commit is contained in:
fufsob committed 2026-09-29 09:16:07 +00:00
1 parent 9bbffe24b4
commit 3e141b46fc
6 files changed
+174 -112

No files matched your search

+23 -12
View File
@@ -62,18 +62,18 @@ STATUS_ICONS = {"ok": "emblem-ok-symbolic", "warn": "dialog-warning-symbolic", "
TOAST_LINES = 4 # a toast says this much of what ran; the Output button, and `o`, have the whole of it
GLOBAL_SHORTCUTS = [
("<Control>f slash", "Filter the rows (list:learned for one column)"),
("<Control>f slash", "Filter the rows, e.g. list:learned"),
("Escape", "Clear the filter"),
("Menu <Shift>F10", "Actions for the selected row (or right-click it)"),
("Menu <Shift>F10", "Actions for the selected row; a right-click opens them too"),
("<Alt>1...<Alt>8", "Jump to a tab"),
("<Control>v", "Paste a link: it is added to this tab"),
("w", "How is a domain routed"),
("<Shift>l", "Follow all logs"),
("o", "Output of the last command"),
("<Control>e", "Read and run as root (pkexec)"),
("<Control>e", "Read and run as root"),
("F5 r", "Refresh now"),
("<Control>question", "Keyboard shortcuts"),
("<Control>w", "Close the window (the tray keeps running)"),
("<Control>w", "Close the window; the tray keeps running"),
("<Control>q", "Quit"),
]
@@ -175,7 +175,8 @@ def accelerator(key):
def display_key(key):
return key.replace("ctrl+", "Ctrl+").replace("space", "Space")
"""Ctrl+r, Shift+n, Space: modifiers and named keys capitalized, a letter as it is typed."""
return "+".join(part.capitalize() if len(part) > 1 else part for part in model.display_key(key).split("+"))
SGR = re.compile(r"\x1b\[([0-9;]*)m")
@@ -400,11 +401,10 @@ class Page(Gtk.Box):
def shortcuts(self):
controller = Gtk.ShortcutController(propagation_phase=Gtk.PropagationPhase.CAPTURE)
for i, action in enumerate(self.tab.actions):
trigger = accelerator(action.key)
for trigger, indices in self.triggers().items():
controller.add_shortcut(Gtk.Shortcut(
trigger=Gtk.ShortcutTrigger.parse_string(trigger),
action=Gtk.CallbackAction.new(self.keyed(trigger, lambda i=i: self.act(i, from_key=True))),
action=Gtk.CallbackAction.new(self.keyed(trigger, lambda indices=indices: self.act_any(indices))),
))
for trigger, callback in (
("slash", lambda *_: self.focus_search()),
@@ -414,10 +414,21 @@ class Page(Gtk.Box):
("r", lambda *_: self.win.app.reload()),
("Menu|<Shift>F10", lambda *_: self.open_menu(None)),
):
if not any(accelerator(a.key) == trigger for a in self.tab.actions):
if trigger not in self.triggers():
controller.add_shortcut(Gtk.Shortcut(trigger=Gtk.ShortcutTrigger.parse_string(trigger), action=Gtk.CallbackAction.new(self.keyed(trigger, callback))))
return controller
def triggers(self):
"""Accelerator -> indices of the tab's actions on it: a toggle is two actions on one key."""
out = {}
for i, action in enumerate(self.tab.actions):
out.setdefault(accelerator(action.key), []).append(i)
return out
def act_any(self, indices):
"""The first of these actions that applies to the selected row; none: the key falls through."""
return any(self.act(i, from_key=True) for i in indices)
def keyed(self, trigger, callback):
"""A key for this tab only while it shows, and never one meant for a text field, a dialog or a focused button."""
def run(*_):
@@ -1041,8 +1052,8 @@ class Window(Adw.ApplicationWindow):
page = self.page()
if page and (actions := [a for a in page.tab.actions if model.offered(a)]):
section = Adw.ShortcutsSection(title=page.tab.title)
for action in actions:
section.add(Adw.ShortcutsItem(title=cap(action.label), accelerator=accelerator(action.key)))
for key, label in model.key_labels(actions):
section.add(Adw.ShortcutsItem(title=cap(label), accelerator=accelerator(key)))
dialog.add(section)
section = Adw.ShortcutsSection(title="Everywhere")
for accel, title in GLOBAL_SHORTCUTS:
@@ -1210,7 +1221,7 @@ class ProxySuiteGui(Adw.Application):
if not model.needs_root(summary.splitlines(), 1):
return rows, summary
if not elevated:
return rows, summary + "\nCtrl+E: read and run as root (pkexec)"
return rows, summary + "\nCtrl+E: read and run as root"
if self.root_read_refused:
return rows, summary + "\nRoot read cancelled: Ctrl+E twice to ask again."
root_rows, why = model.load_tab_as_root(tab, "pkexec")
+68 -55
View File
@@ -566,14 +566,14 @@ TABS = [
Action("R", "restart everything running", lambda r, *_: ["restart"], confirm=True),
Action(
"n",
"new Tor circuits for new connections",
"new Tor circuits",
lambda r, *_: ["tor", "newnym"],
when=lambda r: r["unit"] == "proxy-suite-tor" and r["state"] == "active",
),
# whitelist-bypass: a creator makes the call its joiner joins.
Action("k", "its call link", _wl_argv("link"), when=_wl_role("creator"), mode="dialog"),
Action("c", "copy its call link", _wl_argv("link"), when=_wl_role("creator"), mode="copy"),
Action("Q", "its call link as QR", _wl_argv("link", "--qr"), when=_wl_role("creator"), mode="dialog"),
Action("s", "call link", _wl_argv("link"), when=_wl_role("creator"), mode="dialog"),
Action("c", "copy call link", _wl_argv("link"), when=_wl_role("creator"), mode="copy"),
Action("Q", "call link as QR", _wl_argv("link", "--qr"), when=_wl_role("creator"), mode="dialog"),
Action(
"N",
"drop its call for a new one",
@@ -618,7 +618,7 @@ TABS = [
Action("l", "follow its logs", lambda r, *_: ["logs", r["unit"]], when=ROW, mode="suspend"),
Action(
"n",
"add a profile (name optional)…",
"add a profile…",
lambda r, t, _: _awg_add_argv(t),
prompt="[name] <vpn://… or a .conf path> - e.g. home vpn://… (or paste a whole .conf onto the table)",
stdin=lambda r, t: _awg_add_stdin(t),
@@ -635,7 +635,7 @@ TABS = [
route_rows,
summary=lambda: f"Configured default: {ctl._route_mode_default()}. An override lasts until you switch back to default.",
actions=[
Action("s", "switch to this mode", lambda r, *_: ["proxy", "mode", r["key"]], when=lambda r: not r["active"]),
Action("space", "switch to this mode", lambda r, *_: ["proxy", "mode", r["key"]], when=lambda r: not r["active"]),
Action("i", "rule sets and when each was fetched", lambda r, *_: ["proxy", "rulesets", "list"], mode="dialog", offered=_rule_sets),
Action("u", "fetch the rule sets now", lambda r, *_: ["proxy", "rulesets", "update"], mode="dialog", offered=_rule_sets),
],
@@ -649,11 +649,11 @@ TABS = [
summary=outbound_summary,
actions=[
Action("p", "pin it", lambda r, *_: ["proxy", "pin", r["tag"]], when=lambda r: r["mark"] != "★" and not r["disabled"]),
Action("u", "unpin: let the selection pick", lambda r, *_: ["proxy", "unpin"], when=lambda r: r["mark"] == "★"),
Action("p", "unpin it", lambda r, *_: ["proxy", "unpin"], when=lambda r: r["mark"] == "★"),
Action("t", "test it", lambda r, *_: ["proxy", "outbounds", "test", r["tag"]], when=ROW, mode="dialog"),
Action("D", "test its download speed", lambda r, *_: ["proxy", "outbounds", "test", r["tag"], "--download"], when=ROW, mode="dialog"),
Action("ctrl+t", "test its download speed", lambda r, *_: ["proxy", "outbounds", "test", r["tag"], "--download"], when=ROW, mode="dialog"),
Action(
"v",
"P",
"probe a domain through it…",
lambda r, t, _: ["proxy", "auto", "probe", t, "--via", ctl._backend_tag(r["tag"])],
when=_enabled("AUTOPROXY_ENABLED"),
@@ -663,14 +663,14 @@ TABS = [
Action("T", "test all", lambda r, *_: ["proxy", "outbounds", "test"], mode="dialog"),
Action(
"n",
"add a runtime outbound (tag optional)…",
"add an outbound…",
lambda r, t, _: ["proxy", "outbounds", "add", *_add_args(t)],
prompt="[tag] <url, JSON or vpn://> - e.g. de-1 vless://… or just vless://…",
stdin=lambda r, t: _add_stdin(t),
),
Action(
"h",
"add an outbound chained through this one (tag optional)…",
"add an outbound chained through this one…",
lambda r, t, _: ["proxy", "outbounds", "add", *_add_args(t), "--detour", r["tag"]],
when=ROW,
prompt="[tag] <url or JSON> - e.g. de-1 vless://… or just vless://…",
@@ -685,20 +685,20 @@ TABS = [
Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"], confirm=True),
Action(
"x",
"disable it (never picked, pinned or probed)",
"disable it",
lambda r, *_: ["proxy", "outbounds", "disable", r["tag"]],
when=lambda r: not r["disabled"],
confirm=True,
),
Action("e", "enable it again", lambda r, *_: ["proxy", "outbounds", "enable", r["tag"]], when=lambda r: r["disabled"]),
Action("x", "enable it again", lambda r, *_: ["proxy", "outbounds", "enable", r["tag"]], when=lambda r: r["disabled"]),
# Credentials: proxy-ctl refuses these without root or the group, and the dialog says so.
Action("l", "its URL", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=ROW, mode="dialog"),
Action("c", "copy its URL", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=ROW, mode="copy"),
Action("Q", "its URL as QR", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--qr"], when=ROW, mode="dialog"),
Action("s", "share link", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=ROW, mode="dialog"),
Action("c", "copy share link", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=ROW, mode="copy"),
Action("Q", "share link as QR", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--qr"], when=ROW, mode="dialog"),
Action("J", "its JSON", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--json"], when=ROW, mode="dialog"),
Action("F", "client config for it alone", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--config"], when=ROW, mode="dialog"),
Action("X", "client config with every outbound and rule", lambda r, *_: ["proxy", "config"], mode="dialog"),
Action("C", "the config as it runs here", lambda r, *_: ["proxy", "config", "--raw"], mode="dialog"),
Action("k", "client config for it alone", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--config"], when=ROW, mode="dialog"),
Action("K", "client config with every outbound and rule", lambda r, *_: ["proxy", "config"], mode="dialog"),
Action("V", "the config as it runs here", lambda r, *_: ["proxy", "config", "--raw"], mode="dialog"),
],
),
Tab(
@@ -709,18 +709,18 @@ TABS = [
subscription_rows,
summary=subscription_summary,
actions=[
Action("u", "refetch all", lambda r, *_: ["proxy", "subs", "update"], mode="dialog"),
Action("u", "fetch all now", lambda r, *_: ["proxy", "subs", "update"], mode="dialog"),
Action("l", "follow the update's logs", lambda r, *_: ["logs", "proxy-suite-subscription-update"], mode="suspend"),
Action(
"n",
"add a runtime subscription (tag optional)…",
"add a subscription…",
lambda r, t, _: ["proxy", "subs", "add", *_add_args(t)],
prompt="[tag] <url> - e.g. work https://… or just https://…",
),
Action("d", "remove it", lambda r, *_: ["proxy", "subs", "rm", r["tag"]], when=lambda r: r["source"] == "runtime", confirm=True),
Action("k", "its URL", lambda r, *_: ["proxy", "subs", "link", r["tag"]], when=ROW, mode="dialog"),
Action("y", "copy its URL", lambda r, *_: ["proxy", "subs", "link", r["tag"]], when=ROW, mode="copy"),
Action("Q", "its URL as QR", lambda r, *_: ["proxy", "subs", "link", r["tag"], "--qr"], when=ROW, mode="dialog"),
Action("s", "URL", lambda r, *_: ["proxy", "subs", "link", r["tag"]], when=ROW, mode="dialog"),
Action("c", "copy URL", lambda r, *_: ["proxy", "subs", "link", r["tag"]], when=ROW, mode="copy"),
Action("Q", "URL as QR", lambda r, *_: ["proxy", "subs", "link", r["tag"], "--qr"], when=ROW, mode="dialog"),
],
),
Tab(
@@ -732,13 +732,13 @@ TABS = [
summary=ctl._status_autoproxy,
actions=[
Action("w", "how is it routed", lambda r, *_: ["where", r["domain"]], when=ROW, mode="dialog"),
Action("e", "learn it now", lambda r, *_: ["proxy", "auto", "learn", r["domain"]], when=_kind("queued"), mode="dialog"),
Action("u", "learn it now", lambda r, *_: ["proxy", "auto", "learn", r["domain"]], when=_kind("queued"), mode="dialog"),
Action("p", "probe it through every exit", lambda r, *_: ["proxy", "auto", "probe", r["domain"], "--keep-going"], when=ROW, mode="dialog"),
Action("P", "probe a domain…", lambda r, t, _: ["proxy", "auto", "probe", t], prompt="<domain>[/path]", mode="dialog"),
Action("E", "learn a domain…", lambda r, t, _: ["proxy", "auto", "learn", t], prompt="<domain>", mode="dialog"),
Action("f", "forget it (direct until learned again)", lambda r, *_: ["proxy", "auto", "forget", r["domain"]], when=_kind("routed"), confirm=True),
Action("R", "relearn it from the host it was learned from", lambda r, *_: ["proxy", "auto", "relearn", r["domain"]], when=_kind("routed"), mode="dialog"),
Action("C", "forget everything learned", lambda r, *_: ["proxy", "auto", "clear"], confirm=True),
Action("n", "learn a domain…", lambda r, t, _: ["proxy", "auto", "learn", t], prompt="<domain>", mode="dialog"),
Action("f", "forget it", lambda r, *_: ["proxy", "auto", "forget", r["domain"]], when=_kind("routed"), confirm=True),
Action("u", "relearn it from the host it was learned from", lambda r, *_: ["proxy", "auto", "relearn", r["domain"]], when=_kind("routed"), mode="dialog"),
Action("F", "forget everything learned", lambda r, *_: ["proxy", "auto", "clear"], confirm=True),
Action("i", "routed, judged and bad exits", lambda r, *_: ["proxy", "auto", "list"], mode="dialog"),
],
),
@@ -750,16 +750,17 @@ TABS = [
zapret_rows,
summary=zapret_summary,
actions=[
Action("f", "forget it (may be learned again)", lambda r, *_: ["zapret", "auto", "forget", r["host"]], when=_kind("learned")),
Action("x", "exclude it (never touch or learn it)", lambda r, *_: ["zapret", "auto", "exclude", r["host"]], when=_kind("learned", "pinned")),
Action("u", "unpin it", lambda r, *_: ["zapret", "auto", "unpin", r["host"]], when=_kind("pinned")),
Action("i", "include it (zapret may touch or learn it again)", lambda r, *_: ["zapret", "auto", "include", r["host"]], when=_kind("excluded")),
Action("a", "pin a host (treat it as blocked)…", lambda r, t, _: ["zapret", "auto", "add", t.strip()], prompt="<domain>", offered=_zapret_auto),
Action("X", "exclude a host (never touch or learn it)…", lambda r, t, _: ["zapret", "auto", "exclude", t.strip()], prompt="<domain>", offered=_zapret_auto),
Action("C", "forget all learned hosts", lambda r, *_: ["zapret", "auto", "clear"], confirm=True, offered=_zapret_auto),
Action("f", "forget it", lambda r, *_: ["zapret", "auto", "forget", r["host"]], when=_kind("learned")),
Action("p", "pin it", lambda r, *_: ["zapret", "auto", "add", r["host"]], when=_kind("learned")),
Action("p", "unpin it", lambda r, *_: ["zapret", "auto", "unpin", r["host"]], when=_kind("pinned")),
Action("x", "exclude it", lambda r, *_: ["zapret", "auto", "exclude", r["host"]], when=_kind("learned", "pinned")),
Action("x", "include it again", lambda r, *_: ["zapret", "auto", "include", r["host"]], when=_kind("excluded")),
Action("n", "pin a host as blocked…", lambda r, t, _: ["zapret", "auto", "add", t.strip()], prompt="<domain>", offered=_zapret_auto),
Action("X", "exclude a host…", lambda r, t, _: ["zapret", "auto", "exclude", t.strip()], prompt="<domain>", offered=_zapret_auto),
Action("F", "forget all learned hosts", lambda r, *_: ["zapret", "auto", "clear"], confirm=True, offered=_zapret_auto),
Action("P", "probe the line's cutoff again", lambda r, *_: ["zapret", "cutoff", "probe"], mode="dialog", offered=lambda: ctl.env("ZAPRET_CUTOFF_ENABLED") == "1"),
Action("z", "start / stop zapret", _zapret_toggle),
Action("Z", "restart zapret", lambda *_: ["zapret", "restart"]),
Action("space", "start / stop zapret", _zapret_toggle),
Action("ctrl+r", "restart zapret", lambda *_: ["zapret", "restart"]),
],
),
Tab(
@@ -770,32 +771,31 @@ TABS = [
inbound_rows,
summary=lambda: f"proxy-suite-inbounds: {ctl.svc_state('proxy-suite-inbounds') or 'unknown'}",
actions=[
Action("l", "share link", lambda r, *_: _link(r), when=ROW, mode="dialog"),
Action("s", "share link", lambda r, *_: _link(r), when=ROW, mode="dialog"),
Action("c", "copy share link", lambda r, *_: _link(r), when=ROW, mode="copy"),
Action("Q", "share link as QR", lambda r, *_: _link(r, "--qr"), when=ROW, mode="dialog"),
Action("s", "subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=lambda r: bool(r["user"]), mode="dialog"),
Action("S", "subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=lambda r: bool(r["user"]), mode="dialog"),
# Without subscriptions.baseUrl there is only a file path, with a hint after it: nothing to encode or copy.
Action("S", "subscription URL as QR", lambda r, *_: ["inbounds", "sub", r["user"], "--qr"], when=_sub_url, mode="dialog"),
Action("y", "copy subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=_sub_url, mode="copy"),
Action("U", "subscription URL as QR", lambda r, *_: ["inbounds", "sub", r["user"], "--qr"], when=_sub_url, mode="dialog"),
Action("C", "copy subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=_sub_url, mode="copy"),
Action("J", "client's outbound JSON", lambda r, *_: _link(r, "--json"), when=lambda r: not _amneziawg(r), mode="dialog"),
# Not w/W or o: those are the screen's where and last output.
Action("k", "client config", lambda r, *_: _link(r, "--config"), when=_amneziawg, mode="dialog"),
Action("K", "client config as QR", lambda r, *_: _link(r, "--config", "--qr"), when=_amneziawg, mode="dialog"),
Action("V", "server's inbound JSON", lambda r, *_: ["inbounds", "link", r["tag"], "--server-json"], when=ROW, mode="dialog"),
Action("t", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"),
Action("I", "traffic per inbound", lambda r, *_: ["inbounds", "stats", "--by", "inbound"], mode="dialog"),
Action("O", "traffic per exit", lambda r, *_: ["inbounds", "stats", "--by", "outbound"], mode="dialog"),
Action("n", "who is online", lambda r, *_: ["inbounds", "online"], mode="dialog"),
Action("i", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"),
Action("I", "traffic per listener", lambda r, *_: ["inbounds", "stats", "--by", "inbound"], mode="dialog"),
Action("E", "traffic per exit", lambda r, *_: ["inbounds", "stats", "--by", "outbound"], mode="dialog"),
Action("O", "who is online", lambda r, *_: ["inbounds", "online"], mode="dialog"),
Action(
"a",
"n",
"add a listener…",
lambda r, t, _: ["inbounds", "add", *shlex.split(t)],
prompt="<tag> <type> [--port N] [--reality SNI] [--tls <cert>] [--user U]... - e.g. friends vless --port 20001 --reality www.microsoft.com",
offered=_inbounds_runtime,
),
Action("d", "remove this listener", lambda r, *_: ["inbounds", "rm", r["tag"]], when=_runtime_row, confirm=True, offered=_inbounds_runtime),
Action("d", "remove it", lambda r, *_: ["inbounds", "rm", r["tag"]], when=_runtime_row, confirm=True, offered=_inbounds_runtime),
Action("b", "bind a user to it…", lambda r, t, _: ["inbounds", "bind", t.strip(), r["tag"]], when=ROW, prompt="<user>", offered=_inbounds_runtime),
Action("u", "unbind a user from it…", lambda r, t, _: ["inbounds", "unbind", t.strip(), r["tag"]], when=ROW, prompt="<user>", offered=_inbounds_runtime),
Action("x", "unbind a user from it…", lambda r, t, _: ["inbounds", "unbind", t.strip(), r["tag"]], when=ROW, prompt="<user>", offered=_inbounds_runtime),
],
),
Tab(
@@ -811,11 +811,11 @@ TABS = [
),
actions=[
Action("n", "add a user…", lambda r, t, _: _user_add_argv(t), prompt="<name> [order] [listener]... - e.g. alice 7 vless-in", offered=_inbounds_runtime),
Action("d", "remove this user", lambda r, *_: ["inbounds", "users", "rm", r["name"]], when=_runtime_row, confirm=True, offered=_inbounds_runtime),
Action("d", "remove it", lambda r, *_: ["inbounds", "users", "rm", r["name"]], when=_runtime_row, confirm=True, offered=_inbounds_runtime),
Action("e", "set its order…", lambda r, t, _: ["inbounds", "users", "order", r["name"], t.strip()], when=_runtime_row, prompt="<order>", offered=_inbounds_runtime),
Action("b", "bind it to a listener…", lambda r, t, _: ["inbounds", "bind", r["name"], t.strip()], when=ROW, prompt="<listener>", offered=_inbounds_runtime),
Action("u", "unbind it from a listener…", lambda r, t, _: ["inbounds", "unbind", r["name"], t.strip()], when=ROW, prompt="<listener>", offered=_inbounds_runtime),
Action("t", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"),
Action("x", "unbind it from a listener…", lambda r, t, _: ["inbounds", "unbind", r["name"], t.strip()], when=ROW, prompt="<listener>", offered=_inbounds_runtime),
Action("i", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"),
],
),
Tab(
@@ -826,7 +826,7 @@ TABS = [
[("profile", "Profile"), ("route", "Route")],
app_rows,
actions=[
Action("x", "run a command through it…", lambda r, t, _: ["apps", "run", r["profile"], "--", *shlex.split(t)], when=ROW, prompt="<command> [args]", mode="pause"),
Action("space", "run a command through it…", lambda r, t, _: ["apps", "run", r["profile"], "--", *shlex.split(t)], when=ROW, prompt="<command> [args]", mode="pause"),
],
),
]
@@ -897,7 +897,7 @@ def load_tab(tab, states):
except (Exception, SystemExit) as e:
return [], f"✗ {str(e) or type(e).__name__}" + (f"\n{summary}" if summary else "")
if not rows:
hints = " ".join(f"{a.key}: {short(a.label)}" for a in tab.actions if a.prompt and a.when is None and offered(a))
hints = " ".join(f"{display_key(a.key)}: {short(a.label)}" for a in tab.actions if a.prompt and a.when is None and offered(a))
summary = "Nothing here yet." + (f" {hints}" if hints else "") + (f"\n{summary}" if summary else "")
return rows, summary
@@ -916,6 +916,19 @@ def unique_keys(rows):
return out
def display_key(key):
"""A key as the front ends show it: N reads shift+n, the way ctrl+r does."""
return f"shift+{key.lower()}" if len(key) == 1 and key.isupper() else key
def key_labels(actions):
"""(key, label) per key: the actions that toggle on one key read as one line, "pin it / unpin it"."""
labels = {}
for a in actions:
labels.setdefault(a.key, []).append(a.label)
return [(key, " / ".join(dict.fromkeys(names))) for key, names in labels.items()]
def short(label):
return label.split(" (")[0].removesuffix("…")
+11 -11
View File
@@ -50,15 +50,15 @@ def pack(items, width, gap=" "):
GLOBAL_KEYS = [
("enter", "actions for the selected row (or click it)"),
("enter", "actions for the selected row; a click opens them too"),
("← → ⇥", "switch tab; 1-8 jump to one"),
("/", "filter the rows (list:learned for one column); esc clears"),
("/", "filter the rows, e.g. list:learned; esc clears"),
("click", "a column heading sorts by it, again reverses, a third time unsorts"),
("paste", "a link in the clipboard is added to this tab"),
("w", "how is a domain routed"),
("L", "follow all logs"),
("shift+l", "follow all logs"),
("o", "output of the last command"),
("!", "retry what just failed as root (sudo)"),
("!", "retry what just failed with sudo"),
("#", "switch to root: proxy-tui again under sudo"),
("r", "refresh now"),
("?", "keys"),
@@ -171,7 +171,7 @@ def detail(tab, row, actions):
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" {model.display_key(a.key):<8}", style=ACCENT)
text.append(f"{a.label}\n")
return text
@@ -252,7 +252,7 @@ class Menu(Dialog):
with Vertical(classes="dialog menu"):
yield Label(self.heading, classes="dialog-title", markup=False)
yield Choices(
*(Option(Text.assemble((f"{a.key:<7}", ACCENT), a.label), id=str(i)) for i, a in enumerate(self.actions))
*(Option(Text.assemble((f"{model.display_key(a.key):<8}", ACCENT), a.label), id=str(i)) for i, a in enumerate(self.actions))
)
yield hint("↑↓ or click to choose", ("esc close", "dismiss"))
@@ -494,7 +494,7 @@ class ProxyTui(App):
_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, model.short(a.label)) for a in actions]
shown = [] if width >= WIDE or height >= TALL else [(f"act({tab.actions.index(a)})", model.display_key(a.key), model.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))
@@ -552,7 +552,7 @@ class ProxyTui(App):
self.states, self.status = states, status
# A read root could do: ! retries runs, not reads, so the way out is the whole TUI under sudo.
if model.needs_root(summary.splitlines(), 1):
summary += "\n#: run proxy-tui as root (sudo)"
summary += "\n#: run proxy-tui as root with sudo"
self.show_status()
if visible != self.shown:
self.show_tabs(visible)
@@ -674,7 +674,7 @@ class ProxyTui(App):
self.filters[tab_id] = text
self.refill(tab_id)
self.push_screen(Prompt("Filter rows", "words in any column, or column:value (list:learned); empty clears", self.filters.get(tab_id, "")), apply)
self.push_screen(Prompt("Filter rows", "words in any column, or column:value like list:learned; empty clears", self.filters.get(tab_id, "")), apply)
def action_clear_filter(self):
if self.filters.pop(self.active_tab(), ""):
@@ -692,10 +692,10 @@ class ProxyTui(App):
def action_help(self):
tab = self.tabs[self.active_tab()]
text = Text()
for heading, keys in ((tab.title, [(a.key, a.label) for a in tab.actions if model.offered(a)]), ("Everywhere", GLOBAL_KEYS)):
for heading, keys in ((tab.title, model.key_labels(a for a in tab.actions if model.offered(a))), ("Everywhere", GLOBAL_KEYS)):
text.append(f"{heading}\n", style="bold")
for key, label in keys:
text.append(f" {key:<9}", style=ACCENT)
text.append(f" {model.display_key(key):<9}", style=ACCENT)
text.append(f"{label}\n")
text.append("\n")
text.append(f"Stuck? kill -USR1 {os.getpid()} writes where it is to {trace_path()}\n", style="dim")
+16 -1
View File
@@ -61,18 +61,33 @@ class GuiTest(unittest.TestCase):
self.assertEqual(gui.accelerator("R"), "<Shift>r")
self.assertEqual(gui.accelerator("ctrl+r"), "<Control>r")
self.assertEqual(gui.display_key("ctrl+space"), "Ctrl+Space")
self.assertEqual([gui.display_key(k) for k in ("N", "ctrl+t", "l")], ["Shift+n", "Ctrl+t", "l"])
for tab in model.TABS:
for action in tab.actions:
if action.key:
self.assertTrue(gui.accelerator(action.key))
def test_a_toggle_is_one_shortcut(self):
"""Two actions on one key are one GTK shortcut, which runs the one that applies to the row."""
zapret = next(t for t in model.TABS if t.id == "zapret")
page = types.SimpleNamespace(tab=zapret)
triggers = gui.Page.triggers(page)
pin, unpin = triggers["p"]
self.assertEqual([zapret.actions[i].label for i in (pin, unpin)], ["pin it", "unpin it"])
ran = []
page.act = lambda i, from_key: i == unpin and not ran.append(i)
self.assertTrue(gui.Page.act_any(page, triggers["p"]))
self.assertEqual(ran, [unpin])
page.act = lambda i, from_key: False
self.assertFalse(gui.Page.act_any(page, triggers["p"])) # nothing applies: the key falls through
def test_action_looks(self):
for tab in model.TABS:
for action in tab.actions:
self.assertTrue(gui.action_icon(action).endswith("-symbolic"))
self.assertFalse(gui.is_destructive(model.Action("R", "restart everything running", lambda *_: [], confirm=True)))
self.assertTrue(gui.is_destructive(model.Action("d", "remove it", lambda *_: [], confirm=True)))
self.assertTrue(gui.is_destructive(model.Action("C", "forget all learned hosts", lambda *_: [], confirm=True)))
self.assertTrue(gui.is_destructive(model.Action("F", "forget all learned hosts", lambda *_: [], confirm=True)))
self.assertTrue(gui.is_badge("state", "active"))
self.assertTrue(gui.is_badge("status", "ok"))
self.assertFalse(gui.is_badge("mark", "★"))
+43 -19
View File
@@ -109,8 +109,8 @@ class ModelTest(unittest.TestCase):
with mock.patch.dict(os.environ, {"INBOUNDS_ENABLED": "1", "INBOUNDS_RUNTIME_ENABLED": "0"}):
# Listed from the configuration; nothing to change them with.
self.assertTrue(users.available({}))
self.assertEqual([a.key for a in users.actions if model.offered(a)], ["t"])
self.assertNotIn("a", [a.key for a in inbounds.actions if model.offered(a)])
self.assertEqual([a.key for a in users.actions if model.offered(a)], ["i"])
self.assertNotIn("n", [a.key for a in inbounds.actions if model.offered(a)])
with mock.patch.dict(os.environ, {"INBOUNDS_ENABLED": "0"}):
self.assertFalse(users.available({}))
with mock.patch.dict(os.environ, {"INBOUNDS_ENABLED": "1", "INBOUNDS_RUNTIME_ENABLED": "1"}):
@@ -124,12 +124,12 @@ class ModelTest(unittest.TestCase):
self.assertEqual(actions["n"].argv(None, "carol 7 in ws", {}),
["inbounds", "users", "add", "carol", "--order", "7", "--listener", "in", "--listener", "ws"])
self.assertEqual(actions["n"].argv(None, "carol", {}), ["inbounds", "users", "add", "carol"])
self.assertEqual([a.key for a in model.applicable(users, bob)], ["n", "b", "u", "t"])
self.assertEqual([a.key for a in model.applicable(users, bob)], ["n", "b", "x", "i"])
self.assertEqual(actions["e"].argv(alice, " 9 ", {}), ["inbounds", "users", "order", "alice", "9"])
self.assertEqual(actions["b"].argv(alice, "in", {}), ["inbounds", "bind", "alice", "in"])
actions = {a.key: a for a in inbounds.actions}
row = {"key": "friends/alice", "tag": "friends", "user": "alice", "type": "vless", "port": "20001", "source": "runtime"}
self.assertEqual(actions["a"].argv(None, "friends vless --port 20001", {}), ["inbounds", "add", "friends", "vless", "--port", "20001"])
self.assertEqual(actions["n"].argv(None, "friends vless --port 20001", {}), ["inbounds", "add", "friends", "vless", "--port", "20001"])
self.assertEqual(actions["d"].argv(row), ["inbounds", "rm", "friends"])
self.assertFalse(actions["d"].when({**row, "source": "nix"}))
self.assertEqual(actions["b"].argv(row, "bob", {}), ["inbounds", "bind", "bob", "friends"])
@@ -181,7 +181,7 @@ class ModelTest(unittest.TestCase):
keys = lambda row: {a.key: a for a in model.applicable(tab, row)}
self.assertEqual(model.toggle_argv(vk), ["wl", "off", "vk"])
self.assertEqual(model.restart_argv(home), ["wl", "restart", "home"])
self.assertEqual(keys(vk)["k"].argv(vk), ["wl", "link", "vk"])
self.assertEqual(keys(vk)["s"].argv(vk), ["wl", "link", "vk"])
self.assertEqual(keys(vk)["Q"].argv(vk), ["wl", "link", "vk", "--qr"])
self.assertEqual(keys(vk)["N"].argv(vk), ["wl", "new", "vk"])
self.assertEqual(keys(vk)["a"].argv(vk, "/tmp/c.json", {}), ["wl", "auth", "vk", "/tmp/c.json"])
@@ -189,11 +189,36 @@ class ModelTest(unittest.TestCase):
self.assertNotIn("N", keys(dion)) # a fixed link: its linkFile sets the call
self.assertNotIn("A", keys(vk)) # VK logs in only in a browser
self.assertEqual(keys(dion)["A"].argv(dion), ["wl", "auth", "dion"])
self.assertFalse({"k", "N", "a", "A"} & set(keys(home)))
self.assertFalse({"s", "N", "a", "A"} & set(keys(home)))
self.assertNotIn("j", keys(vk))
with mock.patch.object(model, "TTY", False):
self.assertNotIn("A", keys(dion)) # it asks on a terminal the GUI does not have
def test_a_shared_key_is_a_toggle(self):
"""Actions on one key take turns: each needs a row, and no row gets two of them."""
rows = {
"outbounds": [{"mark": m, "disabled": d} for m in ("", "★") for d in (False, True)],
"zapret": [{"kind": k} for k in ("learned", "pinned", "excluded")],
"autoproxy": [{"kind": k} for k in ("routed", "queued")],
}
for tab in model.TABS:
by_key = {}
for a in tab.actions:
by_key.setdefault(a.key, []).append(a)
for key, actions in by_key.items():
if len(actions) > 1:
self.assertIn(tab.id, rows, f"{tab.id}: {key} is shared; add rows for it here")
self.assertTrue(all(a.when is not None for a in actions), (tab.id, key))
for row in rows[tab.id]:
self.assertLessEqual(sum(bool(a.when(row)) for a in actions), 1, (tab.id, key, row))
self.assertEqual([model.display_key(k) for k in ("F", "ctrl+r", "space", "f")], ["shift+f", "ctrl+r", "space", "f"])
zapret = next(t for t in model.TABS if t.id == "zapret")
labels = dict(model.key_labels(zapret.actions))
self.assertEqual((labels["p"], labels["x"]), ("pin it / unpin it", "exclude it / include it again"))
autoproxy = next(t for t in model.TABS if t.id == "autoproxy")
self.assertEqual([a.argv({"domain": "a.test"}, "", {}) for a in model.applicable(autoproxy, {"kind": "queued", "domain": "a.test"}) if a.key == "u"],
[["proxy", "auto", "learn", "a.test"]])
def test_tor_newnym(self):
tab = model.TABS[0]
tor = {"key": "proxy-suite-tor", "unit": "proxy-suite-tor", "name": "tor", "state": "active"}
@@ -209,15 +234,15 @@ class ModelTest(unittest.TestCase):
env = {}
with mock.patch.object(ctl, "env", lambda name, default="": env.get(name, default)):
self.assertEqual([a.key for a in model.applicable(routing, None)], [])
self.assertEqual([a.key for a in model.applicable(zapret, None)], ["z", "Z"])
self.assertEqual([a.key for a in model.applicable(zapret, None)], ["space", "ctrl+r"])
with tempfile.NamedTemporaryFile("w", suffix=".json") as f:
json.dump([{"name": "ru", "path": "/nonexistent"}], f)
f.flush()
env.update(RULE_SETS_FILE=f.name, ZAPRET_AUTO_ENABLED="1", ZAPRET_CUTOFF_ENABLED="1")
self.assertEqual([a.argv(None, "", {}) for a in model.applicable(routing, None)], [["proxy", "rulesets", "list"], ["proxy", "rulesets", "update"]])
self.assertEqual([a.key for a in model.applicable(zapret, None)], ["a", "X", "C", "P", "z", "Z"])
self.assertEqual([a.key for a in model.applicable(zapret, None)], ["n", "X", "F", "P", "space", "ctrl+r"])
actions = {a.key: a for a in zapret.actions}
self.assertEqual(actions["a"].argv(None, "example.com", {}), ["zapret", "auto", "add", "example.com"])
self.assertEqual(actions["n"].argv(None, "example.com", {}), ["zapret", "auto", "add", "example.com"])
self.assertEqual(actions["X"].argv(None, "example.com", {}), ["zapret", "auto", "exclude", "example.com"])
def test_tray_menu(self):
@@ -347,11 +372,11 @@ class ModelTest(unittest.TestCase):
self.assertEqual([(r["tag"], r["mark"], r["notes"]) for r in rows], [("a", "▸", "via b"), ("b", "★", "never picked")])
self.assertIn("Pinned: b", summary)
with mock.patch.object(ctl, "env", lambda name, default="": ""):
self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["u", "t", "D", "T", "n", "h", "H", "x", "l", "c", "Q", "J", "F", "X", "C"])
self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["p", "t", "ctrl+t", "T", "n", "h", "H", "x", "s", "c", "Q", "J", "k", "K", "V"])
chain = next(a for a in tab.actions if a.key == "h")
self.assertEqual(chain.argv(rows[1], 'c {"type": "socks"}', {}), ["proxy", "outbounds", "add", "c", '{"type": "socks"}', "--detour", "b"])
# Probe exits go by the backend's tag.
probe = next(a for a in tab.actions if a.key == "v")
probe = next(a for a in tab.actions if a.key == "P")
with mock.patch.object(ctl, "env", lambda name, default="": "1" if name == "AUTOPROXY_ENABLED" else ""), mock.patch.object(ctl, "_backend_tags", lambda: {"b": "b-backend"}):
self.assertIn(probe, model.applicable(tab, rows[1]))
self.assertEqual(probe.argv(rows[1], "example.com", {}), ["proxy", "auto", "probe", "example.com", "--via", "b-backend"])
@@ -370,10 +395,9 @@ class ModelTest(unittest.TestCase):
with mock.patch.object(ctl, "_outbound_current", lambda: "a"), mock.patch.object(ctl, "_reputation_by_tag", lambda: {}), mock.patch.object(ctl, "_runtime_tags", lambda kind: []), mock.patch.object(ctl, "_outbound_inventory", lambda: inventory), mock.patch.object(ctl, "env", lambda name, default="": ""):
rows, _ = model.load_tab(tab, {})
self.assertEqual([(r["mark"], r["notes"], r["disabled"]) for r in rows], [("▸", "", False), ("✕", "disabled", True)])
keys = [a.key for a in model.applicable(tab, rows[1])]
self.assertIn("e", keys)
self.assertNotIn("p", keys)
self.assertNotIn("x", keys)
labels = {a.key: a.label for a in model.applicable(tab, rows[1])}
self.assertEqual(labels["x"], "enable it again") # x toggles: disable, enable
self.assertNotIn("p", labels)
self.assertEqual(next(a for a in tab.actions if a.key == "x").argv(rows[0], "", {}), ["proxy", "outbounds", "disable", "a"])
with mock.patch.object(ctl, "_outbound_inventory", lambda: inventory):
self.assertEqual(model.tray_outbounds({"proxy": {"active": True}}), (["a"], ""))
@@ -396,13 +420,13 @@ class ModelTest(unittest.TestCase):
routed, queued = model.autoproxy_rows({})
self.assertEqual(routed["detail"], "via de, learned from www.last.fm")
actions = {a.key: a for a in tab.actions}
for key in ("f", "R"):
for key in ("f", "u"): # u: the last action on it, relearn
self.assertIn(actions[key], model.applicable(tab, routed))
self.assertNotIn(actions[key], model.applicable(tab, queued))
self.assertEqual(actions["f"].argv(routed, "", {}), ["proxy", "auto", "forget", "last.fm"])
self.assertEqual(actions["R"].argv(routed, "", {}), ["proxy", "auto", "relearn", "last.fm"])
self.assertEqual(actions["C"].argv(None, "", {}), ["proxy", "auto", "clear"])
self.assertTrue(actions["f"].confirm and actions["C"].confirm)
self.assertEqual(actions["u"].argv(routed, "", {}), ["proxy", "auto", "relearn", "last.fm"])
self.assertEqual(actions["F"].argv(None, "", {}), ["proxy", "auto", "clear"])
self.assertTrue(actions["f"].confirm and actions["F"].confirm)
def test_load_tab_as_root(self):
"""The GUI's root read: proxy-ctl status --tab through pkexec, and what a refusal says."""
+13 -14
View File
@@ -255,7 +255,7 @@ class TuiTest(unittest.TestCase):
await pilot.pause()
self.assertEqual(self.ran.pop(), ["proxy", "mode", "whitelist"])
# Outbounds: letter shortcuts; the pinned row offers no pin, and nothing removes a declared one.
# Outbounds: letter shortcuts; p pins, and on the pinned row unpins; nothing removes a declared one.
await pilot.press("right")
await self.settle(app, pilot)
# One load asks the backend what it dials once, however many readers need it.
@@ -265,16 +265,15 @@ class TuiTest(unittest.TestCase):
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.assertNotIn("d", app.screen.active_bindings)
await pilot.press("p", "t", "d")
self.assertEqual(self.ran, [["proxy", "pin", "a"], ["proxy", "outbounds", "test", "a"]])
await pilot.press("down")
self.assertNotIn("p", app.screen.active_bindings)
await pilot.press("p", "d", "u")
await pilot.press("down", "p", "d")
self.assertEqual(self.ran.pop(), ["proxy", "unpin"])
self.ran.clear()
await pilot.press("enter")
await pilot.pause()
self.assertIn("unpin it", self.menu_labels(app))
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.
@@ -295,7 +294,7 @@ class TuiTest(unittest.TestCase):
# An empty tab says how to fill it.
await pilot.press("5")
await self.settle(app, pilot)
self.assertIn("Nothing here yet. n: add a runtime subscription", str(app.main.query_one("#subs-summary").content))
self.assertIn("Nothing here yet. n: add a subscription", str(app.main.query_one("#subs-summary").content))
# A tab that cannot read its state says so instead, and how to get the rights for it.
with mock.patch.object(ctl, "_runtime_hidden", lambda kind: "/var/lib/proxy-suite/subscriptions.d"), \
@@ -306,7 +305,7 @@ class TuiTest(unittest.TestCase):
self.assertIn("✗ Cannot read /var/lib/proxy-suite/subscriptions.d", summary)
self.assertIn("#: run proxy-tui as root", summary)
# zapret: an excluded host can be included again, not forgotten.
# zapret: x includes an excluded host again; it cannot be forgotten.
# Brackets in a summary are text, not markup.
self.env["ZAPRET_CUTOFF_ENABLED"] = "1"
self.capture = "Probed: [b] from [/x]\nCutoff: none on this line\n"
@@ -317,21 +316,21 @@ class TuiTest(unittest.TestCase):
await pilot.press("down", "enter")
await pilot.pause()
labels = self.menu_labels(app)
self.assertIn("include it (zapret may touch or learn it again)", labels)
self.assertNotIn("forget it (may be learned again)", labels)
await pilot.press("escape", "i")
self.assertIn("include it again", labels)
self.assertNotIn("forget it", labels)
await pilot.press("escape", "x")
self.assertEqual(self.ran.pop(), ["zapret", "auto", "include", "kept.example"])
# Confirmed actions run only on yes; a click beside a dialog closes it.
await pilot.press("C")
await pilot.press("F")
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.press("F", "n")
await pilot.pause()
self.assertEqual(self.ran, [])
await pilot.press("C", "y")
await pilot.press("F", "y")
await pilot.pause()
self.assertEqual(self.ran.pop(), ["zapret", "auto", "clear"])