From 7de094078cc4d7ecce6f25925932a8b3acaf8de3 Mon Sep 17 00:00:00 2001 From: FUFSoB Date: Tue, 15 Sep 2026 00:15:53 +0500 Subject: [PATCH] feat: proxy-gui --- README.md | 6 +- docs/options/gui.md | 59 + docs/options/index.md | 16 +- docs/options/tray.md | 58 - flake.nix | 6 +- modules/proxy-suite/default.nix | 12 - modules/proxy-suite/options/default.nix | 1 + modules/proxy-suite/options/gui.nix | 25 + modules/proxy-suite/options/tray.nix | 29 +- modules/proxy-suite/service/context.nix | 1 + modules/proxy-suite/service/control.nix | 2 + modules/proxy-suite/service/default.nix | 28 +- modules/proxy-suite/tray.nix | 55 - nix/checks.nix | 5 - nix/checks/gui.nix | 81 ++ nix/checks/module-suite.nix | 5 +- nix/checks/repo.nix | 30 +- nix/checks/tray.nix | 65 - nix/options-doc.nix | 29 +- pkgs/default.nix | 3 - pkgs/proxy-ctl.nix | 99 +- pkgs/proxy-ctl/icons/badges.py | 87 ++ .../icons/io.github.FUFSoB.ProxySuite.svg | 22 + .../icons/proxy-suite-active-symbolic.svg | 0 .../icons/proxy-suite-active.svg | 0 .../icons/proxy-suite-disabled-symbolic.svg | 0 .../icons/proxy-suite-disabled.svg | 0 .../icons/proxy-suite-proxy-symbolic.svg | 0 .../icons/proxy-suite-proxy.svg | 0 .../icons/proxy-suite-tunnel-symbolic.svg | 0 .../icons/proxy-suite-tunnel.svg | 0 .../icons/proxy-suite-zapret-symbolic.svg | 0 .../icons/proxy-suite-zapret.svg | 0 pkgs/proxy-ctl/proxy_ctl.py | 132 +- pkgs/proxy-ctl/proxy_gui.py | 1241 +++++++++++++++++ pkgs/proxy-ctl/proxy_model.py | 578 ++++++++ pkgs/proxy-ctl/proxy_sni.py | 327 +++++ pkgs/proxy-ctl/proxy_tui.py | 469 +------ pkgs/proxy-ctl/test_proxy_ctl.py | 43 + pkgs/proxy-ctl/test_proxy_gui.py | 98 ++ pkgs/proxy-ctl/test_proxy_model.py | 98 ++ pkgs/proxy-ctl/test_proxy_tui.py | 15 +- pkgs/proxy-suite-tray.nix | 52 - pkgs/proxy-suite-tray/main.c | 1233 ---------------- 44 files changed, 2994 insertions(+), 2016 deletions(-) create mode 100644 docs/options/gui.md delete mode 100644 docs/options/tray.md create mode 100644 modules/proxy-suite/options/gui.nix delete mode 100644 modules/proxy-suite/tray.nix create mode 100644 nix/checks/gui.nix delete mode 100644 nix/checks/tray.nix create mode 100644 pkgs/proxy-ctl/icons/badges.py create mode 100644 pkgs/proxy-ctl/icons/io.github.FUFSoB.ProxySuite.svg rename pkgs/{proxy-suite-tray => proxy-ctl}/icons/proxy-suite-active-symbolic.svg (100%) rename pkgs/{proxy-suite-tray => proxy-ctl}/icons/proxy-suite-active.svg (100%) rename pkgs/{proxy-suite-tray => proxy-ctl}/icons/proxy-suite-disabled-symbolic.svg (100%) rename pkgs/{proxy-suite-tray => proxy-ctl}/icons/proxy-suite-disabled.svg (100%) rename pkgs/{proxy-suite-tray => proxy-ctl}/icons/proxy-suite-proxy-symbolic.svg (100%) rename pkgs/{proxy-suite-tray => proxy-ctl}/icons/proxy-suite-proxy.svg (100%) rename pkgs/{proxy-suite-tray => proxy-ctl}/icons/proxy-suite-tunnel-symbolic.svg (100%) rename pkgs/{proxy-suite-tray => proxy-ctl}/icons/proxy-suite-tunnel.svg (100%) rename pkgs/{proxy-suite-tray => proxy-ctl}/icons/proxy-suite-zapret-symbolic.svg (100%) rename pkgs/{proxy-suite-tray => proxy-ctl}/icons/proxy-suite-zapret.svg (100%) create mode 100644 pkgs/proxy-ctl/proxy_gui.py create mode 100644 pkgs/proxy-ctl/proxy_model.py create mode 100644 pkgs/proxy-ctl/proxy_sni.py create mode 100644 pkgs/proxy-ctl/test_proxy_gui.py create mode 100644 pkgs/proxy-ctl/test_proxy_model.py delete mode 100644 pkgs/proxy-suite-tray.nix delete mode 100644 pkgs/proxy-suite-tray/main.c diff --git a/README.md b/README.md index cfa321d..c4592a1 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Bundles [sing-box](https://github.com/SagerNet/sing-box), [XRay](https://github. - Telegram MTProto WebSocket proxy and SSH SOCKS5 tunnel - Cloudflare WARP from a `wgcf` profile, as an outbound or an AWG VPN profile - Server inbounds with share links, QR codes, per-user subscriptions and traffic stats -- A tray indicator, the `proxy-ctl` CLI, and the `proxy-tui` terminal UI +- Proxy Suite GUI (a desktop app with a tray icon), the `proxy-ctl` CLI, and the `proxy-tui` terminal UI ## Setup @@ -88,7 +88,7 @@ services.proxy-suite = { secretFile = "/run/secrets/tg-ws-proxy-secret"; }; - tray.enable = true; + gui.enable = true; }; ``` @@ -105,7 +105,7 @@ See the [options reference](./docs/options/index.md), one page per option group. Usage: proxy-ctl [verb] [args] A group without a verb shows its status or list. - status [--tray] services and routing mode + status [--json] services and routing mode (--tray: deprecated key=value lines) restart restart active services logs [unit] follow logs (default: every proxy-suite unit) where how this host is routed right now diff --git a/docs/options/gui.md b/docs/options/gui.md new file mode 100644 index 0000000..fe5d561 --- /dev/null +++ b/docs/options/gui.md @@ -0,0 +1,59 @@ +# services.proxy-suite.gui + +Part of the [proxy-suite options reference](./index.md). + +## Options + +- gui + - [enable](#services-proxy-suite-gui-enable) + - [autostart](#services-proxy-suite-gui-autostart) + - [refreshInterval](#services-proxy-suite-gui-refreshinterval) + + +## services\.proxy-suite\.gui\.enable + +Whether to enable Proxy Suite GUI, a desktop app with a tray icon for everything proxy-ctl controls at runtime\. + +*Type:* +boolean + +*Default:* + +```nix +false +``` + +*Example:* + +```nix +true +``` + + +## services\.proxy-suite\.gui\.autostart + +Start the GUI hidden in the tray with graphical sessions, as the +` proxy-suite-gui ` systemd user unit on ` graphical-session.target `\. + +*Type:* +boolean + +*Default:* + +```nix +true +``` + + +## services\.proxy-suite\.gui\.refreshInterval + +Status refresh interval, in seconds\. + +*Type:* +positive integer, meaning >0 + +*Default:* + +```nix +3 +``` diff --git a/docs/options/index.md b/docs/options/index.md index 5732c78..f585cef 100644 --- a/docs/options/index.md +++ b/docs/options/index.md @@ -8,12 +8,12 @@ Update the module option docs there instead of editing these files by hand. - [amneziaWg](./amneziaWg.md) - [geodata](./geodata.md) +- [gui](./gui.md) - [inbounds](./inbounds.md) - [perAppRouting](./perAppRouting.md) - [proxy](./proxy.md) - [sshProxy](./sshProxy.md) - [tgWsProxy](./tgWsProxy.md) -- [tray](./tray.md) - [tui](./tui.md) - [userControl](./userControl.md) - [warp](./warp.md) @@ -40,6 +40,11 @@ services.proxy-suite = { assets = pkgs.v2ray-rules-dat; }; }; + gui = { + autostart = true; + enable = false; + refreshInterval = 3; + }; inbounds = { enable = false; listeners = { }; @@ -100,7 +105,6 @@ services.proxy-suite = { }; }; proxy = { - auth = { }; autoProxy = { enable = false; exclude = [ ]; @@ -163,7 +167,6 @@ services.proxy-suite = { singBox = { clashApiPort = 9090; package = pkgs.sing-box; - urlTest = { }; }; subscriptionUpdateInterval = "1d"; subscriptions = [ ]; @@ -240,11 +243,6 @@ services.proxy-suite = { secret = null; secretFile = null; }; - tray = { - autostart = true; - enable = false; - pollInterval = 5; - }; tui = { enable = true; }; @@ -253,9 +251,7 @@ services.proxy-suite = { "global" "perApp" ]; - global = { }; group = "proxy-suite"; - perApp = { }; }; warp = { asAmneziaWg = false; diff --git a/docs/options/tray.md b/docs/options/tray.md deleted file mode 100644 index 359c1b8..0000000 --- a/docs/options/tray.md +++ /dev/null @@ -1,58 +0,0 @@ -# services.proxy-suite.tray - -Part of the [proxy-suite options reference](./index.md). - -## Options - -- tray - - [enable](#services-proxy-suite-tray-enable) - - [autostart](#services-proxy-suite-tray-autostart) - - [pollInterval](#services-proxy-suite-tray-pollinterval) - - -## services\.proxy-suite\.tray\.enable - -Whether to enable the system tray indicator\. - -*Type:* -boolean - -*Default:* - -```nix -false -``` - -*Example:* - -```nix -true -``` - - -## services\.proxy-suite\.tray\.autostart - -Start the tray in graphical sessions (XDG autostart)\. - -*Type:* -boolean - -*Default:* - -```nix -true -``` - - -## services\.proxy-suite\.tray\.pollInterval - -Status refresh interval, in seconds\. - -*Type:* -positive integer, meaning >0 - -*Default:* - -```nix -5 -``` diff --git a/flake.nix b/flake.nix index f507f87..0b2e7ee 100644 --- a/flake.nix +++ b/flake.nix @@ -64,12 +64,13 @@ amneziawg-tools amneziawg-go mkProxyCtl - mkProxySuiteTray mkTgWsProxy tg-ws-proxy - proxy-suite-tray zapret2 ; + # Replaced by Proxy Suite GUI, which mkProxyCtl builds as `.gui`. + proxy-suite-tray = throw "proxy-suite-tray was replaced by Proxy Suite GUI: set services.proxy-suite.gui.enable"; + mkProxySuiteTray = throw "mkProxySuiteTray was replaced by Proxy Suite GUI: set services.proxy-suite.gui.enable"; }; packages = forAll ( @@ -112,7 +113,6 @@ amneziawg-tools amneziawg-go tg-ws-proxy - proxy-suite-tray zapret2 ; xray = import ./pkgs/xray.nix { inherit pkgs; }; diff --git a/modules/proxy-suite/default.nix b/modules/proxy-suite/default.nix index 0c5a858..aa65088 100644 --- a/modules/proxy-suite/default.nix +++ b/modules/proxy-suite/default.nix @@ -182,18 +182,6 @@ in ; } )) - - (lib.mkIf cfg.tray.enable ( - import ./tray.nix { - inherit - config - lib - pkgs - packages - cfg - ; - } - )) ] )) ]; diff --git a/modules/proxy-suite/options/default.nix b/modules/proxy-suite/options/default.nix index c74dd24..6fdd2b4 100644 --- a/modules/proxy-suite/options/default.nix +++ b/modules/proxy-suite/options/default.nix @@ -17,6 +17,7 @@ ./warp.nix ./tg-ws-proxy.nix ./geodata.nix + ./gui.nix ./tray.nix ./tui.nix ./user-control.nix diff --git a/modules/proxy-suite/options/gui.nix b/modules/proxy-suite/options/gui.nix new file mode 100644 index 0000000..97ca761 --- /dev/null +++ b/modules/proxy-suite/options/gui.nix @@ -0,0 +1,25 @@ +{ lib, ... }: + +let + inherit (lib) mkEnableOption mkOption types; +in +{ + options.services.proxy-suite.gui = { + enable = mkEnableOption "Proxy Suite GUI, a desktop app with a tray icon for everything proxy-ctl controls at runtime"; + + autostart = mkOption { + type = types.bool; + default = true; + description = '' + Start the GUI hidden in the tray with graphical sessions, as the + `proxy-suite-gui` systemd user unit on `graphical-session.target`. + ''; + }; + + refreshInterval = mkOption { + type = types.ints.positive; + default = 3; + description = "Status refresh interval, in seconds."; + }; + }; +} diff --git a/modules/proxy-suite/options/tray.nix b/modules/proxy-suite/options/tray.nix index 2ccdd74..836cebe 100644 --- a/modules/proxy-suite/options/tray.nix +++ b/modules/proxy-suite/options/tray.nix @@ -1,22 +1,19 @@ { lib, ... }: let - inherit (lib) mkEnableOption mkOption types; + p = + path: + [ + "services" + "proxy-suite" + ] + ++ lib.splitString "." path; in { - options.services.proxy-suite.tray = { - enable = mkEnableOption "the system tray indicator"; - - autostart = mkOption { - type = types.bool; - default = true; - description = "Start the tray in graphical sessions (XDG autostart)."; - }; - - pollInterval = mkOption { - type = types.ints.positive; - default = 5; - description = "Status refresh interval, in seconds."; - }; - }; + # The tray indicator became Proxy Suite GUI, which has the tray icon built in. + imports = [ + (lib.mkRenamedOptionModule (p "tray.enable") (p "gui.enable")) + (lib.mkRenamedOptionModule (p "tray.autostart") (p "gui.autostart")) + (lib.mkRenamedOptionModule (p "tray.pollInterval") (p "gui.refreshInterval")) + ]; } diff --git a/modules/proxy-suite/service/context.nix b/modules/proxy-suite/service/context.nix index 21f69b0..e6d847f 100644 --- a/modules/proxy-suite/service/context.nix +++ b/modules/proxy-suite/service/context.nix @@ -182,6 +182,7 @@ let inherit (scripts) proxyInboundsLinksFile proxyInboundsSubscriptionsFile; proxyInboundsSubscriptionsBaseUrl = proxyInboundsCfg.subscriptions.baseUrl; inherit amneziaWgProfileNamesFile; + guiRefreshInterval = cfg.gui.refreshInterval; inherit (perAppRouting) perAppRoutingProfilesFile proxychainsConfigFile diff --git a/modules/proxy-suite/service/control.nix b/modules/proxy-suite/service/control.nix index 17621e3..647e652 100644 --- a/modules/proxy-suite/service/control.nix +++ b/modules/proxy-suite/service/control.nix @@ -23,6 +23,7 @@ proxyInboundsLinksFile, proxyInboundsSubscriptionsFile, proxyInboundsSubscriptionsBaseUrl, + guiRefreshInterval, }: { proxyCtl = packages.mkProxyCtl { @@ -36,6 +37,7 @@ proxychainsQuietArg routeModeStateFile amneziaWgProfileNamesFile + guiRefreshInterval ; defaultRouteMode = if (proxyCfg.routing.default == "proxy") then "blacklist" else "whitelist"; perAppRoutingEnabled = if perAppRoutingCfg.enable then "1" else "0"; diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index a0d6ae3..03a0b57 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -135,7 +135,11 @@ in lib.mkMerge [ autoProxyUnits { - environment.systemPackages = [ control.proxyCtl ] ++ lib.optional cfg.tui.enable control.proxyCtl.tui; + environment.systemPackages = [ + control.proxyCtl + ] + ++ lib.optional cfg.tui.enable control.proxyCtl.tui + ++ lib.optional cfg.gui.enable control.proxyCtl.gui; # nftables must be on for transparent routing backends. Global TUN uses # SingBox auto_redirect programs an `inet sing-box` nftables table. @@ -195,7 +199,27 @@ lib.mkMerge [ ] ); - systemd.user.services = mkNamedUnits userServiceEntries; + systemd.user.services = lib.mkMerge [ + (mkNamedUnits userServiceEntries) + (lib.mkIf (cfg.gui.enable && cfg.gui.autostart) { + # Starts hidden in the tray with every graphical session. + proxy-suite-gui = { + description = "Proxy Suite GUI (tray icon)"; + wantedBy = [ "graphical-session.target" ]; + partOf = [ "graphical-session.target" ]; + after = [ "graphical-session.target" ]; + unitConfig.ConditionEnvironment = [ + "|WAYLAND_DISPLAY" + "|DISPLAY" + ]; + serviceConfig = { + ExecStart = "${control.proxyCtl.gui}/bin/proxy-suite-gui --hidden"; + Restart = "on-failure"; + RestartSec = 3; + }; + }; + }) + ]; assertions = import ../service-assertions.nix { inherit lib cfg derived; diff --git a/modules/proxy-suite/tray.nix b/modules/proxy-suite/tray.nix deleted file mode 100644 index 439d7ed..0000000 --- a/modules/proxy-suite/tray.nix +++ /dev/null @@ -1,55 +0,0 @@ -# Tray indicator module for proxy-suite -{ - config, - lib, - pkgs, - packages, - cfg, -}: - -let - tray = cfg.tray; - - proxyTray = packages.mkProxySuiteTray { - pollInterval = tray.pollInterval; - }; - - desktopEntryText = '' - [Desktop Entry] - Type=Application - Version=1.0 - Name=Proxy Suite Tray - Comment=System tray indicator for proxy-suite - Exec=${proxyTray}/bin/proxy-suite-tray - Icon=network-vpn - Categories=Network;System; - StartupNotify=false - Terminal=false - ''; - - desktopEntry = pkgs.writeTextFile { - name = "proxy-suite-tray.desktop"; - destination = "/share/applications/proxy-suite-tray.desktop"; - text = desktopEntryText; - }; - - autostartEntry = pkgs.writeTextFile { - name = "proxy-suite-tray-autostart.desktop"; - destination = "/share/xdg/autostart/proxy-suite-tray.desktop"; - text = '' - ${desktopEntryText} - X-GNOME-Autostart-enabled=true - ''; - }; -in -{ - environment.systemPackages = [ - proxyTray - desktopEntry - ]; - - environment.etc = lib.mkIf tray.autostart { - "xdg/autostart/proxy-suite-tray.desktop".source = - "${autostartEntry}/share/xdg/autostart/proxy-suite-tray.desktop"; - }; -} diff --git a/nix/checks.nix b/nix/checks.nix index 2b84f22..e103726 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -9,7 +9,6 @@ let pkgs = import nixpkgs { inherit system; }; - suitePkgs = import ../pkgs/default.nix { inherit pkgs; }; parserChecks = import ./checks/parsers.nix { inherit pkgs; }; checkLib = import ./checks/lib.nix { inherit @@ -28,7 +27,6 @@ let ; inherit (checkLib) rg; readmeDocSource = builtins.readFile ../nix/readme-doc.nix; - trayModuleSource = builtins.readFile ../modules/proxy-suite/tray.nix; tgWsProxyModuleSource = builtins.readFile ../modules/proxy-suite/tg-ws-proxy.nix; controlModuleSource = builtins.readFile ../modules/proxy-suite/service/control.nix; }; @@ -41,9 +39,6 @@ let }; in moduleSuiteChecks -// { - proxy-suite-tray-build = suitePkgs.proxy-suite-tray; -} // pkgs.lib.optionalAttrs (system == "x86_64-linux") { amneziawg-runtime = amneziaWgRuntime; proxy-inbounds-runtime = proxyInboundsRuntime; diff --git a/nix/checks/gui.nix b/nix/checks/gui.nix new file mode 100644 index 0000000..e36010a --- /dev/null +++ b/nix/checks/gui.nix @@ -0,0 +1,81 @@ +{ + evalProxySuite, + baseModule, + packagePathMatches, +}: + +let + guiFixture = evalProxySuite [ + baseModule + { services.proxy-suite.gui.enable = true; } + ]; + + guiManualFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.gui = { + enable = true; + autostart = false; + }; + } + ]; + + # The old tray options still work, as renames of the GUI's. + deprecatedTrayFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.tray = { + enable = true; + pollInterval = 7; + }; + } + ]; + + tuiOffFixture = evalProxySuite [ + baseModule + { services.proxy-suite.tui.enable = false; } + ]; + + guiPackage = ".*/[^/]*proxy-suite-gui(-[0-9.]+)?$"; +in +{ + assertions = [ + ( + assert packagePathMatches guiManualFixture.config.environment.systemPackages ".*/[^/]*proxy-tui$"; + assert !(packagePathMatches tuiOffFixture.config.environment.systemPackages ".*/[^/]*proxy-tui$"); + assert !(packagePathMatches tuiOffFixture.config.environment.systemPackages guiPackage); + true + ) + ( + assert packagePathMatches guiFixture.config.environment.systemPackages guiPackage; + assert packagePathMatches guiManualFixture.config.environment.systemPackages guiPackage; + true + ) + ( + let + unit = guiFixture.config.systemd.user.services.proxy-suite-gui; + in + assert unit.wantedBy == [ "graphical-session.target" ]; + assert builtins.elem "graphical-session.target" unit.partOf; + assert builtins.match ".*/bin/proxy-suite-gui --hidden$" unit.serviceConfig.ExecStart != null; + true + ) + ( + assert !(guiManualFixture.config.systemd.user.services ? proxy-suite-gui); + assert !(tuiOffFixture.config.systemd.user.services ? proxy-suite-gui); + true + ) + ( + let + cfg = deprecatedTrayFixture.config; + in + assert cfg.services.proxy-suite.gui.enable; + assert cfg.services.proxy-suite.gui.refreshInterval == 7; + assert packagePathMatches cfg.environment.systemPackages guiPackage; + assert builtins.any ( + w: builtins.match ".*services\\.proxy-suite\\.gui\\.enable.*" w != null + ) cfg.warnings; + true + ) + ]; +} diff --git a/nix/checks/module-suite.nix b/nix/checks/module-suite.nix index 37a3e72..5ed0c4e 100644 --- a/nix/checks/module-suite.nix +++ b/nix/checks/module-suite.nix @@ -85,7 +85,7 @@ let ; }; - trayChecks = import ./tray.nix { + guiChecks = import ./gui.nix { inherit evalProxySuite baseModule @@ -256,7 +256,7 @@ let ++ zapretChecks.assertions ++ zapret2Checks.assertions ++ globalProxyModeChecks.assertions - ++ trayChecks.assertions + ++ guiChecks.assertions ++ subscriptionChecks.assertions ++ routeModeChecks.assertions ++ perAppRoutingChecks.assertions @@ -269,4 +269,5 @@ in per-app-zapret-runtime = perAppRoutingChecks.runtime; zapret-hostlist-rules = zapretChecks.rules; zapret2-config = zapret2Checks.runtime; + proxy-suite-gui-build = _minimalProxyCtl.proxyCtl.gui; } diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index fbf7ee9..24d9f2a 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -4,7 +4,6 @@ generatedOptionsDoc, generatedReadmeDoc, readmeDocSource, - trayModuleSource, tgWsProxyModuleSource, controlModuleSource, }: @@ -424,6 +423,34 @@ touch "$out" ''; + # proxy_model: the status strip, tab loads and the tray menu tree, without a UI toolkit. + proxy-model-unit = + pkgs.runCommand "proxy-suite-proxy-model-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; } '' + export PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=${../../pkgs/proxy-ctl} + python ${../../pkgs/proxy-ctl}/test_proxy_model.py + touch "$out" + ''; + + # proxy_gui and proxy_sni import against GTK4/libadwaita, the D-Bus interfaces parse, + # and the tray menu serializes to dbusmenu's layout type. No display needed. + proxy-gui-smoke = + pkgs.runCommand "proxy-suite-proxy-gui-smoke-check" + { + nativeBuildInputs = [ + (pkgs.python3.withPackages (ps: [ ps.pygobject3 ])) + pkgs.gobject-introspection + ]; + buildInputs = [ + pkgs.gtk4 + pkgs.libadwaita + ]; + } + '' + export PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=${../../pkgs/proxy-ctl} + python ${../../pkgs/proxy-ctl}/test_proxy_gui.py + touch "$out" + ''; + # autoProxy slowness routing: sampler and judge. autoproxy-slowness = pkgs.runCommand "proxy-suite-autoproxy-slowness-check" @@ -613,7 +640,6 @@ ) (pkgs.writeText "proxy-suite-readme-doc-source-check" "ok"); package-source = builtins.seq ( - assert !(pkgs.lib.hasInfix "../../pkgs/proxy-suite-tray.nix" trayModuleSource); assert !(pkgs.lib.hasInfix "../../pkgs/tg-ws-proxy.nix" tgWsProxyModuleSource); assert !(pkgs.lib.hasInfix "../../../pkgs/proxy-ctl.nix" controlModuleSource); true diff --git a/nix/checks/tray.nix b/nix/checks/tray.nix deleted file mode 100644 index 08f2bf7..0000000 --- a/nix/checks/tray.nix +++ /dev/null @@ -1,65 +0,0 @@ -{ - evalProxySuite, - baseModule, - packagePathMatches, -}: - -let - trayAutostartFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.tray.enable = true; - } - ]; - - trayManualFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.tray = { - enable = true; - autostart = false; - }; - } - ]; - - tuiOffFixture = evalProxySuite [ - baseModule - { services.proxy-suite.tui.enable = false; } - ]; -in -{ - assertions = [ - ( - assert packagePathMatches trayManualFixture.config.environment.systemPackages ".*/[^/]*proxy-tui$"; - assert !(packagePathMatches tuiOffFixture.config.environment.systemPackages ".*/[^/]*proxy-tui$"); - true - ) - ( - assert packagePathMatches trayAutostartFixture.config.environment.systemPackages - ".*/[^/]*proxy-suite-tray(-[0-9.]+)?$"; - true - ) - ( - assert packagePathMatches trayAutostartFixture.config.environment.systemPackages - ".*/[^/]*proxy-suite-tray\\.desktop$"; - true - ) - ( - assert - builtins.match ".*/share/xdg/autostart/proxy-suite-tray\\.desktop$" ( - builtins.unsafeDiscardStringContext - trayAutostartFixture.config.environment.etc."xdg/autostart/proxy-suite-tray.desktop".source - ) != null; - true - ) - ( - assert !(trayManualFixture.config.environment.etc ? "xdg/autostart/proxy-suite-tray.desktop"); - true - ) - ( - assert packagePathMatches trayManualFixture.config.environment.systemPackages - ".*/[^/]*proxy-suite-tray\\.desktop$"; - true - ) - ]; -} diff --git a/nix/options-doc.nix b/nix/options-doc.nix index 91881e8..847b2aa 100644 --- a/nix/options-doc.nix +++ b/nix/options-doc.nix @@ -17,21 +17,24 @@ let ]; }; - # Visible options only (renamed aliases are hidden), packages shown by name. + # Visible options only (renamed aliases are hidden, and so are groups left + # with nothing but aliases), packages shown by name. visibleConfig = opts: cfg: - lib.mapAttrs ( - name: opt: - if !lib.isOption opt then - visibleConfig opt cfg.${name} - else if lib.isDerivation cfg.${name} then - { - __pretty = _: "pkgs.${lib.getName cfg.${name}}"; - val = null; - } - else - cfg.${name} - ) (lib.filterAttrs (name: opt: name != "_module" && (opt.visible or true) != false) opts); + lib.filterAttrs (name: value: lib.isOption opts.${name} || value != { }) ( + lib.mapAttrs ( + name: opt: + if !lib.isOption opt then + visibleConfig opt cfg.${name} + else if lib.isDerivation cfg.${name} then + { + __pretty = _: "pkgs.${lib.getName cfg.${name}}"; + val = null; + } + else + cfg.${name} + ) (lib.filterAttrs (name: opt: name != "_module" && (opt.visible or true) != false) opts) + ); optionDocs = pkgs.nixosOptionsDoc { options.services.proxy-suite = eval.options.services.proxy-suite; diff --git a/pkgs/default.nix b/pkgs/default.nix index 99f202f..76690eb 100644 --- a/pkgs/default.nix +++ b/pkgs/default.nix @@ -2,7 +2,6 @@ let amneziaWg = import ./amneziawg.nix { inherit pkgs; }; mkTgWsProxy = _args: import ./tg-ws-proxy.nix { inherit pkgs; }; - mkProxySuiteTray = args: import ./proxy-suite-tray.nix ({ inherit pkgs; } // args); zapret2 = import ./zapret2.nix { inherit pkgs; }; mkProxyCtl = import ./proxy-ctl.nix { lib = pkgs.lib; @@ -15,10 +14,8 @@ in amneziawg-go = amneziaWg.userspace; inherit mkTgWsProxy - mkProxySuiteTray mkProxyCtl zapret2 ; tg-ws-proxy = mkTgWsProxy { }; - proxy-suite-tray = mkProxySuiteTray { }; } diff --git a/pkgs/proxy-ctl.nix b/pkgs/proxy-ctl.nix index d6e4d9c..e8b97b3 100644 --- a/pkgs/proxy-ctl.nix +++ b/pkgs/proxy-ctl.nix @@ -35,6 +35,7 @@ autoProxyEnabled, autoProxyStateDir, singBox, + guiRefreshInterval ? 3, }: let @@ -78,6 +79,11 @@ let envFlags = lib.concatStringsSep " " ( lib.mapAttrsToList (name: value: "--set ${name} ${lib.escapeShellArg value}") wrapperEnv ); + # The modules both front-ends import: proxy_ctl for reads, proxy_model for the tabs and the tray menu. + pythonModules = pkgs.runCommand "proxy-suite-python-modules" { } '' + install -Dm644 ${./proxy-ctl/proxy_ctl.py} "$out/proxy_ctl.py" + install -Dm644 ${./proxy-ctl/proxy_model.py} "$out/proxy_model.py" + ''; # A separate package: the Textual closure stays off hosts that don't enable it. # It imports proxy_ctl for reads and runs proxy-ctl for every change. tui = pkgs.symlinkJoin { @@ -91,7 +97,7 @@ let nativeBuildInputs = [ pkgs.makeWrapper ]; postBuild = '' wrapProgram "$out/bin/proxy-tui" \ - --prefix PYTHONPATH : ${pkgs.writeTextDir "proxy_ctl.py" (builtins.readFile ./proxy-ctl/proxy_ctl.py)} \ + --prefix PYTHONPATH : ${pythonModules} \ --prefix PATH : "${ lib.makeBinPath [ proxyCtl @@ -100,11 +106,102 @@ let }" ${envFlags} ''; }; + guiPython = pkgs.python3.withPackages (ps: [ ps.pygobject3 ]); + # Proxy Suite GUI: a GTK4/libadwaita window over the same tabs as the TUI, with a tray icon. + # Separate for the same reason as the TUI: GTK stays off hosts that don't enable it. + gui = pkgs.stdenv.mkDerivation { + pname = "proxy-suite-gui"; + version = "0.2.0"; + dontUnpack = true; + nativeBuildInputs = [ + pkgs.wrapGAppsHook4 + pkgs.gobject-introspection + pkgs.makeWrapper + guiPython + ]; + buildInputs = [ + pkgs.gtk4 + pkgs.libadwaita + pkgs.adwaita-icon-theme + guiPython + ]; + # A Python script: the wrapper is made by hand below, with the GApps arguments. + dontWrapGApps = true; + installPhase = '' + runHook preInstall + install -Dm644 ${./proxy-ctl/proxy_gui.py} "$out/lib/proxy-suite-gui/proxy_gui.py" + install -Dm644 ${./proxy-ctl/proxy_sni.py} "$out/lib/proxy-suite-gui/proxy_sni.py" + + # Tray icons in one flat directory (the tray's IconThemePath), and in hicolor for everything else. + icons="$out/share/proxy-suite-gui/icons" + python3 ${./proxy-ctl/icons/badges.py} ${./proxy-ctl/icons} "$icons" + install -Dm644 ${./proxy-ctl/icons/io.github.FUFSoB.ProxySuite.svg} "$icons/io.github.FUFSoB.ProxySuite.svg" + for icon in "$icons"/*.svg; do + case "$icon" in + *-symbolic.svg) install -Dm644 "$icon" "$out/share/icons/hicolor/symbolic/apps/''${icon##*/}" ;; + *) install -Dm644 "$icon" "$out/share/icons/hicolor/scalable/apps/''${icon##*/}" ;; + esac + done + + mkdir -p "$out/share/applications" "$out/share/systemd/user" + cat > "$out/share/applications/io.github.FUFSoB.ProxySuite.desktop" < "$out/share/systemd/user/proxy-suite-gui.service" < + +proxy-suite-[-symbolic].svg -> proxy-suite--[-symbolic].svg, next to copies of the bases. +The shield is cut away around the badge, so it reads on any panel color. +""" + +import os +import re +import shutil +import sys + +STATES = ("disabled", "zapret", "proxy", "active", "tunnel") +CX, CY = 18.5, 18.5 +CUT, DOT = 5.8, 4.8 # radius of the gap in the shield, and of the badge inside it + +# badge -> (fill, stroke, glyph drawn in the glyph color) +GLYPHS = { + "failed": ( + "#D32F2F", + "#7F0000", + f'' + f'', + ), + "busy": ( + "#FFA000", + "#8D5A00", + "".join(f'' for dx in (-2.2, 0, 2.2)), + ), + "unknown": ( + "#757575", + "#424242", + f'' + f'', + ), +} + + +def inner(svg): + return re.search(r"]*>(.*)", svg, re.S).group(1) + + +def badged(svg, badge, symbolic): + fill, stroke, glyph = GLYPHS[badge] + mask = ( + f'' + f'' + ) + if symbolic: + # One color: the badge is a disc with its glyph knocked out. + mask += ( + f'' + f'{glyph}' + ) + badge_svg = f'' + else: + badge_svg = ( + f'' + f'{glyph}' + ) + return ( + '\n' + f" {mask}\n" + f' {inner(svg)}\n' + f" {badge_svg}\n" + "\n" + ) + + +def main(src, out): + os.makedirs(out, exist_ok=True) + for state in STATES: + for suffix in ("", "-symbolic"): + base = os.path.join(src, f"proxy-suite-{state}{suffix}.svg") + shutil.copyfile(base, os.path.join(out, os.path.basename(base))) + with open(base) as f: + svg = f.read() + for badge in GLYPHS: + with open(os.path.join(out, f"proxy-suite-{state}-{badge}{suffix}.svg"), "w") as f: + f.write(badged(svg, badge, bool(suffix))) + + +if __name__ == "__main__": + main(*sys.argv[1:3]) diff --git a/pkgs/proxy-ctl/icons/io.github.FUFSoB.ProxySuite.svg b/pkgs/proxy-ctl/icons/io.github.FUFSoB.ProxySuite.svg new file mode 100644 index 0000000..9957d93 --- /dev/null +++ b/pkgs/proxy-ctl/icons/io.github.FUFSoB.ProxySuite.svg @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + diff --git a/pkgs/proxy-suite-tray/icons/proxy-suite-active-symbolic.svg b/pkgs/proxy-ctl/icons/proxy-suite-active-symbolic.svg similarity index 100% rename from pkgs/proxy-suite-tray/icons/proxy-suite-active-symbolic.svg rename to pkgs/proxy-ctl/icons/proxy-suite-active-symbolic.svg diff --git a/pkgs/proxy-suite-tray/icons/proxy-suite-active.svg b/pkgs/proxy-ctl/icons/proxy-suite-active.svg similarity index 100% rename from pkgs/proxy-suite-tray/icons/proxy-suite-active.svg rename to pkgs/proxy-ctl/icons/proxy-suite-active.svg diff --git a/pkgs/proxy-suite-tray/icons/proxy-suite-disabled-symbolic.svg b/pkgs/proxy-ctl/icons/proxy-suite-disabled-symbolic.svg similarity index 100% rename from pkgs/proxy-suite-tray/icons/proxy-suite-disabled-symbolic.svg rename to pkgs/proxy-ctl/icons/proxy-suite-disabled-symbolic.svg diff --git a/pkgs/proxy-suite-tray/icons/proxy-suite-disabled.svg b/pkgs/proxy-ctl/icons/proxy-suite-disabled.svg similarity index 100% rename from pkgs/proxy-suite-tray/icons/proxy-suite-disabled.svg rename to pkgs/proxy-ctl/icons/proxy-suite-disabled.svg diff --git a/pkgs/proxy-suite-tray/icons/proxy-suite-proxy-symbolic.svg b/pkgs/proxy-ctl/icons/proxy-suite-proxy-symbolic.svg similarity index 100% rename from pkgs/proxy-suite-tray/icons/proxy-suite-proxy-symbolic.svg rename to pkgs/proxy-ctl/icons/proxy-suite-proxy-symbolic.svg diff --git a/pkgs/proxy-suite-tray/icons/proxy-suite-proxy.svg b/pkgs/proxy-ctl/icons/proxy-suite-proxy.svg similarity index 100% rename from pkgs/proxy-suite-tray/icons/proxy-suite-proxy.svg rename to pkgs/proxy-ctl/icons/proxy-suite-proxy.svg diff --git a/pkgs/proxy-suite-tray/icons/proxy-suite-tunnel-symbolic.svg b/pkgs/proxy-ctl/icons/proxy-suite-tunnel-symbolic.svg similarity index 100% rename from pkgs/proxy-suite-tray/icons/proxy-suite-tunnel-symbolic.svg rename to pkgs/proxy-ctl/icons/proxy-suite-tunnel-symbolic.svg diff --git a/pkgs/proxy-suite-tray/icons/proxy-suite-tunnel.svg b/pkgs/proxy-ctl/icons/proxy-suite-tunnel.svg similarity index 100% rename from pkgs/proxy-suite-tray/icons/proxy-suite-tunnel.svg rename to pkgs/proxy-ctl/icons/proxy-suite-tunnel.svg diff --git a/pkgs/proxy-suite-tray/icons/proxy-suite-zapret-symbolic.svg b/pkgs/proxy-ctl/icons/proxy-suite-zapret-symbolic.svg similarity index 100% rename from pkgs/proxy-suite-tray/icons/proxy-suite-zapret-symbolic.svg rename to pkgs/proxy-ctl/icons/proxy-suite-zapret-symbolic.svg diff --git a/pkgs/proxy-suite-tray/icons/proxy-suite-zapret.svg b/pkgs/proxy-ctl/icons/proxy-suite-zapret.svg similarity index 100% rename from pkgs/proxy-suite-tray/icons/proxy-suite-zapret.svg rename to pkgs/proxy-ctl/icons/proxy-suite-zapret.svg diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index e0d192d..5fe7140 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -46,7 +46,7 @@ HELP = """\ Usage: proxy-ctl [verb] [args] A group without a verb shows its status or list. - status [--tray] services and routing mode + status [--json] services and routing mode (--tray: deprecated key=value lines) restart restart active services logs [unit] follow logs (default: every proxy-suite unit) where how this host is routed right now @@ -303,7 +303,7 @@ COMPLETE = { "help": "usage", } }, - "status": {"flags": {"--tray": "key=value lines for the tray"}}, + "status": {"flags": {"--json": "machine-readable state, with the GUI's overall state"}}, "logs": {"args": lambda: _names([*ALL_SERVICES, *map(_awg_service, _awg_profiles())]), "repeat": True}, "where": {"args": _autoproxy_choices}, "proxy": { @@ -469,24 +469,115 @@ def _route_mode_label(mode): return ROUTE_MODE_LABELS.get(mode, "Unknown") -def _status_tray(): - for key, svc in ( - ("socks", "proxy-suite-socks"), - ("tproxy", "proxy-suite-tproxy"), - ("tun", "proxy-suite-tun"), - ("zapret", "proxy-suite-zapret"), - ): - print(f"{key}_available={_bool(svc_exists(svc))}") - print(f"{key}_active={_bool(svc_active(svc))}") +def _unit_states(units): + """unit -> ActiveState for the units that exist, in one systemctl call.""" + if not units: + return {} + _, out = _run(["systemctl", "show", "--property=Id,LoadState,ActiveState", "--", *units], capture=True, quiet=True) + states = {} + for unit, block in zip(units, out.strip().split("\n\n")): + props = dict(line.split("=", 1) for line in block.splitlines() if "=" in line) + if props.get("LoadState") not in (None, "not-found"): + states[unit] = props.get("ActiveState", "unknown") + return states + + +SNAPSHOT_UNITS = { + "proxy": "proxy-suite-socks", + "tproxy": "proxy-suite-tproxy", + "tun": "proxy-suite-tun", + "zapret": "proxy-suite-zapret", +} +SUBSCRIPTION_UPDATE = "proxy-suite-subscription-update" +BUSY_STATES = ("activating", "deactivating", "reloading") + + +def _snapshot_units(): + return [*ALL_SERVICES, SUBSCRIPTION_UPDATE, *map(_awg_service, _awg_profiles())] + + +def _status_snapshot(states=None): + """What runs, as data: the GUI's tray, `status --json` and `status --tray` all read this. + + states: unit -> ActiveState for the existing units, when the caller already has them. + """ + if states is None: + states = _unit_states(_snapshot_units()) profiles = _awg_profiles() - active = _active_awg_profiles() - print(f"subscription_update_available={_bool(svc_exists('proxy-suite-subscription-update'))}") - print(f"route_mode_available={_bool(svc_exists('proxy-suite-socks'))}") - print(f"route_mode={_route_mode_current()}") - print(f"default_route_mode={_route_mode_default()}") - print(f"awg_available={_bool(profiles)}") - print(f"awg_active={active[0] if active else ''}") - print(f"awg_profiles={','.join(profiles)}") + snapshot = { + name: {"available": unit in states, "active": states.get(unit) == "active"} for name, unit in SNAPSHOT_UNITS.items() + } + snapshot["awg"] = { + "available": bool(profiles), + "profiles": profiles, + "active": next((p for p in profiles if states.get(_awg_service(p)) == "active"), ""), + } + snapshot["route_mode"] = { + "available": "proxy-suite-socks" in states, + "current": _route_mode_current(), + "default": _route_mode_default(), + } + snapshot["subscription_update"] = {"available": SUBSCRIPTION_UPDATE in states, "state": states.get(SUBSCRIPTION_UPDATE, "")} + snapshot["units"] = dict(states) + snapshot["failed"] = sorted(u for u, s in states.items() if s == "failed") + snapshot["overall"] = _overall_state(snapshot) + return snapshot + + +def _overall_state(snapshot): + """base: the tray icon's color (tunnel > active > proxy > zapret > disabled); badge: failed > busy. + + A snapshot of None is state that could not be read. + """ + if snapshot is None: + return {"base": "disabled", "badge": "unknown", "label": "Status unavailable"} + proxy, zapret = snapshot["proxy"]["active"], snapshot["zapret"]["active"] + traffic = snapshot["tun"]["active"] or snapshot["tproxy"]["active"] or bool(snapshot["awg"]["active"]) + if traffic: + base = "tunnel" + elif proxy and zapret: + base = "active" + else: + base = "proxy" if proxy else "zapret" if zapret else "disabled" + if proxy: + label = "Proxy" + (" + traffic" if traffic else "") + (" + zapret" if zapret else "") + label = "Proxy only" if label == "Proxy" else label + elif snapshot["awg"]["active"]: + label = "AmneziaWG" + else: + label = "Zapret only" if zapret else "Inactive" + units = snapshot.get("units") or {} + if snapshot.get("failed"): + badge = "failed" + elif any(s in BUSY_STATES for s in units.values()): + badge = "busy" + else: + badge = "" + return {"base": base, "badge": badge, "label": label} + + +def _status_tray(): + """Deprecated key=value lines, for scripts written against the old tray.""" + snapshot = _status_snapshot() + for key, name in (("socks", "proxy"), ("tproxy", "tproxy"), ("tun", "tun"), ("zapret", "zapret")): + print(f"{key}_available={_bool(snapshot[name]['available'])}") + print(f"{key}_active={_bool(snapshot[name]['active'])}") + print(f"subscription_update_available={_bool(snapshot['subscription_update']['available'])}") + print(f"route_mode_available={_bool(snapshot['route_mode']['available'])}") + print(f"route_mode={snapshot['route_mode']['current']}") + print(f"default_route_mode={snapshot['route_mode']['default']}") + print(f"awg_available={_bool(snapshot['awg']['available'])}") + print(f"awg_active={snapshot['awg']['active']}") + print(f"awg_profiles={','.join(snapshot['awg']['profiles'])}") + + +def _status_json(): + snapshot = _status_snapshot() + if snapshot["proxy"]["active"]: + snapshot["outbound"] = _status_outbound() or "" + snapshot["autoproxy"] = _status_autoproxy() + snapshot["zapret"]["learned"] = _status_zapret() + print(json.dumps(snapshot, indent=2)) def _status_row(key, value): @@ -546,6 +637,9 @@ def _status_zapret(): def cmd_status(*args): + if args[:1] == ("--json",): + _status_json() + return if args[:1] == ("--tray",): _status_tray() return diff --git a/pkgs/proxy-ctl/proxy_gui.py b/pkgs/proxy-ctl/proxy_gui.py new file mode 100644 index 0000000..6af433b --- /dev/null +++ b/pkgs/proxy-ctl/proxy_gui.py @@ -0,0 +1,1241 @@ +"""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 shlex +import signal +import subprocess +import sys +import threading + +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 CTL, 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 + + +STATE_ICONS = {"active": "●", "inactive": "○", "failed": "✗", "activating": "◐", "deactivating": "◐", "reloading": "◐"} +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"], + "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"} + +GLOBAL_SHORTCUTS = [ + ("f slash", "Filter the rows (list:learned for one column)"), + ("Escape", "Clear the filter"), + ("Menu F10", "Actions for the selected row (or right-click it)"), + ("1...8", "Jump to a tab"), + ("w", "How is a domain routed"), + ("l", "Follow all logs"), + ("o", "Output of the last command"), + ("F5 r", "Refresh now"), + ("question", "Keyboard shortcuts"), + ("w", "Close the window (the tray keeps running)"), + ("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; } +.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": "", "alt": "", "shift": ""}[m] for m in parts[:-1]) + name = parts[-1] + if len(name) == 1 and name.isupper(): + mods, name = mods + "", name.lower() + return mods + name + + +def display_key(key): + return key.replace("ctrl+", "Ctrl+").replace("space", "Space") + + +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)) + + +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", "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.prompt: + 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.summary_text = "" + self.detail_shape = None + + self.summary = Gtk.Label(xalign=0, wrap=True, selectable=True, visible=False, css_classes=["summary", "dim-label"]) + + 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) + 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) + 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): + ka, kb = model._natural(a.row.get(name)), model._natural(b.row.get(name)) + try: + return (ka > kb) - (ka < kb) + except TypeError: # a number against text in the same place + sa, sb = str(ka), str(kb) + return (sa > sb) - (sa < sb) + + # --- keys ------------------------------------------------------------------------- + + def shortcuts(self): + controller = Gtk.ShortcutController(propagation_phase=Gtk.PropagationPhase.CAPTURE) + for i, action in enumerate(self.tab.actions): + trigger = accelerator(action.key) + controller.add_shortcut(Gtk.Shortcut( + trigger=Gtk.ShortcutTrigger.parse_string(trigger), + action=Gtk.CallbackAction.new(self.keyed(trigger, lambda i=i: self.act(i, from_key=True))), + )) + for trigger, callback in ( + ("slash", lambda *_: self.focus_search()), + ("w", lambda *_: self.win.where()), + ("l", lambda *_: self.win.follow_logs()), + ("o", lambda *_: self.win.show_last_output()), + ("r", lambda *_: self.win.app.reload()), + ("Menu|F10", lambda *_: self.open_menu(None)), + ): + if not any(accelerator(a.key) == trigger for a in self.tab.actions): + controller.add_shortcut(Gtk.Shortcut(trigger=Gtk.ShortcutTrigger.parse_string(trigger), action=Gtk.CallbackAction.new(self.keyed(trigger, callback)))) + return controller + + 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): + self.rows, self.summary_text = rows, summary + self.refill() + + 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: + 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 + self.split.set_visible(not empty) + self.empty.set_visible(empty) + self.summary.set_visible(bool(summary) and not empty) + if empty: + 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"]) + tab_actions = [(i, a) for i, a in enumerate(self.tab.actions) if a.when is None] + for n, (i, action) in enumerate(tab_actions): + box.append(self.action_button(i, 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.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): + self.proc = proc + self.stop.set_visible(True) + self.spinner.set_visible(True) + + def finished(self, status=0): + self.stop.set_visible(False) + self.spinner.set_visible(False) + 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): + if self.proc and self.proc.poll() is None: + try: + os.killpg(self.proc.pid, signal.SIGTERM) + except OSError: + self.proc.terminate() + + +# --- window ------------------------------------------------------------------------------- + + +class Window(Adw.ApplicationWindow): + def __init__(self, app): + super().__init__(application=app, title=TITLE, default_width=1100, default_height=700, icon_name=APP_ID) + self.app = app + self.set_size_request(360, 360) + self.pages = {} + self.typed = {} # action label -> what was last typed there + self.last_output = None # (title, text) + + 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()) + # 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) + menu = Gio.Menu() + section = Gio.Menu() + 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("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"]) + 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), + ("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", ["f"]) + app.set_accels_for_action("win.shortcuts", ["question"]) + app.set_accels_for_action("app.reload", ["F5"]) + app.set_accels_for_action("app.quit", ["q"]) + app.set_accels_for_action("window.close", ["w"]) + for n in range(1, 9): + app.set_accels_for_action(f"win.tab({n - 1})", [f"{n}"]) + + self.connect("close-request", self.on_close) + + # --- 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): + 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): + 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) + + # --- 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 follow_logs(self): + self.app.run_argv("suspend", ["logs"], self) + return True + + def show_last_output(self): + if self.last_output: + OutputDialog(self, *self.last_output).present(self) + else: + self.toast("Nothing has run yet.") + return True + + def perform(self, action, row): + def with_text(text=""): + try: + argv = action.argv(row, text, self.app.states) + except (ValueError, IndexError) as e: + self.toast(f"Cannot run that: {e}") + return + confirm = action.confirm(row) if callable(action.confirm) else action.confirm + if confirm: + self.app.confirm(argv, lambda: self.app.run_argv(action.mode, argv, self), self) + else: + self.app.run_argv(action.mode, argv, self) + + if not action.prompt: + with_text() + 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 responded(_, response): + text = entry.get_text().strip() + if response == "run" and text: + self.typed[action.label] = text + with_text(text) + + dialog.connect("response", responded) + dialog.present(self) + entry.grab_focus() + + def toast(self, message, output=None): + toast = Adw.Toast(title=GLib.markup_escape_text(message), timeout=6) + if 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 page.tab.actions: + section = Adw.ShortcutsSection(title=page.tab.title) + for action in page.tab.actions: + section.add(Adw.ShortcutsItem(title=cap(action.label), accelerator=accelerator(action.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 on_close(self, _): + if self.app.tray and self.app.tray.available: + self.set_visible(False) + 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 + 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()), ("present", lambda *_: self.present())): + action = Gio.SimpleAction.new(name, None) + action.connect("activate", callback) + self.add_action(action) + 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() + if not options.get("hidden"): + self.present(options.get("tab")) + return 0 + + def do_activate(self): + self.present() + + def do_shutdown(self): + if self.tray: + self.tray.close() + Adw.Application.do_shutdown(self) + + # --- window ------------------------------------------------------------------------------ + + def present(self, tab=None): + if self.window is None: + self.window = Window(self) + 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) + self.window.present() + if page := self.window.page(): + page.focus_default() + self.reload() + + def toggle_window(self): + if self.window and self.window.get_visible() and self.window.is_active(): + self.window.set_visible(False) + else: + self.present() + + 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): + if self.loading: + self.pending = True # one more once this load lands + 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), daemon=True).start() + + def load(self, generation, tab): + model.new_load() + states = model._read_states() + snap = model.snapshot(states) if states else None + tray = (model.tray_menu(snap, model.tray_outbounds(snap)), ctl._overall_state(snap)) + result = {"states": states, "snap": snap, "tray": tray} + 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, *model.load_tab(tab, states)) + GLib.idle_add(self.landed, generation, result) + + def landed(self, generation, result): + self.loading = False + if self.window: + self.window.set_busy(False) + if generation == self.generation: + self.states = result["states"] + snap = result["snap"] + tree, overall = result["tray"] + if self.tray: + failed = snap["failed"] if snap else [] + tooltip = overall["label"] + (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"]) + if self.pending: + self.pending = False + self.reload() + 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() + 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): + body = f"{GLib.markup_escape_text(f'proxy-ctl {shlex.join(argv)}')}" + 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): + """run: a toast; dialog, suspend, pause: output streamed into a dialog; copy: the last line to the clipboard.""" + command = f"proxy-ctl {shlex.join(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), daemon=True).start() + + def stream(self, command, argv, mode, win, dialog, qr): + out = [] + try: + p = subprocess.Popen( + [CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, + text=True, errors="replace", start_new_session=True, + ) + if dialog: + GLib.idle_add(lambda: dialog.running(p) and False) + for line in p.stdout: + out.append(line.rstrip("\n")) + if dialog: + GLib.idle_add(lambda line=out[-1]: dialog.write(line) and False) + status = p.wait() + except OSError as e: + out.append(f"cannot run proxy-ctl: {e}") + status = 127 + GLib.idle_add(lambda: self.ran(command, mode, win, dialog, qr, out, status) and False) + + def ran(self, command, mode, win, dialog, qr, out, status): + last = last_line(out) + text = "\n".join(out) + output = (command, text) + if win is not None: + win.last_output = output + if dialog: + dialog.finished(status) + 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: + dialog.show_qr(last) + elif win is not None: + if mode == "copy" and not status and last: + win.copy_text(last, f"Copied: {last}") + else: + message = f"{last} ({command})" if last else command + win.toast(f"exit {status}: {message}" if status else message, output if len(out) > 1 or status else None) + elif status: + # From the tray: nothing else would say it failed. + note = Gio.Notification.new(f"{command} failed") + note.set_body(last or f"exit status {status}") + note.set_default_action("app.present") + self.send_notification(None, note) + self.reload() + + +def main(argv=None): + return ProxySuiteGui().run(argv if argv is not None else sys.argv) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pkgs/proxy-ctl/proxy_model.py b/pkgs/proxy-ctl/proxy_model.py new file mode 100644 index 0000000..4b15acd --- /dev/null +++ b/pkgs/proxy-ctl/proxy_model.py @@ -0,0 +1,578 @@ +"""What proxy-tui and proxy-suite-gui show and do, without drawing any of it. + +Reads come from proxy_ctl in-process. Every change runs proxy-ctl itself, so +validation, permission errors and systemd triggers stay in one place, and its +die() cannot take a front end down. +""" + +import os +import re +import shlex +import subprocess +import sys +import time +from dataclasses import dataclass, field +from typing import Callable + +import proxy_ctl as ctl + +CTL = "proxy-ctl" + + +def _die(message, status=1): + # Readers run in-process: the message rides the SystemExit, so an empty tab can say why. + sys.exit(message) + + +ctl.die = _die + +_memo = {} # (reader, args) -> result, cleared at the start of every load + + +def _per_load(fn): + def wrapped(*args): + key = (fn, args) + if key not in _memo: + _memo[key] = fn(*args) + return _memo[key] + + return wrapped + + +# Clash API calls and systemctl spawns that several readers repeat within one load. +for _name in ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_autoproxy_next_run", "svc_state"): + setattr(ctl, _name, _per_load(getattr(ctl, _name))) + + +def new_load(): + _memo.clear() + + +@dataclass +class Action: + key: str + label: str + argv: Callable # (selected row or None, prompt text, 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 + 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 + + +@dataclass +class Tab: + id: str + title: str + available: Callable # unit states -> bool + columns: list # (row field, heading) + rows: Callable # unit states -> [row dict with a unique "key"] + summary: Callable = None # () -> text above the table, read with every load + actions: list = field(default_factory=list) + + +def ROW(_): + return True + + +# --- readers ------------------------------------------------------------------ + + +def unit_states(units): + return ctl._unit_states(units) + + +def all_units(): + # The subscription update is read for the status line and the tray; it is no service to toggle. + return ctl._snapshot_units() + + +def _lines(name): + try: + return [line for line in ctl.lines(ctl.read_text(ctl._zapret_auto_file(name))) if line] + except OSError: + return [] + + +TOGGLES = { + "proxy-suite-socks": ["proxy"], + "proxy-suite-tun": ["proxy", "tun"], + "proxy-suite-tproxy": ["proxy", "tproxy"], + "proxy-suite-ssh-proxy": ["ssh"], + "proxy-suite-warp-tunnel": ["warp"], + "proxy-suite-tg-ws-proxy": ["tg"], + "proxy-suite-zapret": ["zapret"], +} +AWG_PREFIX = ctl._awg_service("") +ZAPRET_LISTS = ( + ("learned", "zapret-hosts-auto.txt"), + ("pinned", "zapret-hosts-user.txt"), + ("excluded", "zapret-hosts-user-exclude.txt"), +) + + +def toggle_argv(row, *_): + verb = "off" if row["state"] == "active" else "on" + if row["unit"].startswith(AWG_PREFIX): + return ["awg", verb, row["unit"].removeprefix(AWG_PREFIX)] + return [*TOGGLES[row["unit"]], verb] + + +def service_rows(states): + return [ + {"key": u, "unit": u, "name": u.removeprefix("proxy-suite-"), "state": s} + for u, s in states.items() + if u != ctl.SUBSCRIPTION_UPDATE + ] + + +def route_rows(_): + current = ctl._route_mode_current() + return [ + {"key": m, "active": "●" if m == current else "", "mode": ctl._route_mode_label(m)} + for m in ("default", *ctl.ROUTE_MODES) + ] + + +def outbound_rows(_): + inventory = ctl._outbound_inventory() + pinned = ctl._s(inventory.get("pinned") or "") + sources = inventory.get("sources") or {} + current = ctl._outbound_current() + reputation = ctl._reputation_by_tag() + runtime = set(ctl._runtime_tags("outbound")) + return [ + { + "key": t, + "mark": "★" if t == pinned else "▸" if t == current else "", + "tag": t, + "reputation": reputation.get(t, "-"), + "source": "runtime" if t in runtime else ctl._s(sources.get(t) or "-"), + "runtime": t in runtime, + } + for t in ctl._outbound_tags() + ] + + +def outbound_summary(): + inventory = ctl._outbound_inventory() + if not inventory: + return "No outbounds yet - is proxy-suite-socks running?" + return ( + f"Selection: {ctl._s(inventory.get('selection') or 'first')} " + f"Pinned: {ctl._s(inventory.get('pinned') or '(none)')} " + f"Current: {ctl._outbound_current() or '-'}" + ) + + +def subscription_rows(_): + rows = [] + for source, tags in (("static", ctl._sub_tags()), ("runtime", ctl._runtime_tags("subscription"))): + for t in tags: + cache = ctl._subscription_cache(t) + cached = os.path.isfile(cache) + count = ctl._subscription_proxy_count_text(cache) if cached else "-" + updated = ctl._ago(int(os.path.getmtime(cache)), int(time.time())) + " ago" if cached else "-" + rows.append({"key": t, "tag": t, "proxies": count, "updated": updated, "source": source}) + return rows + + +def autoproxy_rows(_): + state = ctl._autoproxy_state(ctl._autoproxy_dir()) + domains = state.get("domains") or {} + rows = [ + {"key": d, "domain": d, "kind": "routed", "detail": f"via {ctl._s((v or {}).get('exit'))}"} + for d, v in sorted(domains.items()) + ] + backlog = sorted((state.get("backlog") or {}).items(), key=lambda kv: -((kv[1] or {}).get("hits") or 0)) + rows += [ + {"key": h, "domain": h, "kind": "queued", "detail": f"{ctl._s((v or {}).get('hits'))} hits"} + for h, v in backlog + if h not in domains + ] + return rows + + +def zapret_rows(_): + if ctl.env("ZAPRET_AUTO_ENABLED") != "1": + return [] + rows = {} + for kind, name in ZAPRET_LISTS: + for host in _lines(name): + rows.setdefault(f"{kind}:{host}", {"key": f"{kind}:{host}", "host": host, "kind": kind}) + return list(rows.values()) + + +def zapret_summary(): + if ctl.env("ZAPRET_AUTO_ENABLED") != "1": + return 'Learned hostlists need zapret.engine = "zapret2".' + text = " ".join(f"{len(_lines(name))} {kind}" for kind, name in ZAPRET_LISTS) + if ctl.env("ZAPRET_CUTOFF_ENABLED") == "1": + text += "\n" + " ".join(line.strip() for line in _cutoff_status().splitlines()[:2]) + return text + + +_cutoff = {} # ts mtime -> status text: a probe rewrites ts + + +def _cutoff_status(): + try: + mtime = os.path.getmtime(os.path.join(ctl._zapret_state_dir(), "cutoff", "ts")) + except OSError: + mtime = None + if mtime not in _cutoff: + _cutoff.clear() + _cutoff[mtime] = _capture(["zapret", "cutoff", "status"]) + return _cutoff[mtime] + + +def inbound_rows(_): + return [ + {"key": f"{x.get('tag')}/{x.get('user')}", **{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port")}} + for x in ctl._inbound_links() + ] + + +def app_rows(_): + return [ + {"key": ctl._s(p.get("name")), "profile": ctl._s(p.get("name")), "route": ctl._s(p.get("route"))} + for p in ctl._per_app_profiles() + ] + + +def snapshot(states): + """proxy-ctl's status snapshot for these unit states; None when it cannot be read.""" + return _safe(ctl._status_snapshot, states) + + +def status_items(states): + """(label, value, style) for the status line: style is "", "ok", "warn" or "bad".""" + items = [] + overall = ctl._overall_state(snapshot(states) if states else None) + items.append(("", overall["label"], {"failed": "bad", "busy": "warn", "unknown": "bad"}.get(overall["badge"], ""))) + if "proxy-suite-socks" in states: + default = " (default)" if ctl._route_mode_current() == "default" else "" + items.append(("mode ", ctl._route_mode_effective() + default, "")) + items.append(("outbound ", ctl._status_outbound() or "-", "")) + if autoproxy := ctl._status_autoproxy(): + items.append(("autoProxy ", autoproxy, "")) + if zapret := ctl._status_zapret(): + items.append(("zapret ", f"{zapret} learned", "")) + failed = sum(1 for s in states.values() if s == "failed") + if failed: + items.append(("", f"{failed} failed", "bad")) + return items + + +def filter_rows(rows, columns, text): + """Every word must match: column:value in that column (by heading or field), anything else in any column.""" + names = {k.lower(): name for name, heading in columns for k in (name, heading) if k} + + def matches(row, term): + column, sep, value = term.lower().partition(":") + if sep and column in names: + return value in str(row.get(names[column], "")).lower() + return any(term.lower() in str(row.get(name, "")).lower() for name, _ in columns) + + return [r for r in rows if all(matches(r, t) for t in text.split())] + + +def _natural(value): + # "port 443" before "port 2053": digit runs compare as numbers. + return [int(p) if p.isdigit() else p for p in re.split(r"(\d+)", str(value or "").lower())] + + +def _link(row, *extra): + return ["inbounds", "link", row["tag"], *([row["user"]] if row["user"] else []), *extra] + + +def _kind(*kinds): + return lambda row: row["kind"] in kinds + + +def _socks(states): + return "proxy-suite-socks" in states + + +def _enabled(name): + return lambda _: ctl.env(name) == "1" + + +def _zapret_toggle(row, _, states): + return ["zapret", "off" if states.get("proxy-suite-zapret") == "active" else "on"] + + +TABS = [ + Tab( + "services", + "Services", + lambda _: True, + [("name", "Unit"), ("state", "State")], + service_rows, + actions=[ + Action( + "space", + "start / stop", + toggle_argv, + when=lambda r: r["unit"] in TOGGLES or r["unit"].startswith(AWG_PREFIX), + # proxy off takes tun and tproxy down with it. + confirm=lambda r: r["unit"] == "proxy-suite-socks" and r["state"] == "active", + ), + Action("l", "follow its logs", lambda r, *_: ["logs", r["unit"]], when=ROW, mode="suspend"), + Action( + "ctrl+r", + "restart it", + lambda r, *_: ["awg", "restart", r["unit"].removeprefix(AWG_PREFIX)], + when=lambda r: r["unit"].startswith(AWG_PREFIX) and r["state"] == "active", + ), + Action("R", "restart everything running", lambda r, *_: ["restart"], confirm=True), + ], + ), + Tab( + "routing", + "Routing", + _socks, + [("active", ""), ("key", "Mode"), ("mode", "Meaning")], + route_rows, + summary=lambda: f"Configured default: {ctl._route_mode_default()}. An override lasts until you switch back to default.", + actions=[Action("s", "switch to this mode", lambda r, *_: ["proxy", "mode", r["key"]], when=lambda r: not r["active"])], + ), + Tab( + "outbounds", + "Outbounds", + _socks, + [("mark", ""), ("tag", "Tag"), ("reputation", "Reputation"), ("source", "Source")], + outbound_rows, + summary=outbound_summary, + actions=[ + Action("p", "pin it", lambda r, *_: ["proxy", "pin", r["tag"]], when=lambda r: r["mark"] != "★"), + Action("u", "unpin: let the selection pick", lambda r, *_: ["proxy", "unpin"], when=lambda r: r["mark"] == "★"), + Action("t", "test it", lambda r, *_: ["proxy", "outbounds", "test", r["tag"]], when=ROW, mode="dialog"), + Action("T", "test all", lambda r, *_: ["proxy", "outbounds", "test"], mode="dialog"), + Action("n", "add a runtime outbound…", lambda r, t, _: ["proxy", "outbounds", "add", *t.split(None, 1)], prompt=" "), + Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"], confirm=True), + ], + ), + Tab( + "subs", + "Subs", + _socks, + [("tag", "Tag"), ("proxies", "Proxies"), ("updated", "Updated"), ("source", "Source")], + subscription_rows, + summary=lambda: f"proxy-suite-subscription-update: {ctl.svc_state('proxy-suite-subscription-update') or 'unknown'}", + actions=[ + Action("u", "refetch all", lambda r, *_: ["proxy", "subs", "update"], mode="dialog"), + Action("l", "follow the update's logs", lambda r, *_: ["logs", "proxy-suite-subscription-update"], mode="suspend"), + Action("n", "add a runtime subscription…", lambda r, t, _: ["proxy", "subs", "add", *t.split(None, 1)], prompt=" "), + Action("d", "remove it", lambda r, *_: ["proxy", "subs", "rm", r["tag"]], when=lambda r: r["source"] == "runtime", confirm=True), + ], + ), + Tab( + "autoproxy", + "autoProxy", + _enabled("AUTOPROXY_ENABLED"), + [("domain", "Domain"), ("kind", "State"), ("detail", "")], + autoproxy_rows, + summary=ctl._status_autoproxy, + actions=[ + Action("w", "how is it routed", lambda r, *_: ["where", r["domain"]], when=ROW, mode="dialog"), + Action("e", "learn it now", lambda r, *_: ["proxy", "auto", "learn", r["domain"]], when=_kind("queued"), mode="dialog"), + Action("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="[/path]", mode="dialog"), + Action("E", "learn a domain…", lambda r, t, _: ["proxy", "auto", "learn", t], prompt="", mode="dialog"), + Action("i", "routed, judged and bad exits", lambda r, *_: ["proxy", "auto", "list"], mode="dialog"), + ], + ), + Tab( + "zapret", + "zapret", + lambda s: "proxy-suite-zapret" in s or ctl.env("ZAPRET_AUTO_ENABLED") == "1", + [("host", "Host"), ("kind", "List")], + zapret_rows, + summary=zapret_summary, + actions=[ + Action("f", "forget it (may be learned again)", lambda r, *_: ["zapret", "auto", "forget", r["host"]], when=_kind("learned")), + Action("x", "exclude it (never learn)", lambda r, *_: ["zapret", "auto", "exclude", r["host"]], when=_kind("learned", "pinned")), + Action("u", "unpin it", lambda r, *_: ["zapret", "auto", "unpin", r["host"]], when=_kind("pinned")), + Action("i", "include it (may be learned again)", lambda r, *_: ["zapret", "auto", "include", r["host"]], when=_kind("excluded")), + Action("a", "pin a host (always bypass)…", lambda r, t, _: ["zapret", "auto", "add", t], prompt=""), + Action("C", "forget all learned hosts", lambda r, *_: ["zapret", "auto", "clear"], confirm=True), + Action("P", "probe the line's cutoff again", lambda r, *_: ["zapret", "cutoff", "probe"], mode="dialog"), + Action("z", "start / stop zapret", _zapret_toggle), + ], + ), + Tab( + "inbounds", + "Inbounds", + _enabled("INBOUNDS_ENABLED"), + [("tag", "Tag"), ("user", "User"), ("type", "Type"), ("port", "Port")], + inbound_rows, + summary=lambda: f"proxy-suite-inbounds: {ctl.svc_state('proxy-suite-inbounds') or 'unknown'}", + actions=[ + Action("l", "share link", lambda r, *_: _link(r), when=ROW, mode="dialog"), + Action("c", "copy share link", lambda r, *_: _link(r), when=ROW, mode="copy"), + Action("Q", "share link as QR", lambda r, *_: _link(r, "--qr"), when=ROW, mode="dialog"), + Action("s", "subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=lambda r: bool(r["user"]), mode="dialog"), + Action("S", "subscription URL as QR", lambda r, *_: ["inbounds", "sub", r["user"], "--qr"], when=lambda r: bool(r["user"]), mode="dialog"), + Action("y", "copy subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=lambda r: bool(r["user"]), mode="copy"), + Action("t", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"), + ], + ), + Tab( + "apps", + "Apps", + _enabled("PER_APP_ROUTING_ENABLED"), + [("profile", "Profile"), ("route", "Route")], + app_rows, + actions=[ + Action("x", "run a command through it…", lambda r, t, _: ["apps", "run", r["profile"], "--", *shlex.split(t)], when=ROW, prompt=" [args]", mode="pause"), + ], + ), +] + +WHERE = Action("w", "How is a domain routed", lambda r, t, _: ["where", t], prompt="", mode="dialog") + + +def available_tabs(states): + return [t.id for t in TABS if _safe(t.available, states, fallback=False)] + + +def applicable(tab, row): + return [a for a in tab.actions if a.when is None or (row is not None and a.when(row))] + + +def load_tab(tab, states): + """(rows, summary) for a tab: a failed read empties the rows and says why in the summary.""" + summary = (_safe(tab.summary, fallback="") or "") if tab.summary else "" + try: + rows = tab.rows(states) + except (Exception, SystemExit) as e: + return [], f"✗ {str(e) or type(e).__name__}" + (f"\n{summary}" if summary else "") + if not rows: + hints = " ".join(f"{a.key}: {short(a.label)}" for a in tab.actions if a.prompt) + summary = "Nothing here yet." + (f" {hints}" if hints else "") + (f"\n{summary}" if summary else "") + return rows, summary + + +def short(label): + return label.split(" (")[0].removesuffix("…") + + +def _capture(argv): + try: + p = subprocess.run([CTL, *argv], capture_output=True, text=True, stdin=subprocess.DEVNULL) + except OSError as e: + return f"cannot run proxy-ctl: {e}" + return p.stdout + p.stderr + + +def _safe(fn, *args, fallback=None): + try: + return fn(*args) + except (Exception, SystemExit): + return fallback # Unreadable state: shown empty; a tab's own rows say why in its summary. + + +def _read_states(): + return _safe(unit_states, _safe(all_units, fallback=list(ctl.ALL_SERVICES)), fallback={}) + + +# --- tray menu ---------------------------------------------------------------- + + +@dataclass +class MenuItem: + id: str + label: str = "" + kind: str = "normal" # normal, check, radio, separator, submenu + checked: bool = False + enabled: bool = True + argv: list = None # proxy-ctl argv to run when clicked + app: str = "" # or an app action: open, quit + confirm: bool = False + children: list = field(default_factory=list) + + +def _sep(n): + return MenuItem(f"sep-{n}", kind="separator") + + +def tray_menu(snap, outbounds=None): + """The tray's menu for a status snapshot (None: unreadable). outbounds: (tags, pinned) or None.""" + overall = ctl._overall_state(snap) + items = [MenuItem("status", overall["label"] + (f" — {len(snap['failed'])} failed" if snap and snap["failed"] else ""), enabled=False)] + items.append(MenuItem("open", "Open Proxy Suite", app="open")) + if snap is None: + return items + [_sep(0), MenuItem("quit", "Quit", app="quit")] + items.append(_sep(1)) + if snap["proxy"]["available"]: + active = snap["proxy"]["active"] + items.append(MenuItem("proxy", "Proxy", kind="check", checked=active, argv=["proxy", "off" if active else "on"], confirm=active)) + if snap["route_mode"]["available"]: + current = snap["route_mode"]["current"] + items.append( + MenuItem( + "mode", + f"Routing: {ctl._route_mode_label(current)}", + kind="submenu", + children=[ + MenuItem(f"mode-{m}", ctl._route_mode_label(m), kind="radio", checked=m == current, argv=["proxy", "mode", m]) + for m in ("default", *ctl.ROUTE_MODES) + ], + ) + ) + if outbounds and outbounds[0]: + tags, pinned = outbounds + items.append( + MenuItem( + "pin", + f"Outbound: {pinned or 'auto'}", + kind="submenu", + children=[ + MenuItem("pin-auto", "Automatic (unpin)", kind="radio", checked=not pinned, argv=["proxy", "unpin"]), + _sep(2), + *(MenuItem(f"pin-{t}", t, kind="radio", checked=t == pinned, argv=["proxy", "pin", t]) for t in tags), + ], + ) + ) + traffic = [] + for name, label in (("tun", "TUN mode"), ("tproxy", "TProxy mode")): + if snap[name]["available"]: + active = snap[name]["active"] + traffic.append(MenuItem(name, label, kind="check", checked=active, argv=["proxy", name, "off" if active else "on"])) + if snap["awg"]["available"]: + current = snap["awg"]["active"] + traffic.append( + MenuItem( + "awg", + f"AmneziaWG: {current or 'off'}", + kind="submenu", + children=[ + MenuItem("awg-off", "Off", kind="radio", checked=not current, argv=["awg", "off"]), + *(MenuItem(f"awg-{p}", p, kind="radio", checked=p == current, argv=["awg", "on", p]) for p in snap["awg"]["profiles"]), + ], + ) + ) + if traffic: + items += [_sep(3), *traffic] + if snap["zapret"]["available"]: + active = snap["zapret"]["active"] + items += [_sep(4), MenuItem("zapret", "zapret (DPI bypass)", kind="check", checked=active, argv=["zapret", "off" if active else "on"])] + items.append(_sep(5)) + if snap["subscription_update"]["available"]: + busy = snap["subscription_update"]["state"] in ctl.BUSY_STATES + items.append(MenuItem("subs", "Updating subscriptions…" if busy else "Update subscriptions", enabled=not busy, argv=["proxy", "subs", "update"])) + items.append(MenuItem("restart", "Restart active services", argv=["restart"])) + items += [_sep(6), MenuItem("quit", "Quit", app="quit")] + return items + + +def tray_outbounds(snap): + """(tags, pinned) for the tray's pin submenu, when the proxy runs.""" + if not snap or not snap["proxy"]["active"]: + return None + inventory = _safe(ctl._outbound_inventory, fallback={}) or {} + return [ctl._s(t) for t in inventory.get("tags") or []], ctl._s(inventory.get("pinned") or "") + + +def icon_name(overall): + return "proxy-suite-" + overall["base"] + (f"-{overall['badge']}" if overall["badge"] else "") diff --git a/pkgs/proxy-ctl/proxy_sni.py b/pkgs/proxy-ctl/proxy_sni.py new file mode 100644 index 0000000..7e79b03 --- /dev/null +++ b/pkgs/proxy-ctl/proxy_sni.py @@ -0,0 +1,327 @@ +"""A tray icon over D-Bus: org.kde.StatusNotifierItem with a com.canonical.dbusmenu menu. + +Hosts that show these: waybar, KDE Plasma, most wlroots bars, GNOME with the AppIndicator extension. +The menu is proxy_model's MenuItem tree; this module only speaks the protocols. +""" + +import os + +from gi.repository import Gio, GLib + +WATCHER = "org.kde.StatusNotifierWatcher" +ITEM_PATH = "/StatusNotifierItem" +MENU_PATH = "/MenuBar" + +ITEM_XML = """ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +""" + +MENU_XML = """ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +""" + + +def item_properties(item): + """dbusmenu properties of one MenuItem, as plain values.""" + if item.kind == "separator": + return {"type": "separator"} + props = {"label": item.label.replace("_", "__"), "enabled": item.enabled} + if item.kind in ("check", "radio"): + props["toggle-type"] = "checkmark" if item.kind == "check" else "radio" + props["toggle-state"] = 1 if item.checked else 0 + if item.kind == "submenu": + props["children-display"] = "submenu" + return props + + +def _variant(value): + kind = {bool: "b", int: "i", str: "s"}[type(value)] + return GLib.Variant(kind, value) + + +class Menu: + """The item ids a host sees stay put across updates: string ids map to the same numbers.""" + + def __init__(self): + self.numbers = {} # MenuItem id -> dbusmenu id; 0 is the root + self.items = {} # dbusmenu id -> MenuItem + self.children = {0: []} + self.revision = 1 + self.shape = None + + def number(self, item_id): + return self.numbers.setdefault(item_id, len(self.numbers) + 1) + + def update(self, tree): + """Takes a new tree; True when anything a host shows changed.""" + items, children = {}, {0: []} + + def add(parent, nodes): + for node in nodes: + n = self.number(node.id) + items[n] = node + children[parent].append(n) + children[n] = [] + add(n, node.children) + + add(0, tree) + shape = (children, {n: item_properties(i) for n, i in items.items()}) + self.items, self.children = items, children + if shape == self.shape: + return False + self.shape = shape + self.revision += 1 + return True + + def properties(self, n, names=()): + props = item_properties(self.items[n]) if n in self.items else {"children-display": "submenu"} + return {k: _variant(v) for k, v in props.items() if not names or k in names} + + def layout(self, n, depth, names=()): + kids = [] if depth == 0 else [ + GLib.Variant("(ia{sv}av)", self.layout(c, depth - 1, names)) for c in self.children.get(n, []) + ] + return (n, self.properties(n, names), kids) + + +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_available(bool): whether a host shows the icon. + """ + + def __init__(self, connection, app_id, title, icon_theme_path, on_activate, on_menu, on_available=None): + self.connection = connection + 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.menu = Menu() + self.available = False + self.name = f"org.kde.StatusNotifierItem-{os.getpid()}-1" + # register_object_with_closures2 is GLib 2.84's; register_object is the older name for the same. + register = getattr(connection, "register_object_with_closures2", None) or connection.register_object + self.registrations = [ + register(ITEM_PATH, Gio.DBusNodeInfo.new_for_xml(ITEM_XML).interfaces[0], self._item_call, self._item_get, None), + register(MENU_PATH, Gio.DBusNodeInfo.new_for_xml(MENU_XML).interfaces[0], self._menu_call, self._menu_get, None), + ] + self.owner = Gio.bus_own_name_on_connection(connection, self.name, Gio.BusNameOwnerFlags.NONE, None, None) + self.watch = Gio.bus_watch_name_on_connection( + connection, WATCHER, Gio.BusNameWatcherFlags.NONE, self._watcher_appeared, self._watcher_vanished + ) + + def close(self): + Gio.bus_unwatch_name(self.watch) + Gio.bus_unown_name(self.owner) + for r in self.registrations: + self.connection.unregister_object(r) + + # --- what the app changes ----------------------------------------------------- + + def update(self, icon, tooltip, tree, attention=False): + if icon != self.icon: + self.icon = icon + self._emit(ITEM_PATH, "org.kde.StatusNotifierItem", "NewIcon") + if tooltip != self.tooltip: + self.tooltip = tooltip + self._emit(ITEM_PATH, "org.kde.StatusNotifierItem", "NewToolTip") + status = "NeedsAttention" if attention else "Active" + if status != self.status: + self.status = status + self._emit(ITEM_PATH, "org.kde.StatusNotifierItem", "NewStatus", GLib.Variant("(s)", (status,))) + if self.menu.update(tree): + self._emit(MENU_PATH, "com.canonical.dbusmenu", "LayoutUpdated", GLib.Variant("(ui)", (self.menu.revision, 0))) + + def _emit(self, path, interface, signal, args=None): + try: + self.connection.emit_signal(None, path, interface, signal, args) + except GLib.Error: + pass # the bus went away: nothing shows the icon anyway + + # --- registration --------------------------------------------------------------- + + def _watcher_appeared(self, connection, name, owner): + # A bar that restarts brings a new watcher: register again each time. + connection.call( + WATCHER, "/StatusNotifierWatcher", WATCHER, "RegisterStatusNotifierItem", + GLib.Variant("(s)", (self.name,)), None, Gio.DBusCallFlags.NONE, -1, None, self._registered, + ) + + def _registered(self, connection, result): + try: + connection.call_finish(result) + except GLib.Error: + self._set_available(False) + else: + self._set_available(True) + + def _watcher_vanished(self, connection, name): + self._set_available(False) + + def _set_available(self, available): + if available != self.available: + self.available = available + self.on_available(available) + + # --- org.kde.StatusNotifierItem --------------------------------------------------- + + def _item_get(self, connection, sender, path, interface, prop): + values = { + "Category": ("s", "SystemServices"), + "Id": ("s", self.app_id), + "Title": ("s", self.title), + "Status": ("s", self.status), + "WindowId": ("i", 0), + "IconName": ("s", self.icon), + "IconThemePath": ("s", self.icon_theme_path), + "IconPixmap": ("a(iiay)", []), + "OverlayIconName": ("s", ""), + "OverlayIconPixmap": ("a(iiay)", []), + "AttentionIconName": ("s", self.icon), + "AttentionIconPixmap": ("a(iiay)", []), + "AttentionMovieName": ("s", ""), + "ToolTip": ("(sa(iiay)ss)", (self.icon, [], self.title, self.tooltip)), + "ItemIsMenu": ("b", False), + "Menu": ("o", MENU_PATH), + } + return GLib.Variant(*values[prop]) if prop in values else None + + def _item_call(self, connection, sender, path, interface, method, params, invocation): + if method in ("Activate", "SecondaryActivate"): + GLib.idle_add(self.on_activate) + invocation.return_value(None) + + # --- com.canonical.dbusmenu --------------------------------------------------------- + + def _menu_get(self, connection, sender, path, interface, prop): + values = { + "Version": ("u", 3), + "TextDirection": ("s", "ltr"), + "Status": ("s", "normal"), + "IconThemePath": ("as", [self.icon_theme_path] if self.icon_theme_path else []), + } + return GLib.Variant(*values[prop]) if prop in values else None + + def _menu_call(self, connection, sender, path, interface, method, params, invocation): + args = params.unpack() + menu = self.menu + if method == "GetLayout": + parent, depth, names = args + invocation.return_value(GLib.Variant("(u(ia{sv}av))", (menu.revision, menu.layout(parent, depth, names)))) + elif method == "GetGroupProperties": + ids, names = args + found = [(n, menu.properties(n, names)) for n in ids if n in menu.items] if ids else [ + (n, menu.properties(n, names)) for n in menu.items + ] + invocation.return_value(GLib.Variant("(a(ia{sv}))", (found,))) + elif method == "GetProperty": + n, name = args + value = menu.properties(n).get(name) + if value is None: + invocation.return_dbus_error("com.canonical.dbusmenu.Error", f"no property {name} on {n}") + else: + invocation.return_value(GLib.Variant("(v)", (value,))) + elif method == "Event": + self._event(*args[:2]) + invocation.return_value(None) + elif method == "EventGroup": + errors = [n for n, event, _, _ in args[0] if not self._event(n, event)] + invocation.return_value(GLib.Variant("(ai)", (errors,))) + elif method == "AboutToShow": + invocation.return_value(GLib.Variant("(b)", (False,))) + elif method == "AboutToShowGroup": + invocation.return_value(GLib.Variant("(aiai)", ([], [n for n in args[0] if n and n not in menu.items]))) + else: + invocation.return_dbus_error("org.freedesktop.DBus.Error.UnknownMethod", method) + + def _event(self, n, event): + item = self.menu.items.get(n) + if item is None: + return False + if event == "clicked" and item.enabled and item.kind not in ("separator", "submenu"): + GLib.idle_add(self.on_menu, item) + return True diff --git a/pkgs/proxy-ctl/proxy_tui.py b/pkgs/proxy-ctl/proxy_tui.py index c763d1f..dec0dab 100644 --- a/pkgs/proxy-ctl/proxy_tui.py +++ b/pkgs/proxy-ctl/proxy_tui.py @@ -1,19 +1,11 @@ """proxy-tui: an interactive front end to proxy-ctl. -Reads come from proxy_ctl in-process. Every change runs proxy-ctl itself, so -validation, permission errors and systemd triggers stay in one place, and its -die() cannot take the TUI down. +What it shows and does lives in proxy_model, shared with proxy-suite-gui; this is the drawing. """ -import os -import re import shlex import signal import subprocess -import sys -import time -from dataclasses import dataclass, field -from typing import Callable from rich.text import Text from textual import events, work @@ -28,248 +20,17 @@ from textual.theme import Theme from textual.widgets import DataTable, Input, Label, OptionList, RichLog, Static, TabbedContent, TabPane from textual.widgets.option_list import Option -import proxy_ctl as ctl +import proxy_model as model +from proxy_model import CTL, TABS, ctl, filter_rows, _natural, _read_states, _safe -CTL = "proxy-ctl" REFRESH_SECONDS = 3 - - -def _die(message, status=1): - # Readers run in-process: the message rides the SystemExit, so an empty tab can say why. - sys.exit(message) - - -ctl.die = _die - -_memo = {} # (reader, args) -> result, cleared at the start of every load - - -def _per_load(fn): - def wrapped(*args): - key = (fn, args) - if key not in _memo: - _memo[key] = fn(*args) - return _memo[key] - - return wrapped - - -# Clash API calls and systemctl spawns that several readers repeat within one load. -for _name in ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_autoproxy_next_run", "svc_state"): - setattr(ctl, _name, _per_load(getattr(ctl, _name))) - - -@dataclass -class Action: - key: str - label: str - argv: Callable # (selected row or None, prompt text, 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 - 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 - - -@dataclass -class Tab: - id: str - title: str - available: Callable # unit states -> bool - columns: list # (row field, heading) - rows: Callable # unit states -> [row dict with a unique "key"] - summary: Callable = None # () -> text above the table, read with every load - actions: list = field(default_factory=list) - - -def ROW(_): - return True - - -# --- readers ------------------------------------------------------------------ - - -def unit_states(units): - """unit -> ActiveState for the units that exist, in one systemctl call.""" - if not units: - return {} - _, out = ctl._run(["systemctl", "show", "--property=Id,LoadState,ActiveState", "--", *units], capture=True, quiet=True) - states = {} - for unit, block in zip(units, out.strip().split("\n\n")): - props = dict(line.split("=", 1) for line in block.splitlines() if "=" in line) - if props.get("LoadState") not in (None, "not-found"): - states[unit] = props.get("ActiveState", "unknown") - return states - - -def all_units(): - return [*ctl.ALL_SERVICES, *map(ctl._awg_service, ctl._awg_profiles())] - - -def _lines(name): - try: - return [line for line in ctl.lines(ctl.read_text(ctl._zapret_auto_file(name))) if line] - except OSError: - return [] - - -TOGGLES = { - "proxy-suite-socks": ["proxy"], - "proxy-suite-tun": ["proxy", "tun"], - "proxy-suite-tproxy": ["proxy", "tproxy"], - "proxy-suite-ssh-proxy": ["ssh"], - "proxy-suite-warp-tunnel": ["warp"], - "proxy-suite-tg-ws-proxy": ["tg"], - "proxy-suite-zapret": ["zapret"], -} -AWG_PREFIX = ctl._awg_service("") -ZAPRET_LISTS = ( - ("learned", "zapret-hosts-auto.txt"), - ("pinned", "zapret-hosts-user.txt"), - ("excluded", "zapret-hosts-user-exclude.txt"), -) - - -def toggle_argv(row, *_): - verb = "off" if row["state"] == "active" else "on" - if row["unit"].startswith(AWG_PREFIX): - return ["awg", verb, row["unit"].removeprefix(AWG_PREFIX)] - return [*TOGGLES[row["unit"]], verb] - - -def service_rows(states): - return [{"key": u, "unit": u, "name": u.removeprefix("proxy-suite-"), "state": s} for u, s in states.items()] - - -def route_rows(_): - current = ctl._route_mode_current() - return [ - {"key": m, "active": "●" if m == current else "", "mode": ctl._route_mode_label(m)} - for m in ("default", *ctl.ROUTE_MODES) - ] - - -def outbound_rows(_): - inventory = ctl._outbound_inventory() - pinned = ctl._s(inventory.get("pinned") or "") - sources = inventory.get("sources") or {} - current = ctl._outbound_current() - reputation = ctl._reputation_by_tag() - runtime = set(ctl._runtime_tags("outbound")) - return [ - { - "key": t, - "mark": "★" if t == pinned else "▸" if t == current else "", - "tag": t, - "reputation": reputation.get(t, "-"), - "source": "runtime" if t in runtime else ctl._s(sources.get(t) or "-"), - "runtime": t in runtime, - } - for t in ctl._outbound_tags() - ] - - -def outbound_summary(): - inventory = ctl._outbound_inventory() - if not inventory: - return "No outbounds yet - is proxy-suite-socks running?" - return ( - f"Selection: {ctl._s(inventory.get('selection') or 'first')} " - f"Pinned: {ctl._s(inventory.get('pinned') or '(none)')} " - f"Current: {ctl._outbound_current() or '-'}" - ) - - -def subscription_rows(_): - rows = [] - for source, tags in (("static", ctl._sub_tags()), ("runtime", ctl._runtime_tags("subscription"))): - for t in tags: - cache = ctl._subscription_cache(t) - cached = os.path.isfile(cache) - count = ctl._subscription_proxy_count_text(cache) if cached else "-" - updated = ctl._ago(int(os.path.getmtime(cache)), int(time.time())) + " ago" if cached else "-" - rows.append({"key": t, "tag": t, "proxies": count, "updated": updated, "source": source}) - return rows - - -def autoproxy_rows(_): - state = ctl._autoproxy_state(ctl._autoproxy_dir()) - domains = state.get("domains") or {} - rows = [ - {"key": d, "domain": d, "kind": "routed", "detail": f"via {ctl._s((v or {}).get('exit'))}"} - for d, v in sorted(domains.items()) - ] - backlog = sorted((state.get("backlog") or {}).items(), key=lambda kv: -((kv[1] or {}).get("hits") or 0)) - rows += [ - {"key": h, "domain": h, "kind": "queued", "detail": f"{ctl._s((v or {}).get('hits'))} hits"} - for h, v in backlog - if h not in domains - ] - return rows - - -def zapret_rows(_): - if ctl.env("ZAPRET_AUTO_ENABLED") != "1": - return [] - rows = {} - for kind, name in ZAPRET_LISTS: - for host in _lines(name): - rows.setdefault(f"{kind}:{host}", {"key": f"{kind}:{host}", "host": host, "kind": kind}) - return list(rows.values()) - - -def zapret_summary(): - if ctl.env("ZAPRET_AUTO_ENABLED") != "1": - return 'Learned hostlists need zapret.engine = "zapret2".' - text = " ".join(f"{len(_lines(name))} {kind}" for kind, name in ZAPRET_LISTS) - if ctl.env("ZAPRET_CUTOFF_ENABLED") == "1": - text += "\n" + " ".join(line.strip() for line in _cutoff_status().splitlines()[:2]) - return text - - -_cutoff = {} # ts mtime -> status text: a probe rewrites ts - - -def _cutoff_status(): - try: - mtime = os.path.getmtime(os.path.join(ctl._zapret_state_dir(), "cutoff", "ts")) - except OSError: - mtime = None - if mtime not in _cutoff: - _cutoff.clear() - _cutoff[mtime] = _capture(["zapret", "cutoff", "status"]) - return _cutoff[mtime] - - -def inbound_rows(_): - return [ - {"key": f"{x.get('tag')}/{x.get('user')}", **{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port")}} - for x in ctl._inbound_links() - ] - - -def app_rows(_): - return [ - {"key": ctl._s(p.get("name")), "profile": ctl._s(p.get("name")), "route": ctl._s(p.get("route"))} - for p in ctl._per_app_profiles() - ] +STATUS_STYLES = {"ok": "b ansi_green", "warn": "b ansi_yellow", "bad": "b ansi_red", "": "b"} def status_text(states): - parts = [] - if "proxy-suite-socks" in states: - default = " (default)" if ctl._route_mode_current() == "default" else "" - parts.append(("mode ", ctl._route_mode_effective() + default)) - parts.append(("outbound ", ctl._status_outbound() or "-")) - if autoproxy := ctl._status_autoproxy(): - parts.append(("autoProxy ", autoproxy)) - if zapret := ctl._status_zapret(): - parts.append(("zapret ", f"{zapret} learned")) - failed = sum(1 for s in states.values() if s == "failed") - return [ - "[b ansi_cyan]proxy-suite[/]", - *(f"[dim]{label}[/][b]{escape(value)}[/]" for label, value in parts), - *([f"[b ansi_red]{failed} failed[/]"] if failed else []), - ] + return ["[b ansi_cyan]proxy-suite[/]", *( + f"[dim]{escape(label)}[/][{STATUS_STYLES[style]}]{escape(value)}[/]" for label, value, style in model.status_items(states) + )] def pack(items, width, gap=" "): @@ -283,172 +44,6 @@ def pack(items, width, gap=" "): return "\n".join(lines) -def filter_rows(rows, columns, text): - """Every word must match: column:value in that column (by heading or field), anything else in any column.""" - names = {k.lower(): name for name, heading in columns for k in (name, heading) if k} - - def matches(row, term): - column, sep, value = term.lower().partition(":") - if sep and column in names: - return value in str(row.get(names[column], "")).lower() - return any(term.lower() in str(row.get(name, "")).lower() for name, _ in columns) - - return [r for r in rows if all(matches(r, t) for t in text.split())] - - -def _natural(value): - # "port 443" before "port 2053": digit runs compare as numbers. - return [int(p) if p.isdigit() else p for p in re.split(r"(\d+)", str(value or "").lower())] - - -def _link(row, *extra): - return ["inbounds", "link", row["tag"], *([row["user"]] if row["user"] else []), *extra] - - -def _kind(*kinds): - return lambda row: row["kind"] in kinds - - -def _socks(states): - return "proxy-suite-socks" in states - - -def _enabled(name): - return lambda _: ctl.env(name) == "1" - - -def _zapret_toggle(row, _, states): - return ["zapret", "off" if states.get("proxy-suite-zapret") == "active" else "on"] - - -TABS = [ - Tab( - "services", - "Services", - lambda _: True, - [("name", "Unit"), ("state", "State")], - service_rows, - actions=[ - Action( - "space", - "start / stop", - toggle_argv, - when=lambda r: r["unit"] in TOGGLES or r["unit"].startswith(AWG_PREFIX), - # proxy off takes tun and tproxy down with it. - confirm=lambda r: r["unit"] == "proxy-suite-socks" and r["state"] == "active", - ), - Action("l", "follow its logs", lambda r, *_: ["logs", r["unit"]], when=ROW, mode="suspend"), - Action( - "ctrl+r", - "restart it", - lambda r, *_: ["awg", "restart", r["unit"].removeprefix(AWG_PREFIX)], - when=lambda r: r["unit"].startswith(AWG_PREFIX) and r["state"] == "active", - ), - Action("R", "restart everything running", lambda r, *_: ["restart"], confirm=True), - ], - ), - Tab( - "routing", - "Routing", - _socks, - [("active", ""), ("key", "Mode"), ("mode", "Meaning")], - route_rows, - summary=lambda: f"Configured default: {ctl._route_mode_default()}. An override lasts until you switch back to default.", - actions=[Action("s", "switch to this mode", lambda r, *_: ["proxy", "mode", r["key"]], when=lambda r: not r["active"])], - ), - Tab( - "outbounds", - "Outbounds", - _socks, - [("mark", ""), ("tag", "Tag"), ("reputation", "Reputation"), ("source", "Source")], - outbound_rows, - summary=outbound_summary, - actions=[ - Action("p", "pin it", lambda r, *_: ["proxy", "pin", r["tag"]], when=lambda r: r["mark"] != "★"), - Action("u", "unpin: let the selection pick", lambda r, *_: ["proxy", "unpin"], when=lambda r: r["mark"] == "★"), - Action("t", "test it", lambda r, *_: ["proxy", "outbounds", "test", r["tag"]], when=ROW, mode="dialog"), - Action("T", "test all", lambda r, *_: ["proxy", "outbounds", "test"], mode="dialog"), - Action("n", "add a runtime outbound…", lambda r, t, _: ["proxy", "outbounds", "add", *t.split(None, 1)], prompt=" "), - Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"], confirm=True), - ], - ), - Tab( - "subs", - "Subs", - _socks, - [("tag", "Tag"), ("proxies", "Proxies"), ("updated", "Updated"), ("source", "Source")], - subscription_rows, - summary=lambda: f"proxy-suite-subscription-update: {ctl.svc_state('proxy-suite-subscription-update') or 'unknown'}", - actions=[ - Action("u", "refetch all", lambda r, *_: ["proxy", "subs", "update"], mode="dialog"), - Action("l", "follow the update's logs", lambda r, *_: ["logs", "proxy-suite-subscription-update"], mode="suspend"), - Action("n", "add a runtime subscription…", lambda r, t, _: ["proxy", "subs", "add", *t.split(None, 1)], prompt=" "), - Action("d", "remove it", lambda r, *_: ["proxy", "subs", "rm", r["tag"]], when=lambda r: r["source"] == "runtime", confirm=True), - ], - ), - Tab( - "autoproxy", - "autoProxy", - _enabled("AUTOPROXY_ENABLED"), - [("domain", "Domain"), ("kind", "State"), ("detail", "")], - autoproxy_rows, - summary=ctl._status_autoproxy, - actions=[ - Action("w", "how is it routed", lambda r, *_: ["where", r["domain"]], when=ROW, mode="dialog"), - Action("e", "learn it now", lambda r, *_: ["proxy", "auto", "learn", r["domain"]], when=_kind("queued"), mode="dialog"), - Action("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="[/path]", mode="dialog"), - Action("E", "learn a domain…", lambda r, t, _: ["proxy", "auto", "learn", t], prompt="", mode="dialog"), - Action("i", "routed, judged and bad exits", lambda r, *_: ["proxy", "auto", "list"], mode="dialog"), - ], - ), - Tab( - "zapret", - "zapret", - lambda s: "proxy-suite-zapret" in s or ctl.env("ZAPRET_AUTO_ENABLED") == "1", - [("host", "Host"), ("kind", "List")], - zapret_rows, - summary=zapret_summary, - actions=[ - Action("f", "forget it (may be learned again)", lambda r, *_: ["zapret", "auto", "forget", r["host"]], when=_kind("learned")), - Action("x", "exclude it (never learn)", lambda r, *_: ["zapret", "auto", "exclude", r["host"]], when=_kind("learned", "pinned")), - Action("u", "unpin it", lambda r, *_: ["zapret", "auto", "unpin", r["host"]], when=_kind("pinned")), - Action("i", "include it (may be learned again)", lambda r, *_: ["zapret", "auto", "include", r["host"]], when=_kind("excluded")), - Action("a", "pin a host (always bypass)…", lambda r, t, _: ["zapret", "auto", "add", t], prompt=""), - Action("C", "forget all learned hosts", lambda r, *_: ["zapret", "auto", "clear"], confirm=True), - Action("P", "probe the line's cutoff again", lambda r, *_: ["zapret", "cutoff", "probe"], mode="dialog"), - Action("z", "start / stop zapret", _zapret_toggle), - ], - ), - Tab( - "inbounds", - "Inbounds", - _enabled("INBOUNDS_ENABLED"), - [("tag", "Tag"), ("user", "User"), ("type", "Type"), ("port", "Port")], - inbound_rows, - summary=lambda: f"proxy-suite-inbounds: {ctl.svc_state('proxy-suite-inbounds') or 'unknown'}", - actions=[ - Action("l", "share link", lambda r, *_: _link(r), when=ROW, mode="dialog"), - Action("c", "copy share link", lambda r, *_: _link(r), when=ROW, mode="copy"), - Action("Q", "share link as QR", lambda r, *_: _link(r, "--qr"), when=ROW, mode="dialog"), - Action("s", "subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=lambda r: bool(r["user"]), mode="dialog"), - Action("S", "subscription URL as QR", lambda r, *_: ["inbounds", "sub", r["user"], "--qr"], when=lambda r: bool(r["user"]), mode="dialog"), - Action("y", "copy subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=lambda r: bool(r["user"]), mode="copy"), - Action("t", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"), - ], - ), - Tab( - "apps", - "Apps", - _enabled("PER_APP_ROUTING_ENABLED"), - [("profile", "Profile"), ("route", "Route")], - app_rows, - actions=[ - Action("x", "run a command through it…", lambda r, t, _: ["apps", "run", r["profile"], "--", *shlex.split(t)], when=ROW, prompt=" [args]", mode="pause"), - ], - ), -] - GLOBAL_KEYS = [ ("enter", "actions for the selected row (or click it)"), ("← → ⇥", "switch tab; 1-8 jump to one"), @@ -556,25 +151,6 @@ def _update(widget, content): widget.update(content) -def _capture(argv): - try: - p = subprocess.run([CTL, *argv], capture_output=True, text=True, stdin=subprocess.DEVNULL) - except OSError as e: - return f"cannot run proxy-ctl: {e}" - return p.stdout + p.stderr - - -def _safe(fn, *args, fallback=None): - try: - return fn(*args) - except (Exception, SystemExit): - return fallback # Unreadable state: shown empty; a tab's own rows say why in its summary. - - -def _read_states(): - return _safe(unit_states, _safe(all_units, fallback=list(ctl.ALL_SERVICES)), fallback={}) - - # --- dialogs ------------------------------------------------------------------ @@ -692,10 +268,6 @@ class Output(Dialog): # --- main screen -------------------------------------------------------------- -def _short(label): - return label.split(" (")[0].removesuffix("…") - - class Table(DataTable): def _on_mouse_move(self, event): event.prevent_default() # Textual would run DataTable's own handler again after this one. @@ -802,7 +374,7 @@ class ProxyTui(App): super().__init__() self.states = _read_states() self.tabs = {t.id: t for t in TABS} - self.shown = self.available_tabs(self.states) + self.shown = model.available_tabs(self.states) self.rows = {} # tab id -> {row key: row} self.filters = {} # tab id -> text self.sorts = {} # tab id -> (column, descending) @@ -819,9 +391,6 @@ class ProxyTui(App): # Textual drops focus when the terminal loses it, and the table's cursor and footer change with it. event.prevent_default() - def available_tabs(self, states): - return [t.id for t in TABS if _safe(t.available, states, fallback=False)] - def get_default_screen(self): return MainScreen(self.tabs) @@ -874,7 +443,7 @@ class ProxyTui(App): _update(self.main.query_one(f"#{tab_id}-detail", Static), detail(tab, row, actions)) width, height = self.size # The detail panel lists the row's actions when it shows; the key line need not repeat them. - shown = [] if width >= WIDE or height >= TALL else [(f"act({tab.actions.index(a)})", a.key, _short(a.label)) for a in actions] + shown = [] if width >= WIDE or height >= TALL else [(f"act({tab.actions.index(a)})", a.key, model.short(a.label)) for a in actions] # The key keeps its color outside the link: a link's own color would cover it. items = [f"[b ansi_cyan]{escape(k)}[/] [@click=app.{action}]{escape(label)}[/]" for action, k, label in shown + KEY_LINE] _update(self.main.query_one("#keys", Static), pack(items, width - 2)) @@ -886,21 +455,11 @@ class ProxyTui(App): @work(thread=True, exclusive=True, group="load") def load(self, tab_id): - _memo.clear() - tab = self.tabs[tab_id] + model.new_load() states = _read_states() - visible = self.available_tabs(states) + visible = model.available_tabs(states) status = _safe(status_text, states, fallback=["status unavailable"]) - summary = (_safe(tab.summary, fallback="") or "") if tab.summary else "" - try: - rows = tab.rows(states) - except (Exception, SystemExit) as e: - rows = [] - summary = f"✗ {str(e) or type(e).__name__}" + (f"\n{summary}" if summary else "") - else: - if not rows: - hints = " ".join(f"{a.key}: {_short(a.label)}" for a in tab.actions if a.prompt) - summary = "Nothing here yet." + (f" {hints}" if hints else "") + (f"\n{summary}" if summary else "") + rows, summary = model.load_tab(self.tabs[tab_id], states) self.call_from_thread(self.fill, tab_id, states, visible, status, rows, summary) def show_status(self): @@ -969,7 +528,7 @@ class ProxyTui(App): # --- acting --------------------------------------------------------------- def applicable(self, row): - return [a for a in self.tabs[self.active_tab()].actions if a.when is None or (row is not None and a.when(row))] + return model.applicable(self.tabs[self.active_tab()], row) def check_action(self, action, parameters): # A row action that does not apply: its key does nothing. @@ -994,7 +553,7 @@ class ProxyTui(App): self.perform(self.tabs[self.active_tab()].actions[index], self.selected_row()) def action_where(self): - self.perform(Action("w", "How is a domain routed", lambda r, t, _: ["where", t], prompt="", mode="dialog"), None) + self.perform(model.WHERE, None) def on_data_table_header_selected(self, event): tab_id, name = self.active_tab(), event.column_key.value diff --git a/pkgs/proxy-ctl/test_proxy_ctl.py b/pkgs/proxy-ctl/test_proxy_ctl.py index f125536..e59eb8c 100644 --- a/pkgs/proxy-ctl/test_proxy_ctl.py +++ b/pkgs/proxy-ctl/test_proxy_ctl.py @@ -605,5 +605,48 @@ class WhereTest(EnvTest): self.assertEqual(ctl._where_inbounds(config, "example.org", "")[0], "proxy") +class StatusSnapshotTest(EnvTest): + def setUp(self): + super().setUp() + self.patch("_awg_profiles", lambda: ["home", "work"]) + self.patch("_route_mode_current", lambda: "default") + self.patch("_route_mode_default", lambda: "blacklist") + + def overall(self, **states): + units = {f"proxy-suite-{k.replace('_', '-')}": v for k, v in states.items()} + return ctl._status_snapshot(units)["overall"] + + def test_base_priority(self): + self.assertEqual(self.overall(), {"base": "disabled", "badge": "", "label": "Inactive"}) + self.assertEqual(self.overall(zapret="active")["base"], "zapret") + self.assertEqual(self.overall(socks="active")["label"], "Proxy only") + self.assertEqual(self.overall(socks="active", zapret="active")["base"], "active") + both = self.overall(socks="active", zapret="active", tun="active") + self.assertEqual((both["base"], both["label"]), ("tunnel", "Proxy + traffic + zapret")) + self.assertEqual(self.overall(awg_work="active"), {"base": "tunnel", "badge": "", "label": "AmneziaWG"}) + + def test_badges(self): + self.assertEqual(self.overall(socks="active", tun="failed")["badge"], "failed") + self.assertEqual(self.overall(socks="activating", tun="failed")["badge"], "failed") + self.assertEqual(self.overall(socks="active", subscription_update="activating")["badge"], "busy") + self.assertEqual(ctl._overall_state(None)["badge"], "unknown") + + def test_outputs(self): + units = {"proxy-suite-socks": "active", "proxy-suite-awg-work": "active", "proxy-suite-tun": "inactive"} + self.patch("_unit_states", lambda names: {u: s for u, s in units.items() if u in names}) + self.patch("_status_outbound", lambda: "b (pinned)") + self.patch("_status_autoproxy", lambda: "") + self.patch("_status_zapret", lambda: "") + tray = dict(line.split("=", 1) for line in ok(ctl.cmd_status, "--tray").splitlines()) + self.assertEqual( + (tray["socks_active"], tray["tun_available"], tray["tproxy_available"], tray["awg_active"], tray["awg_profiles"]), + ("true", "true", "false", "work", "home,work"), + ) + data = json.loads(ok(ctl.cmd_status, "--json")) + self.assertEqual(data["overall"]["base"], "tunnel") + self.assertEqual(data["outbound"], "b (pinned)") + self.assertEqual(data["route_mode"], {"available": True, "current": "default", "default": "blacklist"}) + + if __name__ == "__main__": unittest.main() diff --git a/pkgs/proxy-ctl/test_proxy_gui.py b/pkgs/proxy-ctl/test_proxy_gui.py new file mode 100644 index 0000000..9141029 --- /dev/null +++ b/pkgs/proxy-ctl/test_proxy_gui.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""proxy_gui and proxy_sni without a display: they import, the tray's D-Bus data is well formed, +key names become GTK accelerators, and every icon the tray can ask for is drawn.""" + +import os +import sys +import tempfile +import unittest + +import proxy_ctl as ctl +import proxy_gui as gui +import proxy_model as model +import proxy_sni as sni +from gi.repository import Gio, GLib + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons")) +import badges # noqa: E402 + + +class GuiTest(unittest.TestCase): + def test_interfaces_parse(self): + item = Gio.DBusNodeInfo.new_for_xml(sni.ITEM_XML).interfaces[0] + menu = Gio.DBusNodeInfo.new_for_xml(sni.MENU_XML).interfaces[0] + self.assertEqual(item.name, "org.kde.StatusNotifierItem") + self.assertEqual(menu.name, "com.canonical.dbusmenu") + self.assertIsNotNone(menu.lookup_method("GetLayout")) + + def test_menu_layout(self): + tree = [ + model.MenuItem("status", "Proxy_only", enabled=False), + model.MenuItem("proxy", "Proxy", kind="check", checked=True, argv=["proxy", "off"]), + model.MenuItem( + "mode", "Routing", kind="submenu", + children=[model.MenuItem("mode-all", "All", kind="radio", checked=False, argv=["proxy", "mode", "all-proxy"])], + ), + ] + menu = sni.Menu() + self.assertTrue(menu.update(tree)) + revision = menu.revision + self.assertFalse(menu.update(tree)) # same shape: hosts keep their copy + self.assertEqual(menu.revision, revision) + + layout = GLib.Variant("(u(ia{sv}av))", (menu.revision, menu.layout(0, -1, []))) + _, (root, _, children) = layout.unpack() + self.assertEqual(root, 0) + labels = [child[1]["label"] for child in children] + self.assertEqual(labels, ["Proxy__only", "Proxy", "Routing"]) # "_" would be a mnemonic + self.assertEqual(children[1][1]["toggle-state"], 1) + self.assertEqual(children[2][2][0][1]["toggle-type"], "radio") + + # Ids stay put when an item goes away and comes back. + proxy_id = menu.numbers["proxy"] + menu.update(tree[:1]) + menu.update(tree) + self.assertEqual(menu.numbers["proxy"], proxy_id) + + def test_accelerators(self): + self.assertEqual(gui.accelerator("space"), "space") + self.assertEqual(gui.accelerator("R"), "r") + self.assertEqual(gui.accelerator("ctrl+r"), "r") + self.assertEqual(gui.display_key("ctrl+space"), "Ctrl+Space") + for tab in model.TABS: + for action in tab.actions: + if action.key: + self.assertTrue(gui.accelerator(action.key)) + + def test_action_looks(self): + for tab in model.TABS: + for action in tab.actions: + self.assertTrue(gui.action_icon(action).endswith("-symbolic")) + self.assertFalse(gui.is_destructive(model.Action("R", "restart everything running", lambda *_: [], confirm=True))) + self.assertTrue(gui.is_destructive(model.Action("d", "remove it", lambda *_: [], confirm=True))) + self.assertTrue(gui.is_destructive(model.Action("C", "forget all learned hosts", lambda *_: [], confirm=True))) + self.assertTrue(gui.is_badge("state", "active")) + self.assertTrue(gui.is_badge("status", "ok")) + self.assertFalse(gui.is_badge("mark", "★")) + + def test_ansi(self): + self.assertEqual( + gui.ansi_segments("\x1b[1;31mfailed\x1b[0m ok\x1b[K"), + [("failed", ("bold", "red")), (" ok", ())], + ) + + def test_every_tray_icon_is_drawn(self): + here = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons") + with tempfile.TemporaryDirectory() as out: + badges.main(here, out) + drawn = set(os.listdir(out)) + for base in badges.STATES: + for badge in ("", *badges.GLYPHS): + name = model.icon_name({"base": base, "badge": badge, "label": ""}) + self.assertIn(f"{name}.svg", drawn) + self.assertIn(f"{name}-symbolic.svg", drawn) + self.assertIn(f"{model.icon_name(ctl._overall_state(None))}.svg", drawn) + + +if __name__ == "__main__": + unittest.main() diff --git a/pkgs/proxy-ctl/test_proxy_model.py b/pkgs/proxy-ctl/test_proxy_model.py new file mode 100644 index 0000000..467b451 --- /dev/null +++ b/pkgs/proxy-ctl/test_proxy_model.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""proxy_model without a front end: the status line and the tray menu turn state into the right proxy-ctl argv.""" + +import unittest +from unittest import mock + +import proxy_ctl as ctl +import proxy_model as model + + +def walk(items): + for item in items: + yield item + yield from walk(item.children) + + +class ModelTest(unittest.TestCase): + def setUp(self): + for name, value in { + "_awg_profiles": lambda: ["home"], + "_route_mode_current": lambda: "default", + "_route_mode_default": lambda: "whitelist", + "_route_mode_effective": lambda: "whitelist", + "_status_outbound": lambda: "b (pinned)", + "_status_autoproxy": lambda: "", + "_status_zapret": lambda: "3", + "_outbound_inventory": lambda: {"tags": ["a", "b"], "pinned": "b"}, + }.items(): + patcher = mock.patch.object(ctl, name, value) + patcher.start() + self.addCleanup(patcher.stop) + + def menu(self, states): + snap = model.snapshot(states) + return {i.id: i for i in walk(model.tray_menu(snap, model.tray_outbounds(snap)))} + + def test_status_items(self): + states = {"proxy-suite-socks": "active", "proxy-suite-zapret": "failed"} + items = model.status_items(states) + self.assertEqual(items[0], ("", "Proxy only", "bad")) + self.assertIn(("mode ", "whitelist (default)", ""), items) + self.assertIn(("zapret ", "3 learned", ""), items) + self.assertEqual(items[-1], ("", "1 failed", "bad")) + self.assertEqual(model.status_items({})[0], ("", "Status unavailable", "bad")) + + def test_services_skip_the_subscription_update(self): + rows = model.service_rows({"proxy-suite-socks": "active", ctl.SUBSCRIPTION_UPDATE: "inactive"}) + self.assertEqual([r["unit"] for r in rows], ["proxy-suite-socks"]) + + def test_tray_menu(self): + states = { + "proxy-suite-socks": "active", + "proxy-suite-tun": "inactive", + "proxy-suite-zapret": "inactive", + ctl.SUBSCRIPTION_UPDATE: "activating", + ctl._awg_service("home"): "active", + } + items = self.menu(states) + self.assertEqual(items["status"].label, "Proxy + traffic") + self.assertEqual((items["proxy"].checked, items["proxy"].argv, items["proxy"].confirm), (True, ["proxy", "off"], True)) + self.assertEqual(items["tun"].argv, ["proxy", "tun", "on"]) + self.assertNotIn("tproxy", items) # not installed + self.assertTrue(items["mode-default"].checked) + self.assertEqual(items["mode-blacklist"].argv, ["proxy", "mode", "blacklist"]) + self.assertEqual(items["pin"].label, "Outbound: b") + self.assertTrue(items["pin-b"].checked) + self.assertEqual(items["pin-a"].argv, ["proxy", "pin", "a"]) + self.assertEqual(items["pin-auto"].argv, ["proxy", "unpin"]) + self.assertTrue(items["awg-home"].checked) + self.assertEqual(items["awg-off"].argv, ["awg", "off"]) + self.assertEqual(items["zapret"].argv, ["zapret", "on"]) + self.assertFalse(items["subs"].enabled) # an update already runs + self.assertEqual(items["quit"].app, "quit") + + def test_tray_menu_without_proxy(self): + items = self.menu({"proxy-suite-zapret": "active"}) + self.assertEqual(items["status"].label, "Zapret only") + for absent in ("proxy", "mode", "pin", "subs"): + self.assertNotIn(absent, items) + self.assertEqual(model.icon_name(ctl._overall_state(model.snapshot({"proxy-suite-zapret": "active"}))), "proxy-suite-zapret") + + def test_tray_menu_unreadable(self): + self.assertEqual([i.id for i in model.tray_menu(None)], ["status", "open", "sep-0", "quit"]) + self.assertEqual(model.icon_name(ctl._overall_state(None)), "proxy-suite-disabled-unknown") + + def test_load_tab(self): + tab = next(t for t in model.TABS if t.id == "outbounds") + with mock.patch.object(ctl, "_outbound_current", lambda: "a"), mock.patch.object(ctl, "_reputation_by_tag", lambda: {}), mock.patch.object(ctl, "_runtime_tags", lambda kind: []): + rows, summary = model.load_tab(tab, {}) + self.assertEqual([(r["tag"], r["mark"]) for r in rows], [("a", "▸"), ("b", "★")]) + self.assertIn("Pinned: b", summary) + self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["u", "t", "T", "n"]) + broken = model.Tab("x", "X", model.ROW, [], lambda _: ctl.die("backend gone")) + self.assertEqual(model.load_tab(broken, {}), ([], "✗ backend gone")) + + +if __name__ == "__main__": + unittest.main() diff --git a/pkgs/proxy-ctl/test_proxy_tui.py b/pkgs/proxy-ctl/test_proxy_tui.py index 8e4788e..7a61256 100644 --- a/pkgs/proxy-ctl/test_proxy_tui.py +++ b/pkgs/proxy-ctl/test_proxy_tui.py @@ -7,6 +7,7 @@ import unittest from unittest import mock import proxy_ctl as ctl +import proxy_model as model import proxy_tui as tui @@ -21,15 +22,15 @@ class TuiTest(unittest.TestCase): self.capture, self.awg, self.current = "", [], mock.Mock(return_value="") self.env = env = {"ZAPRET_AUTO_ENABLED": "1"} for target, name, value in [ - (tui, "unit_states", lambda units: {u: s for u, s in self.units.items() if u in units}), - (tui, "_capture", lambda argv: self.capture), - (tui, "_lines", lambda name: self.zapret[name]), + (model, "unit_states", lambda units: {u: s for u, s in self.units.items() if u in units}), + (model, "_capture", lambda argv: self.capture), + (model, "_lines", lambda name: self.zapret[name]), (ctl, "env", lambda name, default="": env.get(name, default)), (ctl, "_awg_profiles", lambda: self.awg), (ctl, "_route_mode_current", lambda: "default"), (ctl, "_route_mode_effective", lambda: "whitelist"), (ctl, "_outbound_inventory", lambda: {"tags": ["a", "b"], "pinned": "b", "sources": {"a": "config"}}), - (ctl, "_outbound_current", tui._per_load(self.current)), + (ctl, "_outbound_current", model._per_load(self.current)), (ctl, "_reputation_by_tag", lambda: {}), (ctl, "_runtime_tags", lambda kind: []), (ctl, "_sub_tags", lambda: []), @@ -56,7 +57,7 @@ class TuiTest(unittest.TestCase): _subscription_cache=lambda tag: cache.name, _subscription_proxy_count_text=lambda path: "3", ): - self.assertEqual(tui.subscription_rows({})[0]["updated"], "0m ago") + self.assertEqual(model.subscription_rows({})[0]["updated"], "0m ago") def test_filter_sort_pack(self): rows = [{"key": "a", "host": "a.example", "kind": "learned"}, {"key": "b", "host": "learned.org", "kind": "pinned"}] @@ -128,12 +129,12 @@ class TuiTest(unittest.TestCase): # An active AmneziaWG profile restarts on its own; a failed unit shows in the status bar. self.awg = ["p"] - self.units[tui.AWG_PREFIX + "p"] = "active" + self.units[model.AWG_PREFIX + "p"] = "active" self.units["proxy-suite-ssh-proxy"] = "failed" app.action_reload() await self.settle(app, pilot) self.assertIn("1 failed", tui.pack(tui.status_text(app.states), 100)) - app.table().move_cursor(row=list(app.rows["services"]).index(tui.AWG_PREFIX + "p")) + app.table().move_cursor(row=list(app.rows["services"]).index(model.AWG_PREFIX + "p")) await pilot.press("ctrl+r") self.assertEqual(self.ran.pop(), ["awg", "restart", "p"]) app.table().move_cursor(row=list(app.rows["services"]).index("proxy-suite-tun")) diff --git a/pkgs/proxy-suite-tray.nix b/pkgs/proxy-suite-tray.nix deleted file mode 100644 index a1f6f8c..0000000 --- a/pkgs/proxy-suite-tray.nix +++ /dev/null @@ -1,52 +0,0 @@ -{ - pkgs, - pollInterval ? 5, -}: - -pkgs.stdenv.mkDerivation { - pname = "proxy-suite-tray"; - version = "0.1.0"; - - src = ./proxy-suite-tray; - - nativeBuildInputs = [ pkgs.pkg-config ]; - buildInputs = [ - pkgs.gtk3 - pkgs.libayatana-appindicator - ]; - - buildPhase = '' - $CC -o proxy-suite-tray main.c \ - $(pkg-config --cflags --libs gtk+-3.0 ayatana-appindicator3-0.1) \ - -DPOLL_INTERVAL=${toString pollInterval} \ - -O2 -Wall -Werror=discarded-qualifiers - ''; - - installPhase = '' - mkdir -p $out/bin - cp proxy-suite-tray $out/bin/ - - # Install custom icons in hicolor theme - if [ -d icons ]; then - mkdir -p $out/share/icons/hicolor/scalable/apps - mkdir -p $out/share/icons/hicolor/symbolic/apps - cp icons/proxy-suite-disabled.svg \ - icons/proxy-suite-zapret.svg \ - icons/proxy-suite-proxy.svg \ - icons/proxy-suite-active.svg \ - icons/proxy-suite-tunnel.svg \ - $out/share/icons/hicolor/scalable/apps/ - cp icons/proxy-suite-disabled-symbolic.svg \ - icons/proxy-suite-zapret-symbolic.svg \ - icons/proxy-suite-proxy-symbolic.svg \ - icons/proxy-suite-active-symbolic.svg \ - icons/proxy-suite-tunnel-symbolic.svg \ - $out/share/icons/hicolor/symbolic/apps/ - fi - ''; - - meta = { - description = "System tray indicator for proxy-suite"; - mainProgram = "proxy-suite-tray"; - }; -} diff --git a/pkgs/proxy-suite-tray/main.c b/pkgs/proxy-suite-tray/main.c deleted file mode 100644 index 87ddf02..0000000 --- a/pkgs/proxy-suite-tray/main.c +++ /dev/null @@ -1,1233 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#ifndef POLL_INTERVAL -#define POLL_INTERVAL 5 -#endif -#ifndef PROXY_CTL_BIN -#define PROXY_CTL_BIN "/run/current-system/sw/bin/proxy-ctl" -#endif -#define ROUTE_MODE_CHOICE_COUNT 5 - -static AppIndicator *indicator; -static GtkWidget *menu; -static GtkWidget *status_item; -static GtkWidget *proxy_item; -static GtkWidget *route_mode_item; -static GtkWidget *route_mode_items[ROUTE_MODE_CHOICE_COUNT]; -static GtkWidget *tproxy_item; -static GtkWidget *tun_item; -static GtkWidget *awg_item; -static GtkWidget *zapret_item; -static GtkWidget *open_controls_item; -static GtkWidget *controls_window; -static GtkWidget *controls_summary_label; -static GtkWidget *controls_core_status_label; -static GtkWidget *controls_route_mode_status_label; -static GtkWidget *controls_route_mode_combo; -static GtkWidget *controls_traffic_status_label; -static GtkWidget *controls_awg_status_label; -static GtkWidget *controls_awg_combo; -static GtkWidget *controls_zapret_status_label; -static GtkWidget *controls_proxy_button; -static GtkWidget *controls_tproxy_button; -static GtkWidget *controls_tun_button; -static GtkWidget *controls_zapret_button; -static gboolean updating_route_mode_widgets = FALSE; -static gboolean updating_awg_widgets = FALSE; -static gchar **awg_profile_names; -static GtkWidget **awg_profile_items; -static gsize awg_profile_count; - -typedef enum -{ - ROUTE_MODE_UNKNOWN = 0, - ROUTE_MODE_DEFAULT, - ROUTE_MODE_WHITELIST, - ROUTE_MODE_BLACKLIST, - ROUTE_MODE_ALL_PROXY, - ROUTE_MODE_ALL_BYPASS -} RouteMode; - -typedef struct -{ - RouteMode mode; - const char *id; - const char *status_label; - const char *control_label; -} RouteModeInfo; - -static const RouteModeInfo route_mode_infos[ROUTE_MODE_CHOICE_COUNT] = { - {ROUTE_MODE_DEFAULT, "default", "Default", "Default (stop overriding)"}, - {ROUTE_MODE_WHITELIST, "whitelist", "Whitelist (direct by default)", "Whitelist (direct by default)"}, - {ROUTE_MODE_BLACKLIST, "blacklist", "Blacklist (proxy by default)", "Blacklist (proxy by default)"}, - {ROUTE_MODE_ALL_PROXY, "all-proxy", "All Proxy (override)", "All Proxy (override)"}, - {ROUTE_MODE_ALL_BYPASS, "all-bypass", "All Bypass (override)", "All Bypass (override)"}}; - -typedef struct -{ - gboolean loaded; - gboolean socks_available; - gboolean tproxy_available; - gboolean tun_available; - gboolean awg_available; - gboolean zapret_available; - gboolean subscription_update_available; - gboolean route_mode_available; - gboolean socks; - gboolean tproxy; - gboolean tun; - gchar awg_active[64]; - gchar awg_profiles[1024]; - gboolean zapret; - RouteMode route_mode; - RouteMode default_route_mode; -} ServiceState; - -static ServiceState initial_state; - -static gboolean command_succeeds(gchar **argv) -{ - GError *error = NULL; - gint wait_status = 0; - - if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL, NULL, NULL, &wait_status, &error)) - { - g_clear_error(&error); - return FALSE; - } - - if (!g_spawn_check_wait_status(wait_status, &error)) - { - g_clear_error(&error); - return FALSE; - } - - return TRUE; -} - -static gboolean command_stdout(gchar **argv, gchar **stdout_text) -{ - GError *error = NULL; - gint wait_status = 0; - - *stdout_text = NULL; - if (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL, stdout_text, NULL, &wait_status, &error)) - { - g_clear_error(&error); - return FALSE; - } - - if (!g_spawn_check_wait_status(wait_status, &error)) - { - g_clear_error(&error); - g_clear_pointer(stdout_text, g_free); - return FALSE; - } - - return TRUE; -} - -static gboolean on_controls_delete(GtkWidget *widget, GdkEvent *event, gpointer data) -{ - (void)event; - (void)data; - gtk_widget_hide(widget); - return TRUE; -} - -static void on_close_controls(GtkWidget *item, gpointer data) -{ - (void)item; - (void)data; - if (controls_window) - { - gtk_widget_hide(controls_window); - } -} - -static void on_open_controls(GtkWidget *item, gpointer data); - -static gboolean on_open_controls_idle(gpointer data) -{ - (void)data; - on_open_controls(NULL, NULL); - return G_SOURCE_REMOVE; -} - -static GDBusMessage *on_session_bus_message( - GDBusConnection *connection, - GDBusMessage *message, - gboolean incoming, - gpointer user_data) -{ - (void)connection; - (void)user_data; - if (!incoming || !message) - { - return message; - } - if (g_dbus_message_get_message_type(message) != G_DBUS_MESSAGE_TYPE_METHOD_CALL) - { - return message; - } - - const gchar *iface = g_dbus_message_get_interface(message); - const gchar *member = g_dbus_message_get_member(message); - const gchar *path = g_dbus_message_get_path(message); - - if (iface && member && path && - strcmp(iface, "org.kde.StatusNotifierItem") == 0 && - strcmp(member, "Activate") == 0 && - g_str_has_prefix(path, "/org/ayatana/NotificationItem/")) - { - g_idle_add(on_open_controls_idle, NULL); - } - - return message; -} - -static gboolean proxy_ctl_command(const char *arg1, const char *arg2, gchar **stdout_text) -{ - gchar *argv[] = { - (gchar *)PROXY_CTL_BIN, - (gchar *)arg1, - (gchar *)arg2, - NULL}; - - if (stdout_text) - { - return command_stdout(argv, stdout_text); - } - return command_succeeds(argv); -} - -static gboolean run_proxy_ctl(const char *arg1, const char *arg2) -{ - return proxy_ctl_command(arg1, arg2, NULL); -} - -static gboolean run_proxy_ctl3(const char *arg1, const char *arg2, const char *arg3) -{ - gchar *argv[] = { - (gchar *)PROXY_CTL_BIN, - (gchar *)arg1, - (gchar *)arg2, - (gchar *)arg3, - NULL}; - return command_succeeds(argv); -} - -static gboolean parse_proxy_ctl_bool(const char *value) -{ - return value && strcmp(value, "true") == 0; -} - -static const RouteModeInfo *route_mode_info_by_mode(RouteMode mode) -{ - for (gsize i = 0; i < G_N_ELEMENTS(route_mode_infos); ++i) - { - if (route_mode_infos[i].mode == mode) - { - return &route_mode_infos[i]; - } - } - return NULL; -} - -static RouteMode parse_route_mode(const char *value) -{ - if (!value) - { - return ROUTE_MODE_UNKNOWN; - } - for (gsize i = 0; i < G_N_ELEMENTS(route_mode_infos); ++i) - { - if (strcmp(value, route_mode_infos[i].id) == 0) - { - return route_mode_infos[i].mode; - } - } - return ROUTE_MODE_UNKNOWN; -} - -static const char *pick_icon_name( - const char *const *candidates, - gsize candidates_len, - const char *fallback) -{ - GtkIconTheme *theme = gtk_icon_theme_get_default(); - if (!theme) - { - return fallback; - } - - for (gsize i = 0; i < candidates_len; ++i) - { - if (gtk_icon_theme_has_icon(theme, candidates[i])) - { - return candidates[i]; - } - } - - return fallback; -} - -static ServiceState get_service_state(void) -{ - ServiceState state = {0}; - gchar *stdout_text = NULL; - - if (!proxy_ctl_command("status", "--tray", &stdout_text)) - { - return state; - } - - state.loaded = TRUE; - - gchar **lines = g_strsplit(stdout_text, "\n", -1); - for (gchar **line = lines; line && *line; ++line) - { - if ((*line)[0] == '\0') - { - continue; - } - - gchar **parts = g_strsplit(*line, "=", 2); - if (!parts[0] || !parts[1]) - { - g_strfreev(parts); - continue; - } - - if (strcmp(parts[0], "socks_available") == 0) - { - state.socks_available = parse_proxy_ctl_bool(parts[1]); - } - else if (strcmp(parts[0], "socks_active") == 0) - { - state.socks = parse_proxy_ctl_bool(parts[1]); - } - else if (strcmp(parts[0], "tproxy_available") == 0) - { - state.tproxy_available = parse_proxy_ctl_bool(parts[1]); - } - else if (strcmp(parts[0], "tproxy_active") == 0) - { - state.tproxy = parse_proxy_ctl_bool(parts[1]); - } - else if (strcmp(parts[0], "tun_available") == 0) - { - state.tun_available = parse_proxy_ctl_bool(parts[1]); - } - else if (strcmp(parts[0], "tun_active") == 0) - { - state.tun = parse_proxy_ctl_bool(parts[1]); - } - else if (strcmp(parts[0], "awg_available") == 0) - { - state.awg_available = parse_proxy_ctl_bool(parts[1]); - } - else if (strcmp(parts[0], "awg_active") == 0) - { - g_strlcpy(state.awg_active, parts[1], sizeof(state.awg_active)); - } - else if (strcmp(parts[0], "awg_profiles") == 0) - { - g_strlcpy(state.awg_profiles, parts[1], sizeof(state.awg_profiles)); - } - else if (strcmp(parts[0], "zapret_available") == 0) - { - state.zapret_available = parse_proxy_ctl_bool(parts[1]); - } - else if (strcmp(parts[0], "zapret_active") == 0) - { - state.zapret = parse_proxy_ctl_bool(parts[1]); - } - else if (strcmp(parts[0], "subscription_update_available") == 0) - { - state.subscription_update_available = parse_proxy_ctl_bool(parts[1]); - } - else if (strcmp(parts[0], "route_mode_available") == 0) - { - state.route_mode_available = parse_proxy_ctl_bool(parts[1]); - } - else if (strcmp(parts[0], "route_mode") == 0) - { - state.route_mode = parse_route_mode(parts[1]); - } - else if (strcmp(parts[0], "default_route_mode") == 0) - { - state.default_route_mode = parse_route_mode(parts[1]); - } - - g_strfreev(parts); - } - - g_strfreev(lines); - g_free(stdout_text); - - return state; -} - -static const char *traffic_mode_label(const ServiceState *state) -{ - if (state->awg_active[0] != '\0') - { - return "AmneziaWG tunnel enabled"; - } - if (state->tun) - { - return "TUN tunnel enabled"; - } - if (state->tproxy) - { - return "TProxy interception enabled"; - } - return "System-wide routing disabled"; -} - -static const char *route_mode_label(const ServiceState *state) -{ - const RouteModeInfo *info; - - if (state->route_mode == ROUTE_MODE_DEFAULT) - { - switch (state->default_route_mode) - { - case ROUTE_MODE_WHITELIST: - return "Default (Whitelist baseline)"; - case ROUTE_MODE_BLACKLIST: - return "Default (Blacklist baseline)"; - default: - return "Default"; - } - } - - info = route_mode_info_by_mode(state->route_mode); - return info ? info->status_label : "Unknown"; -} - -static gint route_mode_combo_index(RouteMode mode) -{ - for (gsize i = 0; i < G_N_ELEMENTS(route_mode_infos); ++i) - { - if (route_mode_infos[i].mode == mode) - { - return (gint)i; - } - } - return -1; -} - -static void sync_route_mode_widgets(RouteMode mode) -{ - updating_route_mode_widgets = TRUE; - - for (gsize i = 0; i < G_N_ELEMENTS(route_mode_infos); ++i) - { - if (route_mode_items[i]) - { - gtk_check_menu_item_set_active( - GTK_CHECK_MENU_ITEM(route_mode_items[i]), - mode == route_mode_infos[i].mode); - } - } - if (controls_route_mode_combo) - { - gtk_combo_box_set_active(GTK_COMBO_BOX(controls_route_mode_combo), route_mode_combo_index(mode)); - } - - updating_route_mode_widgets = FALSE; -} - -static void sync_awg_widgets(const char *active_profile) -{ - updating_awg_widgets = TRUE; - if (awg_profile_items) - { - gtk_check_menu_item_set_active( - GTK_CHECK_MENU_ITEM(awg_profile_items[0]), - !active_profile || active_profile[0] == '\0'); - for (gsize i = 0; i < awg_profile_count; ++i) - { - gtk_check_menu_item_set_active( - GTK_CHECK_MENU_ITEM(awg_profile_items[i + 1]), - active_profile && strcmp(active_profile, awg_profile_names[i]) == 0); - } - } - if (controls_awg_combo) - { - gtk_combo_box_set_active_id( - GTK_COMBO_BOX(controls_awg_combo), - active_profile && active_profile[0] != '\0' ? active_profile : "off"); - } - updating_awg_widgets = FALSE; -} - -static const char *indicator_label_text(const ServiceState *state) -{ - if (state->socks && (state->tproxy || state->tun || state->awg_active[0] != '\0') && state->zapret) - { - return "Proxy + traffic + zapret"; - } - if (state->socks && (state->tproxy || state->tun || state->awg_active[0] != '\0')) - { - return "Proxy + traffic"; - } - if (state->socks && state->zapret) - { - return "Proxy + zapret"; - } - if (state->socks) - { - return "Proxy only"; - } - if (state->awg_active[0] != '\0') - { - return "AmneziaWG"; - } - if (state->zapret) - { - return "Zapret only"; - } - return "Inactive"; -} - -static void update_status(void) -{ - ServiceState state = get_service_state(); - /* Purple: TUN/TProxy active (highest priority) */ - static const char *const tunnel_icons[] = { - "proxy-suite-tunnel", - "proxy-suite-tunnel-symbolic", - "network-vpn", - "network-vpn-symbolic"}; - /* Green: proxy + zapret, no tunnel */ - static const char *const active_icons[] = { - "proxy-suite-active", - "proxy-suite-active-symbolic", - "network-vpn", - "network-vpn-symbolic"}; - /* Orange: proxy only */ - static const char *const proxy_icons[] = { - "proxy-suite-proxy", - "proxy-suite-proxy-symbolic", - "network-vpn-acquiring", - "network-vpn-acquiring-symbolic", - "network-vpn", - "network-vpn-symbolic"}; - /* Blue: zapret only */ - static const char *const zapret_icons[] = { - "proxy-suite-zapret", - "proxy-suite-zapret-symbolic", - "network-vpn-acquiring", - "network-vpn-acquiring-symbolic", - "network-vpn", - "network-vpn-symbolic"}; - /* Red: everything disabled */ - static const char *const disabled_icons[] = { - "proxy-suite-disabled", - "proxy-suite-disabled-symbolic", - "network-vpn-disconnected", - "network-offline", - "network-error", - "dialog-error", - "network-vpn-disconnected-symbolic", - "network-offline-symbolic", - "network-error-symbolic", - "dialog-error-symbolic"}; - - if (!state.loaded) - { - app_indicator_set_icon( - indicator, - pick_icon_name(disabled_icons, G_N_ELEMENTS(disabled_icons), "network-vpn-disconnected")); - app_indicator_set_label(indicator, "Status unavailable", ""); - - if (status_item) - { - gtk_menu_item_set_label(GTK_MENU_ITEM(status_item), "[Status] proxy-ctl status unavailable"); - } - if (controls_summary_label) - { - gtk_label_set_text(GTK_LABEL(controls_summary_label), "[Status] proxy-ctl status unavailable"); - } - if (controls_core_status_label) - { - gtk_label_set_text(GTK_LABEL(controls_core_status_label), "[Core] Proxy: Unknown"); - } - if (controls_traffic_status_label) - { - gtk_label_set_text(GTK_LABEL(controls_traffic_status_label), "[Traffic] Mode: Unknown"); - } - if (controls_awg_status_label) - { - gtk_label_set_text(GTK_LABEL(controls_awg_status_label), "[AmneziaWG] Profile: Unknown"); - } - if (controls_route_mode_status_label) - { - gtk_label_set_text(GTK_LABEL(controls_route_mode_status_label), "[Routing] Mode: Unknown"); - } - if (controls_zapret_status_label) - { - gtk_label_set_text(GTK_LABEL(controls_zapret_status_label), "[Zapret] DPI bypass: Unknown"); - } - return; - } - - const char *traffic = traffic_mode_label(&state); - const char *route_mode = route_mode_label(&state); - const char *summary = indicator_label_text(&state); - const char *zapret = state.zapret ? "Active" : "Stopped"; - gchar *summary_text = g_strdup_printf( - "[Status] %s | Traffic: %s | Routing: %s | Zapret: %s", - state.socks ? "Proxy ready" : "Proxy down", - traffic, - route_mode, - zapret); - gchar *core_text = g_strdup_printf( - "[Core] Proxy: %s", - state.socks ? "Running" : "Stopped"); - gchar *route_mode_text = g_strdup_printf("[Routing] Mode: %s", route_mode); - gchar *traffic_text = g_strdup_printf("[Traffic] Mode: %s", traffic); - gchar *awg_text = g_strdup_printf( - "[AmneziaWG] Profile: %s", - state.awg_active[0] != '\0' ? state.awg_active : "Off"); - gchar *zapret_text = g_strdup_printf( - "[Zapret] DPI bypass: %s", - zapret); - - if (state.tproxy || state.tun || state.awg_active[0] != '\0') - { - app_indicator_set_icon( - indicator, - pick_icon_name(tunnel_icons, G_N_ELEMENTS(tunnel_icons), "network-vpn")); - } - else if (state.socks && state.zapret) - { - app_indicator_set_icon( - indicator, - pick_icon_name(active_icons, G_N_ELEMENTS(active_icons), "network-vpn")); - } - else if (state.socks) - { - app_indicator_set_icon( - indicator, - pick_icon_name(proxy_icons, G_N_ELEMENTS(proxy_icons), "network-vpn-acquiring")); - } - else if (state.zapret) - { - app_indicator_set_icon( - indicator, - pick_icon_name(zapret_icons, G_N_ELEMENTS(zapret_icons), "network-vpn-acquiring")); - } - else - { - app_indicator_set_icon( - indicator, - pick_icon_name(disabled_icons, G_N_ELEMENTS(disabled_icons), "network-vpn-disconnected")); - } - app_indicator_set_label(indicator, summary, ""); - - if (status_item) - { - gtk_menu_item_set_label(GTK_MENU_ITEM(status_item), summary_text); - } - if (controls_summary_label) - { - gtk_label_set_text(GTK_LABEL(controls_summary_label), summary_text); - } - if (controls_core_status_label) - { - gtk_label_set_text(GTK_LABEL(controls_core_status_label), core_text); - } - if (controls_route_mode_status_label) - { - gtk_label_set_text(GTK_LABEL(controls_route_mode_status_label), route_mode_text); - } - if (controls_traffic_status_label) - { - gtk_label_set_text(GTK_LABEL(controls_traffic_status_label), traffic_text); - } - if (controls_awg_status_label) - { - gtk_label_set_text(GTK_LABEL(controls_awg_status_label), awg_text); - } - if (controls_zapret_status_label) - { - gtk_label_set_text(GTK_LABEL(controls_zapret_status_label), zapret_text); - } - if (proxy_item) - { - gtk_menu_item_set_label(GTK_MENU_ITEM(proxy_item), - state.socks ? "[Core] Stop Proxy" : "[Core] Start Proxy"); - } - if (controls_proxy_button) - { - gtk_button_set_label(GTK_BUTTON(controls_proxy_button), - state.socks ? "Stop Proxy" : "Start Proxy"); - } - if (route_mode_item) - { - gchar *menu_route_mode_text = g_strdup_printf("[Routing] Mode: %s", route_mode); - gtk_menu_item_set_label(GTK_MENU_ITEM(route_mode_item), menu_route_mode_text); - g_free(menu_route_mode_text); - sync_route_mode_widgets(state.route_mode); - } - - if (tproxy_item) - { - gtk_menu_item_set_label(GTK_MENU_ITEM(tproxy_item), - state.tproxy ? "[Traffic] Stop TProxy Mode" : "[Traffic] Start TProxy Mode"); - } - if (controls_tproxy_button) - { - gtk_button_set_label(GTK_BUTTON(controls_tproxy_button), - state.tproxy ? "Stop TProxy Mode" : "Start TProxy Mode"); - } - if (tun_item) - { - gtk_menu_item_set_label(GTK_MENU_ITEM(tun_item), - state.tun ? "[Traffic] Stop TUN Mode" : "[Traffic] Start TUN Mode"); - } - if (awg_item) - { - gchar *label = g_strdup_printf( - "[Traffic] AmneziaWG: %s", - state.awg_active[0] != '\0' ? state.awg_active : "Off"); - gtk_menu_item_set_label(GTK_MENU_ITEM(awg_item), label); - g_free(label); - sync_awg_widgets(state.awg_active); - } - if (controls_tun_button) - { - gtk_button_set_label(GTK_BUTTON(controls_tun_button), - state.tun ? "Stop TUN Mode" : "Start TUN Mode"); - } - if (zapret_item) - { - gtk_menu_item_set_label( - GTK_MENU_ITEM(zapret_item), - state.zapret ? "[Zapret] Stop zapret" : "[Zapret] Start zapret"); - } - if (controls_zapret_button) - { - gtk_button_set_label( - GTK_BUTTON(controls_zapret_button), - state.zapret ? "Stop zapret" : "Start zapret"); - } - - g_free(summary_text); - g_free(core_text); - g_free(route_mode_text); - g_free(traffic_text); - g_free(awg_text); - g_free(zapret_text); -} - -static void on_proxy_toggle(GtkWidget *item, gpointer data) -{ - (void)item; - (void)data; - ServiceState state = get_service_state(); - if (state.socks) - { - run_proxy_ctl("proxy", "off"); - } - else - { - run_proxy_ctl("proxy", "on"); - } - update_status(); -} - -static void on_tproxy_toggle(GtkWidget *item, gpointer data) -{ - (void)item; - (void)data; - ServiceState state = get_service_state(); - if (state.tproxy) - { - run_proxy_ctl3("proxy", "tproxy", "off"); - } - else - { - run_proxy_ctl3("proxy", "tproxy", "on"); - } - update_status(); -} - -static void on_route_mode_menu_toggled(GtkCheckMenuItem *item, gpointer data) -{ - const char *mode; - if (updating_route_mode_widgets || !gtk_check_menu_item_get_active(item)) - { - return; - } - mode = (const char *)data; - if (!mode) - { - return; - } - run_proxy_ctl3("proxy", "mode", mode); - update_status(); -} - -static void on_route_mode_combo_changed(GtkComboBox *combo, gpointer data) -{ - (void)data; - const char *mode; - const gchar *active_id; - if (updating_route_mode_widgets) - { - return; - } - active_id = gtk_combo_box_get_active_id(combo); - if (!active_id) - { - return; - } - mode = active_id; - ServiceState state = get_service_state(); - if (!state.route_mode_available) - { - return; - } - run_proxy_ctl3("proxy", "mode", mode); - update_status(); -} - -static void on_tun_toggle(GtkWidget *item, gpointer data) -{ - (void)item; - (void)data; - ServiceState state = get_service_state(); - if (state.tun) - { - run_proxy_ctl3("proxy", "tun", "off"); - } - else - { - run_proxy_ctl3("proxy", "tun", "on"); - } - update_status(); -} - -static void set_awg_profile(const char *profile) -{ - if (profile && profile[0] != '\0' && strcmp(profile, "off") != 0) - { - run_proxy_ctl3("awg", "on", profile); - } - else - { - run_proxy_ctl("awg", "off"); - } -} - -static void on_awg_menu_toggled(GtkCheckMenuItem *item, gpointer data) -{ - if (updating_awg_widgets || !gtk_check_menu_item_get_active(item)) - { - return; - } - set_awg_profile((const char *)data); - update_status(); -} - -static void on_awg_combo_changed(GtkComboBox *combo, gpointer data) -{ - (void)data; - if (updating_awg_widgets) - { - return; - } - const gchar *profile = gtk_combo_box_get_active_id(combo); - if (!profile) - { - return; - } - set_awg_profile(profile); - update_status(); -} - -static void on_zapret_toggle(GtkWidget *item, gpointer data) -{ - (void)item; - (void)data; - ServiceState state = get_service_state(); - if (state.zapret) - { - run_proxy_ctl("zapret", "off"); - } - else - { - run_proxy_ctl("zapret", "on"); - } - update_status(); -} - -static void on_restart(GtkWidget *item, gpointer data) -{ - (void)item; - (void)data; - run_proxy_ctl("restart", NULL); - update_status(); -} - -static void on_subscription_update(GtkWidget *item, gpointer data) -{ - (void)item; - (void)data; - run_proxy_ctl3("proxy", "subs", "update"); -} - -static void on_open_controls(GtkWidget *item, gpointer data) -{ - (void)item; - (void)data; - if (!controls_window) - { - return; - } - update_status(); - gtk_widget_show_all(controls_window); - gtk_window_present(GTK_WINDOW(controls_window)); -} - -static void on_quit(GtkWidget *item, gpointer data) -{ - (void)item; - (void)data; - gtk_main_quit(); -} - -static gboolean on_timer(gpointer data) -{ - (void)data; - update_status(); - return TRUE; -} - -static void build_controls_window(void) -{ - controls_window = gtk_window_new(GTK_WINDOW_TOPLEVEL); - gtk_window_set_title(GTK_WINDOW(controls_window), "Proxy Suite Controls"); - gtk_window_set_resizable(GTK_WINDOW(controls_window), FALSE); - gtk_container_set_border_width(GTK_CONTAINER(controls_window), 8); - g_signal_connect(controls_window, "delete-event", G_CALLBACK(on_controls_delete), NULL); - - GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6); - gtk_container_add(GTK_CONTAINER(controls_window), box); - - controls_summary_label = gtk_label_new("[Status] Loading service state..."); - gtk_label_set_xalign(GTK_LABEL(controls_summary_label), 0.0f); - gtk_box_pack_start(GTK_BOX(box), controls_summary_label, FALSE, FALSE, 0); - - GtkWidget *core_frame = gtk_frame_new("[Core] Proxy"); - GtkWidget *core_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6); - gtk_container_set_border_width(GTK_CONTAINER(core_box), 6); - gtk_container_add(GTK_CONTAINER(core_frame), core_box); - gtk_box_pack_start(GTK_BOX(box), core_frame, FALSE, FALSE, 0); - - controls_core_status_label = gtk_label_new("[Core] Proxy: Unknown"); - gtk_label_set_xalign(GTK_LABEL(controls_core_status_label), 0.0f); - gtk_box_pack_start(GTK_BOX(core_box), controls_core_status_label, FALSE, FALSE, 0); - - controls_proxy_button = gtk_button_new_with_label("Start Proxy"); - g_signal_connect(controls_proxy_button, "clicked", G_CALLBACK(on_proxy_toggle), NULL); - gtk_box_pack_start(GTK_BOX(core_box), controls_proxy_button, FALSE, FALSE, 0); - - if (initial_state.route_mode_available) - { - GtkWidget *routing_frame = gtk_frame_new("[Routing] Mode"); - GtkWidget *routing_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6); - gtk_container_set_border_width(GTK_CONTAINER(routing_box), 6); - gtk_container_add(GTK_CONTAINER(routing_frame), routing_box); - gtk_box_pack_start(GTK_BOX(box), routing_frame, FALSE, FALSE, 0); - - controls_route_mode_status_label = gtk_label_new("[Routing] Mode: Unknown"); - gtk_label_set_xalign(GTK_LABEL(controls_route_mode_status_label), 0.0f); - gtk_box_pack_start(GTK_BOX(routing_box), controls_route_mode_status_label, FALSE, FALSE, 0); - - controls_route_mode_combo = gtk_combo_box_text_new(); - for (gsize i = 0; i < G_N_ELEMENTS(route_mode_infos); ++i) - { - gtk_combo_box_text_append( - GTK_COMBO_BOX_TEXT(controls_route_mode_combo), - route_mode_infos[i].id, - route_mode_infos[i].control_label); - } - g_signal_connect(controls_route_mode_combo, "changed", G_CALLBACK(on_route_mode_combo_changed), NULL); - gtk_box_pack_start(GTK_BOX(routing_box), controls_route_mode_combo, FALSE, FALSE, 0); - } - - GtkWidget *traffic_frame = gtk_frame_new("[Traffic] System-wide traffic mode"); - GtkWidget *traffic_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6); - gtk_container_set_border_width(GTK_CONTAINER(traffic_box), 6); - gtk_container_add(GTK_CONTAINER(traffic_frame), traffic_box); - gtk_box_pack_start(GTK_BOX(box), traffic_frame, FALSE, FALSE, 0); - - controls_traffic_status_label = gtk_label_new("[Traffic] Mode: Unknown"); - gtk_label_set_xalign(GTK_LABEL(controls_traffic_status_label), 0.0f); - gtk_box_pack_start(GTK_BOX(traffic_box), controls_traffic_status_label, FALSE, FALSE, 0); - - if (initial_state.tproxy_available) - { - controls_tproxy_button = gtk_button_new_with_label("Start TProxy Mode"); - g_signal_connect(controls_tproxy_button, "clicked", G_CALLBACK(on_tproxy_toggle), NULL); - gtk_box_pack_start(GTK_BOX(traffic_box), controls_tproxy_button, FALSE, FALSE, 0); - } - - if (initial_state.tun_available) - { - controls_tun_button = gtk_button_new_with_label("Start TUN Mode"); - g_signal_connect(controls_tun_button, "clicked", G_CALLBACK(on_tun_toggle), NULL); - gtk_box_pack_start(GTK_BOX(traffic_box), controls_tun_button, FALSE, FALSE, 0); - } - - if (initial_state.awg_available) - { - controls_awg_status_label = gtk_label_new("[AmneziaWG] Profile: Off"); - gtk_label_set_xalign(GTK_LABEL(controls_awg_status_label), 0.0f); - gtk_box_pack_start(GTK_BOX(traffic_box), controls_awg_status_label, FALSE, FALSE, 0); - - controls_awg_combo = gtk_combo_box_text_new(); - gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_awg_combo), "off", "AmneziaWG Off"); - for (gsize i = 0; i < awg_profile_count; ++i) - { - gtk_combo_box_text_append( - GTK_COMBO_BOX_TEXT(controls_awg_combo), - awg_profile_names[i], - awg_profile_names[i]); - } - g_signal_connect(controls_awg_combo, "changed", G_CALLBACK(on_awg_combo_changed), NULL); - gtk_box_pack_start(GTK_BOX(traffic_box), controls_awg_combo, FALSE, FALSE, 0); - } - - if (initial_state.zapret_available) - { - GtkWidget *zapret_frame = gtk_frame_new("[Zapret] DPI bypass"); - GtkWidget *zapret_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6); - gtk_container_set_border_width(GTK_CONTAINER(zapret_box), 6); - gtk_container_add(GTK_CONTAINER(zapret_frame), zapret_box); - gtk_box_pack_start(GTK_BOX(box), zapret_frame, FALSE, FALSE, 0); - - controls_zapret_status_label = gtk_label_new("[Zapret] DPI bypass: Unknown"); - gtk_label_set_xalign(GTK_LABEL(controls_zapret_status_label), 0.0f); - gtk_box_pack_start(GTK_BOX(zapret_box), controls_zapret_status_label, FALSE, FALSE, 0); - - controls_zapret_button = gtk_button_new_with_label("Start zapret"); - g_signal_connect(controls_zapret_button, "clicked", G_CALLBACK(on_zapret_toggle), NULL); - gtk_box_pack_start(GTK_BOX(zapret_box), controls_zapret_button, FALSE, FALSE, 0); - } - - GtkWidget *tools_frame = gtk_frame_new("[Tools] Maintenance"); - GtkWidget *tools_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6); - gtk_container_set_border_width(GTK_CONTAINER(tools_box), 6); - gtk_container_add(GTK_CONTAINER(tools_frame), tools_box); - gtk_box_pack_start(GTK_BOX(box), tools_frame, FALSE, FALSE, 0); - - if (initial_state.subscription_update_available) - { - GtkWidget *sub_update_button = gtk_button_new_with_label("Update Subscriptions"); - g_signal_connect(sub_update_button, "clicked", G_CALLBACK(on_subscription_update), NULL); - gtk_box_pack_start(GTK_BOX(tools_box), sub_update_button, FALSE, FALSE, 0); - } - - GtkWidget *restart_button = gtk_button_new_with_label("Restart Active Services"); - g_signal_connect(restart_button, "clicked", G_CALLBACK(on_restart), NULL); - gtk_box_pack_start(GTK_BOX(tools_box), restart_button, FALSE, FALSE, 0); - - GtkWidget *close_button = gtk_button_new_with_label("Close Window"); - g_signal_connect(close_button, "clicked", G_CALLBACK(on_close_controls), NULL); - gtk_box_pack_start(GTK_BOX(tools_box), close_button, FALSE, FALSE, 0); - - GtkWidget *quit_button = gtk_button_new_with_label("Exit Tray"); - g_signal_connect(quit_button, "clicked", G_CALLBACK(on_quit), NULL); - gtk_box_pack_start(GTK_BOX(tools_box), quit_button, FALSE, FALSE, 0); - - gtk_widget_show_all(controls_window); - gtk_widget_hide(controls_window); -} - -static void build_menu(void) -{ - menu = gtk_menu_new(); - - status_item = gtk_menu_item_new_with_label("[Status] Loading service state..."); - gtk_widget_set_sensitive(status_item, FALSE); - gtk_menu_shell_append(GTK_MENU_SHELL(menu), status_item); - - gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); - - proxy_item = gtk_menu_item_new_with_label("[Core] Start Proxy"); - g_signal_connect(proxy_item, "activate", G_CALLBACK(on_proxy_toggle), NULL); - gtk_menu_shell_append(GTK_MENU_SHELL(menu), proxy_item); - - if (initial_state.route_mode_available) - { - route_mode_item = gtk_menu_item_new_with_label("[Routing] Mode: Unknown"); - GtkWidget *route_mode_menu = gtk_menu_new(); - GSList *route_group = NULL; - - for (gsize i = 0; i < G_N_ELEMENTS(route_mode_infos); ++i) - { - route_mode_items[i] = gtk_radio_menu_item_new_with_label( - route_group, - route_mode_infos[i].control_label); - g_signal_connect( - route_mode_items[i], - "toggled", - G_CALLBACK(on_route_mode_menu_toggled), - (gpointer)route_mode_infos[i].id); - gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_items[i]); - route_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(route_mode_items[i])); - } - - gtk_menu_item_set_submenu(GTK_MENU_ITEM(route_mode_item), route_mode_menu); - gtk_menu_shell_append(GTK_MENU_SHELL(menu), route_mode_item); - } - - open_controls_item = gtk_menu_item_new_with_label("Open Controls"); - g_signal_connect(open_controls_item, "activate", G_CALLBACK(on_open_controls), NULL); - gtk_menu_shell_append(GTK_MENU_SHELL(menu), open_controls_item); - - gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); - - if (initial_state.tproxy_available) - { - tproxy_item = gtk_menu_item_new_with_label("[Traffic] Start TProxy Mode"); - g_signal_connect(tproxy_item, "activate", G_CALLBACK(on_tproxy_toggle), NULL); - gtk_menu_shell_append(GTK_MENU_SHELL(menu), tproxy_item); - } - - if (initial_state.tun_available) - { - tun_item = gtk_menu_item_new_with_label("[Traffic] Start TUN Mode"); - g_signal_connect(tun_item, "activate", G_CALLBACK(on_tun_toggle), NULL); - gtk_menu_shell_append(GTK_MENU_SHELL(menu), tun_item); - } - - - if (initial_state.awg_available) - { - awg_item = gtk_menu_item_new_with_label("[Traffic] AmneziaWG: Off"); - GtkWidget *awg_menu = gtk_menu_new(); - GSList *awg_group = NULL; - awg_profile_items = g_new0(GtkWidget *, awg_profile_count + 1); - - awg_profile_items[0] = gtk_radio_menu_item_new_with_label(awg_group, "Off"); - g_signal_connect( - awg_profile_items[0], - "toggled", - G_CALLBACK(on_awg_menu_toggled), - (gpointer)""); - gtk_menu_shell_append(GTK_MENU_SHELL(awg_menu), awg_profile_items[0]); - awg_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(awg_profile_items[0])); - - for (gsize i = 0; i < awg_profile_count; ++i) - { - awg_profile_items[i + 1] = gtk_radio_menu_item_new_with_label( - awg_group, - awg_profile_names[i]); - g_signal_connect( - awg_profile_items[i + 1], - "toggled", - G_CALLBACK(on_awg_menu_toggled), - awg_profile_names[i]); - gtk_menu_shell_append(GTK_MENU_SHELL(awg_menu), awg_profile_items[i + 1]); - awg_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(awg_profile_items[i + 1])); - } - gtk_menu_item_set_submenu(GTK_MENU_ITEM(awg_item), awg_menu); - gtk_menu_shell_append(GTK_MENU_SHELL(menu), awg_item); - } - - if (initial_state.zapret_available) - { - gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); - - zapret_item = gtk_menu_item_new_with_label("[Zapret] Start zapret"); - g_signal_connect(zapret_item, "activate", G_CALLBACK(on_zapret_toggle), NULL); - gtk_menu_shell_append(GTK_MENU_SHELL(menu), zapret_item); - } - - if (initial_state.subscription_update_available) - { - gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); - - GtkWidget *sub_update_item = gtk_menu_item_new_with_label("Update Subscriptions"); - g_signal_connect(sub_update_item, "activate", G_CALLBACK(on_subscription_update), NULL); - gtk_menu_shell_append(GTK_MENU_SHELL(menu), sub_update_item); - } - - gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); - - GtkWidget *restart_item = gtk_menu_item_new_with_label("[Tools] Restart Active Services"); - g_signal_connect(restart_item, "activate", G_CALLBACK(on_restart), NULL); - gtk_menu_shell_append(GTK_MENU_SHELL(menu), restart_item); - - gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); - - GtkWidget *quit_item = gtk_menu_item_new_with_label("Exit"); - g_signal_connect(quit_item, "activate", G_CALLBACK(on_quit), NULL); - gtk_menu_shell_append(GTK_MENU_SHELL(menu), quit_item); - - gtk_widget_show_all(menu); -} - -int main(int argc, char *argv[]) -{ - if (!gtk_init_check(&argc, &argv)) - { - fprintf(stderr, "proxy-suite-tray: failed to initialize GTK\n"); - return 1; - } - - GError *bus_error = NULL; - GDBusConnection *session_bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &bus_error); - if (session_bus) - { - g_dbus_connection_add_filter(session_bus, on_session_bus_message, NULL, NULL); - g_object_unref(session_bus); - } - else - { - fprintf( - stderr, - "proxy-suite-tray: warning: failed to monitor session bus: %s\n", - bus_error ? bus_error->message : "unknown error"); - g_clear_error(&bus_error); - } - - indicator = app_indicator_new( - "proxy-suite-tray", - "proxy-suite-disabled", - APP_INDICATOR_CATEGORY_SYSTEM_SERVICES); - app_indicator_set_status(indicator, APP_INDICATOR_STATUS_ACTIVE); - - initial_state = get_service_state(); - if (initial_state.awg_profiles[0] != '\0') - { - awg_profile_names = g_strsplit(initial_state.awg_profiles, ",", -1); - awg_profile_count = g_strv_length(awg_profile_names); - } - build_menu(); - build_controls_window(); - app_indicator_set_menu(indicator, GTK_MENU(menu)); - app_indicator_set_secondary_activate_target(indicator, open_controls_item); - - update_status(); - - g_timeout_add_seconds(POLL_INTERVAL, on_timer, NULL); - - gtk_main(); - g_strfreev(awg_profile_names); - g_free(awg_profile_items); - return 0; -}