1827 lines
84 KiB
Python
1827 lines
84 KiB
Python
"""proxy-suite-gui: a desktop app, with a tray icon, for everything proxy-tui does.
|
|
|
|
What it shows and does lives in proxy_model, shared with proxy-tui; this is GTK drawing.
|
|
Reads run on a worker thread; every change runs proxy-ctl, as in the TUI.
|
|
"""
|
|
|
|
import os
|
|
import re
|
|
import signal
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
|
|
import gi
|
|
|
|
gi.require_version("Gtk", "4.0")
|
|
gi.require_version("Gdk", "4.0")
|
|
gi.require_version("Adw", "1")
|
|
from gi.repository import Adw, Gdk, Gio, GLib, GObject, Gtk, Pango # noqa: E402
|
|
|
|
import proxy_model as model # noqa: E402
|
|
from proxy_model import STATE_ICONS, TABS, ctl # noqa: E402
|
|
|
|
APP_ID = "io.github.FUFSoB.ProxySuite"
|
|
TITLE = "Proxy Suite"
|
|
ICON_DIR = os.environ.get("PROXY_GUI_ICON_DIR") or os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons")
|
|
|
|
|
|
def refresh_seconds():
|
|
try:
|
|
return max(1, int(os.environ.get("PROXY_GUI_REFRESH", "3")))
|
|
except ValueError:
|
|
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"],
|
|
"bad": ["error"],
|
|
"★": ["warning", "heading"],
|
|
"▸": ["success", "heading"],
|
|
"●": ["success", "heading"],
|
|
"runtime": ["accent"],
|
|
"pinned": ["accent"],
|
|
"excluded": ["dim-label"],
|
|
"✕": ["dim-label"],
|
|
"disabled": ["dim-label"],
|
|
"queued": ["warning"],
|
|
}
|
|
TAB_ICONS = {
|
|
"services": "system-run-symbolic",
|
|
"routing": "go-jump-symbolic",
|
|
"outbounds": "network-server-symbolic",
|
|
"subs": "folder-download-symbolic",
|
|
"autoproxy": "web-browser-symbolic",
|
|
"zapret": "channel-secure-symbolic",
|
|
"inbounds": "preferences-system-sharing-symbolic",
|
|
"apps": "view-app-grid-symbolic",
|
|
}
|
|
STATUS_ICONS = {"ok": "emblem-ok-symbolic", "warn": "dialog-warning-symbolic", "bad": "dialog-error-symbolic", "": "network-wired-symbolic"}
|
|
TOAST_LINES = 4 # a toast says this much of what ran; the Output button, and `o`, have the whole of it
|
|
|
|
GLOBAL_SHORTCUTS = [
|
|
("<Control>f slash", "Filter the rows, e.g. list:learned"),
|
|
("Escape", "Clear the filter"),
|
|
("Menu <Shift>F10", "Actions for the selected row; a right-click opens them too"),
|
|
("<Alt>1...<Alt>8", "Jump to a tab"),
|
|
("<Control>v", "Paste a link: it is added to this tab"),
|
|
("w", "How is a domain routed"),
|
|
("<Shift>l", "Follow all logs"),
|
|
("o", "Output of the last command"),
|
|
("<Control>e", "Read and run as root"),
|
|
("F5 r", "Refresh now"),
|
|
("<Control>question", "Keyboard shortcuts"),
|
|
("<Control>w", "Close the window; the tray keeps running"),
|
|
("<Control>q", "Quit"),
|
|
]
|
|
|
|
CSS = """
|
|
.status-strip { padding: 2px 12px 10px 12px; }
|
|
.status-chip {
|
|
padding: 3px 10px;
|
|
border-radius: 999px;
|
|
background-color: alpha(currentColor, 0.07);
|
|
font-feature-settings: "tnum";
|
|
}
|
|
.status-chip .chip-label { opacity: 0.65; }
|
|
.status-chip .chip-value { font-weight: 600; }
|
|
.status-chip.ok { background-color: color-mix(in srgb, var(--success-bg-color) 18%, transparent); color: var(--success-color); }
|
|
.status-chip.warn { background-color: color-mix(in srgb, var(--warning-bg-color) 22%, transparent); color: var(--warning-color); }
|
|
.status-chip.bad { background-color: color-mix(in srgb, var(--error-bg-color) 18%, transparent); color: var(--error-color); }
|
|
.status-chip.ok .chip-label, .status-chip.warn .chip-label, .status-chip.bad .chip-label { opacity: 0.8; }
|
|
|
|
.summary { padding: 8px 14px 0 14px; }
|
|
.selector-bar { padding: 8px 14px 0 14px; }
|
|
.filter-bar { padding: 8px 12px; }
|
|
.row-count { font-feature-settings: "tnum"; }
|
|
|
|
.table-card {
|
|
margin: 0 12px 12px 12px;
|
|
border-radius: 12px;
|
|
border: 1px solid var(--border-color);
|
|
background-color: var(--view-bg-color);
|
|
}
|
|
.table-card > scrolledwindow { border-radius: 12px; }
|
|
columnview.data-table { background-color: transparent; }
|
|
columnview.data-table > header > button {
|
|
padding: 8px 10px;
|
|
font-size: 0.85em;
|
|
font-weight: 600;
|
|
color: alpha(currentColor, 0.6);
|
|
background-color: alpha(currentColor, 0.03);
|
|
}
|
|
columnview.data-table > listview > row { min-height: 34px; border-color: alpha(currentColor, 0.06); }
|
|
columnview.data-table > listview > row > cell { padding: 0 10px; }
|
|
columnview.data-table > listview > row:hover { background-color: alpha(currentColor, 0.04); }
|
|
columnview.data-table > listview > row:selected { background-color: alpha(var(--accent-bg-color), 0.2); }
|
|
columnview.data-table > listview > row:selected:hover { background-color: alpha(var(--accent-bg-color), 0.26); }
|
|
columnview.data-table > listview > row:selected > cell:first-child label { color: var(--accent-color); font-weight: 600; }
|
|
|
|
.badge {
|
|
padding: 1px 8px;
|
|
border-radius: 999px;
|
|
font-size: 0.9em;
|
|
font-weight: 600;
|
|
background-color: alpha(currentColor, 0.08);
|
|
}
|
|
.badge.success { background-color: color-mix(in srgb, var(--success-bg-color) 18%, transparent); }
|
|
.badge.warning { background-color: color-mix(in srgb, var(--warning-bg-color) 22%, transparent); }
|
|
.badge.error { background-color: color-mix(in srgb, var(--error-bg-color) 18%, transparent); }
|
|
.badge.accent { background-color: alpha(var(--accent-bg-color), 0.16); }
|
|
.badge.dim-label { opacity: 0.7; }
|
|
|
|
.keycap {
|
|
padding: 0 6px;
|
|
min-width: 12px;
|
|
border-radius: 5px;
|
|
border: 1px solid var(--border-color);
|
|
border-bottom-width: 2px;
|
|
font-family: monospace;
|
|
font-size: 0.85em;
|
|
color: alpha(currentColor, 0.7);
|
|
background-color: alpha(currentColor, 0.04);
|
|
}
|
|
|
|
.detail { padding: 18px; }
|
|
.detail-title { margin-bottom: 2px; }
|
|
.detail .primary-action { margin-top: 4px; }
|
|
.detail .no-actions { margin-top: 12px; }
|
|
.empty-actions button { min-width: 240px; }
|
|
/* Some themes only lift a hovered button with a shadow, which a dark background hides. */
|
|
button.pill:hover { background-image: image(alpha(currentColor, 0.08)); }
|
|
button.pill:active { background-image: image(alpha(currentColor, 0.16)); }
|
|
|
|
.output-card {
|
|
margin: 0 12px 12px 12px;
|
|
border-radius: 12px;
|
|
border: 1px solid var(--border-color);
|
|
background-color: var(--view-bg-color);
|
|
}
|
|
.output-card > textview, .output-view { background-color: transparent; }
|
|
.output-view { font-family: monospace; padding: 12px; }
|
|
.qr { background: white; padding: 12px; border-radius: 12px; }
|
|
"""
|
|
|
|
|
|
def accelerator(key):
|
|
"""A TUI key name as a GTK accelerator: space, ctrl+r, R (shift+r), l."""
|
|
parts = key.split("+")
|
|
mods = "".join({"ctrl": "<Control>", "alt": "<Alt>", "shift": "<Shift>"}[m] for m in parts[:-1])
|
|
name = parts[-1]
|
|
if len(name) == 1 and name.isupper():
|
|
mods, name = mods + "<Shift>", name.lower()
|
|
return mods + name
|
|
|
|
|
|
def display_key(key):
|
|
"""Ctrl+r, Shift+n, Space: modifiers and named keys capitalized, a letter as it is typed."""
|
|
return "+".join(part.capitalize() if len(part) > 1 else part for part in model.display_key(key).split("+"))
|
|
|
|
|
|
SGR = re.compile(r"\x1b\[([0-9;]*)m")
|
|
ANY_ESCAPE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]")
|
|
SGR_TAGS = {"1": "bold", "2": "dim", "31": "red", "91": "red", "32": "green", "92": "green", "33": "yellow", "93": "yellow", "36": "cyan", "96": "cyan", "35": "magenta", "34": "blue"}
|
|
|
|
|
|
def ansi_segments(line):
|
|
"""(text, tags) runs of a line with SGR colors; other escapes dropped."""
|
|
tags, pos, out = set(), 0, []
|
|
for m in SGR.finditer(line):
|
|
if m.start() > pos:
|
|
out.append((ANY_ESCAPE.sub("", line[pos:m.start()]), tuple(sorted(tags))))
|
|
for code in (m.group(1) or "0").split(";"):
|
|
if code in ("0", ""):
|
|
tags.clear()
|
|
elif code in ("22",):
|
|
tags -= {"bold", "dim"}
|
|
elif code == "39":
|
|
tags -= {"red", "green", "yellow", "cyan", "magenta", "blue"}
|
|
elif code in SGR_TAGS:
|
|
tags.add(SGR_TAGS[code])
|
|
pos = m.end()
|
|
if pos < len(line):
|
|
out.append((ANY_ESCAPE.sub("", line[pos:]), tuple(sorted(tags))))
|
|
return out
|
|
|
|
|
|
# (light, dark) foregrounds from the GNOME palette: the dark-theme ones stay readable on a dark view.
|
|
ANSI_COLORS = {
|
|
"red": ("#c01c28", "#ff7b63"),
|
|
"green": ("#26a269", "#8ff0a4"),
|
|
"yellow": ("#9c6e03", "#f8e45c"),
|
|
"cyan": ("#1a5fb4", "#99c1f1"),
|
|
"magenta": ("#813d9c", "#dc8add"),
|
|
"blue": ("#1c71d8", "#62a0ea"),
|
|
}
|
|
|
|
|
|
def rgba(color):
|
|
value = Gdk.RGBA()
|
|
value.parse(color)
|
|
return value
|
|
|
|
|
|
def plain(line):
|
|
return "".join(t for t, _ in ansi_segments(line))
|
|
|
|
|
|
# Failed state reads in a row before the tray says "Status unavailable" (one every 3 s).
|
|
STALE_READS_UNKNOWN = 3
|
|
|
|
|
|
def last_line(lines):
|
|
return next((plain(line).strip() for line in reversed(lines) if plain(line).strip()), "")
|
|
|
|
|
|
# --- rows -------------------------------------------------------------------------
|
|
|
|
|
|
class RowItem(GObject.Object):
|
|
__gtype_name__ = "ProxySuiteRow"
|
|
version = GObject.Property(type=int, default=0)
|
|
|
|
def __init__(self, row):
|
|
super().__init__()
|
|
self.row = row
|
|
|
|
def set_row(self, row):
|
|
if row != self.row:
|
|
self.row = row
|
|
self.version += 1
|
|
return True
|
|
return False
|
|
|
|
|
|
def cell_text(name, value):
|
|
value = "" if value is None else str(value)
|
|
if name == "state":
|
|
return f"{STATE_ICONS.get(value, '?')} {value}", STATE_CLASSES.get(value, [])
|
|
return value, CELL_CLASSES.get(value, [])
|
|
|
|
|
|
BADGE_VALUES = {"ok", "bad", "runtime", "pinned", "excluded", "disabled", "queued"}
|
|
|
|
|
|
def is_badge(name, value):
|
|
"""Statuses draw as a tinted pill; markers like ★ stay plain text."""
|
|
return (name == "state" and bool(value)) or str(value) in BADGE_VALUES
|
|
|
|
|
|
def cap(text):
|
|
return text[:1].upper() + text[1:]
|
|
|
|
|
|
def is_destructive(action):
|
|
"""Red only for what loses data; stopping or restarting asks first, but stays calm."""
|
|
return action.mode == "run" and action.label.startswith(("remove", "forget"))
|
|
|
|
|
|
def action_icon(action):
|
|
label = action.label.lower()
|
|
if action.fields:
|
|
return "document-edit-symbolic"
|
|
if "qr" in label:
|
|
return "view-grid-symbolic"
|
|
return {
|
|
"copy": "edit-copy-symbolic",
|
|
"suspend": "format-justify-left-symbolic",
|
|
"pause": "utilities-terminal-symbolic",
|
|
"dialog": "utilities-terminal-symbolic",
|
|
}.get(action.mode, "media-playback-start-symbolic")
|
|
|
|
|
|
def keycap(key):
|
|
return Gtk.Label(label=display_key(key), css_classes=["keycap"], valign=Gtk.Align.CENTER)
|
|
|
|
|
|
class Page(Gtk.Box):
|
|
"""One tab: summary, filter, table, and the selected row's detail with its actions."""
|
|
|
|
def __init__(self, win, tab):
|
|
super().__init__(orientation=Gtk.Orientation.VERTICAL)
|
|
self.win, self.tab = win, tab
|
|
self.rows = [] # the last load, unfiltered
|
|
self.collapsed = set() # a tree tab's groups folded away, by row key
|
|
self.summary_text = ""
|
|
self.detail_shape = None
|
|
self.loaded = False # whether a load has landed here: before that the tab is not empty, it is unread
|
|
|
|
self.summary = Gtk.Label(xalign=0, wrap=True, selectable=True, visible=False, css_classes=["summary", "dim-label"])
|
|
|
|
# The tab's one choice apart from its rows (Routing: the mode), above everything else, so
|
|
# it is there whatever the rows are.
|
|
self.selector_values = []
|
|
self.selector_setting = False
|
|
self.selector_drop = None
|
|
if tab.selector:
|
|
self.selector_drop = Gtk.DropDown(model=Gtk.StringList(), valign=Gtk.Align.CENTER, tooltip_text=f"Shortcut: {display_key(tab.selector.key)}")
|
|
self.selector_drop.connect("notify::selected", self.on_selector_changed)
|
|
label = Gtk.Label(label=tab.selector.label, css_classes=["heading"], mnemonic_widget=self.selector_drop)
|
|
self.selector_bar = Gtk.Box(spacing=12, css_classes=["selector-bar"], visible=False)
|
|
self.selector_bar.append(label)
|
|
self.selector_bar.append(self.selector_drop)
|
|
self.append(self.selector_bar)
|
|
|
|
self.search = Gtk.SearchEntry(placeholder_text="Filter: words in any column, or column:value", hexpand=True)
|
|
self.search.connect("search-changed", lambda _: self.refill())
|
|
self.search.connect("stop-search", self.on_stop_search)
|
|
self.count = Gtk.Label(css_classes=["dim-label", "caption", "row-count"])
|
|
self.filter_bar = Gtk.Box(spacing=12, css_classes=["filter-bar"])
|
|
self.filter_bar.append(self.search)
|
|
self.filter_bar.append(self.count)
|
|
|
|
self.store = Gio.ListStore(item_type=RowItem)
|
|
self.view = Gtk.ColumnView(css_classes=["data-table"], show_row_separators=True, reorderable=False)
|
|
self.sorted = Gtk.SortListModel(model=self.store, sorter=self.view.get_sorter())
|
|
self.selection = Gtk.SingleSelection(model=self.sorted, autoselect=True, can_unselect=False)
|
|
self.selection.connect("notify::selected-item", lambda *_: self.selection_changed())
|
|
self.view.set_model(self.selection)
|
|
self.sorters = []
|
|
for i, (name, heading) in enumerate(tab.columns):
|
|
factory = Gtk.SignalListItemFactory()
|
|
factory.connect("setup", self.cell_setup)
|
|
factory.connect("bind", self.cell_bind, name)
|
|
factory.connect("unbind", self.cell_unbind)
|
|
column = Gtk.ColumnViewColumn(title=heading, factory=factory, resizable=True)
|
|
column.set_expand(i == len(tab.columns) - 1)
|
|
sorter = Gtk.CustomSorter.new(lambda a, b, name: self.compare(a, b, name), name)
|
|
self.sorters.append(sorter)
|
|
# A tree keeps its order: it is the order its groups pick in.
|
|
if not tab.tree:
|
|
column.set_sorter(sorter)
|
|
self.view.append_column(column)
|
|
self.view.connect("activate", lambda view, pos: self.open_menu(None))
|
|
|
|
click = Gtk.GestureClick(button=Gdk.BUTTON_SECONDARY)
|
|
click.connect("pressed", self.on_right_click)
|
|
self.view.add_controller(click)
|
|
# On the window, so keys work wherever focus is: an empty tab has no table to focus.
|
|
win.add_controller(self.shortcuts())
|
|
|
|
scroller = Gtk.ScrolledWindow(child=self.view, vexpand=True, hexpand=True, overflow=Gtk.Overflow.HIDDEN)
|
|
table = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, css_classes=["table-card"], overflow=Gtk.Overflow.HIDDEN)
|
|
table.append(scroller)
|
|
content = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
|
|
content.append(self.summary)
|
|
content.append(self.filter_bar)
|
|
content.append(table)
|
|
self.detail = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=18, css_classes=["detail"])
|
|
detail_scroller = Gtk.ScrolledWindow(child=self.detail, hscrollbar_policy=Gtk.PolicyType.NEVER)
|
|
self.split = Adw.OverlaySplitView(
|
|
content=content, sidebar=detail_scroller, sidebar_position=Gtk.PackType.END, show_sidebar=True,
|
|
min_sidebar_width=280, max_sidebar_width=440, sidebar_width_fraction=0.36,
|
|
)
|
|
self.split.set_vexpand(True)
|
|
self.append(self.split)
|
|
self.tab_icon = TAB_ICONS.get(tab.id, "view-list-symbolic")
|
|
self.empty = Adw.StatusPage(title="Nothing here yet", icon_name=self.tab_icon, visible=False, vexpand=True)
|
|
self.empty.set_child(self.tab_actions_box())
|
|
self.append(self.empty)
|
|
# Until this tab has loaded once there is nothing to keep on screen: say it is coming,
|
|
# rather than claim the tab is empty.
|
|
self.loading = Adw.StatusPage(title="Loading…", visible=True, vexpand=True)
|
|
self.loading.set_child(Adw.Spinner(width_request=32, height_request=32, halign=Gtk.Align.CENTER))
|
|
self.append(self.loading)
|
|
self.split.set_visible(False)
|
|
self.popover = None
|
|
|
|
# --- cells ---------------------------------------------------------------------
|
|
|
|
def cell_setup(self, factory, item):
|
|
item.set_child(Gtk.Label(xalign=0, ellipsize=Pango.EllipsizeMode.END, valign=Gtk.Align.CENTER))
|
|
|
|
def cell_bind(self, factory, item, name):
|
|
label, row = item.get_child(), item.get_item()
|
|
|
|
def paint(*_):
|
|
value = row.row.get(name)
|
|
text, classes = cell_text(name, value)
|
|
badge = bool(text) and is_badge(name, value)
|
|
label.set_text(text)
|
|
label.set_tooltip_text(text if len(text) > 30 else None)
|
|
label.set_css_classes(["badge", *classes] if badge else classes)
|
|
label.set_halign(Gtk.Align.START if badge else Gtk.Align.FILL)
|
|
|
|
paint()
|
|
label._handler = (row, row.connect("notify::version", paint))
|
|
|
|
def cell_unbind(self, factory, item):
|
|
label = item.get_child()
|
|
if getattr(label, "_handler", None):
|
|
row, handler = label._handler
|
|
row.disconnect(handler)
|
|
label._handler = None
|
|
|
|
def compare(self, a, b, name):
|
|
# Text and digit runs alternate in the same places, so the lists always compare.
|
|
ka, kb = model._natural(a.row.get(name)), model._natural(b.row.get(name))
|
|
return (ka > kb) - (ka < kb)
|
|
|
|
# --- keys -------------------------------------------------------------------------
|
|
|
|
def shortcuts(self):
|
|
controller = Gtk.ShortcutController(propagation_phase=Gtk.PropagationPhase.CAPTURE)
|
|
for trigger, indices in self.triggers().items():
|
|
controller.add_shortcut(Gtk.Shortcut(
|
|
trigger=Gtk.ShortcutTrigger.parse_string(trigger),
|
|
action=Gtk.CallbackAction.new(self.keyed(trigger, lambda indices=indices: self.act_any(indices))),
|
|
))
|
|
for trigger, callback in (
|
|
("slash", lambda *_: self.focus_search()),
|
|
("w", lambda *_: self.win.where()),
|
|
("<Shift>l", lambda *_: self.win.follow_logs()),
|
|
("o", lambda *_: self.win.show_last_output()),
|
|
("r", lambda *_: self.win.app.reload(fresh_root=True)),
|
|
("Menu|<Shift>F10", lambda *_: self.open_menu(None)),
|
|
*([(accelerator(self.tab.selector.key), lambda *_: self.open_selector())] if self.tab.selector else []),
|
|
):
|
|
if trigger not in self.triggers():
|
|
controller.add_shortcut(Gtk.Shortcut(trigger=Gtk.ShortcutTrigger.parse_string(trigger), action=Gtk.CallbackAction.new(self.keyed(trigger, callback))))
|
|
return controller
|
|
|
|
def triggers(self):
|
|
"""Accelerator -> indices of the tab's actions on it: a toggle is two actions on one key."""
|
|
out = {}
|
|
for i, action in enumerate(self.tab.actions):
|
|
out.setdefault(accelerator(action.key), []).append(i)
|
|
return out
|
|
|
|
def act_any(self, indices):
|
|
"""The first of these actions that applies to the selected row; none: the key falls through."""
|
|
return any(self.act(i, from_key=True) for i in indices)
|
|
|
|
def keyed(self, trigger, callback):
|
|
"""A key for this tab only while it shows, and never one meant for a text field, a dialog or a focused button."""
|
|
def run(*_):
|
|
if self.win.page() is not self or self.win.get_visible_dialog() is not None:
|
|
return False
|
|
focus = self.win.get_focus()
|
|
if isinstance(focus, Gtk.Editable):
|
|
return False
|
|
if trigger in ("space", "Return") and not (focus is self.view or (focus and focus.is_ancestor(self.view))):
|
|
return False
|
|
return callback() is not False
|
|
return run
|
|
|
|
def focus_default(self):
|
|
if self.split.get_visible():
|
|
self.view.grab_focus()
|
|
else:
|
|
self.empty.child_focus(Gtk.DirectionType.TAB_FORWARD)
|
|
|
|
def focus_search(self):
|
|
return self.search.get_mapped() and self.search.grab_focus()
|
|
|
|
def on_stop_search(self, entry):
|
|
entry.set_text("")
|
|
self.view.grab_focus()
|
|
|
|
# --- filling ------------------------------------------------------------------------
|
|
|
|
def fill(self, rows, summary, selector=None):
|
|
self.rows, self.summary_text, self.loaded = rows, summary, True
|
|
self.fill_selector(selector)
|
|
self.refill()
|
|
|
|
def fill_selector(self, state):
|
|
"""The selector as read: its options and the current one, set without running anything."""
|
|
if self.selector_drop is None:
|
|
return
|
|
self.selector_bar.set_visible(state is not None)
|
|
if state is None:
|
|
return
|
|
options, current = state
|
|
values = [v for v, _ in options]
|
|
self.selector_setting = True
|
|
try:
|
|
if values != self.selector_values:
|
|
self.selector_values = values
|
|
self.selector_drop.set_model(Gtk.StringList.new([label for _, label in options]))
|
|
if current in values and self.selector_drop.get_selected() != values.index(current):
|
|
self.selector_drop.set_selected(values.index(current))
|
|
finally:
|
|
self.selector_setting = False
|
|
|
|
def on_selector_changed(self, drop, _):
|
|
index = drop.get_selected()
|
|
if self.selector_setting or not 0 <= index < len(self.selector_values):
|
|
return
|
|
argv = model.selector_argv(self.tab, self.selector_values[index])
|
|
if argv:
|
|
self.win.app.run_argv("run", argv, self.win)
|
|
|
|
def open_selector(self):
|
|
if self.selector_drop is None or not self.selector_bar.get_visible():
|
|
return False
|
|
self.selector_drop.grab_focus()
|
|
return self.selector_drop.activate()
|
|
|
|
def refill(self):
|
|
rows, summary = self.rows, self.summary_text
|
|
if text := self.search.get_text().strip():
|
|
rows = model.filter_rows(rows, self.tab.columns, text)
|
|
self.count.set_text(f"{len(rows)} of {len(self.rows)}")
|
|
else:
|
|
if self.tab.tree:
|
|
rows = model.fold_rows(rows, self.collapsed)
|
|
self.count.set_text(f"{len(rows)} row{'' if len(rows) == 1 else 's'}")
|
|
self.summary.set_text(summary)
|
|
keys = [r["key"] for r in rows]
|
|
current = [self.store.get_item(i).row["key"] for i in range(self.store.get_n_items())]
|
|
if keys == current:
|
|
# The same rows: cells repaint themselves, so selection and scroll stay put.
|
|
changed = False
|
|
for i, r in enumerate(rows):
|
|
changed |= self.store.get_item(i).set_row(r)
|
|
if changed:
|
|
for sorter in self.sorters:
|
|
sorter.changed(Gtk.SorterChange.DIFFERENT)
|
|
else:
|
|
selected = self.selected_key()
|
|
self.store.splice(0, self.store.get_n_items(), [RowItem(r) for r in rows])
|
|
if selected in keys:
|
|
for pos in range(self.sorted.get_n_items()):
|
|
if self.sorted.get_item(pos).row["key"] == selected:
|
|
self.selection.set_selected(pos)
|
|
break
|
|
empty = not self.rows and not text
|
|
loading = empty and not self.loaded
|
|
self.split.set_visible(not empty)
|
|
self.empty.set_visible(empty and not loading)
|
|
self.loading.set_visible(loading)
|
|
self.summary.set_visible(bool(summary) and not empty)
|
|
if empty and not loading:
|
|
unreadable = summary.startswith("✗")
|
|
self.empty.set_title("Cannot read this" if unreadable else "Nothing here yet")
|
|
self.empty.set_icon_name("dialog-error-symbolic" if unreadable else self.tab_icon)
|
|
self.empty.set_description(GLib.markup_escape_text(summary.removeprefix("Nothing here yet.").strip()))
|
|
if self.win.page() is self:
|
|
self.win.sync_details_toggle()
|
|
self.selection_changed()
|
|
|
|
def selected_row(self):
|
|
item = self.selection.get_selected_item()
|
|
return item.row if item else None
|
|
|
|
def selected_key(self):
|
|
row = self.selected_row()
|
|
return row["key"] if row else None
|
|
|
|
# --- detail and actions -----------------------------------------------------------------
|
|
|
|
def tab_actions_box(self):
|
|
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12, halign=Gtk.Align.CENTER, css_classes=["empty-actions"])
|
|
for n, action in enumerate(model.applicable(self.tab, None)):
|
|
box.append(self.action_button(self.tab.actions.index(action), action, suggested=n == 0))
|
|
return box
|
|
|
|
def action_button(self, i, action, suggested=False):
|
|
content = Adw.ButtonContent(icon_name=action_icon(action), label=cap(action.label))
|
|
button = Gtk.Button(child=content, css_classes=["pill"], tooltip_text=f"Shortcut: {display_key(action.key)}")
|
|
if is_destructive(action):
|
|
button.add_css_class("destructive-action")
|
|
elif suggested:
|
|
button.add_css_class("suggested-action")
|
|
button.connect("clicked", lambda *_: self.act(i))
|
|
return button
|
|
|
|
def action_row(self, i, action):
|
|
item = Adw.ActionRow(title=cap(action.label), use_markup=False, activatable=True)
|
|
item.add_prefix(Gtk.Image(icon_name=action_icon(action)))
|
|
if action.key:
|
|
item.add_suffix(keycap(action.key))
|
|
if is_destructive(action):
|
|
item.add_css_class("error")
|
|
item.connect("activated", lambda *_: self.act(i))
|
|
return item
|
|
|
|
def selection_changed(self):
|
|
row = self.selected_row()
|
|
actions = model.applicable(self.tab, row)
|
|
shape = (repr(row), [a.label for a in actions])
|
|
if shape == self.detail_shape:
|
|
return
|
|
self.detail_shape = shape
|
|
while child := self.detail.get_first_child():
|
|
self.detail.remove(child)
|
|
row_actions = [a for a in actions if a.when is not None]
|
|
tab_actions = [a for a in actions if a.when is None]
|
|
if row:
|
|
header = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
|
|
header.append(Gtk.Label(label=row["key"], xalign=0, wrap=True, wrap_mode=Pango.WrapMode.WORD_CHAR, selectable=True, css_classes=["title-3", "detail-title"]))
|
|
if row.get("state"):
|
|
text, classes = cell_text("state", row["state"])
|
|
header.append(Gtk.Label(label=text, halign=Gtk.Align.START, css_classes=["badge", *classes]))
|
|
if row_actions:
|
|
primary = row_actions.pop(0)
|
|
button = self.action_button(self.tab.actions.index(primary), primary, suggested=True)
|
|
button.add_css_class("primary-action")
|
|
header.append(button)
|
|
self.detail.append(header)
|
|
|
|
fields, shown = Adw.PreferencesGroup(title="Details"), 0
|
|
for name, heading in self.tab.columns:
|
|
value = row.get(name)
|
|
text, classes = cell_text(name, value)
|
|
if not heading or not text or name == "state":
|
|
continue
|
|
if is_badge(name, value):
|
|
item = Adw.ActionRow(title=heading, use_markup=False)
|
|
item.add_suffix(Gtk.Label(label=text, valign=Gtk.Align.CENTER, css_classes=["badge", *classes]))
|
|
else:
|
|
item = Adw.ActionRow(title=heading, subtitle=text, use_markup=False, subtitle_selectable=True, css_classes=["property"])
|
|
fields.add(item)
|
|
shown += 1
|
|
if shown:
|
|
self.detail.append(fields)
|
|
for heading, group in (("Actions", row_actions), (self.tab.title, tab_actions)):
|
|
if not group:
|
|
continue
|
|
section = Adw.PreferencesGroup(title=heading)
|
|
for action in group:
|
|
section.add(self.action_row(self.tab.actions.index(action), action))
|
|
self.detail.append(section)
|
|
if not actions:
|
|
self.detail.append(Gtk.Label(label="No actions here.", css_classes=["dim-label", "no-actions"]))
|
|
|
|
def act(self, index, from_key=False):
|
|
action, row = self.tab.actions[index], self.selected_row()
|
|
if action not in model.applicable(self.tab, row):
|
|
return from_key is False # a key that does not apply falls through
|
|
self.win.perform(action, row)
|
|
return True
|
|
|
|
def on_right_click(self, gesture, n, x, y):
|
|
# Select the row under the pointer first: its cell labels know their row.
|
|
widget = self.view.pick(x, y, Gtk.PickFlags.DEFAULT)
|
|
while widget is not None and widget is not self.view:
|
|
for candidate in (widget, widget.get_first_child()):
|
|
if handler := getattr(candidate, "_handler", None):
|
|
self.select_item(handler[0])
|
|
widget = None
|
|
break
|
|
else:
|
|
widget = widget.get_parent()
|
|
rect = Gdk.Rectangle()
|
|
rect.x, rect.y, rect.width, rect.height = int(x), int(y), 1, 1
|
|
self.open_menu(rect)
|
|
|
|
def select_item(self, item):
|
|
for pos in range(self.sorted.get_n_items()):
|
|
if self.sorted.get_item(pos) is item:
|
|
self.selection.set_selected(pos)
|
|
return
|
|
|
|
def open_menu(self, rect):
|
|
row = self.selected_row()
|
|
actions = model.applicable(self.tab, row)
|
|
if not actions:
|
|
self.win.toast(f"No actions for {row['key'] if row else self.tab.title}.")
|
|
return True
|
|
menu = Gio.Menu()
|
|
section = Gio.Menu()
|
|
for action in actions:
|
|
label = cap(action.label)
|
|
item = Gio.MenuItem.new(label, None)
|
|
item.set_action_and_target_value("win.act", GLib.Variant("(si)", (self.tab.id, self.tab.actions.index(action))))
|
|
item.set_attribute_value("accel", GLib.Variant("s", accelerator(action.key)))
|
|
(section if action.when is not None else menu).append_item(item)
|
|
menu.prepend_section(None, section)
|
|
if self.popover:
|
|
self.popover.unparent()
|
|
self.popover = Gtk.PopoverMenu(menu_model=menu, has_arrow=rect is not None)
|
|
self.popover.set_parent(self.view if self.view.get_mapped() else self.empty)
|
|
if rect is None:
|
|
rect = Gdk.Rectangle()
|
|
rect.x, rect.y, rect.width, rect.height = 24, 24, 1, 1
|
|
self.popover.set_pointing_to(rect)
|
|
self.popover.popup()
|
|
return True
|
|
|
|
|
|
# --- dialogs ----------------------------------------------------------------------------
|
|
|
|
|
|
class OutputDialog(Adw.Dialog):
|
|
"""A command's output, streamed while it runs; a link that was asked for as QR shows the code."""
|
|
|
|
def __init__(self, win, title, text=None, keep_running=False):
|
|
super().__init__(title=title, content_width=820, content_height=560)
|
|
self.win, self.proc, self.keep_running = win, None, keep_running
|
|
self.lines = []
|
|
view = Adw.ToolbarView()
|
|
header = Adw.HeaderBar(title_widget=Adw.WindowTitle(title="Output", subtitle=title))
|
|
self.copy = Gtk.Button(icon_name="edit-copy-symbolic", tooltip_text="Copy the output")
|
|
self.copy.connect("clicked", lambda *_: self.win.copy_text("\n".join(plain(line) for line in self.lines), "Copied the output."))
|
|
header.pack_start(self.copy)
|
|
self.stop = Gtk.Button(label="Stop", css_classes=["destructive-action"], visible=False, valign=Gtk.Align.CENTER)
|
|
self.stop.connect("clicked", lambda *_: self.terminate())
|
|
header.pack_end(self.stop)
|
|
self.retry_with = None # () -> run it again as root
|
|
self.retry = Gtk.Button(label="Retry as Root", css_classes=["suggested-action"], visible=False, valign=Gtk.Align.CENTER)
|
|
self.retry.connect("clicked", lambda *_: (self.close(), self.retry_with()))
|
|
header.pack_end(self.retry)
|
|
self.spinner = Adw.Spinner(visible=False)
|
|
header.pack_end(self.spinner)
|
|
self.result = Gtk.Label(visible=False, valign=Gtk.Align.CENTER)
|
|
header.pack_end(self.result)
|
|
view.add_top_bar(header)
|
|
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
|
|
self.qr = Gtk.Picture(visible=False, can_shrink=True, content_fit=Gtk.ContentFit.CONTAIN, css_classes=["qr"], halign=Gtk.Align.CENTER)
|
|
self.qr.set_size_request(280, 280)
|
|
self.qr.set_margin_top(6)
|
|
self.qr.set_margin_bottom(12)
|
|
box.append(self.qr)
|
|
self.buffer = Gtk.TextBuffer()
|
|
self.tags = {name: self.buffer.create_tag(name) for name in ("bold", "dim", *ANSI_COLORS)}
|
|
self.tags["bold"].set_property("weight", Pango.Weight.BOLD)
|
|
self.text = Gtk.TextView(buffer=self.buffer, editable=False, monospace=True, wrap_mode=Gtk.WrapMode.WORD_CHAR, css_classes=["output-view"], cursor_visible=False)
|
|
# Themes can be dark without Adwaita knowing, so the text color decides.
|
|
self.text.connect("map", self.paint_tags)
|
|
style = Adw.StyleManager.get_default()
|
|
dark_handler = style.connect("notify::dark", lambda *_: GLib.idle_add(lambda: self.paint_tags() and False))
|
|
self.connect("closed", lambda *_: style.disconnect(dark_handler))
|
|
self.scroller = Gtk.ScrolledWindow(child=self.text, vexpand=True)
|
|
card = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, css_classes=["output-card"], overflow=Gtk.Overflow.HIDDEN)
|
|
card.append(self.scroller)
|
|
box.append(card)
|
|
view.set_content(box)
|
|
self.set_child(view)
|
|
self.follow = text is None
|
|
if text is not None:
|
|
for line in text.splitlines():
|
|
self.write(line)
|
|
self.connect("closed", lambda *_: None if self.keep_running else self.terminate())
|
|
|
|
def paint_tags(self, *_):
|
|
fg = self.text.get_color()
|
|
dark = 0.299 * fg.red + 0.587 * fg.green + 0.114 * fg.blue > 0.5
|
|
for name, (light_color, dark_color) in ANSI_COLORS.items():
|
|
self.tags[name].set_property("foreground_rgba", rgba(dark_color if dark else light_color))
|
|
self.tags["dim"].set_property("foreground_rgba", rgba("#9a9996" if dark else "#77767b"))
|
|
|
|
def running(self, proc, stoppable=True):
|
|
self.proc = proc
|
|
self.stop.set_visible(stoppable) # a run as root is not ours to stop
|
|
self.spinner.set_visible(True)
|
|
|
|
def finished(self, status=0, retry=None):
|
|
self.stop.set_visible(False)
|
|
self.spinner.set_visible(False)
|
|
self.retry.set_visible(retry is not None)
|
|
self.retry_with = retry
|
|
if status == -signal.SIGTERM:
|
|
text, classes = "stopped", ["dim-label"]
|
|
elif status:
|
|
text, classes = f"exit {status}", ["error"]
|
|
else:
|
|
text, classes = "done", ["success"]
|
|
self.result.set_text(text)
|
|
self.result.set_css_classes(["badge", *classes])
|
|
self.result.set_visible(True)
|
|
|
|
def write(self, line):
|
|
self.lines.append(line)
|
|
end = self.buffer.get_end_iter()
|
|
if self.buffer.get_char_count():
|
|
self.buffer.insert(end, "\n")
|
|
for text, tags in ansi_segments(line):
|
|
end = self.buffer.get_end_iter()
|
|
if tags:
|
|
self.buffer.insert_with_tags_by_name(end, text, *tags)
|
|
else:
|
|
self.buffer.insert(end, text)
|
|
if self.follow:
|
|
adj = self.scroller.get_vadjustment()
|
|
GLib.idle_add(lambda: adj.set_value(adj.get_upper()) and False)
|
|
|
|
def show_qr(self, text):
|
|
try:
|
|
png = subprocess.run(["qrencode", "-t", "PNG", "-s", "8", "-m", "2", "-o", "-"], input=text.encode(), capture_output=True, check=True).stdout
|
|
except (OSError, subprocess.CalledProcessError):
|
|
self.write("\x1b[33m(qrencode is missing: no QR code)\x1b[0m")
|
|
return
|
|
self.qr.set_paintable(Gdk.Texture.new_from_bytes(GLib.Bytes.new(png)))
|
|
self.qr.set_visible(True)
|
|
|
|
def terminate(self):
|
|
model.stop(self.proc)
|
|
|
|
|
|
# --- 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=TILED_SIZE[0], default_height=TILED_SIZE[1], icon_name=APP_ID)
|
|
self.app = app
|
|
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 -> {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
|
|
|
|
self.toasts = Adw.ToastOverlay()
|
|
view = Adw.ToolbarView(top_bar_style=Adw.ToolbarStyle.RAISED)
|
|
header = Adw.HeaderBar()
|
|
self.stack = Adw.ViewStack(vexpand=True)
|
|
switcher = Adw.ViewSwitcher(stack=self.stack, policy=Adw.ViewSwitcherPolicy.WIDE)
|
|
header.set_title_widget(switcher)
|
|
refresh = Gtk.Button(icon_name="view-refresh-symbolic", tooltip_text="Refresh now (F5)")
|
|
refresh.connect("clicked", lambda *_: app.reload(fresh_root=True))
|
|
# A slow load shows a spinner in the refresh button's place.
|
|
self.refresh_stack = Gtk.Stack(transition_type=Gtk.StackTransitionType.CROSSFADE)
|
|
self.refresh_stack.add_named(refresh, "idle")
|
|
self.refresh_stack.add_named(Adw.Spinner(halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER), "busy")
|
|
self.busy_timer = None
|
|
header.pack_start(self.refresh_stack)
|
|
self.root_badge = Gtk.Image(icon_name="dialog-password-symbolic", tooltip_text="Reads and actions run as root (Ctrl+E)", visible=app.elevated(), css_classes=["warning"])
|
|
header.pack_start(self.root_badge)
|
|
menu = Gio.Menu()
|
|
section = Gio.Menu()
|
|
section.append("Paste a link into this tab", "win.paste")
|
|
section.append("How is a domain routed…", "win.where")
|
|
section.append("Follow all logs", "win.logs")
|
|
section.append("Output of the last command", "win.last-output")
|
|
menu.append_section(None, section)
|
|
section = Gio.Menu()
|
|
section.append("Read and run as root", "app.elevated")
|
|
menu.append_section(None, section)
|
|
section = Gio.Menu()
|
|
section.append("Keyboard Shortcuts", "win.shortcuts")
|
|
section.append("About Proxy Suite", "win.about")
|
|
section.append("Quit", "app.quit")
|
|
menu.append_section(None, section)
|
|
header.pack_end(Gtk.MenuButton(icon_name="open-menu-symbolic", menu_model=menu, primary=True, tooltip_text="Main menu"))
|
|
# Narrow windows fold the details and actions away: this brings them over the table.
|
|
self.details_toggle = Gtk.ToggleButton(icon_name="sidebar-show-right-symbolic", tooltip_text="Details and actions", visible=False)
|
|
self.details_toggle.connect("toggled", lambda b: self.page() and self.page().split.set_show_sidebar(b.get_active()))
|
|
header.pack_end(self.details_toggle)
|
|
view.add_top_bar(header)
|
|
|
|
self.status = Adw.WrapBox(child_spacing=18, line_spacing=2, css_classes=["status-strip"])
|
|
self.status_items = None
|
|
view.add_top_bar(self.status)
|
|
self.banner = Adw.Banner(title="", revealed=False, button_label="Retry", action_name="app.reload")
|
|
view.add_top_bar(self.banner)
|
|
|
|
for tab in TABS:
|
|
page = Page(self, tab)
|
|
self.pages[tab.id] = page
|
|
self.stack.add_titled_with_icon(page, tab.id, tab.title, TAB_ICONS.get(tab.id, "view-list-symbolic"))
|
|
self.stack.connect("notify::visible-child", lambda *_: self.on_tab_changed())
|
|
self.bar = Adw.ViewSwitcherBar(stack=self.stack)
|
|
view.set_content(self.stack)
|
|
view.add_bottom_bar(self.bar)
|
|
breakpoint = Adw.Breakpoint.new(Adw.BreakpointCondition.parse("max-width: 720sp"))
|
|
breakpoint.add_setter(switcher, "visible", GObject.Value(bool, False))
|
|
breakpoint.add_setter(self.bar, "reveal", GObject.Value(bool, True))
|
|
breakpoint.add_setter(self.details_toggle, "visible", GObject.Value(bool, True))
|
|
for page in self.pages.values():
|
|
breakpoint.add_setter(page.split, "collapsed", GObject.Value(bool, True))
|
|
breakpoint.add_setter(page.split, "show-sidebar", GObject.Value(bool, False))
|
|
page.split.connect("notify::show-sidebar", lambda split, _: self.page() is not None and split is self.page().split and self.sync_details_toggle())
|
|
self.add_breakpoint(breakpoint)
|
|
|
|
self.toasts.set_child(view)
|
|
self.set_content(self.toasts)
|
|
|
|
for name, callback, param in (
|
|
("where", lambda *_: self.where(), None),
|
|
("paste", lambda *_: self.paste(), None),
|
|
("logs", lambda *_: self.follow_logs(), None),
|
|
("last-output", lambda *_: self.show_last_output(), None),
|
|
("shortcuts", lambda *_: self.show_shortcuts(), None),
|
|
("about", lambda *_: self.show_about(), None),
|
|
("filter", lambda *_: self.page().focus_search(), None),
|
|
("act", self.on_act, GLib.VariantType.new("(si)")),
|
|
("tab", lambda _, p: self.jump(p.get_int32()), GLib.VariantType.new("i")),
|
|
):
|
|
action = Gio.SimpleAction.new(name, param)
|
|
action.connect("activate", callback)
|
|
self.add_action(action)
|
|
app.set_accels_for_action("win.filter", ["<Control>f"])
|
|
app.set_accels_for_action("win.paste", ["<Control>v"])
|
|
app.set_accels_for_action("app.elevated", ["<Control>e"])
|
|
app.set_accels_for_action("win.shortcuts", ["<Control>question"])
|
|
app.set_accels_for_action("app.reload", ["F5"])
|
|
app.set_accels_for_action("app.quit", ["<Control>q"])
|
|
app.set_accels_for_action("window.close", ["<Control>w"])
|
|
for n in range(1, 9):
|
|
app.set_accels_for_action(f"win.tab({n - 1})", [f"<Alt>{n}"])
|
|
|
|
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):
|
|
return self.stack.get_visible_child()
|
|
|
|
def shown(self):
|
|
return [tab.id for tab in TABS if self.stack.get_page(self.pages[tab.id]).get_visible()]
|
|
|
|
def show_tabs(self, visible):
|
|
for tab in TABS:
|
|
self.stack.get_page(self.pages[tab.id]).set_visible(tab.id in visible)
|
|
if self.stack.get_visible_child_name() not in visible and visible:
|
|
self.stack.set_visible_child_name(visible[0])
|
|
# The bar counts visible tabs only when told to reveal, so hiding tabs could leave it folded away.
|
|
reveal = self.bar.get_reveal()
|
|
self.bar.set_reveal(not reveal)
|
|
self.bar.set_reveal(reveal)
|
|
|
|
def jump(self, index):
|
|
shown = self.shown()
|
|
if 0 <= index < len(shown):
|
|
self.stack.set_visible_child_name(shown[index])
|
|
|
|
def sync_details_toggle(self):
|
|
if page := self.page():
|
|
self.details_toggle.set_active(page.split.get_show_sidebar())
|
|
self.details_toggle.set_sensitive(page.split.get_visible())
|
|
|
|
def on_tab_changed(self):
|
|
page = self.page()
|
|
if page:
|
|
self.sync_details_toggle()
|
|
page.focus_default()
|
|
self.app.reload()
|
|
|
|
def set_busy(self, busy):
|
|
if self.busy_timer:
|
|
GLib.source_remove(self.busy_timer)
|
|
self.busy_timer = None
|
|
if busy:
|
|
self.busy_timer = GLib.timeout_add(400, self.show_busy)
|
|
else:
|
|
self.refresh_stack.set_visible_child_name("idle")
|
|
|
|
def show_busy(self):
|
|
self.busy_timer = None
|
|
self.refresh_stack.set_visible_child_name("busy")
|
|
return False
|
|
|
|
def show_status(self, items):
|
|
# Only a change rebuilds the chips: the refresh tick sends the same items every few seconds.
|
|
if items == self.status_items:
|
|
return
|
|
self.status_items = items
|
|
while child := self.status.get_first_child():
|
|
self.status.remove(child)
|
|
for n, (label, value, style) in enumerate(items):
|
|
chip = Gtk.Box(spacing=6, css_classes=["status-chip", *([style] if style else [])])
|
|
if n == 0:
|
|
chip.append(Gtk.Image(icon_name=STATUS_ICONS[style], pixel_size=14))
|
|
if label:
|
|
chip.append(Gtk.Label(label=label.strip(), css_classes=["chip-label"]))
|
|
chip.append(Gtk.Label(label=value, css_classes=["chip-value"], ellipsize=Pango.EllipsizeMode.END))
|
|
self.status.append(chip)
|
|
|
|
def fill(self, states, visible, status, tab_id, rows, summary, stale=False, selector=None):
|
|
# A read that came back empty after a good one keeps what is on screen: every tab
|
|
# and row blinking out and back is worse than a banner saying the read failed.
|
|
if stale:
|
|
self.banner.set_title("Cannot read service states: showing the last good read")
|
|
self.banner.set_revealed(True)
|
|
return
|
|
self.show_status(status)
|
|
unreadable = not states
|
|
self.banner.set_title("Cannot read service states: is systemd reachable?" if unreadable else "")
|
|
self.banner.set_revealed(unreadable)
|
|
if visible != self.shown():
|
|
self.show_tabs(visible)
|
|
if tab_id in self.pages and tab_id in visible:
|
|
self.pages[tab_id].fill(rows, summary, selector)
|
|
|
|
# --- acting ----------------------------------------------------------------------------------
|
|
|
|
def on_act(self, _, param):
|
|
tab_id, index = param.unpack()
|
|
page = self.pages[tab_id]
|
|
action, row = page.tab.actions[index], page.selected_row()
|
|
if action in model.applicable(page.tab, row):
|
|
self.perform(action, row)
|
|
|
|
def where(self):
|
|
self.perform(model.WHERE, None)
|
|
return True
|
|
|
|
def paste(self):
|
|
"""Ctrl+V anywhere but a text field: whatever is in the clipboard is added to this tab, once confirmed."""
|
|
if isinstance(self.get_focus(), Gtk.Editable) or self.get_visible_dialog() is not None:
|
|
return False
|
|
page = self.page()
|
|
if page is not None:
|
|
self.get_clipboard().read_text_async(None, lambda clipboard, result: self.pasted(page, clipboard, result))
|
|
return True
|
|
|
|
def pasted(self, page, clipboard, result):
|
|
try:
|
|
text = clipboard.read_text_finish(result)
|
|
except GLib.Error as e:
|
|
self.toast(f"Cannot read the clipboard: {e.message}")
|
|
return
|
|
argv, what, stdin = model.paste_argv(page.tab.id, text)
|
|
if argv is None:
|
|
self.toast(what)
|
|
else:
|
|
# Asked first: a web page can put a link in the clipboard, and one stray Ctrl+V
|
|
# would have root fetch its subscription.
|
|
self.app.confirm(argv, lambda: self.app.run_argv("run", argv, self, stdin=stdin), self, stdin=stdin)
|
|
|
|
def follow_logs(self):
|
|
self.app.run_argv("suspend", ["logs"], self)
|
|
return True
|
|
|
|
def show_last_output(self):
|
|
if self.last_output:
|
|
dialog = OutputDialog(self, *self.last_output)
|
|
dialog.retry.set_visible(self.last_retry is not None)
|
|
dialog.retry_with = self.last_retry
|
|
dialog.present(self)
|
|
else:
|
|
self.toast("Nothing has run yet.")
|
|
return True
|
|
|
|
def perform(self, action, row):
|
|
if action.mode == "fold":
|
|
page = self.page()
|
|
if page is not None and row is not None:
|
|
page.collapsed.symmetric_difference_update({row["key"]})
|
|
page.refill()
|
|
return
|
|
|
|
def with_values(values=None):
|
|
try:
|
|
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
|
|
if model.needs_confirm(action, row):
|
|
self.app.confirm(argv, lambda: self.app.run_argv(action.mode, argv, self, stdin=stdin), self)
|
|
else:
|
|
self.app.run_argv(action.mode, argv, self, stdin=stdin)
|
|
|
|
if not action.fields:
|
|
with_values()
|
|
return
|
|
def ran(values):
|
|
self.typed[action.label] = values
|
|
with_values(values)
|
|
|
|
title = cap(action.label.removesuffix("…"))
|
|
dialog, form = form_dialog(title, action, row, self.typed.get(action.label), self.app.states, ran)
|
|
dialog.present(self)
|
|
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:
|
|
# wrap it over a few lines instead, and keep the rest one button (or `o`) away.
|
|
label = Gtk.Label(
|
|
label=message,
|
|
wrap=True,
|
|
wrap_mode=Pango.WrapMode.WORD_CHAR,
|
|
natural_wrap_mode=Gtk.NaturalWrapMode.WORD,
|
|
lines=TOAST_LINES,
|
|
ellipsize=Pango.EllipsizeMode.END,
|
|
xalign=0,
|
|
justify=Gtk.Justification.LEFT,
|
|
max_width_chars=64,
|
|
)
|
|
toast = Adw.Toast(custom_title=label, timeout=8)
|
|
if retry: # one button: the output stays a keypress away (o)
|
|
toast.set_button_label("Retry as Root")
|
|
toast.connect("button-clicked", lambda *_: retry())
|
|
elif output:
|
|
toast.set_button_label("Output")
|
|
toast.connect("button-clicked", lambda *_: OutputDialog(self, *output).present(self))
|
|
self.toasts.add_toast(toast)
|
|
|
|
def copy_text(self, text, message):
|
|
self.get_clipboard().set(text)
|
|
self.toast(message)
|
|
|
|
def show_shortcuts(self):
|
|
dialog = Adw.ShortcutsDialog()
|
|
page = self.page()
|
|
if page and (actions := [a for a in page.tab.actions if model.offered(a)]):
|
|
section = Adw.ShortcutsSection(title=page.tab.title)
|
|
for key, label in model.key_labels(actions):
|
|
section.add(Adw.ShortcutsItem(title=cap(label), accelerator=accelerator(key)))
|
|
if page.tab.selector:
|
|
section.add(Adw.ShortcutsItem(title=f"Choose the {page.tab.selector.label.lower()}", accelerator=accelerator(page.tab.selector.key)))
|
|
dialog.add(section)
|
|
section = Adw.ShortcutsSection(title="Everywhere")
|
|
for accel, title in GLOBAL_SHORTCUTS:
|
|
section.add(Adw.ShortcutsItem(title=title, accelerator=accel))
|
|
dialog.add(section)
|
|
dialog.present(self)
|
|
return True
|
|
|
|
def show_about(self):
|
|
Adw.AboutDialog(
|
|
application_name=TITLE, application_icon=APP_ID, developer_name="proxy-suite-flake",
|
|
comments="Everything proxy-ctl controls, in a window and the tray.",
|
|
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.hide_to_tray()
|
|
return True # the tray icon brings it back
|
|
self.app.quit()
|
|
return False
|
|
|
|
|
|
# --- application --------------------------------------------------------------------------------
|
|
|
|
|
|
class ProxySuiteGui(Adw.Application):
|
|
def __init__(self):
|
|
super().__init__(application_id=APP_ID, flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)
|
|
self.add_main_option("hidden", 0, GLib.OptionFlags.NONE, GLib.OptionArg.NONE, "Start in the tray, without a window", None)
|
|
self.add_main_option("tab", 0, GLib.OptionFlags.NONE, GLib.OptionArg.STRING, "Open this tab: " + ", ".join(t.id for t in TABS), "ID")
|
|
self.add_main_option("refresh", 0, GLib.OptionFlags.NONE, GLib.OptionArg.INT, "Seconds between refreshes", "SECONDS")
|
|
self.window = None
|
|
self.tray = None
|
|
self.states = {}
|
|
self.refresh = refresh_seconds()
|
|
self.loading = False
|
|
self.pending = False
|
|
self.generation = 0
|
|
self.failed = None # units in failed state at the last load; None before the first
|
|
# model.FAILURE_EVENTS failures (unit -> mark): on screen in the window now, and seen there
|
|
# before. A seen one stops marking the tray and the status line once the window is left.
|
|
self.viewing = {}
|
|
self.seen = {}
|
|
self.root_read_refused = False # pkexec for a tab read was dismissed: not asked again until Ctrl+E flips
|
|
# tab id -> (rows, summary, when) of its last root read: pkexec asks for the password each
|
|
# time, so not on every refresh; again on F5, Ctrl+E, or after a root action.
|
|
self.root_reads = {}
|
|
self.pending_fresh = False
|
|
self.stale_reads = 0 # empty state reads in a row, after one that worked
|
|
self.timer = None
|
|
|
|
def do_startup(self):
|
|
Adw.Application.do_startup(self)
|
|
display = Gdk.Display.get_default()
|
|
if display:
|
|
Gtk.IconTheme.get_for_display(display).add_search_path(ICON_DIR)
|
|
css = Gtk.CssProvider()
|
|
css.load_from_string(CSS)
|
|
# Above a user gtk.css theme: these rules are only for this window's own classes.
|
|
Gtk.StyleContext.add_provider_for_display(display, css, Gtk.STYLE_PROVIDER_PRIORITY_USER + 1)
|
|
for name, callback in (("quit", lambda *_: self.quit()), ("reload", lambda *_: self.reload(fresh_root=True)), ("present", lambda *_: self.present())):
|
|
action = Gio.SimpleAction.new(name, None)
|
|
action.connect("activate", callback)
|
|
self.add_action(action)
|
|
elevated = Gio.SimpleAction.new_stateful("elevated", None, GLib.Variant.new_boolean(False))
|
|
elevated.set_enabled(ctl.privileged())
|
|
elevated.connect("change-state", self.on_elevated)
|
|
self.add_action(elevated)
|
|
retry = Gio.SimpleAction.new("retry-root", GLib.VariantType.new("as"))
|
|
retry.connect("activate", lambda _, argv: self.run_argv("run", argv.unpack(), None, root=True))
|
|
self.add_action(retry)
|
|
self.hold() # the tray and notifications outlive the window
|
|
try:
|
|
from proxy_sni import StatusNotifierItem
|
|
|
|
self.tray = StatusNotifierItem(
|
|
self.get_dbus_connection(), APP_ID, TITLE, ICON_DIR,
|
|
on_activate=self.toggle_window, on_menu=self.on_tray_menu, on_available=self.on_tray_available,
|
|
)
|
|
except (GLib.Error, ImportError) as e:
|
|
print(f"proxy-suite-gui: no tray icon: {e}", file=sys.stderr)
|
|
|
|
def do_command_line(self, command_line):
|
|
options = command_line.get_options_dict().end().unpack()
|
|
if "refresh" in options and options["refresh"] > 0:
|
|
self.refresh = options["refresh"]
|
|
if self.timer:
|
|
GLib.source_remove(self.timer)
|
|
self.timer = None
|
|
if self.timer is None:
|
|
self.timer = GLib.timeout_add_seconds(self.refresh, self.tick)
|
|
self.reload()
|
|
# proxy-suite:// links, from xdg-open (the .desktop file's %u): shown even to --hidden.
|
|
links = [a for a in command_line.get_arguments()[1:] if a.lower().startswith(model.DEEP_LINK_SCHEME + ":")]
|
|
if not options.get("hidden") or links:
|
|
# 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)
|
|
for link in links:
|
|
self.open_link(link)
|
|
return 0
|
|
|
|
def open_link(self, link):
|
|
"""A proxy-suite:// link: what it adds, run once confirmed."""
|
|
argv, why, stdin = model.deep_link_argv(link)
|
|
if argv is None:
|
|
self.window.toast(why)
|
|
return
|
|
# Asked first, as a paste is: any web page can open such a link.
|
|
self.confirm(argv, lambda: self.run_argv("run", argv, self.window, stdin=stdin), self.window, stdin=stdin)
|
|
|
|
def do_activate(self):
|
|
self.present()
|
|
|
|
def do_shutdown(self):
|
|
if self.tray:
|
|
self.tray.close()
|
|
Adw.Application.do_shutdown(self)
|
|
|
|
# --- window ------------------------------------------------------------------------------
|
|
|
|
def elevated(self):
|
|
return self.lookup_action("elevated").get_state().get_boolean()
|
|
|
|
def on_elevated(self, action, value):
|
|
action.set_state(value)
|
|
self.root_read_refused = False
|
|
self.root_reads.clear()
|
|
if self.window:
|
|
self.window.root_badge.set_visible(value.get_boolean())
|
|
self.reload(fresh_root=True) # tabs only root can read
|
|
|
|
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.
|
|
self.window.connect("notify::is-active", lambda w, _: w.is_active() or self.leave_window())
|
|
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, token=None):
|
|
if self.window and self.window.get_visible() and self.window.is_active():
|
|
self.window.hide_to_tray()
|
|
else:
|
|
self.present(token=token)
|
|
|
|
def leave_window(self):
|
|
if self.viewing:
|
|
self.seen.update(self.viewing)
|
|
self.viewing.clear()
|
|
self.reload()
|
|
|
|
def on_tray_available(self, available):
|
|
if not available and self.window is None:
|
|
# Started hidden, and nothing shows the tray: no way back to the window but this.
|
|
GLib.timeout_add_seconds(5, lambda: (self.present() if not self.tray.available and self.window is None else None) and False)
|
|
|
|
# --- loads ----------------------------------------------------------------------------------
|
|
|
|
def tick(self):
|
|
self.reload()
|
|
return True
|
|
|
|
def reload(self, fresh_root=False):
|
|
"""fresh_root: read a root-only tab as root again (F5, Ctrl+E), not from the last read."""
|
|
if self.loading:
|
|
self.pending = True # one more once this load lands
|
|
self.pending_fresh = self.pending_fresh or fresh_root
|
|
return
|
|
self.loading = True
|
|
self.generation += 1
|
|
window = self.window if self.window and self.window.get_visible() else None
|
|
if window:
|
|
window.set_busy(True)
|
|
tab = window.pages[window.stack.get_visible_child_name()].tab if window and window.stack.get_visible_child_name() else None
|
|
threading.Thread(target=self.load, args=(self.generation, tab, self.elevated(), dict(self.seen), fresh_root), daemon=True).start()
|
|
|
|
def load(self, generation, tab, elevated, seen, fresh_root=False):
|
|
# landed() always runs: it is what clears self.loading, else no reload would start again.
|
|
result = None
|
|
try:
|
|
result = self.gather(tab, elevated, seen, fresh_root)
|
|
except (Exception, SystemExit) as e:
|
|
print(f"proxy-suite-gui: load failed: {e!r}", file=sys.stderr)
|
|
finally:
|
|
GLib.idle_add(self.landed, generation, result)
|
|
|
|
def gather(self, tab, elevated, seen, fresh_root=False):
|
|
model.new_load()
|
|
states = model._read_states()
|
|
marks = model._safe(model.failure_marks, states, fallback={})
|
|
states = model.unseen(states, marks, seen)
|
|
snap = model.snapshot(states) if states else None
|
|
outbound = model._safe(ctl._status_outbound, fallback="") if snap and snap["proxy"]["active"] else ""
|
|
tray = (model.tray_menu(snap, model.tray_outbounds(snap)), ctl._overall_state(snap), outbound)
|
|
result = {"states": states, "snap": snap, "tray": tray, "marks": marks}
|
|
if tab is not None:
|
|
result["visible"] = model.available_tabs(states)
|
|
result["status"] = model._safe(model.status_items, states, fallback=[("", "Status unavailable", "bad")])
|
|
result["tab"] = (tab.id, *self.load_tab(tab, states, elevated, fresh_root))
|
|
result["selector"] = model.selector_state(tab)
|
|
return result
|
|
|
|
def load_tab(self, tab, states, elevated, fresh_root=False):
|
|
"""The tab as this user reads it; what only root can read, through pkexec when actions run as root:
|
|
once, and again on fresh_root."""
|
|
rows, summary = model.load_tab(tab, states)
|
|
if not model.needs_root(summary.splitlines(), 1):
|
|
return rows, summary
|
|
if not elevated:
|
|
return rows, summary + "\nCtrl+E: read and run as root"
|
|
if self.root_read_refused:
|
|
return rows, summary + "\nRoot read cancelled: Ctrl+E twice to ask again."
|
|
cached = self.root_reads.get(tab.id)
|
|
if cached and not fresh_root:
|
|
root_rows, why, when = cached
|
|
return root_rows, why + f"\nRead as root at {time.strftime('%H:%M:%S', time.localtime(when))}: F5 to read again."
|
|
root_rows, why = model.load_tab_as_root(tab, "pkexec")
|
|
if root_rows is None:
|
|
# ponytail: one refusal stops the asking, else the password dialog is back every refresh
|
|
self.root_read_refused = why == "authentication cancelled"
|
|
return rows, summary + f"\nAs root: {why}"
|
|
self.root_reads[tab.id] = (root_rows, why, time.time())
|
|
return root_rows, why
|
|
|
|
def landed(self, generation, result):
|
|
self.loading = False
|
|
if self.window:
|
|
self.window.set_busy(False)
|
|
# None: the load failed; what is shown stays.
|
|
if generation == self.generation and result is not None:
|
|
# Nothing read, after a read that worked: keep the last good one, tray and all.
|
|
stale = not result["states"] and bool(self.states)
|
|
self.stale_reads = self.stale_reads + 1 if stale else 0
|
|
if stale and self.stale_reads >= STALE_READS_UNKNOWN and self.tray:
|
|
# One failed read is a blip; this many is no state to show at all: the last
|
|
# good one may say "tunnel" while nothing runs any more.
|
|
tree, overall, _ = result["tray"]
|
|
self.tray.update(model.icon_name(overall), overall["label"], tree, attention=True)
|
|
if not stale:
|
|
self.states = result["states"]
|
|
marks = result["marks"]
|
|
# A failure that is over, or failed again since, is no longer the one seen.
|
|
self.seen = {u: m for u, m in self.seen.items() if marks.get(u) == m}
|
|
self.viewing = {u: m for u, m in self.viewing.items() if marks.get(u) == m}
|
|
if "tab" in result and self.window and self.window.is_active():
|
|
self.viewing.update((u, m) for u, m in marks.items() if u not in self.seen)
|
|
snap = result["snap"]
|
|
tree, overall, outbound = result["tray"]
|
|
if self.tray:
|
|
failed = snap["failed"] if snap else []
|
|
tooltip = overall["label"] + (f"\nOutbound: {outbound}" if outbound else "") + (f"\nFailed: {', '.join(failed)}" if failed else "")
|
|
self.tray.update(model.icon_name(overall), tooltip, tree, attention=bool(failed))
|
|
self.notify_failures(snap)
|
|
if "tab" in result and self.window:
|
|
self.window.fill(self.states, result["visible"], result["status"], *result["tab"], stale=stale, selector=result.get("selector"))
|
|
if self.pending:
|
|
fresh, self.pending, self.pending_fresh = self.pending_fresh, False, False
|
|
self.reload(fresh_root=fresh)
|
|
return False
|
|
|
|
def notify_failures(self, snap):
|
|
if snap is None:
|
|
return
|
|
failed = set(snap["failed"])
|
|
if self.failed is not None:
|
|
for unit in sorted(failed - self.failed):
|
|
note = Gio.Notification.new(f"{unit} failed")
|
|
note.set_body(f"See its logs: proxy-ctl logs {unit}")
|
|
note.set_priority(Gio.NotificationPriority.HIGH)
|
|
note.set_default_action("app.present")
|
|
self.send_notification(f"failed-{unit}", note)
|
|
for unit in self.failed - failed:
|
|
self.withdraw_notification(f"failed-{unit}")
|
|
self.failed = failed
|
|
|
|
# --- running proxy-ctl ---------------------------------------------------------------------------
|
|
|
|
def on_tray_menu(self, item):
|
|
if item.app == "open":
|
|
self.present(token=self.tray.take_token() if self.tray else None)
|
|
elif item.app == "quit":
|
|
self.quit()
|
|
elif item.argv:
|
|
run = lambda: self.run_argv("run", item.argv, None)
|
|
if item.confirm:
|
|
self.confirm(item.argv, run, self.window if self.window and self.window.get_visible() else None)
|
|
else:
|
|
run()
|
|
|
|
def confirm(self, argv, then, parent, stdin=None):
|
|
body = f"<tt>{GLib.markup_escape_text(model.shown(argv, stdin=stdin))}</tt>"
|
|
dialog = Adw.AlertDialog(heading="Run this?", body=body, body_use_markup=True, close_response="cancel", default_response="run")
|
|
dialog.add_response("cancel", "Cancel")
|
|
dialog.add_response("run", "Run")
|
|
dialog.set_response_appearance("run", Adw.ResponseAppearance.DESTRUCTIVE)
|
|
dialog.connect("response", lambda _, r: r == "run" and then())
|
|
dialog.present(parent)
|
|
|
|
def run_argv(self, mode, argv, win, root=False, stdin=None):
|
|
"""run: a toast; dialog, suspend, pause: output streamed into a dialog; copy: the last line to the clipboard.
|
|
root, or the elevated toggle: through pkexec. Never `apps run`, which is per user.
|
|
stdin: text proxy-ctl reads (argv says "-"), kept out of argv and pkexec's log."""
|
|
# "wrap" is proxy-ctl's alias of `apps run`: never as root either. `apps add`/`rm` may be.
|
|
root = (root or self.elevated()) and argv[:2] != ["apps", "run"] and argv[:1] != ["wrap"]
|
|
# Only ever shown (toast, dialog title, notification): credentials blanked.
|
|
command = model.shown(argv, "pkexec" if root else None)
|
|
retry_argv = argv
|
|
qr = "--qr" in argv
|
|
if qr:
|
|
argv = [a for a in argv if a != "--qr"]
|
|
dialog = None
|
|
if win is not None and mode in ("dialog", "suspend", "pause"):
|
|
dialog = OutputDialog(win, command, keep_running=mode == "pause")
|
|
dialog.present(win)
|
|
elif win is not None:
|
|
win.toast(f"… {command}")
|
|
threading.Thread(target=self.stream, args=(command, argv, mode, win, dialog, qr, root, retry_argv, stdin), daemon=True).start()
|
|
|
|
def stream(self, command, argv, mode, win, dialog, qr, root, retry_argv, stdin=None):
|
|
out = []
|
|
try:
|
|
p = model.popen(argv, "pkexec" if root else None, stdin=stdin)
|
|
if dialog:
|
|
GLib.idle_add(lambda: dialog.running(p, stoppable=not root) and False)
|
|
for line in model.output_lines(p):
|
|
out.append(line)
|
|
if dialog:
|
|
GLib.idle_add(lambda line=out[-1]: dialog.write(line) and False)
|
|
if getattr(p, "proxy_suite_stopped", False):
|
|
# Root's may outlive its closed pipe a while: reaped whenever it goes.
|
|
threading.Thread(target=p.wait, daemon=True).start()
|
|
status = -signal.SIGTERM
|
|
else:
|
|
status = p.wait()
|
|
except OSError as e:
|
|
out.append(f"cannot run proxy-ctl: {e}")
|
|
status = 127
|
|
if root and status == 126 and not out:
|
|
out.append("authentication cancelled") # pkexec: the password dialog was dismissed
|
|
GLib.idle_add(lambda: self.ran(command, mode, win, dialog, qr, out, status, retry_argv, stdin, root) and False)
|
|
|
|
def ran(self, command, mode, win, dialog, qr, out, status, retry_argv, stdin=None, root=False):
|
|
last = last_line(out)
|
|
text = "\n".join(out)
|
|
output = (command, text)
|
|
retry = (lambda: self.run_argv(mode, retry_argv, win, root=True, stdin=stdin)) if model.needs_root(out, status) else None
|
|
if win is not None:
|
|
win.last_output = output
|
|
win.last_retry = retry
|
|
if dialog:
|
|
dialog.finished(status, retry)
|
|
if status == -signal.SIGTERM:
|
|
dialog.write("\x1b[2m(stopped)\x1b[0m")
|
|
elif status:
|
|
dialog.write(f"\x1b[31m(exit status {status})\x1b[0m")
|
|
elif qr and last:
|
|
# A --config is the whole multi-line .conf, not its last line.
|
|
dialog.show_qr("\n".join(plain(line) for line in out).strip("\n") if "--config" in retry_argv else last)
|
|
elif win is not None:
|
|
# A toast is on screen for anyone to see: the link copied, or one in an error, blanked.
|
|
if mode == "copy" and not status and last:
|
|
win.copy_text(last, f"Copied: {model.redact(last)}")
|
|
else:
|
|
message = f"{model.redact(last)} ({command})" if last else command
|
|
# Anything it printed is worth a button: the toast shows a few lines of it at most.
|
|
win.toast(f"exit {status}: {message}" if status else message, output if out else None, retry)
|
|
elif status:
|
|
# From the tray: nothing else would say it failed.
|
|
note = Gio.Notification.new(f"{command} failed")
|
|
note.set_body(model.redact(last) if last else f"exit status {status}")
|
|
note.set_default_action("app.present")
|
|
if retry:
|
|
note.add_button_with_target("Retry as Root", "app.retry-root", GLib.Variant("as", retry_argv))
|
|
self.send_notification(None, note)
|
|
if root and not status:
|
|
# What root just changed: the last root reads no longer show it.
|
|
self.root_reads.clear()
|
|
self.reload()
|
|
|
|
|
|
def main(argv=None):
|
|
# Commands run with no terminal here: what asks on one is left out.
|
|
model.TTY = False
|
|
return ProxySuiteGui().run(argv if argv is not None else sys.argv)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|