//! Outbounds: adding one from a link, the list with pins, delays and switches, the routing //! mode, and subscriptions. use std::collections::HashMap; use gpui_kit::assets::IconName; use gpui_kit::component::button::{Button, ButtonVariants as _}; use gpui_kit::component::input::{Input, InputState}; use gpui_kit::component::notification::Notification; use gpui_kit::component::radio::RadioGroup; use gpui_kit::component::tag::Tag; use gpui_kit::component::*; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; use ps_client::edits::{self, OutboundSource}; use ps_ipc::Request; use serde_json::Value; use super::widgets::{card, hint, page, Inactive as _}; use crate::i18n::{tr, trf}; use crate::model::Model; const MODES: [(&str, &str); 5] = [ ("default", "As configured"), ("whitelist", "Proxy only listed sites"), ("blacklist", "Proxy all but listed sites"), ("all-proxy", "Proxy everything"), ("all-bypass", "Proxy nothing"), ]; pub struct OutboundsPage { model: Entity, link: Entity, tag: Entity, sub_url: Entity, /// The last delay test of each outbound: milliseconds, or why it failed. delays: HashMap>, testing: bool, _subscriptions: Vec, } impl OutboundsPage { pub fn new(model: Entity, window: &mut Window, cx: &mut Context) -> Self { let link = cx.new(|cx| InputState::new(window, cx).placeholder(tr("vless://…, ss://…, trojan://…, hysteria2://… or JSON"))); let tag = cx.new(|cx| InputState::new(window, cx).placeholder(tr("from the link"))); let sub_url = cx.new(|cx| InputState::new(window, cx).placeholder("https://provider.example/sub/…")); let subscriptions = vec![cx.observe(&model, |_, _, cx| cx.notify())]; Self { model, link, tag, sub_url, delays: HashMap::new(), testing: false, _subscriptions: subscriptions } } fn add(&mut self, window: &mut Window, cx: &mut Context) { let text = self.link.read(cx).value().trim().to_owned(); if text.is_empty() { return; } let source = match OutboundSource::parse(&text) { Ok(s) => s, Err(e) => { window.push_notification(Notification::error(trf("Not an outbound: {}", &[&format!("{e:#}")])).autohide(false), cx); return; } }; let typed = self.tag.read(cx).value().trim().to_owned(); let tag = if typed.is_empty() { edits::link_tag(&text) } else { typed }; self.link.update(cx, |s, cx| s.set_value("", window, cx)); self.tag.update(cx, |s, cx| s.set_value("", window, cx)); let what = trf("Added {}", &[&tag]); self.model.update(cx, |m, cx| m.edit(what, move |c| edits::add_outbound(c, &tag, &source, None), cx)); } fn add_subscription(&mut self, window: &mut Window, cx: &mut Context) { let url = self.sub_url.read(cx).value().trim().to_owned(); if url.is_empty() { return; } let tag = edits::subscription_tag(&url); self.sub_url.update(cx, |s, cx| s.set_value("", window, cx)); self.model.update(cx, |m, cx| m.edit(trf("Subscription {} added; fetching it", &[&tag]), move |c| edits::add_subscription(c, &tag, &url), cx)); } fn test(&mut self, tags: Vec, cx: &mut Context) { self.testing = true; cx.notify(); let job = self.model.read(cx).bridge().call(Request::Test { tags }); cx.spawn(async move |this, cx| { let result = job.await; this.update(cx, |this, cx| { this.testing = false; match result { Ok(list) => { for t in list.as_array().into_iter().flatten() { let tag = t["tag"].as_str().unwrap_or("").to_owned(); let delay = t["delay"].as_u64().ok_or_else(|| t["error"].as_str().unwrap_or(tr("no reason given")).to_owned()); this.delays.insert(tag, delay); } } Err(e) => { this.delays.clear(); this.delays.insert(String::new(), Err(format!("{e:#}"))); } } cx.notify(); }) .ok(); }) .detach(); } fn row(&self, tag: &str, inv: &Value, ix: usize, cx: &mut Context) -> Div { let pinned = inv["pinned"] == tag; let disabled = inv["disabled"].as_array().is_some_and(|d| d.iter().any(|x| x == tag)); let source = inv["sources"][tag].as_str().unwrap_or("").to_owned(); let own = source == "static"; let mut notes = vec![source.clone()]; if let Some(r) = inv["runsOn"][tag].as_str() { notes.push(r.to_owned()); } if let Some(h) = inv["detours"][tag].as_str() { notes.push(trf("through {}", &[&h])); } let delay = match self.delays.get(tag) { Some(Ok(ms)) => Tag::success().child(format!("{ms} ms")).into_any_element(), Some(Err(e)) => div().max_w(px(220.)).truncate().text_xs().text_color(cx.theme().danger).child(trf("failed: {}", &[&e])).into_any_element(), None => div().into_any_element(), }; let (model_pin, model_dis, model_rm) = (self.model.clone(), self.model.clone(), self.model.clone()); let (t_pin, t_dis, t_rm, t_test) = (tag.to_owned(), tag.to_owned(), tag.to_owned(), tag.to_owned()); div() .h_flex() .gap_3() .items_center() .py_2() .border_t_1() .border_color(cx.theme().border) .child( div() .v_flex() .flex_1() .min_w_0() .child(div().h_flex().gap_2().items_center().child(div().font_medium().truncate().child(tag.to_owned())).when(pinned, |d| d.child(Tag::primary().child(tr("pinned")))).when(disabled, |d| d.child(Tag::secondary().child(tr("disabled"))))) .child(div().text_xs().text_color(cx.theme().muted_foreground).child(notes.join(" · "))), ) .child(delay) .child(Button::new(("test", ix)).small().ghost().icon(IconName::Gauge).tooltip(tr("Test its delay")).on_click(cx.listener(move |this, _, _, cx| this.test(vec![t_test.clone()], cx)))) .child(Button::new(("pin", ix)).small().ghost().icon(if pinned { IconName::PinOff } else { IconName::Pin }).tooltip(if pinned { tr("Back to automatic selection") } else { tr("Always use this one") }).on_click(move |_, _, cx| { let req = Request::Pin { tag: if pinned { None } else { Some(t_pin.clone()) }, group: None }; let what = if pinned { tr("Back to automatic selection").to_owned() } else { trf("Pinned to {}", &[&t_pin]) }; model_pin.update(cx, |m, cx| m.request(what, req, cx)); })) .child(Button::new(("disable", ix)).small().ghost().icon(IconName::Power).tooltip(if disabled { tr("Use it again") } else { tr("Leave it out") }).on_click(move |_, _, cx| { let what = if disabled { trf("{} is back", &[&t_dis]) } else { trf("{} is left out", &[&t_dis]) }; let req = Request::Disable { tag: t_dis.clone(), disabled: !disabled }; model_dis.update(cx, |m, cx| m.request(what, req, cx)); })) .when(own, |d| { d.child(Button::new(("remove", ix)).small().ghost().icon(IconName::Trash).tooltip(tr("Remove it")).on_click(move |_, _, cx| { let tag = t_rm.clone(); model_rm.update(cx, |m, cx| m.edit(trf("Removed {}", &[&tag]), move |c| edits::remove_outbound(c, &tag), cx)); })) }) } } impl Render for OutboundsPage { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { let m = self.model.read(cx); let inv = m.outbounds()["inventory"].clone(); let mode = m.status()["proxy"]["mode"].as_str().unwrap_or("default").to_owned(); let subs: Vec = m.config()["proxy"]["subscriptions"].as_array().into_iter().flatten().filter_map(|s| s["tag"].as_str().map(str::to_owned)).collect(); let tags: Vec = inv["tags"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect(); let add = card(tr("Add an outbound"), Some(Button::new("add").small().primary().icon(IconName::Plus).label(tr("Add")).on_click(cx.listener(|this, _, window, cx| this.add(window, cx))).into_any_element()), cx) .child(hint(tr("A share link from your provider, or a sing-box or XRay outbound as JSON. Links stay on this computer, in the service's configuration."), cx)) .child(div().h_flex().gap_3().child(div().flex_1().min_w_0().child(Input::new(&self.link))).child(div().w(px(180.)).child(Input::new(&self.tag)))); let mut list = card( trf("Outbounds ({})", &[&tags.len()]), Some(Button::new("test-all").small().icon(IconName::Gauge).label(if self.testing { tr("Testing…") } else { tr("Test all") }).inactive(self.testing || tags.is_empty(), cx).on_click(cx.listener(|this, _, _, cx| this.test(Vec::new(), cx))).into_any_element()), cx, ); if let Some(Err(e)) = self.delays.get("") { list = list.child(div().text_sm().text_color(cx.theme().danger).child(trf("Testing failed: {}", &[&e]))); } if tags.is_empty() { list = list.child(hint(tr("None yet: add a link above, or a subscription below."), cx)); } for (i, tag) in tags.iter().enumerate() { list = list.child(self.row(tag, &inv, i, cx)); } let model = self.model.clone(); let modes = card(tr("Routing mode"), None, cx).child(hint(tr("Overrides the routing rules until changed back; “As configured” follows them."), cx)).child( RadioGroup::vertical("mode").children(MODES.map(|(_, label)| tr(label))).selected_index(MODES.iter().position(|(v, _)| *v == mode)).on_change(move |ix, _, cx| { let (value, label) = MODES[*ix]; let req = Request::Mode { mode: if value == "default" { None } else { Some(value.into()) } }; model.update(cx, |m, cx| m.request(trf("Mode: {}", &[&tr(label)]), req, cx)); }), ); let model = self.model.clone(); let mut subscriptions = card( tr("Subscriptions"), Some( Button::new("subs-update") .small() .icon(IconName::RefreshCw) .label(tr("Update all")) .inactive(subs.is_empty(), cx) .on_click(move |_, _, cx| model.update(cx, |m, cx| m.request(tr("Subscriptions updated"), Request::SubsUpdate { tag: None }, cx))) .into_any_element(), ), cx, ) .child( div() .h_flex() .gap_3() .child(div().flex_1().min_w_0().child(Input::new(&self.sub_url))) .child(Button::new("sub-add").small().icon(IconName::Plus).label(tr("Add")).on_click(cx.listener(|this, _, window, cx| this.add_subscription(window, cx)))), ); for (i, tag) in subs.into_iter().enumerate() { let model = self.model.clone(); let t = tag.clone(); subscriptions = subscriptions.child( div() .h_flex() .items_center() .py_1() .border_t_1() .border_color(cx.theme().border) .child(div().flex_1().child(tag)) .child(Button::new(("sub-rm", i)).small().ghost().icon(IconName::Trash).tooltip(tr("Remove it")).on_click(move |_, _, cx| { let tag = t.clone(); model.update(cx, |m, cx| m.edit(trf("Removed subscription {}", &[&tag]), move |c| edits::remove_subscription(c, &tag), cx)); })), ); } page(tr("Outbounds"), cx).child(add).child(list).child(modes).child(subscriptions) } } /// This page's words, in Russian (i18n). pub const RU: &[(&str, &str)] = &[ ("As configured", "Как настроено"), ("Proxy only listed sites", "Прокси только для сайтов из списка"), ("Proxy all but listed sites", "Прокси для всех, кроме сайтов из списка"), ("Proxy everything", "Прокси для всего"), ("Proxy nothing", "Без прокси"), ("vless://…, ss://…, trojan://…, hysteria2://… or JSON", "vless://…, ss://…, trojan://…, hysteria2://… или JSON"), ("from the link", "из ссылки"), ("Not an outbound: {}", "Это не выход: {}"), ("Added {}", "Добавлен выход: {}"), ("Subscription {} added; fetching it", "Подписка {} добавлена, загружаем её"), ("no reason given", "причина неизвестна"), ("through {}", "через {}"), ("failed: {}", "не удалось: {}"), ("pinned", "закреплён"), ("disabled", "исключён"), ("Test its delay", "Проверить задержку"), ("Back to automatic selection", "Вернуть автоматический выбор"), ("Always use this one", "Всегда использовать этот"), ("Pinned to {}", "Закреплён: {}"), ("Use it again", "Использовать снова"), ("Leave it out", "Исключить"), ("{} is back", "{}: снова используется"), ("{} is left out", "{}: исключён"), ("Remove it", "Удалить"), ("Removed {}", "Удалён: {}"), ("Add an outbound", "Добавить выход"), ("Add", "Добавить"), ("A share link from your provider, or a sing-box or XRay outbound as JSON. Links stay on this computer, in the service's configuration.", "Ссылка от вашего провайдера или выход sing-box либо XRay в виде JSON. Ссылки остаются на этом компьютере, в конфигурации службы."), ("Outbounds ({})", "Выходы ({})"), ("Testing…", "Проверка…"), ("Test all", "Проверить все"), ("Testing failed: {}", "Проверка не удалась: {}"), ("None yet: add a link above, or a subscription below.", "Пока пусто: добавьте ссылку выше или подписку ниже."), ("Routing mode", "Режим маршрутизации"), ("Overrides the routing rules until changed back; “As configured” follows them.", "Заменяет правила маршрутизации, пока не вернёте прежний режим; «Как настроено» следует правилам."), ("Mode: {}", "Режим: {}"), ("Subscriptions", "Подписки"), ("Update all", "Обновить все"), ("Subscriptions updated", "Подписки обновлены"), ("Removed subscription {}", "Подписка удалена: {}"), ("Outbounds", "Выходы"), ];