Files
proxy-suite-flake/windows/crates/ps-gui/src/shell.rs
T
faumarayandClaude Opus 5.5 c0b089dea8 windows: the app leaves a system proxy set by hand alone; a calmer tray
- The check for a system proxy a killed app left on the local proxy ran
  on every refresh while the option was off, so a proxy the user pointed
  at the listener by hand was switched off within two seconds. It now
  runs once, at the start. The registry sits behind a small trait, and
  the state machine has tests.
- The tray's tooltip and menu are only touched when what they say
  changes (a menu rebuilt while open would close).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 02:24:01 +03:00

212 lines
8.1 KiB
Rust

//! The app's life: one window, opened again from the tray; the tray icon, coloured by how things
//! are, with switches in its menu; quitting. Closing the window leaves the app in the tray; with
//! no tray (a desktop without one), closing it quits.
use gpui_kit::*;
use gpui_tray::{Icon, Tray};
use ps_client::edits;
use serde_json::Value;
use crate::model::{Connection, Model};
use crate::sysproxy::SystemProxy;
use crate::ui::AppView;
actions!(proxy_suite, [OpenWindow, ToggleProxy, ToggleDpi, ToggleTelegram, Quit]);
struct Shell {
model: Entity<Model>,
window: Option<WindowHandle<AppView>>,
tray: Option<Tray>,
/// The icon's colour and the tooltip now: the tray is only touched when they change (a
/// menu rebuilt while open would close).
colour: &'static str,
tooltip: String,
system_proxy: SystemProxy,
/// The system proxy's last failure, said once.
system_proxy_error: Option<String>,
}
impl Global for Shell {}
pub fn start(model: Entity<Model>, open: bool, cx: &mut App) {
cx.on_action(open_window).on_action(toggle_proxy).on_action(toggle_dpi).on_action(toggle_telegram).on_action(quit);
cx.set_global(Shell { model: model.clone(), window: None, tray: None, colour: "", tooltip: String::new(), system_proxy: SystemProxy::default(), system_proxy_error: None });
let mut builder = Tray::builder().tooltip("Proxy Suite").on_activate(OpenWindow).menu(menu);
if let Some(icon) = icon("#6b7280", cx) {
builder = builder.icon(icon);
}
let tray = builder.build(cx);
match tray {
Ok(tray) => cx.global_mut::<Shell>().tray = Some(tray),
Err(e) => eprintln!("proxy-suite: no tray icon ({e}); closing the window quits"),
}
cx.on_window_closed(|cx, _| {
if cx.global::<Shell>().tray.is_none() && cx.windows().is_empty() {
cx.quit();
}
})
.detach();
cx.observe(&model, |_, cx| refresh(cx)).detach();
if open || cx.global::<Shell>().tray.is_none() {
open_window(&OpenWindow, cx);
}
}
fn status(cx: &App) -> (Value, bool) {
let m = cx.global::<Shell>().model.read(cx);
(m.status().clone(), *m.connection() == Connection::Up)
}
/// How things are, as a colour: working, something failed, all off, no service.
fn colour(cx: &App) -> &'static str {
let (s, up) = status(cx);
if !up {
return "#dc2626";
}
let parts = [(&s["proxy"]["on"], &s["proxy"]["state"]), (&s["zapret"]["enabled"], &s["zapret"]["state"]), (&s["tgWsProxy"]["enabled"], &s["tgWsProxy"]["state"])];
let wanted: Vec<&Value> = parts.iter().filter(|(on, _)| **on == true).map(|(_, state)| *state).collect();
if wanted.is_empty() {
"#6b7280"
} else if wanted.iter().any(|state| **state == "failed") {
"#d97706"
} else {
"#16a34a"
}
}
/// A filled shield, the app's mark, in `fill`.
fn icon(fill: &str, cx: &App) -> Option<Icon> {
let svg = format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><path d="M12 2.2 4.2 5.1v6.1c0 4.9 3.3 9.1 7.8 10.6 4.5-1.5 7.8-5.7 7.8-10.6V5.1Z" fill="{fill}" stroke="#ffffff" stroke-width="1.4" stroke-linejoin="round"/></svg>"##
);
Icon::from_gpui(&Image::from_bytes(ImageFormat::Svg, svg.into_bytes()), cx).build().inspect_err(|e| eprintln!("proxy-suite: the tray icon: {e}")).ok()
}
/// The system proxy, as the configuration and the local proxy's state say.
fn system_proxy(cx: &mut App) {
let m = cx.global::<Shell>().model.read(cx);
let (s, c) = (m.status(), m.config());
let up = *m.connection() == Connection::Up;
let want = up && c["proxy"]["systemProxy"]["enable"] == true && s["proxy"]["on"] == true && s["proxy"]["state"] == "active";
let listener = s["proxy"]["listener"].as_str().unwrap_or("").replace("0.0.0.0:", "127.0.0.1:");
let bypass: Vec<String> = c["proxy"]["systemProxy"]["bypass"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_owned)).collect();
if listener.is_empty() || c.is_null() {
return;
}
let shell = cx.global_mut::<Shell>();
match shell.system_proxy.update(want, &listener, &bypass) {
Ok(()) => shell.system_proxy_error = None,
Err(e) if shell.system_proxy_error.as_ref() != Some(&e) => {
eprintln!("proxy-suite: the system proxy: {e}");
shell.system_proxy_error = Some(e);
}
Err(_) => {}
}
}
fn refresh(cx: &mut App) {
system_proxy(cx);
let Some(tray) = cx.global::<Shell>().tray.clone() else { return };
let fill = colour(cx);
if fill != cx.global::<Shell>().colour {
cx.global_mut::<Shell>().colour = fill;
if let Some(icon) = icon(fill, cx)
&& let Err(e) = tray.set_icon(icon, cx)
{
eprintln!("proxy-suite: the tray icon: {e}");
}
}
let (s, up) = status(cx);
let tip = if up {
let on = |v: &Value| if *v == true { "on" } else { "off" };
format!("Proxy Suite — proxy {}, DPI bypass {}, Telegram proxy {}", on(&s["proxy"]["on"]), on(&s["zapret"]["enabled"]), on(&s["tgWsProxy"]["enabled"]))
} else {
"Proxy Suite — the service is not running".into()
};
// The tooltip says what the menu's checks do: the same news.
if tip != cx.global::<Shell>().tooltip {
cx.global_mut::<Shell>().tooltip = tip.clone();
let _ = tray.set_tooltip(Some(tip), cx);
let _ = tray.refresh_menu(cx);
}
}
fn menu(cx: &mut App) -> Vec<MenuItem> {
let (s, up) = status(cx);
vec![
MenuItem::action("Open Proxy Suite", OpenWindow),
MenuItem::separator(),
MenuItem::action("Local proxy", ToggleProxy).checked(s["proxy"]["on"] == true).disabled(!up),
MenuItem::action("DPI bypass", ToggleDpi).checked(s["zapret"]["enabled"] == true).disabled(!up),
MenuItem::action("Telegram proxy", ToggleTelegram).checked(s["tgWsProxy"]["enabled"] == true).disabled(!up),
MenuItem::separator(),
MenuItem::action("Quit", Quit),
]
}
fn open_window(_: &OpenWindow, cx: &mut App) {
if let Some(window) = cx.global::<Shell>().window
&& window.update(cx, |_, window, _| window.activate_window()).is_ok()
{
return;
}
let model = cx.global::<Shell>().model.clone();
let options = WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::centered(None, size(px(1080.), px(720.)), cx))),
titlebar: Some(TitlebarOptions { title: Some("Proxy Suite".into()), ..Default::default() }),
window_min_size: Some(size(px(720.), px(480.))),
app_id: Some("proxy-suite".into()),
..Default::default()
};
match gpui_kit::open_window(options, cx, |window, cx| cx.new(|cx| AppView::new(model, window, cx))) {
Ok((window, _)) => cx.global_mut::<Shell>().window = window.downcast(),
Err(e) => eprintln!("proxy-suite: opening the window: {e}"),
}
}
fn toggle_proxy(_: &ToggleProxy, cx: &mut App) {
let model = cx.global::<Shell>().model.clone();
let on = model.read(cx).status()["proxy"]["on"] == true;
model.update(cx, |m, cx| m.set_proxy(!on, cx));
}
fn toggle_dpi(_: &ToggleDpi, cx: &mut App) {
let model = cx.global::<Shell>().model.clone();
let on = model.read(cx).status()["zapret"]["enabled"] != true;
model.update(cx, |m, cx| {
m.edit(
if on { "The DPI bypass is on" } else { "The DPI bypass is off" },
move |c| {
edits::set_zapret_enabled(c, on);
Ok(())
},
cx,
)
});
}
fn toggle_telegram(_: &ToggleTelegram, cx: &mut App) {
let model = cx.global::<Shell>().model.clone();
let on = model.read(cx).status()["tgWsProxy"]["enabled"] != true;
model.update(cx, |m, cx| {
m.edit(
if on { "The Telegram proxy is on" } else { "The Telegram proxy is off" },
move |c| {
edits::set_tg_ws_proxy_enabled(c, on);
Ok(())
},
cx,
)
});
}
fn quit(_: &Quit, cx: &mut App) {
cx.global_mut::<Shell>().system_proxy.restore();
if let Some(tray) = cx.global::<Shell>().tray.clone() {
let _ = tray.close(cx);
}
cx.quit();
}