feat: params in gui/tui

This commit is contained in:
FUFSoB committed 2026-10-10 23:17:44 +05:00
1 parent 584c8ba0a0
commit cacd51595c
17 files changed
+1341 -197

No files matched your search

+7
View File
@@ -166,6 +166,8 @@ Changes and secrets need root or the userControl group.
add a group (failover by default)
proxy groups rm <tag> remove a group added with groups add
proxy groups members <tag> add|rm <member...>
proxy groups members <tag> set [member...]
exactly these members, in this order
proxy groups strategy <tag> failover|urltest|selector
proxy priority [list] the top level in the order it is picked in
proxy priority <tag> <n>|up|down|--clear
@@ -180,6 +182,8 @@ Changes and secrets need root or the userControl group.
rule named after the target, extended (priority 50:
ahead of the configuration's, at 100 to 500)
proxy rules matches <name> add|rm <match...>
proxy rules matches <name> set [match...]
exactly these matches
proxy rules target <name> <target>
proxy rules priority <name> <n>|up|down
lower goes first; up/down moves past the next row
@@ -257,6 +261,9 @@ Changes and secrets need root or the userControl group.
inbounds users order <name> <N> a runtime user's order (serverSource number)
inbounds bind|unbind <user> <tag> put a user on a listener, or take it off
(a runtime user, or a runtime listener)
inbounds users listeners <user> [tag...]
put a user on exactly these listeners
inbounds users on <tag> [user...] put exactly these users on a listener
inbounds add <tag> <type> [--port N] [--via V] [--transport T] [--path P] [--host H]
[--reality SNI[,SNI]] [--tls <cert>] [--alpn a,b] [--flow vision] [--method M]
[--listen A] [--user U]... [more: see inbounds add --help]
+11
View File
@@ -9,6 +9,7 @@ Part of the [proxy-suite options reference](./index.md).
- gui
- [enable](#services-proxy-suite-gui-enable)
- [autostart](#services-proxy-suite-gui-autostart)
- [floating](#services-proxy-suite-gui-floating)
- [refreshInterval](#services-proxy-suite-gui-refreshinterval)
<a id="services-proxy-suite-gui-enable"></a>
@@ -27,6 +28,16 @@ Start the GUI in the tray on login to a graphical session\.
**Type:** boolean\
**Default:** `true`
<a id="services-proxy-suite-gui-floating"></a>
## services\.proxy-suite\.gui\.floating
Open the window floating, sized to the screen, where a tiling compositor (niri, sway,
Hyprland, i3) would tile it\. It opens at a fixed size, which those compositors float,
then resizes as usual\. Turn off to let the compositor tile it\.
**Type:** boolean\
**Default:** `true`
<a id="services-proxy-suite-gui-refreshinterval"></a>
## services\.proxy-suite\.gui\.refreshInterval
+1
View File
@@ -67,6 +67,7 @@ services.proxy-suite = {
gui = {
autostart = true;
enable = false;
floating = true;
refreshInterval = 3;
};
inbounds = {
+15
View File
@@ -101,6 +101,21 @@ outbound, a subscription URL a subscription. An AmneziaWG `vpn://` link or a who
becomes a global profile, or an outbound when pasted onto the Outbounds tab. See
[Use an AmneziaWG config](./amneziawg.md).
Adding a rule, an outbound, a group, a listener or a user opens a form with one field per
parameter. Optional fields are marked, and the values the field knows (outbounds, users,
listeners, strategies) are offered: in the TUI, → completes one, and in the app, a list beside
the field picks one. Less common flags sit under "More options". The command the form will run
shows below it. In the TUI, tab moves between fields and enter or ctrl+s runs; in the app, Run
stays off until nothing is missing.
Fields that take several values (a rule's domains and addresses, a group's members, a
listener's users) are lists: each value sits on its own line, enter adds the one typed, and
pasting several adds each. The same lists edit what is already there: one action opens a
rule's matches, a group's members, a listener's users or a user's listeners as they are now.
You add or take out values in one go, and what changes is marked before you run it. It runs as
one command (`proxy rules matches <name> set`, `proxy groups members <tag> set`,
`inbounds users on <tag>`, `inbounds users listeners <user>`), so the inbounds restart once.
## Commands
```sh
+10
View File
@@ -20,5 +20,15 @@ in
default = 3;
description = "How often the status refreshes, in seconds.";
};
floating = mkOption {
type = types.bool;
default = true;
description = ''
Open the window floating, sized to the screen, where a tiling compositor (niri, sway,
Hyprland, i3) would tile it. It opens at a fixed size, which those compositors float,
then resizes as usual. Turn off to let the compositor tile it.
'';
};
};
}
+5 -2
View File
@@ -6,7 +6,7 @@
# $watched: whether proxy-suite-outbound-groups drives this instance's failover groups through
# its Clash API. Without it (the TUN instances) a failover group is sing-box's own urltest.
#
# Output: {groups: {name: {strategy, failback, interval, members, pinned}}, outbounds: [the
# Output: {groups: {name: {strategy, failback, interval, members, listed, pinned}}, outbounds: [the
# sing-box group outbounds], top: [what the top level picks among, in order], loops: [groups
# inside themselves], warnings, errors}.
# Errors mean the config cannot be built (a group inside itself); warnings are dropped members
@@ -71,9 +71,12 @@ def glob_regex: "^" + (gsub("(?<c>[.+^$()\\[\\]{}|\\\\])"; "\\\(.c)") | gsub("\\
| .warnings += (if $usable == [] then ["group '\($g)' has no available member; it blocks until one is"] else [] end)
| (if $all == [] then ["block"] else $all end) as $all
| (if $usable == [] then ["block"] else $usable end) as $usable
# listed: the members the group names itself, which the front ends edit; members adds those
# its subscriptions and patterns pull in.
| .groups[$g] = {strategy: $cfg.strategy, failback: ($cfg.failback != false),
interval: ($cfg.interval // (if $cfg.strategy == "urltest" then $interval else "30s" end)),
members: $all, pinned: $pinned, runtime: ($cfg.runtime // false)}
members: $all, listed: [($cfg.outbounds // [])[] | select(. != $g)],
pinned: $pinned, runtime: ($cfg.runtime // false)}
| .outbounds += [
if ($cfg.strategy == "urltest" or ($cfg.strategy == "failover" and ($watched | not))) and $pinned == "" then
{type: "urltest", tag: $g, outbounds: $usable, url: $url,
+2
View File
@@ -49,6 +49,7 @@ let
proxyInboundsSubscriptionsBaseUrl = proxyInboundsCfg.subscriptions.baseUrl;
proxyInboundsXray = "${proxyInboundsCfg.package}/bin/xray";
guiRefreshInterval = cfg.gui.refreshInterval;
guiFloating = cfg.gui.floating;
# proxy_ctl.py reads these as "1"/"0" strings.
flag = enabled: if enabled then "1" else "0";
in
@@ -56,6 +57,7 @@ in
proxyCtl = packages.mkProxyCtl {
inherit
guiRefreshInterval
guiFloating
subscriptionTagsFile
perAppRoutingProfilesFile
proxychainsConfigFile
+4 -1
View File
@@ -8,6 +8,8 @@
# (modules/proxy-suite/service/control.nix); proxy_ctl.py reads every name with env().
env,
guiRefreshInterval ? 3,
# The window opens floating where a tiling compositor would tile it (proxy_gui.open_floating).
guiFloating ? true,
# Off where proxy-suitectl runs the units (nix-on-droid): proxy-ctl reaches it through
# SUPERVISOR_CTL, and systemd stays out of the closure.
withSystemd ? true,
@@ -150,7 +152,8 @@ let
}" \
--prefix PATH : /run/wrappers/bin \
--set PROXY_GUI_ICON_DIR "$out/share/proxy-suite-gui/icons" \
--set PROXY_GUI_REFRESH ${toString guiRefreshInterval} ${envFlags}
--set PROXY_GUI_REFRESH ${toString guiRefreshInterval} \
--set PROXY_GUI_FLOATING ${if guiFloating then "1" else "0"} ${envFlags}
'';
meta = {
description = "Desktop app and tray icon for proxy-suite";
+69 -5
View File
@@ -91,6 +91,8 @@ Changes and secrets need root or the userControl group.
add a group (failover by default)
proxy groups rm <tag> remove a group added with groups add
proxy groups members <tag> add|rm <member...>
proxy groups members <tag> set [member...]
exactly these members, in this order
proxy groups strategy <tag> failover|urltest|selector
proxy priority [list] the top level in the order it is picked in
proxy priority <tag> <n>|up|down|--clear
@@ -105,6 +107,8 @@ Changes and secrets need root or the userControl group.
rule named after the target, extended (priority 50:
ahead of the configuration's, at 100 to 500)
proxy rules matches <name> add|rm <match...>
proxy rules matches <name> set [match...]
exactly these matches
proxy rules target <name> <target>
proxy rules priority <name> <n>|up|down
lower goes first; up/down moves past the next row
@@ -182,6 +186,9 @@ Changes and secrets need root or the userControl group.
inbounds users order <name> <N> a runtime user's order (serverSource number)
inbounds bind|unbind <user> <tag> put a user on a listener, or take it off
(a runtime user, or a runtime listener)
inbounds users listeners <user> [tag...]
put a user on exactly these listeners
inbounds users on <tag> [user...] put exactly these users on a listener
inbounds add <tag> <type> [--port N] [--via V] [--transport T] [--path P] [--host H]
[--reality SNI[,SNI]] [--tls <cert>] [--alpn a,b] [--flow vision] [--method M]
[--listen A] [--user U]... [more: see inbounds add --help]
@@ -998,8 +1005,12 @@ COMPLETE = {
"add": "add a user at runtime",
"rm": "remove a runtime user",
"order": "set a runtime user's order",
"listeners": "put a user on exactly these listeners",
"on": "put exactly these users on a listener",
}
},
"inbounds users listeners": {"args": lambda: {**_inbound_runtime_names("users"), **_inbound_runtime_names("listeners")}, "repeat": True},
"inbounds users on": {"args": lambda: {**_inbound_runtime_names("listeners"), **_inbound_runtime_names("users")}, "repeat": True},
"inbounds users add": {"flags": {"--order": "its serverSource number", "--listener": "a listener to put it on"}},
"inbounds users rm": {"args": lambda: _inbound_runtime_names("users", "runtime")},
"inbounds users order": {"args": lambda: _inbound_runtime_names("users", "runtime")},
@@ -2599,8 +2610,8 @@ def cmd_groups(verb="list", *args):
_runtime_reload()
print(f"Removed group: {tag}")
elif verb == "members":
if len(args) < 3 or args[1] not in ("add", "rm"):
usage("proxy groups members <tag> add|rm <member...>")
if not (len(args) >= 3 and args[1] in ("add", "rm") or len(args) >= 2 and args[1] == "set"):
usage("proxy groups members <tag> add|rm <member...> | set [member...]")
tag, action, names = args[0], args[1], list(args[2:])
with _group_lock(tag):
data = _read_group_file(tag)
@@ -2608,6 +2619,12 @@ def cmd_groups(verb="list", *args):
if action == "add":
_group_check_members(tag, names)
members += [n for n in names if n not in members]
elif action == "set":
# Exactly these, in this order: an edit that adds some and takes others out, in one reload.
_group_check_members(tag, names)
members = list(dict.fromkeys(names))
if not members and not data.get("subscriptions") and not data.get("match"):
die(f"That would leave '{tag}' empty; remove the group instead: proxy-ctl proxy groups rm {tag}")
else:
missing = [n for n in names if n not in members]
if missing:
@@ -3553,7 +3570,7 @@ def cmd_rules(verb="list", *args):
_rules_list()
elif verb == "add":
_rules_add(*args)
elif verb == "matches" and len(args) >= 3 and args[1] in ("add", "rm"):
elif verb == "matches" and (len(args) >= 3 and args[1] in ("add", "rm") or len(args) >= 2 and args[1] == "set"):
_rules_matches(*args)
elif verb == "target" and len(args) == 2:
_rule_check_target(args[1])
@@ -3591,7 +3608,7 @@ def cmd_rules(verb="list", *args):
else:
usage(
"proxy rules [list] | add <target> <match...> [--name <name>] [--priority <n>]"
" | matches <name> add|rm <match...> | target <name> <target>"
" | matches <name> add|rm <match...> | matches <name> set [match...] | target <name> <target>"
" | priority <name> <n>|up|down | disable|enable <name> | rm <name>"
)
@@ -3651,6 +3668,14 @@ def _rules_matches(name, op, *words):
def change(rules):
rule = _rule_find(rules, name)
if op == "set":
# One write for an edit that adds some and takes others out: what the front ends send.
before = _rule_matches(rule)
for kind in RULE_MATCH_KINDS:
rule[kind] = []
_rule_add_matches(rule, matches)
after = _rule_matches(rule)
return f"{name}: {after or 'matches nothing'}" if after != before else f"{name}: nothing changed"
if op == "add":
done = _rule_add_matches(rule, matches)
else:
@@ -6115,6 +6140,38 @@ def _inbound_runtime_change(*args, stdin=None):
"""A change to the spool, then the reload that applies it, then what it left out."""
_, out = _inbound_runtime(*args, stdin=stdin)
sys.stdout.write(out)
_inbound_runtime_apply()
def _inbound_bindings_set(user=None, tag=None, wanted=()):
"""One user on exactly these listeners, or one listener with exactly these users: the binds
and unbinds between what is and what is wanted, then one reload, so connections drop once."""
rows = _inbound_runtime_rows("users")
if user is not None:
row = next((r for r in rows if _s(r.get("name")) == user), None)
if row is None:
die(f"Unknown user: {user}")
now = {(user, _s(t)) for t in row.get("listeners") or []}
want = {(user, t) for t in wanted}
else:
now = {(_s(r.get("name")), tag) for r in rows if tag in (r.get("listeners") or [])}
want = {(u, tag) for u in wanted}
changes = [("unbind", *pair) for pair in sorted(now - want)] + [("bind", *pair) for pair in sorted(want - now)]
if not changes:
print("Nothing to change.")
return
applied = False
try:
for verb, u, t in changes:
sys.stdout.write(_inbound_runtime(verb, u, t)[1])
applied = True
finally:
# One that failed stops the rest; those before it are saved, and applied here.
if applied:
_inbound_runtime_apply()
def _inbound_runtime_apply():
if systemctl("start", "proxy-suite-inbounds-reload.service")[0]:
die("Saved, but applying it failed - see: proxy-ctl logs proxy-suite-inbounds-reload")
p = subprocess.run(
@@ -6135,8 +6192,15 @@ def _inbound_users(verb="list", *args):
_inbound_runtime_change("users", "rm", *args)
elif verb == "order" and len(args) == 2:
_inbound_runtime_change("users", "order", *args)
elif verb == "listeners" and args:
_inbound_bindings_set(user=args[0], wanted=args[1:])
elif verb == "on" and args:
_inbound_bindings_set(tag=args[0], wanted=args[1:])
else:
usage("inbounds users [list] | add <name> [--order N] [--listener <tag>]... | rm <name> | order <name> <N>")
usage(
"inbounds users [list] | add <name> [--order N] [--listener <tag>]... | rm <name> | order <name> <N>"
" | listeners <name> [tag...] | on <tag> [user...]"
)
def cmd_inbounds(verb="list", *args):
+340 -33
View File
@@ -34,6 +34,29 @@ def refresh_seconds():
return 3
def floating():
"""Whether the window opens floating (gui.floating): on unless turned off."""
return os.environ.get("PROXY_GUI_FLOATING", "1") != "0"
MIN_SIZE = (360, 360)
TILED_SIZE = (1100, 700)
def floating_size(screen=None):
"""A floating window's first size: most of the screen, wider than tall, within reason.
screen: (width, height) of the monitor, else the first one's."""
if screen is None:
display = Gdk.Display.get_default()
monitors = display.get_monitors() if display else None
geometry = monitors.get_item(0).get_geometry() if monitors and monitors.get_n_items() else None
screen = (geometry.width, geometry.height) if geometry else None
if not screen:
return 1280, 800
width, height = screen
return max(MIN_SIZE[0], min(int(width * 0.72), 1600)), max(MIN_SIZE[1], min(int(height * 0.78), 1000))
STATE_CLASSES = {"active": ["success"], "inactive": ["dim-label"], "failed": ["error", "heading"], "activating": ["warning"], "deactivating": ["warning"], "reloading": ["warning"]}
CELL_CLASSES = {
"ok": ["success"],
@@ -280,7 +303,7 @@ def is_destructive(action):
def action_icon(action):
label = action.label.lower()
if action.prompt:
if action.fields:
return "document-edit-symbolic"
if "qr" in label:
return "view-grid-symbolic"
@@ -813,13 +836,259 @@ class OutputDialog(Adw.Dialog):
# --- window -------------------------------------------------------------------------------
class ItemsRow:
"""A list field: an expanded row whose first line adds a value (enter, or the + button; a
paste of several adds each), then a row per value with a button that takes it out. Editing
what a row holds, what changes is marked: added ones with a +, taken-out ones struck through,
with a button that puts them back. changed() after every change."""
def __init__(self, f, title, values, was, changed):
self.was, self.changed = list(was), changed
self.removed = {v for v in self.was if v not in values}
self.added = [v for v in values if v not in self.was]
self.lines = [] # the value rows shown now
self.expander = Adw.ExpanderRow(title=title, expanded=True)
example = model.field_example(f)
self.entry = Adw.EntryRow(title=f"Add one - e.g. {example}" if example else "Add one")
self.entry.connect("entry-activated", lambda *_: self.add(self.entry.get_text()))
self.entry.connect("changed", lambda *_: self.changed()) # typed but not added yet counts too
plus = Gtk.Button(icon_name="list-add-symbolic", valign=Gtk.Align.CENTER, tooltip_text="Add it", css_classes=["flat"])
plus.connect("clicked", lambda *_: self.add(self.entry.get_text()))
self.entry.add_suffix(plus)
self.expander.add_row(self.entry)
self.show()
@property
def value(self):
listed = [v for v in self.was if v not in self.removed] + self.added
return listed + [v for v in model.items(self.entry.get_text()) if v not in listed]
def add(self, text):
typed = model.items(text)
if text == self.entry.get_text():
self.entry.set_text("")
for v in typed:
self.removed.discard(v)
if v not in self.value:
self.added.append(v)
self.show()
def toggle(self, _, value):
if value in self.added:
self.added.remove(value)
else:
self.removed.symmetric_difference_update({value})
self.show()
def show(self):
for line in self.lines:
self.expander.remove(line)
self.lines = []
changes = model.item_changes(self.was, [v for v in self.was if v not in self.removed] + self.added)
for value, state in changes:
text = GLib.markup_escape_text(value)
line = Adw.ActionRow(title=f"<s>{text}</s>" if state == "removed" else text, css_classes=["dim-label"] if state == "removed" else [])
if self.was and state != "kept":
mark = Gtk.Image(icon_name="list-add-symbolic" if state == "added" else "list-remove-symbolic", css_classes=["success" if state == "added" else "error"])
line.add_prefix(mark)
back = state == "removed"
button = Gtk.Button(
icon_name="edit-undo-symbolic" if back else "user-trash-symbolic",
tooltip_text="Put it back" if back else "Take it out",
valign=Gtk.Align.CENTER,
css_classes=["flat"],
)
button.connect("clicked", self.toggle, value)
line.add_suffix(button)
self.expander.add_row(line)
self.lines.append(line)
added = sum(1 for _, s in changes if s == "added")
removed = sum(1 for _, s in changes if s == "removed")
kept = len(changes) - removed
summary = [f"{kept} in the list" if kept else "None yet"]
if self.was:
summary += [f"{added} added"] * bool(added) + [f"{removed} taken out"] * bool(removed)
self.expander.set_subtitle(" · ".join(summary))
self.changed()
class Form:
"""What an action asks for, a row per field: an entry, a drop-down where only some values go,
and a menu of the known ones beside an entry that takes others too. Under the rows, the hint
of the field in focus and the command the form runs."""
def __init__(self, action, row, remembered, states, changed):
self.action, self.row, self.states, self.changed = action, row, states, changed
self.choices = model.form_choices(action, row)
self.current = model.form_current(action, row)
self.rows = {} # field name -> its Adw.EntryRow, Adw.ComboRow or ItemsRow's expander
self.lists = {} # list field name -> its ItemsRow
self.built = False # rows call update as they are made; it waits for all of them
values = model.form_start(action, row, remembered)
self.widget = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
rows = Gtk.ListBox(selection_mode=Gtk.SelectionMode.NONE, css_classes=["boxed-list"])
for f in action.fields:
if not f.advanced:
rows.append(self.field(f, values.get(f.name, "")))
more = [f for f in action.fields if f.advanced]
if more:
# Open from the start when something was typed there last time.
expander = Adw.ExpanderRow(title="More options", expanded=any(values.get(f.name) for f in more))
for f in more:
expander.add_row(self.field(f, values.get(f.name, "")))
rows.append(expander)
self.hint = Gtk.Label(xalign=0, wrap=True, wrap_mode=Pango.WrapMode.WORD_CHAR, css_classes=["dim-label", "caption"])
self.preview = Gtk.Label(xalign=0, wrap=True, wrap_mode=Pango.WrapMode.WORD_CHAR, selectable=True, css_classes=["monospace", "caption"])
for widget in (rows, self.hint, self.preview):
self.widget.append(widget)
self.show_hint(action.fields[0])
self.built = True
self.update()
def field(self, f, value):
# An edit of what a row holds may well end empty: nothing to mark there.
title = f"{f.label} (optional)" if f.optional and not f.current else f.label
choices = self.choices.get(f.name) or {}
if f.items:
items = ItemsRow(f, title, model.items(value), self.current.get(f.name, []), self.update)
if choices:
items.entry.add_suffix(self.choice_menu(f, items.add, choices))
self.lists[f.name] = items
row = items.expander
elif f.fixed and choices:
names = list(choices)
row = Adw.ComboRow(title=title, model=Gtk.StringList.new(["Default" if f.optional else "Choose…", *names]))
row.set_selected(names.index(value) + 1 if value in names else 0)
row.connect("notify::selected", lambda *_: self.update())
else:
row = Adw.EntryRow(title=title, text=value, activates_default=True)
if f.number:
row.set_input_purpose(Gtk.InputPurpose.DIGITS)
row.connect("changed", lambda *_: self.update())
if choices:
row.add_suffix(self.choice_menu(f, lambda value, entry=row: (entry.set_text(value), entry.set_position(-1)), choices))
row.set_tooltip_text(f.hint or None)
focus = Gtk.EventControllerFocus()
focus.connect("enter", lambda *_: self.show_hint(f))
row.add_controller(focus)
self.rows[f.name] = row
return row
def focus(self, name):
(self.lists[name].entry if name in self.lists else self.rows[name]).grab_focus()
def choice_menu(self, f, pick_value, choices):
"""The known values, a click away: pick_value(value) sets the field, or adds it to a list."""
items = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
popover = Gtk.Popover(child=Gtk.ScrolledWindow(child=items, propagate_natural_height=True, max_content_height=320, hscrollbar_policy=Gtk.PolicyType.NEVER))
def pick(_, value):
pick_value(value)
popover.popdown()
for value, description in choices.items():
line = Gtk.Box(spacing=12)
line.append(Gtk.Label(label=value, xalign=0, hexpand=True))
if description:
line.append(Gtk.Label(label=description, xalign=1, css_classes=["dim-label", "caption"]))
button = Gtk.Button(child=line, css_classes=["flat"])
button.connect("clicked", pick, value)
items.append(button)
return Gtk.MenuButton(icon_name="pan-down-symbolic", popover=popover, valign=Gtk.Align.CENTER, tooltip_text="Known values", css_classes=["flat"])
def show_hint(self, f):
choices = self.choices.get(f.name) or {}
listed = ""
if choices and not f.fixed:
names = list(choices)
listed = ("Any of: " if f.items else "For example: ") + ", ".join(names[:8]) + (f" and {len(names) - 8} more" if len(names) > 8 else "")
how = "Enter or + adds one; a paste of several adds each." if f.items else ""
self.hint.set_label(" · ".join(p for p in (f"{f.label}: {f.hint}" if f.hint else "", listed, how) if p))
self.hint.set_visible(bool(self.hint.get_label()))
def values(self):
values = {}
for f in self.action.fields:
row = self.rows[f.name]
if f.name in self.lists:
values[f.name] = self.lists[f.name].value
elif isinstance(row, Adw.ComboRow):
names = list(self.choices.get(f.name) or {})
index = row.get_selected()
values[f.name] = names[index - 1] if 0 < index <= len(names) else ""
else:
values[f.name] = row.get_text()
return values
def update(self):
"""The preview, the rows that hold something wrong, and whether it can run: changed(ok)."""
if not self.built:
return
values = self.values()
problems = list(model.form_problems(self.action, values, self.row, self.choices, self.current))
filled = model.form_values(self.action, values)
# Red for what is there and wrong; what is missing, or not changed yet, is only listed.
wrong = {name for name, _ in problems if filled[name] and name not in self.current}
for name, row in self.rows.items():
if name in wrong:
row.add_css_class("error")
else:
row.remove_css_class("error")
try:
if problems:
raise ValueError("; ".join(why for _, why in problems))
argv, stdin = model.form_argv(self.action, self.row, values, self.states, self.choices, self.current)
self.preview.set_label(model.shown(argv, stdin=stdin))
self.preview.remove_css_class("dim-label")
ok = True
except (ValueError, IndexError) as e: # what is missing, or an unbalanced quote
self.preview.set_label(str(e) if problems else f"Cannot run that: {e}")
self.preview.add_css_class("dim-label")
ok = False
self.changed(ok)
FORM_WIDTH = 540 # an alert dialog's width cramps a form of several fields
def form_dialog(title, action, row, values, states, ran):
"""An action's form in a dialog: Cancel and Run in its header, Run only once the form can run.
ran({field: value}) when Run is pressed. Returns (dialog, form)."""
dialog = Adw.Dialog(title=title, content_width=FORM_WIDTH)
cancel = Gtk.Button(label="Cancel")
cancel.connect("clicked", lambda *_: dialog.close())
run = Gtk.Button(label="Run", css_classes=["suggested-action"])
header = Adw.HeaderBar(show_start_title_buttons=False, show_end_title_buttons=False)
header.pack_start(cancel)
header.pack_end(run)
form = Form(action, row, values, states, run.set_sensitive)
form.widget.set_margin_top(12)
form.widget.set_margin_bottom(18)
form.widget.set_margin_start(18)
form.widget.set_margin_end(18)
view = Adw.ToolbarView(content=Gtk.ScrolledWindow(child=form.widget, propagate_natural_height=True, hscrollbar_policy=Gtk.PolicyType.NEVER))
view.add_top_bar(header)
dialog.set_child(view)
dialog.set_default_widget(run) # enter in an entry runs
def clicked(_):
values = form.values()
dialog.close()
ran(values)
run.connect("clicked", clicked)
return dialog, form
class Window(Adw.ApplicationWindow):
def __init__(self, app):
super().__init__(application=app, title=TITLE, default_width=1100, default_height=700, icon_name=APP_ID)
super().__init__(application=app, title=TITLE, default_width=TILED_SIZE[0], default_height=TILED_SIZE[1], icon_name=APP_ID)
self.app = app
self.set_size_request(360, 360)
self.set_size_request(*MIN_SIZE)
self.unfix = None # the map handler that lets a window opened floating resize again
self.shown_size = None # (width, height) when last hidden to the tray
self.pages = {}
self.typed = {} # action label -> what was last typed there
self.typed = {} # action label -> {field: value} last run from its form
self.last_output = None # (title, text)
self.last_retry = None # () -> the last run again as root, when only root could do it
@@ -914,6 +1183,38 @@ class Window(Adw.ApplicationWindow):
self.connect("close-request", self.on_close)
def open_floating(self, width, height):
"""The next time it maps, open floating at this size. Nothing on Wayland asks for that,
but niri, sway, Hyprland and i3 float a window that opens at a fixed size: so it is fixed
until its first frame is on screen, then resizes as any window does. Elsewhere it just
opens at this size."""
if self.unfix:
self.disconnect(self.unfix)
self.set_default_size(width, height)
self.set_size_request(width, height)
self.set_resizable(False)
def mapped(_):
self.disconnect(self.unfix)
self.unfix = None
clock = self.get_frame_clock()
painted = None
def unfix(*_):
# After the frame that maps it: the compositor has decided by then.
if painted is not None:
clock.disconnect(painted)
self.set_resizable(True)
self.set_size_request(*MIN_SIZE)
self.set_default_size(width, height)
if clock is None:
GLib.idle_add(lambda: unfix() and False)
else:
painted = clock.connect("after-paint", unfix)
self.unfix = self.connect("map", mapped)
# --- tabs ----------------------------------------------------------------------------------
def page(self):
@@ -1053,10 +1354,12 @@ class Window(Adw.ApplicationWindow):
page.refill()
return
def with_text(text=""):
def with_values(values=None):
try:
argv = action.argv(row, text, self.app.states)
stdin = action.stdin(row, text) if action.stdin else None
if action.fields:
argv, stdin = model.form_argv(action, row, values, self.app.states)
else:
argv, stdin = action.argv(row, {}, self.app.states), action.stdin(row, {}) if action.stdin else None
except (ValueError, IndexError) as e:
self.toast(f"Cannot run that: {e}")
return
@@ -1065,28 +1368,17 @@ class Window(Adw.ApplicationWindow):
else:
self.app.run_argv(action.mode, argv, self, stdin=stdin)
if not action.prompt:
with_text()
if not action.fields:
with_values()
return
title = action.label.removesuffix("…")
dialog = Adw.AlertDialog(heading=cap(title), close_response="cancel", default_response="run")
entry = Gtk.Entry(placeholder_text=action.prompt, text=self.typed.get(action.label, ""), activates_default=True, width_chars=40)
dialog.set_extra_child(entry)
dialog.add_response("cancel", "Cancel")
dialog.add_response("run", "Run")
dialog.set_response_appearance("run", Adw.ResponseAppearance.SUGGESTED)
dialog.set_response_enabled("run", bool(entry.get_text().strip()))
entry.connect("changed", lambda e: dialog.set_response_enabled("run", bool(e.get_text().strip())))
def ran(values):
self.typed[action.label] = values
with_values(values)
def responded(_, response):
text = entry.get_text().strip()
if response == "run" and text:
self.typed[action.label] = text
with_text(text)
dialog.connect("response", responded)
title = cap(action.label.removesuffix("…"))
dialog, form = form_dialog(title, action, row, self.typed.get(action.label), self.app.states, ran)
dialog.present(self)
entry.grab_focus()
form.focus(action.fields[0].name)
def toast(self, message, output=None, retry=None):
# A toast title is one ellipsized line, which hides most of what a command said:
@@ -1139,9 +1431,15 @@ class Window(Adw.ApplicationWindow):
website="https://github.com/FUFSoB/proxy-suite-flake", license_type=Gtk.License.CUSTOM,
).present(self)
def hide_to_tray(self):
"""To the tray, keeping the size it had: it opens at that size again."""
if self.get_width() and self.get_height():
self.shown_size = (self.get_width(), self.get_height())
self.set_visible(False)
def on_close(self, _):
if self.app.tray and self.app.tray.available:
self.set_visible(False)
self.hide_to_tray()
return True # the tray icon brings it back
self.app.quit()
return False
@@ -1218,7 +1516,10 @@ class ProxySuiteGui(Adw.Application):
self.timer = GLib.timeout_add_seconds(self.refresh, self.tick)
self.reload()
if not options.get("hidden"):
self.present(options.get("tab"))
# A launcher's token comes along when the running instance is asked to show itself.
platform = command_line.get_platform_data()
token = platform.lookup_value("activation-token", None) if platform else None
self.present(options.get("tab"), token=token.get_string() if token else None)
return 0
def do_activate(self):
@@ -1242,7 +1543,9 @@ class ProxySuiteGui(Adw.Application):
self.window.root_badge.set_visible(value.get_boolean())
self.reload(fresh_root=True) # tabs only root can read
def present(self, tab=None):
def present(self, tab=None, token=None):
"""token: an xdg-activation token, from the tray or a launcher: with it the compositor
gives the window focus, which it may refuse a window that only asks."""
if self.window is None:
self.window = Window(self)
# Hidden to the tray or switched away from: what it showed has been seen.
@@ -1250,16 +1553,20 @@ class ProxySuiteGui(Adw.Application):
self.window.show_tabs(model.available_tabs(self.states) if self.states else ["services"])
if tab and tab in self.window.pages:
self.window.stack.set_visible_child_name(tab)
if floating() and not self.window.get_visible():
self.window.open_floating(*(self.window.shown_size or floating_size()))
if token:
self.window.set_startup_id(token)
self.window.present()
if page := self.window.page():
page.focus_default()
self.reload()
def toggle_window(self):
def toggle_window(self, token=None):
if self.window and self.window.get_visible() and self.window.is_active():
self.window.set_visible(False)
self.window.hide_to_tray()
else:
self.present()
self.present(token=token)
def leave_window(self):
if self.viewing:
@@ -1395,7 +1702,7 @@ class ProxySuiteGui(Adw.Application):
def on_tray_menu(self, item):
if item.app == "open":
self.present()
self.present(token=self.tray.take_token() if self.tray else None)
elif item.app == "quit":
self.quit()
elif item.argv:
+356 -100
View File
@@ -17,7 +17,7 @@ import subprocess
import sys
import time
import zlib
from dataclasses import dataclass, field
from dataclasses import dataclass, field, replace
from typing import Callable
import proxy_ctl as ctl
@@ -58,18 +58,34 @@ def new_load():
_memo.clear()
@dataclass
class Field:
"""One thing an action asks for before it runs: a box of its own in the form."""
name: str # its key in the values argv and stdin get
label: str
hint: str = "" # what it takes, or an example
optional: bool = False
choices: Callable = None # selected row or None -> {value: description}: offered while typing; anything else still goes
fixed: bool = False # the choices are the only values: picked from a list
items: bool = False # a list, each value a box of its own; its value is a list of strings
current: Callable = None # items: selected row -> what it holds now. The form edits that, and runs only a change
number: bool = False
advanced: bool = False # folded away under "More options"
@dataclass
class Action:
key: str
label: str
argv: Callable # (selected row or None, prompt text, unit states) -> proxy-ctl argv
argv: Callable # (selected row or None, {field: value}, unit states) -> proxy-ctl argv
when: Callable = None # row -> applies; None: a tab-wide action that needs no row
prompt: str = "" # ask for text first
fields: list = field(default_factory=list) # ask for these first
confirm: bool | Callable = False # or row -> ask first
mode: str = "run" # run: result in the feedback line; dialog: output streamed into a dialog; suspend: hand over the terminal; pause: suspend, then wait for enter; copy: last line to the clipboard
offered: Callable = None # () -> this configuration has it; None: every one does
tty: bool = False # it asks on the terminal: only a front end that hands the terminal over offers it
stdin: Callable = None # (selected row or None, prompt text) -> text proxy-ctl reads on stdin, or None
stdin: Callable = None # (selected row or None, {field: value}) -> text proxy-ctl reads on stdin, or None
@dataclass
@@ -112,6 +128,159 @@ def needs_confirm(action, row):
return action.confirm(row) if callable(action.confirm) else action.confirm
# --- forms --------------------------------------------------------------------
def field_choices(f, row=None):
"""A field's choices, {value: description}; unreadable state costs the choices, not the form."""
return {str(k): str(v or "") for k, v in (_safe(f.choices, row, fallback=None) or {}).items()} if f.choices else {}
def form_choices(action, row=None):
"""{field: its choices}, read once when a form opens."""
return {f.name: field_choices(f, row) for f in action.fields if f.choices}
def items(value):
"""A list field's value: its values in order, once each. Text is several, space-separated (a paste)."""
values = value.split() if isinstance(value, str) else [str(v).strip() for v in value or []]
return list(dict.fromkeys(v for v in values if v))
def form_values(action, values):
"""Every field's value: text stripped, a list field's a list; what was left out is empty."""
values = values or {}
return {f.name: items(values.get(f.name)) if f.items else str(values.get(f.name) or "").strip() for f in action.fields}
def form_current(action, row=None):
"""{field: what the row holds now} for the fields that edit it, read once when a form opens."""
return {f.name: items(_safe(f.current, row, fallback=None)) for f in action.fields if f.current}
def form_start(action, row=None, remembered=None):
"""What a form opens with: what is there now where it edits that, else what was last run from it."""
return {**{k: v for k, v in (remembered or {}).items() if k not in {f.name for f in action.fields if f.current}}, **form_current(action, row)}
def form_problems(action, values, row=None, choices=None, current=None):
"""(field name, why) for each field the form cannot run with yet.
choices and current: form_choices and form_current as already read."""
values = form_values(action, values)
for f in action.fields:
value = values[f.name]
if not value:
if not f.optional:
yield f.name, f"{f.label} is needed"
continue
if f.number and not re.fullmatch(r"-?\d+", value):
yield f.name, f"{f.label} is a number"
if f.fixed:
allowed = (choices or {}).get(f.name)
allowed = field_choices(f, row) if allowed is None else allowed
if allowed and value not in allowed:
yield f.name, f"{f.label} is one of: {', '.join(allowed)}"
edits = [f for f in action.fields if f.current]
if edits:
current = form_current(action, row) if current is None else current
if all(values[f.name] == current.get(f.name, []) for f in edits):
yield edits[0].name, "Nothing changed yet"
def form_problem(action, values, row=None, choices=None, current=None):
"""Why the form cannot run yet, or ""."""
return next((why for _, why in form_problems(action, values, row, choices, current)), "")
def form_argv(action, row, values, states, choices=None, current=None):
"""(argv, stdin) the filled form runs. ValueError: it cannot run, and why."""
values = form_values(action, values)
if problem := form_problem(action, values, row, choices, current):
raise ValueError(problem)
argv = action.argv(row, values, states)
return argv, action.stdin(row, values) if action.stdin else None
def field_example(f):
"""The example in a field's hint, or "": what an empty box shows when the whole hint does not fit."""
return f.hint.rpartition("e.g. ")[2] if "e.g. " in f.hint else ""
def item_changes(was, now):
"""A list field's edit, item by item: (value, "kept" | "added" | "removed"), what was there first."""
return [(v, "kept" if v in now else "removed") for v in was] + [(v, "added") for v in now if v not in was]
def _opt(flag, value):
"""--flag value, or nothing for an empty value."""
return [flag, value] if value else []
def _each(flag, values):
"""--flag v for every value of a list field: a repeatable flag."""
return [a for v in values for a in (flag, v)]
def _extra(text):
"""Flags typed as on the command line: the escape hatch for those without a field."""
return shlex.split(text) if text else []
def _listed(words):
"""Words that never change, as a field's choices."""
return lambda _: dict.fromkeys(words, "")
# Field choices, read when a form opens. Looked up through ctl at each read: tests patch it.
def _outbounds(_):
return {**ctl._outbound_choices(), **ctl._group_choices()}
def _targets(row):
return {**dict.fromkeys(ctl.RULE_TARGETS, ""), **_outbounds(row)}
def _users(_):
return ctl._inbound_runtime_names("users")
def _listeners(_):
return ctl._inbound_runtime_names("listeners")
def _rule_matches(row):
"""What the selected runtime rule matches now, as `rules add` spells each."""
rule = next((r for r in ctl._runtime_rules() if r["name"] == row["name"]), None)
return [f"{ctl.RULE_MATCH_SPELLING[kind]}{v}" for kind in ctl.RULE_MATCH_KINDS for v in rule.get(kind) or []] if rule else []
def _group_listed(row):
"""The members a group names itself; an inventory from before `listed` has only all of them."""
group = ctl._outbound_groups().get(row["tag"]) or {}
return group.get("listed", group.get("members") or [])
def _listener_users(row):
return [ctl._s(u.get("name")) for u in ctl._inbound_runtime_rows("users") if row["tag"] in (u.get("listeners") or [])]
def _user_listeners(row):
user = next((u for u in ctl._inbound_runtime_rows("users") if ctl._s(u.get("name")) == row["name"]), {})
return [ctl._s(t) for t in user.get("listeners") or []]
MATCHES = Field("matches", "Matches", "domains, addresses, geosite:x, geoip:x or ruleset:x - e.g. bank.example or 10.0.0.0/8", items=True)
MEMBERS = Field("members", "Members", "outbounds and groups, in the order tried", optional=True, items=True, choices=_outbounds)
DOMAIN = Field("domain", "Domain", "e.g. example.com")
PROBE = Field("domain", "Domain", "e.g. example.com, or example.com/path")
COMMAND = Field("command", "Command", "as in a shell, e.g. firefox --private-window")
def _app_via(_):
# What the shell completion offers after `apps add --via`: it knows what this host can pin.
return ctl._complete_tree("apps", "add", "--via")
# What proxy-ctl and systemctl print when only root may do it.
# ponytail: matches the wording; an exit status of its own (77) if that ever drifts.
ROOT_HINT = re.compile(r"re-run with sudo|run with sudo|run as root|Interactive authentication required|Access denied")
@@ -366,25 +535,14 @@ def _awg_available(_):
return bool(ctl._awg_profiles()) or ctl.env("AWG_RUNTIME_GLOBAL") == "1"
def _awg_add(text):
"""[name] <config> as typed: (name or None, the config or a path to it)."""
text = text.strip()
if ctl._awg_source(text):
return None, text
parts = text.split(None, 1)
return (parts[0], parts[1].strip()) if len(parts) == 2 else (None, text)
def _awg_add_argv(text):
name, source = _awg_add(text)
def _awg_add_argv(v):
# The config itself goes on stdin: in argv its keys would show in ps, sudo's log and here.
what = "-" if ctl._awg_source(source) else _path(source)
return ["awg", "add", *([name] if name else []), what]
what = "-" if ctl._awg_source(v["source"]) else _path(v["source"])
return ["awg", "add", *([v["name"]] if v["name"] else []), what]
def _awg_add_stdin(text):
_, source = _awg_add(text)
return source if ctl._awg_source(source) else None
def _awg_add_stdin(v):
return v["source"] if ctl._awg_source(v["source"]) else None
def subscription_rows(_):
@@ -526,10 +684,8 @@ def _runtime_row(row):
return row.get("source") == "runtime"
def _user_add_argv(text):
words = shlex.split(text)
order = ["--order", words[1]] if len(words) > 1 else []
return ["inbounds", "users", "add", *words[:1], *order, *(a for t in words[2:] for a in ("--listener", t))]
def _user_add_argv(v):
return ["inbounds", "users", "add", v["name"], *_opt("--order", v["order"]), *_each("--listener", v["listeners"])]
def app_rows(_):
@@ -545,10 +701,8 @@ def app_rows(_):
]
def _via_run_argv(text):
"""<outbound> <command> [args], as typed, to `apps run --via`."""
words = shlex.split(text)
return ["apps", "run", "--via", *words[:1], "--", *words[1:]]
def _via_run_argv(v):
return ["apps", "run", "--via", v["outbound"], "--", *shlex.split(v["command"])]
def _via_offered():
@@ -643,29 +797,27 @@ def _sub_url(row, user="user"):
return bool(row[user]) and bool(ctl.env("INBOUNDS_SUB_BASE_URL"))
def _add_source(text):
"""[tag] <url, JSON or config> as typed: (tag or None, the rest)."""
text = text.strip()
return (None, text) if text.startswith("{") else _awg_add(text)
def _secret(source):
# A link's userinfo and query, a JSON outbound, a config: credentials, all of them.
return "://" in source or source.startswith("{") or ctl._awg_source(source)
def _add_args(text):
def _add_args(v):
"""[tag] <source> as `proxy-ctl ... add` takes them. A link, JSON or AmneziaWG config
becomes "-": _add_stdin hands it over on stdin, out of ps and pkexec's or sudo's log."""
name, source = _add_source(text)
if not source:
return [] # proxy-ctl says what it wants
return [*([name] if name else []), "-" if _secret(source) else source]
return [*([v["tag"]] if v["tag"] else []), "-" if _secret(v["source"]) else v["source"]]
def _add_stdin(text):
_, source = _add_source(text)
return source if source and _secret(source) else None
def _add_stdin(v):
return v["source"] if _secret(v["source"]) else None
def _source_fields(what, example):
"""[tag] <source>: what most adds take."""
return [
Field("tag", "Tag", "derived from the link if empty", optional=True),
Field("source", what, example),
]
def _zapret_auto():
@@ -725,17 +877,17 @@ TABS = [
"j",
"set the call it joins…",
# On stdin: the call link is what lets anyone into the call.
lambda r, t, _: ["wl", "join", _wl_entry(r)["name"], "-"],
stdin=lambda r, t: t.strip(),
lambda r, v, _: ["wl", "join", _wl_entry(r)["name"], "-"],
stdin=lambda r, v: v["link"],
when=_wl_role("joiner"),
prompt="<call link> - a room id, a slug or a URL",
fields=[Field("link", "Call link", "a room id, a slug or a URL")],
),
Action(
"a",
"replace its login with a cookies file…",
lambda r, t, _: ["wl", "auth", _wl_entry(r)["name"], _path(t)],
lambda r, v, _: ["wl", "auth", _wl_entry(r)["name"], _path(v["path"])],
when=_wl_role("creator"),
prompt="<path> - cookies exported from the desktop Creator",
fields=[Field("path", "Cookies file", "a path: cookies exported from the desktop Creator")],
),
Action(
"A",
@@ -761,9 +913,12 @@ TABS = [
Action(
"n",
"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),
lambda r, v, _: _awg_add_argv(v),
fields=[
Field("name", "Name", "e.g. home; from the config if empty", optional=True),
Field("source", "Config", "vpn://… or a .conf path (or paste a whole .conf onto the table)"),
],
stdin=lambda r, v: _awg_add_stdin(v),
offered=lambda: ctl.env("AWG_RUNTIME_GLOBAL") == "1",
),
Action("d", "remove it", lambda r, *_: ["awg", "rm", r["profile"]], when=lambda r: r["source"] == "runtime", confirm=True),
@@ -788,19 +943,34 @@ TABS = [
Action(
"n",
"add a rule…",
lambda r, t, _: ["proxy", "rules", "add", *shlex.split(t)],
prompt="<proxy|direct|block|outbound> <domain, address, geosite:x, geoip:x or ruleset:x…> [--name n] [--priority n]"
" - e.g. direct bank.example 10.0.0.0/8",
lambda r, v, _: ["proxy", "rules", "add", v["target"], *v["matches"], *_opt("--name", v["name"]), *_opt("--priority", v["priority"])],
fields=[
Field("target", "Target", "proxy, direct, block or an outbound", choices=_targets),
MATCHES,
Field("name", "Name", "the target's if empty; an existing rule's name extends it", optional=True),
Field("priority", "Priority", "lower goes first; 50 if empty", optional=True, number=True),
],
),
Action(
"a",
"edit its domains and addresses…",
lambda r, v, _: ["proxy", "rules", "matches", r["name"], "set", *v["matches"]],
when=_runtime_rule,
fields=[replace(MATCHES, optional=True, current=_rule_matches)],
),
Action(
"t",
"send it elsewhere…",
lambda r, v, _: ["proxy", "rules", "target", r["name"], v["target"]],
when=_runtime_rule,
fields=[Field("target", "Target", "proxy, direct, block or an outbound", choices=_targets)],
),
Action("a", "add domains or addresses to it…", lambda r, t, _: ["proxy", "rules", "matches", r["name"], "add", *t.split()], when=_runtime_rule, prompt="<domain, address, geosite:x, geoip:x or ruleset:x…>"),
Action("x", "remove domains or addresses from it…", lambda r, t, _: ["proxy", "rules", "matches", r["name"], "rm", *t.split()], when=_runtime_rule, prompt="<domain, address, geosite:x, geoip:x or ruleset:x…>"),
Action("t", "send it elsewhere…", lambda r, t, _: ["proxy", "rules", "target", r["name"], t.strip()], when=_runtime_rule, prompt="<proxy, direct, block or an outbound>"),
Action(
"y",
"set its priority…",
lambda r, t, _: ["proxy", "rules", "priority", r["name"], t.strip()],
lambda r, v, _: ["proxy", "rules", "priority", r["name"], v["priority"]],
when=_runtime_rule,
prompt="<number> - lower goes first; the configuration's sections are at 100 to 500",
fields=[Field("priority", "Priority", "lower goes first; the configuration's sections are at 100 to 500", number=True)],
),
Action("plus", "move it up", lambda r, *_: ["proxy", "rules", "priority", r["name"], "up"], when=_runtime_rule),
Action("minus", "move it down", lambda r, *_: ["proxy", "rules", "priority", r["name"], "down"], when=_runtime_rule),
@@ -833,39 +1003,57 @@ TABS = [
Action(
"P",
"probe a domain through it…",
lambda r, t, _: ["proxy", "auto", "probe", t, "--via", ctl._backend_tag(r["tag"])],
lambda r, v, _: ["proxy", "auto", "probe", v["domain"], "--via", ctl._backend_tag(r["tag"])],
when=lambda r: _exit(r) and _enabled("AUTOPROXY_ENABLED")(r),
prompt="<domain>[/path]",
fields=[PROBE],
mode="dialog",
),
Action("T", "test all", lambda r, *_: ["proxy", "outbounds", "test"], mode="dialog"),
Action(
"n",
"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),
lambda r, v, _: ["proxy", "outbounds", "add", *_add_args(v)],
fields=_source_fields("Link", "vless://…, its JSON or an AmneziaWG vpn://…"),
stdin=lambda r, v: _add_stdin(v),
),
Action(
"N",
"add an AmneziaWG outbound on an interface of its own…",
lambda r, t, _: ["proxy", "outbounds", "add", *_add_args(t), "--interface"],
prompt="[tag] <vpn://… or a .conf path> - apps can then run through it (proxy-ctl apps run --via)",
stdin=lambda r, t: _add_stdin(t),
lambda r, v, _: ["proxy", "outbounds", "add", *_add_args(v), "--interface"],
fields=_source_fields("Config", "vpn://… or a .conf path - apps can then run through it (proxy-ctl apps run --via)"),
stdin=lambda r, v: _add_stdin(v),
offered=lambda: ctl.env("AWG_RUNTIME_IFACE_OUTBOUNDS") == "1",
),
Action(
"g",
"add a group…",
lambda r, t, _: ["proxy", "groups", "add", *shlex.split(t)],
prompt="<tag> <member…> [--sub <subscription>] [--match <pattern>] [--strategy failover|urltest|selector]",
lambda r, v, _: [
"proxy", "groups", "add", v["tag"], *v["members"], *_each("--sub", v["subs"]), *_each("--match", v["match"]),
*_opt("--strategy", v["strategy"]), *_opt("--interval", v["interval"]), *_extra(v["extra"]),
],
fields=[
Field("tag", "Tag", "the group's own tag, e.g. auto"),
MEMBERS,
Field("subs", "Subscriptions", "every entry of these", optional=True, items=True, choices=lambda _: dict.fromkeys(ctl._sub_tags(), "")),
Field("match", "Match", "every outbound whose tag matches, e.g. de-*", optional=True, items=True),
Field("strategy", "Strategy", "failover if empty", optional=True, fixed=True, choices=_listed(ctl.GROUP_STRATEGIES)),
Field("interval", "Test interval", "a duration: 30s, 1m, 1m30s", optional=True, advanced=True),
Field("extra", "Other flags", "as on the command line, e.g. --no-failback", optional=True, advanced=True),
],
),
Action(
"m",
"add members to the group…",
lambda r, t, _: ["proxy", "groups", "members", r["tag"], "add", *t.split()],
"edit the group's members…",
lambda r, v, _: ["proxy", "groups", "members", r["tag"], "set", *v["members"]],
when=lambda r: r["group"] and r["runtime"],
prompt="<member…>",
fields=[
replace(
MEMBERS,
hint="outbounds and groups, in the order tried; its subscriptions and patterns add theirs",
choices=lambda r: {t: d for t, d in _outbounds(r).items() if t != r["tag"]}, # not itself
current=_group_listed,
)
],
),
Action(
"M",
@@ -877,33 +1065,36 @@ TABS = [
Action(
"S",
"change the group's strategy…",
lambda r, t, _: ["proxy", "groups", "strategy", r["tag"], t.strip()],
lambda r, v, _: ["proxy", "groups", "strategy", r["tag"], v["strategy"]],
when=lambda r: r["group"] and r["runtime"],
prompt="failover, urltest or selector",
fields=[Field("strategy", "Strategy", "how the group picks a member", fixed=True, choices=_listed(ctl.GROUP_STRATEGIES))],
),
Action(
"y",
"set its priority…",
lambda r, t, _: ["proxy", "priority", r["tag"], t.strip() or "--clear"],
lambda r, v, _: ["proxy", "priority", r["tag"], v["priority"] or "--clear"],
when=lambda r: not r["parent"],
prompt="<number> - lower goes first; empty: back to the default order",
fields=[Field("priority", "Priority", "lower goes first; empty: back to the default order", optional=True, number=True)],
),
Action("plus", "move it up", lambda r, *_: ["proxy", "priority", r["tag"], "up"], when=lambda r: not r["parent"]),
Action("minus", "move it down", lambda r, *_: ["proxy", "priority", r["tag"], "down"], when=lambda r: not r["parent"]),
Action(
"h",
"add an outbound chained through this one…",
lambda r, t, _: ["proxy", "outbounds", "add", *_add_args(t), "--detour", r["tag"]],
lambda r, v, _: ["proxy", "outbounds", "add", *_add_args(v), "--detour", r["tag"]],
when=_exit,
prompt="[tag] <url or JSON> - e.g. de-1 vless://… or just vless://…",
stdin=lambda r, t: _add_stdin(t),
fields=_source_fields("Link", "vless://… or its JSON"),
stdin=lambda r, v: _add_stdin(v),
),
Action(
"H",
"chain it through another outbound…",
lambda r, t, _: ["proxy", "outbounds", "chain", r["tag"], *t.split()],
lambda r, v, _: ["proxy", "outbounds", "chain", r["tag"], v["hop"], *([v["tag"]] if v["tag"] else [])],
when=_exit,
prompt="<hop tag> [new tag] - a copy of this one dialing through the hop",
fields=[
Field("hop", "Through", "the outbound a copy of this one dials through", choices=lambda _: ctl._outbound_choices()),
Field("tag", "New tag", "<this>-via-<hop> if empty", optional=True),
],
),
Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"] and not r["group"], confirm=True),
Action("d", "remove the group", lambda r, *_: ["proxy", "groups", "rm", r["tag"]], when=lambda r: r["runtime"] and r["group"], confirm=True),
@@ -938,9 +1129,9 @@ TABS = [
Action(
"n",
"add a subscription…",
lambda r, t, _: ["proxy", "subs", "add", *_add_args(t)],
prompt="[tag] <url> - e.g. work https://… or just https://…",
stdin=lambda r, t: _add_stdin(t),
lambda r, v, _: ["proxy", "subs", "add", *_add_args(v)],
fields=_source_fields("URL", "https://…"),
stdin=lambda r, v: _add_stdin(v),
),
Action("d", "remove it", lambda r, *_: ["proxy", "subs", "rm", r["tag"]], when=lambda r: r["source"] == "runtime", confirm=True),
Action("s", "URL", lambda r, *_: ["proxy", "subs", "link", r["tag"]], when=ROW, mode="dialog"),
@@ -959,8 +1150,8 @@ TABS = [
Action("w", "how is it routed", lambda r, *_: ["where", r["domain"]], when=ROW, 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("n", "learn a domain…", lambda r, t, _: ["proxy", "auto", "learn", t], prompt="<domain>", mode="dialog"),
Action("P", "probe a domain…", lambda r, v, _: ["proxy", "auto", "probe", v["domain"]], fields=[PROBE], mode="dialog"),
Action("n", "learn a domain…", lambda r, v, _: ["proxy", "auto", "learn", v["domain"]], fields=[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),
@@ -981,8 +1172,8 @@ TABS = [
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("n", "pin a host as blocked…", lambda r, v, _: ["zapret", "auto", "add", v["domain"]], fields=[DOMAIN], offered=_zapret_auto),
Action("X", "exclude a host…", lambda r, v, _: ["zapret", "auto", "exclude", v["domain"]], fields=[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("space", "start / stop zapret", _zapret_toggle),
@@ -1015,13 +1206,39 @@ TABS = [
Action(
"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",
lambda r, v, _: [
"inbounds", "add", v["tag"], v["type"], *_opt("--port", v["port"]), *_opt("--reality", ",".join(v["reality"])),
*_opt("--tls", v["tls"]), *_each("--user", v["users"]), *_opt("--via", v["via"]), *_opt("--transport", v["transport"]),
*_extra(v["extra"]),
],
fields=[
Field("tag", "Tag", "e.g. friends"),
Field("type", "Type", "the protocol", fixed=True, choices=_listed(ctl.INBOUND_TYPES)),
Field("port", "Port", "one from inbounds.runtime.ports if empty", optional=True, number=True),
Field("reality", "REALITY", "the server names it poses as, e.g. www.microsoft.com", optional=True, items=True),
Field("tls", "TLS certificate", "one from inbounds.runtime.tlsCertificates", optional=True),
Field("users", "Users", "who may connect", optional=True, items=True, choices=_users),
Field("via", "Via", "where its traffic exits", optional=True, choices=_outbounds),
Field("transport", "Transport", "raw if empty", optional=True, fixed=True, choices=_listed(("raw", "ws", "grpc", "httpupgrade", "xhttp")), advanced=True),
Field(
"extra",
"Other flags",
"as on the command line: " + " ".join(f for f in ctl.INBOUND_ADD_FLAGS if f not in ("--port", "--reality", "--tls", "--via", "--transport")),
optional=True,
advanced=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("x", "unbind a user from it…", lambda r, t, _: ["inbounds", "unbind", t.strip(), r["tag"]], when=ROW, prompt="<user>", offered=_inbounds_runtime),
Action(
"b",
"edit who is on it…",
lambda r, v, _: ["inbounds", "users", "on", r["tag"], *v["users"]],
when=ROW,
fields=[Field("users", "Users", "who may connect through this listener", optional=True, items=True, choices=_users, current=_listener_users)],
offered=_inbounds_runtime,
),
],
),
Tab(
@@ -1036,11 +1253,34 @@ TABS = [
else "Users from the configuration. inbounds.runtime would let you add and bind them here."
),
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(
"n",
"add a user…",
lambda r, v, _: _user_add_argv(v),
fields=[
Field("name", "Name", "e.g. alice"),
Field("order", "Order", "its position in links and subscriptions", optional=True, number=True),
Field("listeners", "Listeners", "the ones it may connect to", optional=True, items=True, choices=_listeners),
],
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("x", "unbind it from a listener…", lambda r, t, _: ["inbounds", "unbind", r["name"], t.strip()], when=ROW, prompt="<listener>", offered=_inbounds_runtime),
Action(
"e",
"set its order…",
lambda r, v, _: ["inbounds", "users", "order", r["name"], v["order"]],
when=_runtime_row,
fields=[Field("order", "Order", "its position in links and subscriptions", number=True)],
offered=_inbounds_runtime,
),
Action(
"b",
"edit its listeners…",
lambda r, v, _: ["inbounds", "users", "listeners", r["name"], *v["listeners"]],
when=ROW,
fields=[Field("listeners", "Listeners", "the ones it may connect to", optional=True, items=True, choices=_listeners, current=_user_listeners)],
offered=_inbounds_runtime,
),
# The user's one subscription, as the inbounds tab has it on each of the user's rows.
Action("s", "subscription URL", lambda r, *_: ["inbounds", "sub", r["name"]], when=ROW, mode="dialog"),
Action("c", "copy subscription URL", lambda r, *_: ["inbounds", "sub", r["name"]], when=lambda r: _sub_url(r, "name"), mode="copy"),
@@ -1056,15 +1296,31 @@ TABS = [
[("profile", "Profile"), ("route", "Route"), ("via", "Via"), ("source", "Source")],
app_rows,
actions=[
Action("n", "add a profile…", lambda r, t, _: ["apps", "add", *shlex.split(t)], prompt="<name> [--route tun|tproxy|…] [--via <outbound>] - e.g. game --via de"),
Action(
"n",
"add a profile…",
lambda r, v, _: ["apps", "add", v["name"], *_opt("--route", v["route"]), *_opt("--via", v["via"])],
fields=[
Field("name", "Name", "e.g. game"),
Field("route", "Route", "how its apps are routed", optional=True, fixed=True, choices=_listed(ctl.APP_ROUTES)),
Field("via", "Via", "the outbound it goes through", optional=True, choices=_app_via),
],
),
Action("d", "remove it", lambda r, *_: ["apps", "rm", r["profile"]], when=lambda r: r["source"] == "runtime", confirm=True),
Action("space", "run a command through it…", lambda r, t, _: ["apps", "run", r["profile"], "--", *shlex.split(t)], when=ROW, prompt="<command> [args]", mode="pause"),
Action("v", "run a command via an outbound…", lambda r, t, _: _via_run_argv(t), prompt="<outbound> <command> [args] - e.g. de firefox", mode="pause", offered=_via_offered),
Action("space", "run a command through it…", lambda r, v, _: ["apps", "run", r["profile"], "--", *shlex.split(v["command"])], when=ROW, fields=[COMMAND], mode="pause"),
Action(
"v",
"run a command via an outbound…",
lambda r, v, _: _via_run_argv(v),
fields=[Field("outbound", "Outbound", "e.g. de", choices=lambda _: dict.fromkeys(ctl._via_outbounds(), "")), COMMAND],
mode="pause",
offered=_via_offered,
),
],
),
]
WHERE = Action("w", "How is a domain routed", lambda r, t, _: ["where", t], prompt="<domain>", mode="dialog")
WHERE = Action("w", "How is a domain routed", lambda r, v, _: ["where", v["domain"]], fields=[DOMAIN], mode="dialog")
# The share-link schemes scripts/proxy_url_parsers.py parses. http(s) is both an HTTP proxy
# and how a subscription is spelled, so for those the tab pasted into decides.
@@ -1158,7 +1414,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"{display_key(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.fields 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
+14 -3
View File
@@ -35,6 +35,7 @@ ITEM_XML = """
<method name="Activate"><arg name="x" type="i" direction="in"/><arg name="y" type="i" direction="in"/></method>
<method name="SecondaryActivate"><arg name="x" type="i" direction="in"/><arg name="y" type="i" direction="in"/></method>
<method name="Scroll"><arg name="delta" type="i" direction="in"/><arg name="orientation" type="s" direction="in"/></method>
<method name="ProvideXdgActivationToken"><arg name="token" type="s" direction="in"/></method>
<signal name="NewTitle"/>
<signal name="NewIcon"/>
<signal name="NewAttentionIcon"/>
@@ -171,7 +172,8 @@ class Menu:
class StatusNotifierItem:
"""Exports the icon and its menu on connection, and keeps it registered while a watcher runs.
on_activate(): a click on the icon. on_menu(item): a menu item was clicked.
on_activate(token): a click on the icon, with the host's xdg-activation token or None.
on_menu(item): a menu item was clicked; take_token() has the host's token for it.
on_available(bool): whether a host shows the icon.
"""
@@ -180,6 +182,7 @@ class StatusNotifierItem:
self.app_id, self.title, self.icon_theme_path = app_id, title, icon_theme_path
self.on_activate, self.on_menu, self.on_available = on_activate, on_menu, on_available or (lambda _: None)
self.icon, self.tooltip, self.status = "proxy-suite-disabled-unknown", "", "Active"
self.token = None # from ProvideXdgActivationToken, for the click that follows
self.menu = Menu()
self.available = False
self.name = f"org.kde.StatusNotifierItem-{os.getpid()}-1"
@@ -270,9 +273,17 @@ class StatusNotifierItem:
}
return GLib.Variant(*values[prop]) if prop in values else None
def take_token(self):
"""The xdg-activation token the host last handed over, once: a window it opens gets focus with it."""
token, self.token = self.token, None
return token
def _item_call(self, connection, sender, path, interface, method, params, invocation):
if method in ("Activate", "SecondaryActivate"):
GLib.idle_add(self.on_activate)
if method == "ProvideXdgActivationToken":
# A host that has one sends it just before Activate, or a menu click.
self.token = params.unpack()[0] or None
elif method in ("Activate", "SecondaryActivate"):
GLib.idle_add(lambda: self.on_activate(self.take_token()) and False)
invocation.return_value(None)
# --- com.canonical.dbusmenu ---------------------------------------------------------
+287 -14
View File
@@ -18,13 +18,15 @@ from rich.text import Text
from textual import work
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Container, Vertical
from textual.containers import Container, Horizontal, Vertical, VerticalScroll
from textual.content import Content
from textual.markup import escape
from textual.message import Message
from textual.coordinate import Coordinate
from textual.screen import ModalScreen, Screen
from textual.suggester import Suggester
from textual.theme import Theme
from textual.widgets import DataTable, Input, Label, OptionList, RichLog, Static, TabbedContent, TabPane
from textual.widgets import Collapsible, DataTable, Input, Label, OptionList, RichLog, Select, Static, TabbedContent, TabPane
from textual.widgets.option_list import Option
import proxy_model as model
@@ -236,6 +238,256 @@ class Prompt(Dialog):
self.dismiss(self.query_one(Input).value.strip())
class Completer(Suggester):
"""A field's choices, completing what is typed (its last word, in a list field's box); → takes it.
taken: () -> values already in the list, not offered again."""
def __init__(self, choices, words=False, taken=lambda: ()):
super().__init__(use_cache=False, case_sensitive=True)
self.choices, self.words, self.taken = list(choices), words, taken
async def get_suggestion(self, value):
last = value.rsplit(" ", 1)[-1] if self.words else value
if not last:
return None
head = value[: len(value) - len(last)]
taken = {*(value.split() if self.words else ()), *self.taken()}
return next((head + c for c in self.choices if c.lower().startswith(last.lower()) and c != last and c not in taken), None)
def _listing(choices, limit=6):
"""A field's choices as its hint line lists them."""
names = list(choices)
return ", ".join(names[:limit]) + (f" and {len(names) - limit} more" if len(names) > limit else "")
PLACEHOLDER_ROOM = 56 # of a hint, what a box shows before it cuts the rest
def placeholder(f):
"""(what the box shows while empty, what goes under it): a hint too long for the box goes
under it, whole, and the box keeps its example."""
if len(f.hint) <= PLACEHOLDER_ROOM:
return f.hint, ""
return model.field_example(f), f.hint
ITEM_LOOKS = {"kept": (" ", ""), "added": ("+ ", "green"), "removed": ("− ", "red strike dim")}
class Items(Vertical):
"""A list field: a box to type a value into (enter adds it; a paste of several adds each), and
under it the list, a value per line. Enter or a click on one takes it out, or puts back one
that was there. Editing what a row holds, what changes is marked: + added, − taken out."""
class Changed(Message):
pass
def __init__(self, f, values, was, choices, hint_text):
super().__init__(id=f"field-{f.name}", classes="items")
self.f, self.was, self.choices, self.hint_text = f, list(was), choices, hint_text
self.removed = {v for v in self.was if v not in values}
self.added = [v for v in values if v not in self.was]
@property
def value(self):
listed = [v for v in self.was if v not in self.removed] + self.added
# What is typed but not added yet counts too: tab or ctrl+s past it must not drop it.
pending = model.items(self.query_one(Input).value) if self.is_mounted else []
return listed + [v for v in pending if v not in listed]
def compose(self) -> ComposeResult:
shown, _ = placeholder(self.f)
yield Input(placeholder=shown or "add one", suggester=Completer(self.choices, True, lambda: self.value) if self.choices else None)
yield Choices(classes="item-list")
if self.hint_text:
yield Label(self.hint_text, classes="field-hint", markup=False)
def on_mount(self):
self.show()
def focus(self, scroll_visible=True):
self.query_one(Input).focus(scroll_visible)
return self
def show(self):
rows = model.item_changes(self.was, self.value)
listed = self.query_one(".item-list", Choices)
at = listed.highlighted
listed.clear_options()
for value, state in rows:
mark, style = ITEM_LOOKS[state if self.was else "kept"]
listed.add_option(Option(Text.assemble((mark, style), (printable(value), style)), id=value))
listed.display = bool(rows)
if rows and at is not None:
listed.highlighted = min(at, len(rows) - 1)
self.post_message(self.Changed())
# A highlight only while the list has focus: elsewhere it would read as a value picked.
def on_descendant_focus(self, event):
if isinstance(event.widget, Choices) and event.widget.highlighted is None and event.widget.option_count:
event.widget.highlighted = 0
def on_descendant_blur(self, event):
if isinstance(event.widget, Choices):
event.widget.highlighted = None
def on_input_submitted(self, event):
# Enter in an empty box is the form's: it runs.
if not event.value.strip():
return
event.stop()
typed = model.items(event.value)
event.input.value = ""
for v in typed:
self.removed.discard(v)
if v not in self.value:
self.added.append(v)
self.show()
def on_input_changed(self, event):
event.stop()
self.post_message(self.Changed())
def on_option_list_option_selected(self, event):
event.stop()
v = event.option.id
if v in self.added:
self.added.remove(v)
else:
self.removed.symmetric_difference_update({v})
self.show()
class Form(Dialog):
"""What an action asks for, one box per field: tab moves on, enter runs once nothing is missing.
Dismissed with {field: value}, or None."""
# ctrl+s runs from anywhere: enter on a list field opens the list.
BINDINGS = [Binding("escape", "dismiss", "cancel"), Binding("ctrl+s", "submit", "run", priority=True)]
def __init__(self, title, action, row, remembered):
super().__init__()
self.heading, self.action, self.row = title, action, row
self.choices = model.form_choices(action, row)
self.current = model.form_current(action, row)
self.values = model.form_start(action, row, remembered)
self.tried = False # enter pressed with something missing: what is, in red
def compose(self) -> ComposeResult:
fields = self.action.fields
with Vertical(classes="dialog form"):
yield Label(printable(self.heading), classes="dialog-title", markup=False)
# Not a tab stop of its own: tab goes field to field.
with VerticalScroll(classes="fields", can_focus=False):
for f in fields:
if not f.advanced:
yield from self.field(f)
more = [f for f in fields if f.advanced]
if more:
# Open from the start when something was typed there last time.
with Collapsible(title="More options", collapsed=not any(self.values.get(f.name) for f in more)):
for f in more:
yield from self.field(f)
yield Static(classes="preview")
hints = ["tab next field", "→ completes"]
if any(f.items for f in fields):
hints.append("enter adds to a list; on a value, takes it out")
yield hint(*hints, ("enter/ctrl+s run", "submit"), ("esc cancel", "dismiss"))
def field(self, f):
"""The label beside its box; under the box, what does not fit in it and what it can be."""
value, choices = self.values.get(f.name, [] if f.items else ""), self.choices.get(f.name) or {}
shown, below = placeholder(f)
if choices and not f.fixed:
listed = ("any of: " if f.items else "e.g. ") + _listing(choices)
below = f"{below}\n{listed}" if below else listed
with Horizontal(classes="field"):
# An edit of what a row holds may well end empty: nothing to mark there.
yield Label(Text.assemble((f.label, "bold"), ("\noptional" if f.optional and not f.current else "", "dim")), classes="field-label")
with Vertical(classes="field-box"):
if f.items:
yield Items(f, model.items(value), self.current.get(f.name, []), choices, below)
return
if f.fixed and choices:
options = [(Text.assemble(c, (f" {d}", "dim")) if d else c, c) for c, d in choices.items()]
yield Select(options, prompt="default" if f.optional else "choose…", value=value if value in choices else Select.NULL, id=f"field-{f.name}")
yield Label(f.hint, classes="field-hint", markup=False)
return
yield Input(
value,
placeholder=shown,
type="integer" if f.number else "text",
suggester=Completer(choices) if choices else None,
id=f"field-{f.name}",
)
if below:
yield Label(below, classes="field-hint", markup=False)
def on_mount(self):
self.show_preview()
def read(self):
values = {}
for f in self.action.fields:
widget = self.query_one(f"#field-{f.name}")
if isinstance(widget, Items):
values[f.name] = widget.value
else:
values[f.name] = "" if isinstance(widget, Select) and widget.is_blank() else str(widget.value)
return values
def problems(self, values):
return model.form_problems(self.action, values, self.row, self.choices, self.current)
def show_preview(self):
"""The command the form runs, credentials blanked, or what it still needs: red once enter found it missing."""
values = self.read()
problems = [why for _, why in self.problems(values)]
try:
if problems:
raise ValueError("; ".join(problems))
argv, stdin = model.form_argv(self.action, self.row, values, self.app.states, self.choices, self.current)
text = Text(printable(model.shown(argv, stdin=stdin)), style="dim")
except (ValueError, IndexError) as e: # what is missing, or an unbalanced quote
text = Text(f"✗ {e}", style="red" if self.tried else "dim")
_update(self.query_one(".preview", Static), text)
def on_input_changed(self, _):
self.show_preview()
def on_select_changed(self, _):
self.show_preview()
def on_items_changed(self, _):
if self.is_mounted:
self.show_preview()
def on_input_submitted(self, event):
event.stop()
self.action_submit()
def action_submit(self):
values = self.read()
self.tried = True
problem = next(self.problems(values), None)
if problem:
# To the first field that needs something, out of More options if it is in there.
widget = self.query_one(f"#field-{problem[0]}")
for collapsible in widget.ancestors:
if isinstance(collapsible, Collapsible):
collapsible.collapsed = False
widget.focus()
self.show_preview()
return
try:
model.form_argv(self.action, self.row, values, self.app.states, self.choices, self.current)
except (ValueError, IndexError):
self.show_preview() # says why
return
self.dismiss(values)
class Confirm(Dialog):
BINDINGS = [Binding("y,enter", "dismiss(True)", "yes"), Binding("n,escape", "dismiss(False)", "no")]
@@ -468,9 +720,28 @@ class ProxyTui(App):
ModalScreen { align: center middle; }
.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 { text-style: dim; margin-top: 1; }
.dialog-hint { width: 1fr; text-style: dim; margin-top: 1; }
.dialog Input { width: 1fr; border: tall $border-blurred; }
.dialog Input:focus { border: tall $border; }
.form { width: 84; }
.form .fields { height: auto; max-height: 70vh; background: $background; }
.field { height: auto; }
.field-label { width: 16; padding: 1 1 0 0; }
.field-box { width: 1fr; height: auto; }
/* A hint wraps under its box rather than run off the dialog's edge. */
.field-hint { width: 1fr; text-style: dim; padding: 0 1; }
.items { height: auto; }
.items .item-list { height: auto; max-height: 8; border: none; padding: 0 1; background: $background; }
.items .item-list > .option-list--option-highlighted { background: $background; text-style: none; }
.items .item-list:focus > .option-list--option-highlighted { background: $block-hover-background; text-style: bold; }
.form Select { width: 1fr; }
.form Select > SelectCurrent { border: tall $border-blurred; background: $background; }
.form Select:focus > SelectCurrent { border: tall $border; }
.form Select > SelectOverlay { background: $background; }
.form Collapsible { border: none; padding: 0; margin-top: 1; background: $background; }
.form Collapsible > Contents { padding: 0; }
.form CollapsibleTitle { padding: 0; color: $accent; }
.form .preview { margin-top: 1; }
.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; }
@@ -490,7 +761,7 @@ class ProxyTui(App):
self.loaded = {} # tab id -> the last load, refilled at once when sorting or filtering changes
self.selectors = {} # tab id -> its selector's (options, current) as last read
self.status = []
self.typed = {} # prompt title -> what was last typed there
self.typed = {} # action label -> {field: value} last run from its form
self.feedback_timer = None
self.last_output = None # (title, text)
self.retry = None # (mode, argv, stdin) of the last run that only root could do
@@ -802,10 +1073,12 @@ class ProxyTui(App):
self.refill(self.active_tab())
return
def with_text(text=""):
def with_values(values=None):
try:
argv = action.argv(row, text, self.states)
stdin = action.stdin(row, text) if action.stdin else None
if action.fields:
argv, stdin = model.form_argv(action, row, values, self.states)
else:
argv, stdin = action.argv(row, {}, self.states), action.stdin(row, {}) if action.stdin else None
except (ValueError, IndexError) as e: # an unbalanced quote in a typed command
self.feedback(f"Cannot run that: {e}", False)
return
@@ -814,16 +1087,16 @@ class ProxyTui(App):
else:
self.run_argv(action.mode, argv, stdin)
def typed(text):
if text:
self.typed[action.label] = text
with_text(text)
def filled(values):
if values is not None:
self.typed[action.label] = values
with_values(values)
if action.prompt:
if action.fields:
title = action.label.removesuffix("…")
self.push_screen(Prompt(title[:1].upper() + title[1:], action.prompt, self.typed.get(action.label, "")), typed)
self.push_screen(Form(title[:1].upper() + title[1:], action, row, self.typed.get(action.label)), filled)
else:
with_text()
with_values()
def run_argv(self, mode, argv, stdin=None):
"""stdin: text proxy-ctl reads (argv says "-"); only for runs that stay in the TUI."""
+30
View File
@@ -1400,6 +1400,12 @@ class RuntimeEntryTest(RuntimeSpoolTest):
# Released, they go through.
ok(ctl.cmd_groups, "members", "pool", "add", "vless-example")
self.assertEqual(json.loads(ctl.read_text(self.path("outbounds.d/pool.group")))["outbounds"], ["primary", "vless-example"])
# set: exactly these, in this order; never none, which would leave the group empty.
ok(ctl.cmd_groups, "members", "pool", "set", "vless-example", "primary", "vless-example")
self.assertEqual(json.loads(ctl.read_text(self.path("outbounds.d/pool.group")))["outbounds"], ["vless-example", "primary"])
status, _, err = run(ctl.cmd_groups, "members", "pool", "set")
self.assertNotEqual(status, 0)
self.assertIn("leave 'pool' empty", err)
# rm takes its lock file along; one waiting on the old one locks the new one instead.
lock = self.path("outbounds.d/.pool.group.lock")
ok(ctl.cmd_groups, "rm", "pool")
@@ -2234,6 +2240,21 @@ class InboundRuntimeTest(EnvTest):
self.assertIn("declared in the configuration", err)
# A refusal changes nothing, so nothing is reloaded.
self.assertEqual(len(self.started), 2)
# Exactly these: what is between now and then is bound and unbound, and reloaded once.
ok(ctl.cmd_inbounds, "users", "add", "carol")
self.assertEqual(len(self.started), 3)
ok(ctl.cmd_inbounds, "users", "listeners", "alice", "friends")
ok(ctl.cmd_inbounds, "users", "on", "friends", "alice", "carol")
rows = {r["name"]: r for r in json.loads(ok(ctl.cmd_inbounds, "users", "--json"))}
self.assertEqual((rows["alice"]["listeners"], rows["carol"]["listeners"]), (["friends"], ["friends"]))
self.assertEqual(len(self.started), 5)
self.assertEqual(ok(ctl.cmd_inbounds, "users", "on", "friends", "carol", "alice"), "Nothing to change.\n")
self.assertEqual(len(self.started), 5)
# One that cannot be done stops there: bob and vless-in are both the configuration's.
status, _, err = run(ctl.cmd_inbounds, "users", "on", "vless-in")
self.assertEqual(status, 1)
self.assertIn("declared in the configuration", err)
self.assertEqual(len(self.started), 5)
ok(ctl.cmd_inbounds, "rm", "friends")
self.assertIn("vless-in", ok(ctl.cmd_inbounds, "users"))
@@ -2618,6 +2639,15 @@ class RoutingRulesTest(EnvTest):
self.assertEqual((rule["domains"], rule["ips"], rule["target"], rule["disabled"], rule["priority"]), (["b.example"], ["1.1.1.1/32"], "de", True, 450))
ok(ctl.cmd_rules, "enable", "direct")
self.assertFalse(self.rules()["direct"]["disabled"])
# set: exactly these, in one write - what an edit in the TUI or the app sends.
applied = self.applied
self.assertEqual(ok(ctl.cmd_rules, "matches", "direct", "set", "b.example", "geosite:netflix"), "direct: b.example, geosite:netflix\n")
rule = self.rules()["direct"]
self.assertEqual((rule["domains"], rule["ips"], rule["geosites"]), (["b.example"], [], ["netflix"]))
self.assertEqual(self.applied, applied + 1)
self.assertEqual(ok(ctl.cmd_rules, "matches", "direct", "set", "b.example", "geosite:netflix"), "direct: nothing changed\n")
self.assertEqual(run(ctl.cmd_rules, "matches", "direct", "set", "not a match!")[0], 1)
self.assertEqual(ok(ctl.cmd_rules, "matches", "direct", "set"), "direct: matches nothing\n")
self.assertEqual(run(ctl.cmd_rules, "priority", "direct", "1.5")[0], 1)
self.assertEqual(run(ctl.cmd_rules, "rm", "nope")[0], 1)
ok(ctl.cmd_rules, "rm", "direct")
+20 -1
View File
@@ -13,7 +13,7 @@ import proxy_ctl as ctl
import proxy_gui as gui
import proxy_model as model
import proxy_sni as sni
from gi.repository import Adw, Gio, GLib, Gtk
from gi.repository import Adw, Gio, GLib, GObject, Gtk
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons"))
import badges # noqa: E402
@@ -100,6 +100,25 @@ class GuiTest(unittest.TestCase):
self.assertIsNotNone(Gtk.Label.find_property(name), name)
self.assertGreater(gui.TOAST_LINES, 1)
def test_form_widgets_are_there(self):
"""A form's rows, its dialog and what they are set up with exist in this libadwaita.
Built for real only with a display: GTK segfaults without one."""
for cls, names in (
(Adw.EntryRow, ("text", "activates-default", "input-purpose")),
(Adw.ComboRow, ("model", "selected")),
(Adw.ExpanderRow, ("expanded",)),
(Adw.Dialog, ("content-width", "default-widget")),
(Gtk.MenuButton, ("popover", "icon-name")),
(Gtk.ScrolledWindow, ("propagate-natural-height", "max-content-height")),
):
for name in names:
self.assertIsNotNone(cls.find_property(name), f"{cls.__name__}:{name}")
self.assertTrue(callable(gui.form_dialog))
# A list field: enter in its entry adds, and its rows come and go inside the expander.
self.assertNotEqual(GObject.signal_lookup("entry-activated", Adw.EntryRow), 0)
self.assertTrue(callable(getattr(Adw.ExpanderRow, "remove", None)))
self.assertTrue(callable(getattr(Adw.ExpanderRow, "set_subtitle", None)))
def test_ansi(self):
self.assertEqual(
gui.ansi_segments("\x1b[1;31mfailed\x1b[0m ok\x1b[K"),
+115 -33
View File
@@ -27,6 +27,15 @@ def walk(items):
yield from walk(item.children)
def form(action, row=None, **values):
"""(argv, stdin) an action's form runs with these fields filled, as both front ends run it."""
return model.form_argv(action, row, values, {})
def form_argv(action, row=None, **values):
return form(action, row, **values)[0]
class ModelTest(unittest.TestCase):
def setUp(self):
for name, value in {
@@ -140,23 +149,36 @@ class ModelTest(unittest.TestCase):
bob, alice = model.inbound_user_rows({})
self.assertEqual((bob["listeners"], alice["problems"]), ("in", "no listeners"))
actions = {a.key: a for a in users.actions}
self.assertEqual(actions["n"].argv(None, "carol 7 in ws", {}),
self.assertEqual(form_argv(actions["n"], name="carol", order="7", listeners="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", "x", "s", "i"])
self.assertEqual(form_argv(actions["n"], name="carol"), ["inbounds", "users", "add", "carol"])
self.assertEqual([a.key for a in model.applicable(users, bob)], ["n", "b", "s", "i"])
self.assertEqual(actions["s"].argv(bob), ["inbounds", "sub", "bob"])
# A URL to copy or encode only with subscriptions.baseUrl: else it is a file path.
with mock.patch.dict(os.environ, {"INBOUNDS_SUB_BASE_URL": "https://sub.example"}):
self.assertEqual([a.key for a in model.applicable(users, bob)], ["n", "b", "x", "s", "c", "Q", "i"])
self.assertEqual([a.key for a in model.applicable(users, bob)], ["n", "b", "s", "c", "Q", "i"])
self.assertEqual(actions["Q"].argv(bob), ["inbounds", "sub", "bob", "--qr"])
self.assertEqual(actions["e"].argv(alice, " 9 ", {}), ["inbounds", "users", "order", "alice", "9"])
self.assertEqual(actions["b"].argv(alice, "in", {}), ["inbounds", "bind", "alice", "in"])
self.assertEqual(form_argv(actions["e"], alice, order=" 9 "), ["inbounds", "users", "order", "alice", "9"])
# One action puts a user on its listeners: those it is on now to start from.
with mock.patch.object(ctl, "_inbound_runtime_rows", lambda kind: rows):
self.assertEqual(model.form_current(actions["b"], bob), {"listeners": ["in"]})
self.assertEqual(form_argv(actions["b"], bob, listeners=["in", "ws"]), ["inbounds", "users", "listeners", "bob", "in", "ws"])
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["n"].argv(None, "friends vless --port 20001", {}), ["inbounds", "add", "friends", "vless", "--port", "20001"])
self.assertEqual(form_argv(actions["n"], tag="friends", type="vless", port="20001"), ["inbounds", "add", "friends", "vless", "--port", "20001"])
# Every field a flag, users one --user each, server names one comma-separated flag, and the rest as typed.
self.assertEqual(
form_argv(actions["n"], tag="f", type="vless", reality=["a.example", "b.example"], users=["alice", "bob"], via="de", transport="ws", extra="--path '/a b'"),
["inbounds", "add", "f", "vless", "--reality", "a.example,b.example", "--user", "alice", "--user", "bob", "--via", "de", "--transport", "ws", "--path", "/a b"],
)
self.assertEqual(model.form_problem(actions["n"], {"tag": "f", "type": "ftp"}), "Type is one of: " + ", ".join(ctl.INBOUND_TYPES))
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"])
# And one puts users on a listener.
self.assertNotIn("x", {a.key for a in model.applicable(inbounds, row)})
with mock.patch.object(ctl, "_inbound_runtime_rows", lambda kind: [{"name": "alice", "listeners": ["friends"]}, {"name": "bob", "listeners": []}]):
self.assertEqual(model.form_current(actions["b"], row), {"users": ["alice"]})
self.assertEqual(form_argv(actions["b"], row, users=["bob"]), ["inbounds", "users", "on", "friends", "bob"])
def test_inbound_rows_carry_no_presence(self):
"""XRay keys the online map by user, not by inbound, so a per-listener row
@@ -215,9 +237,8 @@ class ModelTest(unittest.TestCase):
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"])
self.assertEqual(keys(home)["j"].argv(home, " abc-def ", {}), ["wl", "join", "home", "-"])
self.assertEqual(keys(home)["j"].stdin(home, " abc-def "), "abc-def")
self.assertEqual(form_argv(keys(vk)["a"], vk, path="/tmp/c.json"), ["wl", "auth", "vk", "/tmp/c.json"])
self.assertEqual(form(keys(home)["j"], home, link=" abc-def "), (["wl", "join", "home", "-"], "abc-def"))
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"])
@@ -284,8 +305,8 @@ class ModelTest(unittest.TestCase):
)
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["n"].argv(None, "example.com", {}), ["zapret", "auto", "add", "example.com"])
self.assertEqual(actions["X"].argv(None, "example.com", {}), ["zapret", "auto", "exclude", "example.com"])
self.assertEqual(form_argv(actions["n"], domain="example.com"), ["zapret", "auto", "add", "example.com"])
self.assertEqual(form_argv(actions["X"], domain="example.com"), ["zapret", "auto", "exclude", "example.com"])
def test_routing_tab(self):
"""Rules in match order, actions on the runtime ones only, and the mode as a selector."""
@@ -310,10 +331,32 @@ class ModelTest(unittest.TestCase):
self.assertEqual(by(off)["e"].argv(off, "", {}), ["proxy", "rules", "enable", "off"])
self.assertEqual(by(work)["e"].argv(work, "", {}), ["proxy", "rules", "disable", "work"])
self.assertEqual(by(work)["plus"].argv(work, "", {}), ["proxy", "rules", "priority", "work", "up"])
self.assertEqual(by(work)["a"].argv(work, "a.example 1.1.1.1", {}), ["proxy", "rules", "matches", "work", "add", "a.example", "1.1.1.1"])
self.assertEqual(by(work)["t"].argv(work, " proxy ", {}), ["proxy", "rules", "target", "work", "proxy"])
self.assertEqual(form_argv(by(work)["t"], work, target=" proxy "), ["proxy", "rules", "target", "work", "proxy"])
# One action edits the matches: it opens with what the rule has, runs only a change,
# and sends the whole list, so adding and taking out are one write.
edit = by(work)["a"]
self.assertNotIn("x", by(work))
rules = [{"name": "work", "domains": ["work.example"], "ips": ["10.0.0.0/8"], "geosites": ["netflix"]}]
with mock.patch.object(ctl, "_runtime_rules", lambda: rules):
current = model.form_current(edit, work)
self.assertEqual(current, {"matches": ["work.example", "10.0.0.0/8", "geosite:netflix"]})
self.assertEqual(model.form_start(edit, work, {"matches": ["stale"]}), current) # what is there, not what was typed
self.assertEqual(model.form_problem(edit, current, work), "Nothing changed yet")
self.assertEqual(form_argv(edit, work, matches=["work.example", "a.example"]), ["proxy", "rules", "matches", "work", "set", "work.example", "a.example"])
# All taken out is a change too.
self.assertEqual(form_argv(edit, work, matches=[]), ["proxy", "rules", "matches", "work", "set"])
self.assertEqual(
model.item_changes(["a", "b"], ["b", "c"]),
[("a", "removed"), ("b", "kept"), ("c", "added")],
)
self.assertTrue(by(work)["d"].confirm)
self.assertEqual(by(None)["n"].argv(None, "direct bank.example --name bank", {}), ["proxy", "rules", "add", "direct", "bank.example", "--name", "bank"])
add = by(None)["n"]
self.assertEqual(form_argv(add, target="direct", matches=" bank.example 10.0.0.0/8 ", name="bank"), ["proxy", "rules", "add", "direct", "bank.example", "10.0.0.0/8", "--name", "bank"])
self.assertEqual(form_argv(add, target="de", matches="a.test", priority="10"), ["proxy", "rules", "add", "de", "a.test", "--priority", "10"])
# What the form still needs, field by field; nothing runs until it has it.
self.assertEqual(list(model.form_problems(add, {"priority": "soon"})), [("target", "Target is needed"), ("matches", "Matches is needed"), ("priority", "Priority is a number")])
with self.assertRaisesRegex(ValueError, "Target is needed"):
form(add, matches="a.test")
# The mode: a selector over the table, not rows in it.
options, current = model.selector_state(tab)
self.assertEqual([v for v, _ in options], ["default", *ctl.ROUTE_MODES])
@@ -429,15 +472,16 @@ class ModelTest(unittest.TestCase):
# The Services tab's row for the instance toggles it through `awg` too.
self.assertEqual(model.toggle_argv({"unit": "proxy-suite-awg@added", "state": "active"}), ["awg", "off", "added"])
add = next(a for a in tab.actions if a.key == "n")
self.assertEqual((add.argv(None, "work vpn://AAAA", {}), add.stdin(None, "work vpn://AAAA")), (["awg", "add", "work", "-"], "vpn://AAAA"))
self.assertEqual((add.argv(None, "vpn://AAAA", {}), add.stdin(None, "vpn://AAAA")), (["awg", "add", "-"], "vpn://AAAA"))
self.assertEqual(form(add, name="work", source="vpn://AAAA"), (["awg", "add", "work", "-"], "vpn://AAAA"))
self.assertEqual(form(add, source="vpn://AAAA"), (["awg", "add", "-"], "vpn://AAAA"))
# A path goes as one: proxy-ctl reads it, and it may run as root elsewhere.
self.assertEqual((add.argv(None, "work /tmp/w.conf", {}), add.stdin(None, "work /tmp/w.conf")), (["awg", "add", "work", "/tmp/w.conf"], None))
self.assertEqual(form(add, name="work", source="/tmp/w.conf"), (["awg", "add", "work", "/tmp/w.conf"], None))
# A whole config, pasted into the field: on stdin.
conf = "[Interface]\nPrivateKey = k\n[Peer]\nPublicKey = p"
self.assertEqual(form(add, source=conf), (["awg", "add", "-"], conf))
outbound_add = next(a for a in next(t for t in model.TABS if t.id == "outbounds").actions if a.key == "n")
self.assertEqual(outbound_add.argv(None, "de vpn://AAAA", {}), ["proxy", "outbounds", "add", "de", "-"])
self.assertEqual(outbound_add.stdin(None, "de vpn://AAAA"), "vpn://AAAA")
self.assertEqual(outbound_add.argv(None, "de vless://x", {}), ["proxy", "outbounds", "add", "de", "-"])
self.assertEqual(outbound_add.stdin(None, "de vless://x"), "vless://x")
self.assertEqual(form(outbound_add, tag="de", source="vpn://AAAA"), (["proxy", "outbounds", "add", "de", "-"], "vpn://AAAA"))
self.assertEqual(form(outbound_add, tag="de", source="vless://x"), (["proxy", "outbounds", "add", "de", "-"], "vless://x"))
def test_popen_feeds_stdin(self):
with mock.patch.object(model, "CTL", "cat"):
@@ -469,13 +513,38 @@ class ModelTest(unittest.TestCase):
with mock.patch.object(ctl, "env", lambda name, default="": ""):
self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["p", "t", "ctrl+t", "T", "n", "g", "y", "plus", "minus", "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", "-", "--detour", "b"])
self.assertEqual(chain.stdin(rows[1], 'c {"type": "socks"}'), '{"type": "socks"}')
self.assertEqual(form(chain, rows[1], tag="c", source='{"type": "socks"}'), (["proxy", "outbounds", "add", "c", "-", "--detour", "b"], '{"type": "socks"}'))
through = next(a for a in tab.actions if a.key == "H")
self.assertEqual(form_argv(through, rows[0], hop="b"), ["proxy", "outbounds", "chain", "a", "b"])
self.assertEqual(form_argv(through, rows[0], hop="b", tag="a2"), ["proxy", "outbounds", "chain", "a", "b", "a2"])
# A group: members, subscriptions and patterns lists, a flag per value; the strategy from its list.
group = next(a for a in tab.actions if a.key == "g")
with mock.patch.object(ctl, "_outbound_inventory", lambda: inventory), mock.patch.object(ctl, "_outbound_groups", lambda: {}):
self.assertEqual(model.form_choices(group)["members"], {"a": "", "b": ""})
self.assertEqual(
form_argv(group, tag="g", members=["a", "b", "a"], subs=["work"], match=["de-*", "nl-*"], strategy="urltest", extra="--no-failback"),
["proxy", "groups", "add", "g", "a", "b", "--sub", "work", "--match", "de-*", "--match", "nl-*", "--strategy", "urltest", "--no-failback"],
)
# Its members edited in one go: those it names itself, not what its subscription pulls in,
# and never itself.
members = next(a for a in tab.actions if a.key == "m")
auto = {"tag": "auto", "group": True, "runtime": True}
groups = {"auto": {"members": ["a", "b", "sub-1"], "listed": ["a", "b"], "runtime": True}}
with mock.patch.object(ctl, "_outbound_inventory", lambda: {**inventory, "groups": groups}):
self.assertEqual(model.form_current(members, auto), {"members": ["a", "b"]})
self.assertNotIn("auto", model.form_choices(members, auto)["members"])
self.assertEqual(form_argv(members, auto, members=["b", "c"]), ["proxy", "groups", "members", "auto", "set", "b", "c"])
# An inventory from before `listed`: all of them.
with mock.patch.object(ctl, "_outbound_inventory", lambda: {**inventory, "groups": {"auto": {"members": ["a"]}}}):
self.assertEqual(model.form_current(members, auto), {"members": ["a"]})
self.assertEqual(model.form_problem(group, {"tag": "g", "strategy": "random"}), "Strategy is one of: failover, urltest, selector")
with self.assertRaisesRegex(ValueError, "No closing quotation"):
form(group, tag="g", extra="--match 'x")
# Probe exits go by the backend's tag.
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"])
self.assertEqual(form_argv(probe, rows[1], domain="example.com"), ["proxy", "auto", "probe", "example.com", "--via", "b-backend"])
broken = model.Tab("x", "X", model.ROW, [], lambda _: ctl.die("backend gone"))
self.assertEqual(model.load_tab(broken, {}), ([], "✗ backend gone"))
# outbounds.d is root-only: the inventory still says which are runtime, so they can be removed.
@@ -544,19 +613,32 @@ class ModelTest(unittest.TestCase):
with mock.patch.object(ctl, "_outbound_inventory", lambda: inventory):
self.assertEqual(model.tray_outbounds({"proxy": {"active": True}}), (["a"], ""))
def test_add_prompt_takes_an_optional_tag(self):
def test_add_form_takes_an_optional_tag(self):
subs = next(t for t in model.TABS if t.id == "subs")
add = next(a for a in subs.actions if a.key == "n")
self.assertIn("[tag]", add.prompt)
self.assertEqual([(f.name, f.optional) for f in add.fields], [("tag", True), ("source", False)])
# The URL, token and all, on stdin.
self.assertEqual((add.argv(None, "https://x.test/s", {}), add.stdin(None, "https://x.test/s")), (["proxy", "subs", "add", "-"], "https://x.test/s"))
self.assertEqual((add.argv(None, " work https://x.test/s ", {}), add.stdin(None, " work https://x.test/s ")), (["proxy", "subs", "add", "work", "-"], "https://x.test/s"))
# Only a tag: proxy-ctl says what is missing.
self.assertEqual((add.argv(None, "work", {}), add.stdin(None, "work")), (["proxy", "subs", "add", "work"], None))
self.assertEqual(form(add, source="https://x.test/s"), (["proxy", "subs", "add", "-"], "https://x.test/s"))
self.assertEqual(form(add, tag=" work ", source=" https://x.test/s "), (["proxy", "subs", "add", "work", "-"], "https://x.test/s"))
# Only a tag: the form says what is missing, and nothing runs.
self.assertEqual(model.form_problem(add, {"tag": "work"}), "URL is needed")
outbounds = next(t for t in model.TABS if t.id == "outbounds")
add = next(a for a in outbounds.actions if a.key == "n")
# JSON has spaces in it: all of it on stdin.
self.assertEqual((add.argv(None, '{"type": "socks"}', {}), add.stdin(None, '{"type": "socks"}')), (["proxy", "outbounds", "add", "-"], '{"type": "socks"}'))
self.assertEqual(form(add, source='{"type": "socks"}'), (["proxy", "outbounds", "add", "-"], '{"type": "socks"}'))
def test_every_form_opens(self):
"""Every action that asks: fields named once, its choices readable or empty when state is not,
and an empty form says what it needs rather than running."""
actions = [a for t in model.TABS for a in t.actions if a.fields] + [model.WHERE]
with mock.patch.object(ctl, "env", lambda name, default="": default):
for action in actions:
names = [f.name for f in action.fields]
self.assertEqual(len(names), len(set(names)), action.label)
choices = model.form_choices(action, {"name": "x", "tag": "x", "profile": "x", "unit": "x"})
self.assertTrue(all(isinstance(c, dict) for c in choices.values()), action.label)
if any(not f.optional for f in action.fields):
self.assertNotEqual(model.form_problem(action, {}), "", action.label)
def test_shown_commands_hide_credentials(self):
argv = ["proxy", "outbounds", "add", "de", "vless://uuid-1@de.test:443?security=reality&pbk=K&sid=S#DE"]
+55 -5
View File
@@ -300,7 +300,7 @@ class TuiTest(unittest.TestCase):
await pilot.press("enter")
await pilot.pause()
self.assertIsInstance(app.screen, tui.Menu)
self.assertEqual(self.menu_labels(app)[:2], ["add a rule…", "add domains or addresses to it…"])
self.assertEqual(self.menu_labels(app)[:2], ["add a rule…", "edit its domains and addresses…"])
await pilot.press("escape")
await pilot.pause()
await pilot.press("minus")
@@ -319,6 +319,48 @@ class TuiTest(unittest.TestCase):
app.action_choose("default") # already: nothing runs
self.assertEqual(self.ran, [])
# n: a form, one box per field. Enter with the target missing stays, on the target.
await pilot.press("n")
await pilot.pause()
self.assertIsInstance(app.screen, tui.Form)
self.assertEqual(app.focused.id, "field-target")
self.assertIn("✗ Target is needed; Matches is needed", str(app.screen.query_one(".preview").content))
await pilot.press("tab", "enter")
await pilot.pause()
self.assertIsInstance(app.screen, tui.Form)
self.assertEqual((app.focused.id, self.ran), ("field-target", []))
# → takes the suggestion. Matches are a list: enter adds what is typed, a value a line,
# and what is typed but not added yet counts too. A priority takes digits only;
# the preview is the command.
await pilot.press(*"dir", "right", "tab", *"a.test b.test", "enter", *"c.test")
await pilot.pause()
listed = app.screen.query_one("#field-matches .item-list")
self.assertEqual([str(listed.get_option_at_index(i).prompt).strip() for i in range(listed.option_count)], ["a.test", "b.test"])
# Down into the list, enter takes b.test out; tab on to the name, then the priority.
await pilot.press("tab", "down", "enter", "tab", "tab", *"x1x0")
await pilot.pause()
self.assertEqual(app.screen.query_one("#field-matches").value, ["a.test", "c.test"])
self.assertEqual(app.screen.query_one("#field-priority").value, "10")
self.assertIn("proxy-ctl proxy rules add direct a.test c.test --priority 10", str(app.screen.query_one(".preview").content))
await pilot.press("enter")
await pilot.pause()
self.assertEqual(self.ran.pop(), ["proxy", "rules", "add", "direct", "a.test", "c.test", "--priority", "10"])
# One action edits a rule's matches: it opens with what the rule has, marks what
# changes, and runs nothing until something does.
await pilot.press("a")
await pilot.pause()
self.assertIsInstance(app.screen, tui.Form)
await pilot.press("ctrl+s")
await pilot.pause()
self.assertIn("Nothing changed yet", str(app.screen.query_one(".preview").content))
await pilot.press(*"d.test", "enter", "tab", "enter")
await pilot.pause()
listed = app.screen.query_one("#field-matches .item-list")
self.assertEqual([str(listed.get_option_at_index(i).prompt) for i in range(listed.option_count)], ["− bank.example", "+ d.test"])
await pilot.press("ctrl+s")
await pilot.pause()
self.assertEqual(self.ran.pop(), ["proxy", "rules", "matches", "bank", "set", "d.test"])
# 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)
@@ -345,15 +387,23 @@ class TuiTest(unittest.TestCase):
self.assertEqual(app.screen.query_one(tui.Choices).highlighted, 1)
await pilot.press("escape")
# Prompts: add takes "<tag> <url>", the URL on stdin.
await pilot.press("n", *"x vless://h", "enter")
# Add takes a tag and a link, the link on stdin.
await pilot.press("n", "x", "tab", *"vless://h", "enter")
await pilot.pause()
self.assertEqual(self.ran.pop(), (["proxy", "outbounds", "add", "x", "-"], "vless://h"))
# A prompt remembers what was typed into it last.
# A form remembers what was typed into it last.
await pilot.press("n")
await pilot.pause()
self.assertEqual(app.screen.query_one(tui.Input).value, "x vless://h")
self.assertEqual([i.value for i in app.screen.query(tui.Input)], ["x", "vless://h"])
await pilot.press("escape")
await pilot.pause()
# A group: members complete word by word, the strategy is picked from a list.
await pilot.press("g", *"auto", "tab", "a", "right", "tab", "tab", "tab")
await pilot.pause()
self.assertEqual((app.focused.id, app.screen.query_one("#field-members").value), ("field-strategy", ["a"]))
await pilot.press("enter", "down", "down", "enter", "ctrl+s")
await pilot.pause()
self.assertEqual(self.ran.pop(), ["proxy", "groups", "add", "auto", "a", "--strategy", "urltest"])
# An empty tab says how to fill it.
await pilot.press("5")