diff --git a/windows/crates/ps-gui/src/ui/mod.rs b/windows/crates/ps-gui/src/ui/mod.rs index 46fce78..a0b4d16 100644 --- a/windows/crates/ps-gui/src/ui/mod.rs +++ b/windows/crates/ps-gui/src/ui/mod.rs @@ -2,6 +2,7 @@ //! notification. mod dpi; +mod outbounds; mod overview; mod telegram; mod widgets; @@ -58,6 +59,7 @@ pub struct AppView { page: Page, dpi: Entity, telegram: Entity, + outbounds: Entity, _subscriptions: Vec, } @@ -75,7 +77,8 @@ impl AppView { ]; let dpi = cx.new(|cx| dpi::DpiPage::new(model.clone(), window, cx)); let telegram = cx.new(|cx| telegram::TelegramPage::new(model.clone(), window, cx)); - Self { model, page: Page::Overview, dpi, telegram, _subscriptions: subscriptions } + let outbounds = cx.new(|cx| outbounds::OutboundsPage::new(model.clone(), window, cx)); + Self { model, page: Page::Overview, dpi, telegram, outbounds, _subscriptions: subscriptions } } fn sidebar(&self, cx: &mut Context) -> impl IntoElement { @@ -95,6 +98,7 @@ impl Render for AppView { Page::Overview => overview::render(&self.model, window, cx).into_any_element(), Page::Dpi => self.dpi.clone().into_any_element(), Page::Telegram => self.telegram.clone().into_any_element(), + Page::Outbounds => self.outbounds.clone().into_any_element(), other => widgets::page(other.title(), cx).child(div().text_color(cx.theme().muted_foreground).child("Not here yet.")).into_any_element(), }; div() diff --git a/windows/crates/ps-gui/src/ui/outbounds.rs b/windows/crates/ps-gui/src/ui/outbounds.rs new file mode 100644 index 0000000..4f33954 --- /dev/null +++ b/windows/crates/ps-gui/src/ui/outbounds.rs @@ -0,0 +1,241 @@ +//! 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}; +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("vless://…, ss://…, trojan://…, hysteria2://… or JSON")); + let tag = cx.new(|cx| InputState::new(window, cx).placeholder("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(format!("Not an outbound: {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 = format!("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(format!("Subscription {tag} added; fetching it"), 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("failed").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(format!("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(format!("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("pinned"))).when(disabled, |d| d.child(Tag::secondary().child("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("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 { "Back to automatic selection" } else { "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 { "Back to automatic selection".to_owned() } else { format!("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 { "Use it again" } else { "Leave it out" }).on_click(move |_, _, cx| { + let what = format!("{t_dis} {}", if disabled { "is back" } else { "is left out" }); + 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("Remove it").on_click(move |_, _, cx| { + let tag = t_rm.clone(); + model_rm.update(cx, |m, cx| m.edit(format!("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("Add an outbound", Some(Button::new("add").small().primary().icon(IconName::Plus).label("Add").on_click(cx.listener(|this, _, window, cx| this.add(window, cx))).into_any_element()), cx) + .child(hint("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( + format!("Outbounds ({})", tags.len()), + Some(Button::new("test-all").small().icon(IconName::Gauge).label(if self.testing { "Testing…" } else { "Test all" }).disabled(self.testing || tags.is_empty()).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(format!("Testing failed: {e}"))); + } + if tags.is_empty() { + list = list.child(hint("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("Routing mode", None, cx).child(hint("Overrides the routing rules until changed back; “As configured” follows them.", cx)).child( + RadioGroup::vertical("mode").children(MODES.map(|(_, label)| 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(format!("Mode: {label}"), req, cx)); + }), + ); + + let model = self.model.clone(); + let mut subscriptions = card( + "Subscriptions", + Some( + Button::new("subs-update") + .small() + .icon(IconName::RefreshCw) + .label("Update all") + .disabled(subs.is_empty()) + .on_click(move |_, _, cx| model.update(cx, |m, cx| m.request("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("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("Remove it").on_click(move |_, _, cx| { + let tag = t.clone(); + model.update(cx, |m, cx| m.edit(format!("Removed subscription {tag}"), move |c| edits::remove_subscription(c, &tag), cx)); + })), + ); + } + + page("Outbounds", cx).child(add).child(list).child(modes).child(subscriptions) + } +} diff --git a/windows/tools/dev-service.sh b/windows/tools/dev-service.sh index 0bc2dba..21915ea 100755 --- a/windows/tools/dev-service.sh +++ b/windows/tools/dev-service.sh @@ -24,7 +24,9 @@ cat >"$STATE/server.json" <