windows: the app in Russian

Every page, the tray's menu and tooltip, and the notifications, as Windows'
display language is (GetUserDefaultUILanguage) or as chosen in Settings >
This app. English stays the key in the code: tr()/trf() (i18n.rs) look it
up in the page's own RU table. What the service says and proxy-ctl stay
English.

Changing the language rebuilds the window on the same page. That needed the
window's handle untyped: gpui-kit's Root holds the view, so the typed handle
was always None, and the tray's Open made a second window rather than
raising the first (fixed too). An AmneziaWG outbound no longer shows its
kind twice. tools/screenshots.sh takes SHOT_LANGUAGE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-27 23:28:52 +03:00
1 parent 803e18db9d
commit e9de863c4b
22 files changed
+882 -305

No files matched your search

+3 -2
View File
@@ -31,7 +31,7 @@ tray icon) or with `proxy-ctl`, as upstream's is.
| whitelist-bypass | `whitelistBypass`: [whitelist-bypass](https://github.com/kulikov0/whitelist-bypass)'s headless creators and joiners (WB Stream, Telemost, DION, Bitrix; VK creators), built from upstream's source: a joiner is an outbound of the proxy tunnelled through a video call, a creator the call's free end. `proxy-ctl wl` gives the links and logins |
| SSH tunnel | `sshProxy`: Windows' own OpenSSH as a SOCKS listener (`ssh -D`) for other programs, and, with `asOutbound`, an outbound of the proxy (sing-box's SSH client) |
| TUN | sing-box's TUN (wintun), `proxy-ctl proxy tun on` — **see the caveats** |
| The app | **Proxy Suite** in the Start Menu, and a tray icon from sign-in: the proxy, DPI bypass and Telegram proxy at a glance and a click; outbounds, subscriptions and the routing mode; zapret's presets and sites; tg-ws-proxy's links; whitelist-bypass's joiners and creators (links, logins); autoProxy's routes, probes and exits; the logs; **every option** in its JSON editor, checked by the service before it takes it; the system proxy; a light and a dark theme (or as Windows is set); a newer release installed from its Overview |
| The app | **Proxy Suite** in the Start Menu, and a tray icon from sign-in: the proxy, DPI bypass and Telegram proxy at a glance and a click; outbounds, subscriptions and the routing mode; zapret's presets and sites; tg-ws-proxy's links; whitelist-bypass's joiners and creators (links, logins); autoProxy's routes, probes and exits; the logs; **every option** in its JSON editor, checked by the service before it takes it; the system proxy; in English or Russian (as Windows is set, or chosen); a light and a dark theme (or as Windows is set); a newer release installed from its Overview |
Not in this release, still to come: Tor's onion service,
the kill switch, server inbounds and the XRay-only backend. Their options are accepted (they are upstream's), but the
@@ -50,7 +50,8 @@ DPI bypass, which runs on Windows only, shows as inactive.
| ![Outbounds](docs/screenshots/outbounds.png) | ![autoProxy](docs/screenshots/autoproxy.png) |
| ![AmneziaWG](docs/screenshots/amneziawg.png) | ![Whitelist bypass](docs/screenshots/whitelist-bypass.png) |
| ![Telegram proxy](docs/screenshots/telegram.png) | ![Settings](docs/screenshots/settings.png) |
| ![Overview, dark](docs/screenshots/overview-dark.png) | ![Components](docs/screenshots/components.png) |
| ![Overview, dark](docs/screenshots/overview-dark.png) | ![Logs](docs/screenshots/logs.png) |
| ![Overview, in Russian](docs/screenshots/overview-ru.png) | ![Components](docs/screenshots/components.png) |
## What has been verified
+1
View File
@@ -28,4 +28,5 @@ windows-sys = { workspace = true, features = [
"Win32_Graphics_Dwm",
"Win32_System_Threading",
"Win32_UI_WindowsAndMessaging",
"Win32_Globalization",
] }
+86
View File
@@ -0,0 +1,86 @@
//! The app's words in the user's language: English, as the code writes them, or Russian. Each
//! page keeps its Russian beside its English (its `RU` table); `tr` and `trf` look a text up,
//! and a text without a translation stays English. What the service says (its warnings and
//! errors) stays English, as `proxy-ctl` does.
use std::collections::HashMap;
use std::fmt::Display;
use std::sync::LazyLock;
use std::sync::atomic::{AtomicBool, Ordering};
static RUSSIAN: AtomicBool = AtomicBool::new(false);
/// Every page's table, and the app's own.
static TABLE: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
let tables: [&[(&str, &str)]; 15] = [
RU,
crate::model::RU,
crate::shell::RU,
crate::ui::RU,
crate::ui::widgets::RU,
crate::ui::overview::RU,
crate::ui::dpi::RU,
crate::ui::telegram::RU,
crate::ui::whitelist::RU,
crate::ui::outbounds::RU,
crate::ui::autoproxy::RU,
crate::ui::amneziawg::RU,
crate::ui::logs::RU,
crate::ui::settings::RU,
crate::ui::components::RU,
];
tables.iter().flat_map(|t| t.iter().copied()).collect()
});
pub fn set_russian(on: bool) {
RUSSIAN.store(on, Ordering::Relaxed);
}
pub fn russian() -> bool {
RUSSIAN.load(Ordering::Relaxed)
}
/// Whether Windows' own language (the user's display language) is Russian; elsewhere, the
/// locale's.
pub fn system_russian() -> bool {
#[cfg(windows)]
{
// SAFETY: no arguments.
let id = unsafe { windows_sys::Win32::Globalization::GetUserDefaultUILanguage() };
// The primary language: LANG_RUSSIAN.
id & 0x3ff == 0x19
}
#[cfg(not(windows))]
{
["LC_ALL", "LC_MESSAGES", "LANG"].iter().find_map(|v| std::env::var(v).ok().filter(|s| !s.is_empty())).is_some_and(|s| s.starts_with("ru"))
}
}
/// `en` in the user's language.
pub fn tr(en: &'static str) -> &'static str {
if !russian() {
return en;
}
TABLE.get(en).copied().unwrap_or(en)
}
/// `en` in the user's language, each `{}` in it taking the next of `args`.
pub fn trf(en: &'static str, args: &[&dyn Display]) -> String {
let mut out = String::new();
let mut args = args.iter();
let mut parts = tr(en).split("{}");
if let Some(first) = parts.next() {
out.push_str(first);
}
for part in parts {
match args.next() {
Some(a) => out.push_str(&a.to_string()),
None => out.push_str("{}"),
}
out.push_str(part);
}
out
}
/// The app's own words, outside the pages.
pub const RU: &[(&str, &str)] = &[];
+4 -1
View File
@@ -9,6 +9,7 @@
mod assets;
mod bridge;
mod i18n;
mod model;
mod prefs;
mod shell;
@@ -47,7 +48,9 @@ fn main() {
// The window closing does not end the app: the tray does (shell.rs).
gpui_kit::application().with_assets(assets::AppAssets).with_quit_mode(QuitMode::Explicit).run(move |cx| {
gpui_kit::init(cx);
cx.set_global(prefs::load());
let prefs = prefs::load();
i18n::set_russian(prefs.language.russian());
cx.set_global(prefs);
prefs::tune_dark(cx);
prefs::apply_theme(None, cx);
let model = cx.new(|cx| model::Model::new(bridge, cx));
+15 -5
View File
@@ -10,6 +10,7 @@ use ps_ipc::Request;
use serde_json::Value;
use crate::bridge::Bridge;
use crate::i18n::{tr, trf};
/// What a change came to.
pub enum Outcome {
@@ -85,7 +86,7 @@ impl Model {
if let Update::Installing { version, started: true, at } = &m.update
&& at.elapsed() >= SETUP_WAIT
{
m.update = Update::Failed(format!("the setup of {version} did not finish (the service's log, on the Logs page, may say why)").into());
m.update = Update::Failed(trf("the setup of {} did not finish (the service's log, on the Logs page, may say why)", &[version]).into());
}
let due = m.update_checked.is_none_or(|t| t.elapsed() >= UPDATE_CHECK);
if m.connection == Connection::Up && due && cx.global::<crate::prefs::Prefs>().check_updates {
@@ -221,7 +222,7 @@ impl Model {
Ok(_) => m.update = Update::Installing { version, started: true, at: Instant::now() },
Err(e) => {
let e: SharedString = format!("{e:#}").into();
cx.emit(Outcome::Failed(format!("Updating to {version}: {e}").into()));
cx.emit(Outcome::Failed(trf("Updating to {}: {}", &[&version, &e]).into()));
m.update = Update::Failed(e);
}
}
@@ -322,7 +323,7 @@ impl Model {
what,
async move {
if let Some(e) = job.await?.apply_error {
bail!("saved, but not applied: {e}");
bail!(trf("saved, but not applied: {}", &[&e]));
}
Ok(())
},
@@ -347,7 +348,7 @@ impl Model {
})
.await?;
if let Some(e) = saved.apply_error {
bail!("saved, but not applied: {e}");
bail!(trf("saved, but not applied: {}", &[&e]));
}
bridge.call(Request::Start { unit: "proxy-suite-socks".into() }).await?;
} else {
@@ -355,6 +356,15 @@ impl Model {
}
Ok(())
};
self.track(if on { "The proxy is on" } else { "The proxy is off" }, job, cx);
self.track(tr(if on { "The proxy is on" } else { "The proxy is off" }), job, cx);
}
}
/// The changes' words, in Russian (i18n).
pub const RU: &[(&str, &str)] = &[
("the setup of {} did not finish (the service's log, on the Logs page, may say why)", "установка {} не завершилась (причину может подсказать журнал службы на странице «Журналы»)"),
("Updating to {}: {}", "Обновление до {}: {}"),
("saved, but not applied: {}", "сохранено, но не применено: {}"),
("The proxy is on", "Локальный прокси включён"),
("The proxy is off", "Локальный прокси выключен"),
];
+38 -6
View File
@@ -1,5 +1,5 @@
//! The app's own preferences, each user's: its look, and whether it looks for updates. All
//! else is the service's configuration.
//! The app's own preferences, each user's: its language and look, and whether it looks for
//! updates. All else is the service's configuration.
//!
//! In `%APPDATA%\ProxySuite\app.json` (elsewhere `$XDG_CONFIG_HOME/proxy-suite/app.json`).
@@ -24,9 +24,35 @@ impl ThemeChoice {
pub const ALL: [(ThemeChoice, &'static str); 3] = [(ThemeChoice::System, "As Windows"), (ThemeChoice::Light, "Light"), (ThemeChoice::Dark, "Dark")];
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum Language {
/// Windows' own display language: Russian when it is, else English.
#[default]
#[serde(rename = "system")]
System,
#[serde(rename = "en")]
English,
#[serde(rename = "ru")]
Russian,
}
impl Language {
/// Each named in its own language.
pub const ALL: [(Language, &'static str); 3] = [(Language::System, "As Windows"), (Language::English, "English"), (Language::Russian, "Русский")];
pub fn russian(self) -> bool {
match self {
Language::System => crate::i18n::system_russian(),
Language::English => false,
Language::Russian => true,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Prefs {
pub language: Language,
pub theme: ThemeChoice,
/// At start and daily, ask the service whether a newer release is out.
pub check_updates: bool,
@@ -34,7 +60,7 @@ pub struct Prefs {
impl Default for Prefs {
fn default() -> Self {
Self { theme: ThemeChoice::System, check_updates: true }
Self { language: Language::System, theme: ThemeChoice::System, check_updates: true }
}
}
@@ -68,12 +94,18 @@ impl Prefs {
/// Changes the preferences, saves them, and shows what changed.
pub fn change(cx: &mut App, edit: impl FnOnce(&mut Prefs)) {
let before = cx.global::<Prefs>().theme;
let before = cx.global::<Prefs>().clone();
edit(cx.global_mut::<Prefs>());
cx.global::<Prefs>().save();
if cx.global::<Prefs>().theme != before {
let now = cx.global::<Prefs>().clone();
now.save();
if now.theme != before.theme {
apply_theme(None, cx);
}
if now.language.russian() != before.language.russian() {
crate::i18n::set_russian(now.language.russian());
// What the pages made once (placeholders, lists) is made again, in the new words.
crate::shell::reopen_window(cx);
}
cx.refresh_windows();
}
+60 -15
View File
@@ -2,6 +2,7 @@
//! 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 crate::i18n::{tr, trf};
use gpui_kit::*;
use gpui_tray::{Icon, Tray};
use ps_client::edits;
@@ -15,7 +16,8 @@ actions!(proxy_suite, [OpenWindow, ToggleProxy, ToggleDpi, ToggleTelegram, Quit]
struct Shell {
model: Entity<Model>,
window: Option<WindowHandle<AppView>>,
/// The window (gpui-kit's root holds the view: no handle typed by it) and its view.
window: Option<(AnyWindowHandle, Entity<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).
@@ -24,13 +26,15 @@ struct Shell {
system_proxy: SystemProxy,
/// The system proxy's last failure, said once.
system_proxy_error: Option<String>,
/// The window is closing to open again (the language changed): not a reason to quit.
reopening: bool,
}
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 });
cx.set_global(Shell { model: model.clone(), window: None, tray: None, colour: "", tooltip: String::new(), system_proxy: SystemProxy::default(), system_proxy_error: None, reopening: false });
let mut builder = Tray::builder().tooltip("Proxy Suite").on_activate(OpenWindow).menu(menu);
if let Some(icon) = icon("#6b7280", cx) {
@@ -42,7 +46,7 @@ pub fn start(model: Entity<Model>, open: bool, cx: &mut App) {
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() {
if cx.global::<Shell>().tray.is_none() && cx.windows().is_empty() && !cx.global::<Shell>().reopening {
cx.quit();
}
})
@@ -120,10 +124,10 @@ fn refresh(cx: &mut App) {
}
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"]))
let on = |v: &Value| if *v == true { tr("on") } else { tr("off") };
trf("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()
tr("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 {
@@ -136,18 +140,44 @@ fn refresh(cx: &mut App) {
fn menu(cx: &mut App) -> Vec<MenuItem> {
let (s, up) = status(cx);
vec![
MenuItem::action("Open Proxy Suite", OpenWindow),
MenuItem::action(tr("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::action(tr("Local proxy"), ToggleProxy).checked(s["proxy"]["on"] == true).disabled(!up),
MenuItem::action(tr("DPI bypass"), ToggleDpi).checked(s["zapret"]["enabled"] == true).disabled(!up),
MenuItem::action(tr("Telegram proxy"), ToggleTelegram).checked(s["tgWsProxy"]["enabled"] == true).disabled(!up),
MenuItem::separator(),
MenuItem::action("Quit", Quit),
MenuItem::action(tr("Quit"), Quit),
]
}
/// The window, if open, closed and opened again on the same page: what its pages made once
/// (lists, placeholders) is made again, in the language just chosen. The tray's menu and
/// tooltip follow too.
pub fn reopen_window(cx: &mut App) {
cx.global_mut::<Shell>().tooltip.clear();
cx.defer(|cx| {
refresh(cx);
let Some((window, view)) = cx.global::<Shell>().window.clone() else { return };
let page = view.read(cx).page();
cx.global_mut::<Shell>().reopening = true;
let closed = window.update(cx, |_, window, _| window.remove_window()).is_ok();
cx.global_mut::<Shell>().window = None;
if closed {
cx.defer(move |cx| {
open_window(&OpenWindow, cx);
if let Some((_, view)) = cx.global::<Shell>().window.clone() {
view.update(cx, |v, cx| v.show(page, cx));
}
cx.global_mut::<Shell>().reopening = false;
});
} else {
cx.global_mut::<Shell>().reopening = false;
}
});
}
fn open_window(_: &OpenWindow, cx: &mut App) {
if let Some(window) = cx.global::<Shell>().window
if let Some((window, _)) = cx.global::<Shell>().window
&& window.update(cx, |_, window, _| window.activate_window()).is_ok()
{
return;
@@ -161,7 +191,7 @@ fn open_window(_: &OpenWindow, cx: &mut App) {
..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(),
Ok((window, view)) => cx.global_mut::<Shell>().window = Some((window, view)),
Err(e) => eprintln!("proxy-suite: opening the window: {e}"),
}
}
@@ -177,7 +207,7 @@ fn toggle_dpi(_: &ToggleDpi, cx: &mut App) {
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" },
if on { tr("The DPI bypass is on") } else { tr("The DPI bypass is off") },
move |c| {
edits::set_zapret_enabled(c, on);
Ok(())
@@ -192,7 +222,7 @@ fn toggle_telegram(_: &ToggleTelegram, cx: &mut App) {
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" },
if on { tr("The Telegram proxy is on") } else { tr("The Telegram proxy is off") },
move |c| {
edits::set_tg_ws_proxy_enabled(c, on);
Ok(())
@@ -209,3 +239,18 @@ fn quit(_: &Quit, cx: &mut App) {
}
cx.quit();
}
/// The tray's words, in Russian (i18n).
pub const RU: &[(&str, &str)] = &[
("on", "вкл."),
("off", "выкл."),
("Proxy Suite — proxy {}, DPI bypass {}, Telegram proxy {}", "Proxy Suite — прокси: {}, обход DPI: {}, прокси для Telegram: {}"),
("Proxy Suite — the service is not running", "Proxy Suite — служба не запущена"),
("Open Proxy Suite", "Открыть Proxy Suite"),
("Local proxy", "Локальный прокси"),
("Quit", "Выйти"),
("The DPI bypass is on", "Обход DPI включён"),
("The DPI bypass is off", "Обход DPI выключен"),
("The Telegram proxy is on", "Прокси для Telegram включён"),
("The Telegram proxy is off", "Прокси для Telegram выключен"),
];
+50 -19
View File
@@ -12,11 +12,13 @@ use gpui_kit::component::radio::RadioGroup;
use gpui_kit::component::switch::Switch;
use gpui_kit::component::tag::Tag;
use gpui_kit::component::*;
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use ps_client::edits;
use ps_ipc::Request;
use serde_json::Value;
use crate::i18n::{tr, trf};
use super::widgets::{card, hint, page, state_tag};
use crate::model::Model;
@@ -37,7 +39,7 @@ pub struct AmneziaWgPage {
impl AmneziaWgPage {
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let name = cx.new(|cx| InputState::new(window, cx).placeholder("home"));
let text = cx.new(|cx| TextareaState::new(window, cx).rows(5).placeholder("vpn://… from AmneziaVPN, or a .conf: [Interface] …"));
let text = cx.new(|cx| TextareaState::new(window, cx).rows(5).placeholder(tr("vpn://… from AmneziaVPN, or a .conf: [Interface] …")));
let subscriptions = vec![cx.observe(&model, |this, _, cx| {
if this.loaded_at.is_none_or(|t| t.elapsed() > Duration::from_secs(3)) {
this.load(cx);
@@ -63,7 +65,7 @@ impl AmneziaWgPage {
}
fn set(&mut self, name: String, on: bool, cx: &mut Context<Self>) {
let what = format!("{name}: {}", if on { "tunnel up" } else { "tunnel down" });
let what = if on { trf("{}: tunnel up", &[&name]) } else { trf("{}: tunnel down", &[&name]) };
let job = self.model.read(cx).bridge().call(Request::AwgSet { name, on });
let model = self.model.clone();
cx.spawn(async move |this, cx| {
@@ -102,12 +104,12 @@ impl AmneziaWgPage {
}
self.name.update(cx, |s, cx| s.set_value("", window, cx));
self.text.update(cx, |s, cx| s.set_value("", window, cx));
let what = format!("AmneziaWG profile '{name}' added");
let what = trf("AmneziaWG profile '{}' added", &[&name]);
self.model.update(cx, |m, cx| m.edit(what, move |c| edits::add_awg_profile(c, &name, &text, kind), cx));
}
fn remove(&mut self, name: String, cx: &mut Context<Self>) {
self.model.update(cx, |m, cx| m.edit(format!("AmneziaWG profile '{name}' removed"), move |c| edits::remove_awg_profile(c, &name), cx));
self.model.update(cx, |m, cx| m.edit(trf("AmneziaWG profile '{}' removed", &[&name]), move |c| edits::remove_awg_profile(c, &name), cx));
}
}
@@ -116,7 +118,7 @@ impl Render for AmneziaWgPage {
let m = self.model.read(cx);
let body = page("AmneziaWG", cx);
if m.config().is_null() {
return body.child(hint("Waiting for the service…", cx));
return body.child(hint(tr("Waiting for the service…"), cx));
}
let on = m.config()["amneziaWg"]["enable"] == true;
let model = self.model.clone();
@@ -124,7 +126,7 @@ impl Render for AmneziaWgPage {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
if on { "AmneziaWG is on" } else { "AmneziaWG is off" },
if on { tr("AmneziaWG is on") } else { tr("AmneziaWG is off") },
move |c| {
edits::set_path(c, &["amneziaWg", "enable"], on.into());
Ok(())
@@ -134,26 +136,26 @@ impl Render for AmneziaWgPage {
})
});
let about = card("AmneziaWG", Some(enable.into_any_element()), cx).child(hint(
"WireGuard with AmneziaVPN's obfuscation. A system-wide profile is a VPN of its own (a network adapter, its routes and DNS); with one peer that takes everything, it also blocks what would leave outside the tunnel. An outbound profile is one more exit for the proxy, with nothing else changed.",
tr("WireGuard with AmneziaVPN's obfuscation. A system-wide profile is a VPN of its own (a network adapter, its routes and DNS); with one peer that takes everything, it also blocks what would leave outside the tunnel. An outbound profile is one more exit for the proxy, with nothing else changed."),
cx,
));
let mut profiles = card("Profiles", Some(Button::new("awg-reload").small().icon(IconName::RefreshCw).on_click(cx.listener(|this, _, _, cx| this.load(cx))).into_any_element()), cx);
let mut profiles = card(tr("Profiles"), Some(Button::new("awg-reload").small().icon(IconName::RefreshCw).on_click(cx.listener(|this, _, _, cx| this.load(cx))).into_any_element()), cx);
match &self.list {
Err(e) => profiles = profiles.child(div().text_sm().text_color(cx.theme().danger).child(e.clone())),
Ok(l) => {
let list = l["profiles"].as_array().cloned().unwrap_or_default();
if list.is_empty() {
profiles = profiles.child(hint("None yet: add one below.", cx));
profiles = profiles.child(hint(tr("None yet: add one below."), cx));
}
for (i, p) in list.iter().enumerate() {
let name = p["name"].as_str().unwrap_or("").to_owned();
let vpn = p["kind"] == "vpn";
let state = p["state"].as_str().unwrap_or("").to_owned();
let kind = match p["kind"].as_str().unwrap_or("") {
"vpn" => Tag::info().child("system VPN"),
"userspace" => Tag::secondary().child("outbound"),
_ => Tag::secondary().child("outbound (WireGuard)"),
"vpn" => Tag::info().child(tr("system VPN")),
"userspace" => Tag::secondary().child(tr("outbound")),
_ => Tag::secondary().child(tr("outbound (WireGuard)")),
};
let mut line = div()
.h_flex()
@@ -161,13 +163,14 @@ impl Render for AmneziaWgPage {
.items_center()
.child(div().font_medium().child(name.clone()))
.child(kind)
.child(if state == "windows-only" { Tag::secondary().child("Windows only") } else { state_tag(&state) })
// An outbound's state is "outbound" while AmneziaWG is on: its kind says so.
.when(state != "outbound", |d| d.child(if state == "windows-only" { Tag::secondary().child(tr("Windows only")) } else { state_tag(&state) }))
.child(div().flex_1());
if vpn {
let (n1, n2) = (name.clone(), name.clone());
let running = matches!(state.as_str(), "active" | "activating");
line = line
.child(Button::new(("awg-log", i)).small().ghost().label("Log").on_click(cx.listener(move |this, _, _, cx| this.toggle_log(n1.clone(), cx))))
.child(Button::new(("awg-log", i)).small().ghost().label(tr("Log")).on_click(cx.listener(move |this, _, _, cx| this.toggle_log(n1.clone(), cx))))
.child(
Switch::new(("awg-on", i))
.checked(running)
@@ -180,7 +183,7 @@ impl Render for AmneziaWgPage {
let mut row = div().v_flex().gap_2().py_2().border_t_1().border_color(cx.theme().border).child(line);
match self.logs.get(&name) {
Some(Ok(lines)) => {
let text = if lines.is_empty() { "(no log yet)".to_owned() } else { lines.join("\n") };
let text = if lines.is_empty() { tr("(no log yet)").to_owned() } else { lines.join("\n") };
row = row.child(div().text_xs().font_family("monospace").text_color(cx.theme().muted_foreground).child(text));
}
Some(Err(e)) => row = row.child(hint(e.clone(), cx)),
@@ -191,16 +194,44 @@ impl Render for AmneziaWgPage {
}
}
let kinds = RadioGroup::horizontal("awg-kind").children(KINDS.map(|(_, label)| label)).selected_index(Some(self.kind)).on_change(cx.listener(|this, ix: &usize, _, cx| {
let kinds = RadioGroup::horizontal("awg-kind").children(KINDS.map(|(_, label)| tr(label))).selected_index(Some(self.kind)).on_change(cx.listener(|this, ix: &usize, _, cx| {
this.kind = *ix;
cx.notify();
}));
let add = card("Add a profile", Some(Button::new("awg-add").small().primary().icon(IconName::Plus).label("Add").on_click(cx.listener(|this, _, window, cx| this.add(window, cx))).into_any_element()), cx)
.child(div().v_flex().gap_1().child(div().text_sm().child("Name (also the adapter's)")).child(Input::new(&self.name)))
let add = card(tr("Add a profile"), Some(Button::new("awg-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(div().v_flex().gap_1().child(div().text_sm().child(tr("Name (also the adapter's)"))).child(Input::new(&self.name)))
.child(kinds)
.child(Textarea::new(&self.text))
.child(hint("The link or .conf stays in the service's configuration, which only you and administrators read. Starting at sign-in (autostart), the endpoint and the rest are in Settings, under amneziaWg.profiles.", cx));
.child(hint(tr("The link or .conf stays in the service's configuration, which only you and administrators read. Starting at sign-in (autostart), the endpoint and the rest are in Settings, under amneziaWg.profiles."), cx));
body.child(about).child(profiles).child(add)
}
}
/// This page's words, in Russian (i18n).
pub const RU: &[(&str, &str)] = &[
("vpn://… from AmneziaVPN, or a .conf: [Interface] …", "vpn://… из AmneziaVPN или .conf: [Interface] …"),
("{}: tunnel up", "{}: туннель запущен"),
("{}: tunnel down", "{}: туннель остановлен"),
("AmneziaWG profile '{}' added", "Профиль AmneziaWG «{}» добавлен"),
("AmneziaWG profile '{}' removed", "Профиль AmneziaWG «{}» удалён"),
("Waiting for the service…", "Ожидание службы…"),
("AmneziaWG is on", "AmneziaWG включён"),
("AmneziaWG is off", "AmneziaWG выключен"),
("WireGuard with AmneziaVPN's obfuscation. A system-wide profile is a VPN of its own (a network adapter, its routes and DNS); with one peer that takes everything, it also blocks what would leave outside the tunnel. An outbound profile is one more exit for the proxy, with nothing else changed.", "WireGuard с обфускацией AmneziaVPN. Профиль для всей системы — это отдельный VPN (сетевой адаптер, его маршруты и DNS); если единственный узел (peer) забирает весь трафик, он также блокирует всё, что пошло бы мимо туннеля. Профиль-выход — ещё один выход для прокси, остальное не меняется."),
("Profiles", "Профили"),
("None yet: add one below.", "Пока нет: добавьте ниже."),
("system VPN", "VPN для всей системы"),
("outbound", "выход прокси"),
("outbound (WireGuard)", "выход прокси (WireGuard)"),
("Windows only", "Только Windows"),
("Log", "Журнал"),
("(no log yet)", "(журнала пока нет)"),
("System-wide VPN", "VPN для всей системы"),
("Outbound (AmneziaWG)", "Выход (AmneziaWG)"),
("Outbound (plain WireGuard)", "Выход (обычный WireGuard)"),
("Add a profile", "Добавить профиль"),
("Add", "Добавить"),
("Name (also the adapter's)", "Имя (также имя адаптера)"),
("The link or .conf stays in the service's configuration, which only you and administrators read. Starting at sign-in (autostart), the endpoint and the rest are in Settings, under amneziaWg.profiles.", "Ссылка или .conf остаётся в конфигурации службы, которую читаете только вы и администраторы. Запуск при входе в систему (автозапуск), конечная точка (endpoint) и остальное — в «Настройках», в разделе amneziaWg.profiles."),
];
+84 -38
View File
@@ -17,6 +17,7 @@ use ps_ipc::Request;
use serde_json::{Value, json};
use super::widgets::{card, hint, page, Inactive as _};
use crate::i18n::{tr, trf};
use crate::model::Model;
pub struct AutoProxyPage {
@@ -38,7 +39,7 @@ pub struct AutoProxyPage {
impl AutoProxyPage {
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let site = cx.new(|cx| InputState::new(window, cx).placeholder("example.com"));
let exclude = cx.new(|cx| TextareaState::new(window, cx).rows(4).placeholder("intranet.example — one per line"));
let exclude = cx.new(|cx| TextareaState::new(window, cx).rows(4).placeholder(tr("intranet.example — one per line")));
let slow = cx.new(|cx| InputState::new(window, cx).placeholder("150"));
let subscriptions = vec![cx.observe_in(&model, window, |this, _, window, cx| {
this.sync(window, cx);
@@ -99,7 +100,7 @@ impl AutoProxyPage {
fn site(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<String> {
let site = self.site.read(cx).value().trim().trim_start_matches("https://").trim_start_matches("http://").trim_end_matches('/').to_owned();
if site.is_empty() {
window.push_notification(Notification::error("Type a site first: example.com"), cx);
window.push_notification(Notification::error(tr("Type a site first: example.com")), cx);
return None;
}
Some(site)
@@ -126,11 +127,11 @@ impl AutoProxyPage {
fn learn(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(site) = self.site(window, cx) else { return };
let site = site.split('/').next().unwrap_or("").to_owned();
self.model.update(cx, |m, cx| m.request(format!("{site}: probed now, routed if it needs it"), Request::AutoLearn { hosts: vec![site] }, cx));
self.model.update(cx, |m, cx| m.request(trf("{}: probed now, routed if it needs it", &[&site]), Request::AutoLearn { hosts: vec![site] }, cx));
}
fn forget(&mut self, domain: Option<String>, cx: &mut Context<Self>) {
let what = domain.as_ref().map_or("Everything learned is forgotten".to_owned(), |d| format!("{d} is forgotten"));
let what = domain.as_ref().map_or(tr("Everything learned is forgotten").to_owned(), |d| trf("{} is forgotten", &[d]));
let job = self.model.read(cx).bridge().call(Request::AutoForget { domain });
let model = self.model.clone();
cx.spawn(async move |this, cx| {
@@ -145,7 +146,7 @@ impl AutoProxyPage {
let exclude: Vec<String> = self.exclude.read(cx).value().lines().map(|l| l.trim().to_owned()).filter(|l| !l.is_empty()).collect();
let slow_text = self.slow.read(cx).value().trim().to_owned();
let Ok(slow) = (if slow_text.is_empty() { Ok(0) } else { slow_text.parse::<u32>() }) else {
window.push_notification(Notification::error(format!("“{slow_text}” is not a speed in KiB/s (0 turns it off)")), cx);
window.push_notification(Notification::error(trf("“{}” is not a speed in KiB/s (0 turns it off)", &[&slow_text])), cx);
return;
};
self.shown = (self.exclude.read(cx).value().to_string(), self.slow.read(cx).value().to_string());
@@ -173,7 +174,7 @@ impl Render for AutoProxyPage {
let a = m.config()["proxy"]["autoProxy"].clone();
let body = page("autoProxy", cx);
if m.config().is_null() {
return body.child(hint("Waiting for the service…", cx));
return body.child(hint(tr("Waiting for the service…"), cx));
}
let list = self.list.clone();
let on = a["enable"] == true;
@@ -183,7 +184,7 @@ impl Render for AutoProxyPage {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
if on { "autoProxy is on" } else { "autoProxy is off" },
if on { tr("autoProxy is on") } else { tr("autoProxy is off") },
move |c| {
edits::set_path(c, &["proxy", "autoProxy", "enable"], on.into());
Ok(())
@@ -194,20 +195,20 @@ impl Render for AutoProxyPage {
});
let running = list.as_ref().is_ok_and(|l| l["running"] == true);
let state = match (on, running) {
(false, _) => Tag::secondary().child("off"),
(true, false) => Tag::warning().child("waiting for the local proxy"),
(true, true) => Tag::success().child("running"),
(false, _) => Tag::secondary().child(tr("off")),
(true, false) => Tag::warning().child(tr("waiting for the local proxy")),
(true, true) => Tag::success().child(tr("running")),
};
let about = card("autoProxy", Some(enable.into_any_element()), cx)
.child(div().h_flex().child(state))
.child(hint(
"It probes the sites your apps reach directly through each exit, direct first. A site blocked directly but reached through an exit is routed through it; one that crawls directly can move to an exit that carries it faster. Blocks zapret can fix stay direct.",
tr("It probes the sites your apps reach directly through each exit, direct first. A site blocked directly but reached through an exit is routed through it; one that crawls directly can move to an exit that carries it faster. Blocks zapret can fix stay direct."),
cx,
));
let probing = self.probing;
let mut try_card = card("Probe or learn a site", None, cx)
.child(hint("Probe: how it answers through each exit, nothing changed. Learn: probe it now and route it if it needs it.", cx))
let mut try_card = card(tr("Probe or learn a site"), None, cx)
.child(hint(tr("Probe: how it answers through each exit, nothing changed. Learn: probe it now and route it if it needs it."), cx))
.child(
div()
.h_flex()
@@ -217,29 +218,29 @@ impl Render for AutoProxyPage {
Button::new("ap-probe")
.small()
.icon(IconName::Gauge)
.label(if probing { "Probing…" } else { "Probe" })
.label(if probing { tr("Probing…") } else { tr("Probe") })
.inactive(probing || !running, cx)
.on_click(cx.listener(|this, _, window, cx| this.probe(window, cx))),
)
.child(Button::new("ap-learn").small().primary().icon(IconName::Plus).label("Learn").inactive(!running, cx).on_click(cx.listener(|this, _, window, cx| this.learn(window, cx)))),
.child(Button::new("ap-learn").small().primary().icon(IconName::Plus).label(tr("Learn")).inactive(!running, cx).on_click(cx.listener(|this, _, window, cx| this.learn(window, cx)))),
);
match &self.probe {
Some(Ok(p)) => {
let verdict = p["verdict"].as_str().unwrap_or("");
let text = match verdict {
"ok" => "Reachable directly: nothing to do".to_owned(),
"destination" => format!("Blocked directly: routed through {}", p["exit"].as_str().unwrap_or("an exit")),
"censor" => "Cut on the way: zapret's to fix, left direct".to_owned(),
"both-fail" => "Fails through every exit: not a block".to_owned(),
"unreachable" => "No exit reaches it at all".to_owned(),
"ok" => tr("Reachable directly: nothing to do").to_owned(),
"destination" => trf("Blocked directly: routed through {}", &[&p["exit"].as_str().unwrap_or(tr("an exit"))]),
"censor" => tr("Cut on the way: zapret's to fix, left direct").to_owned(),
"both-fail" => tr("Fails through every exit: not a block").to_owned(),
"unreachable" => tr("No exit reaches it at all").to_owned(),
v => v.to_owned(),
};
try_card = try_card.child(div().font_medium().child(text));
for r in p["rows"].as_array().into_iter().flatten() {
let f = &r["fetch"];
let what = match f["status"].as_u64() {
Some(s) => format!("{s}, {} bytes{}", f["bytes"], f["block"].as_str().filter(|b| !b.is_empty()).map(|b| format!(", {b} page")).unwrap_or_default()),
None => format!("no answer ({})", f["error"].as_str().unwrap_or("")),
Some(s) => trf("{}, {} bytes{}", &[&s, &f["bytes"], &f["block"].as_str().filter(|b| !b.is_empty()).map(|b| trf(", {} page", &[&b])).unwrap_or_default()]),
None => trf("no answer ({})", &[&f["error"].as_str().unwrap_or("")]),
};
let judgement = r["judgement"].as_str().unwrap_or("");
let tag = match judgement {
@@ -262,13 +263,13 @@ impl Render for AutoProxyPage {
}
let mut routed = card(
"Routed sites",
tr("Routed sites"),
Some(
div()
.h_flex()
.gap_2()
.child(Button::new("ap-reload").small().icon(IconName::RefreshCw).on_click(cx.listener(|this, _, _, cx| this.load(cx))))
.child(Button::new("ap-clear").small().ghost().icon(IconName::Trash).label("Forget all").on_click(cx.listener(|this, _, _, cx| this.forget(None, cx))))
.child(Button::new("ap-clear").small().ghost().icon(IconName::Trash).label(tr("Forget all")).on_click(cx.listener(|this, _, _, cx| this.forget(None, cx))))
.into_any_element(),
),
cx,
@@ -278,34 +279,32 @@ impl Render for AutoProxyPage {
Ok(l) => {
let domains = l["domains"].as_array().cloned().unwrap_or_default();
if domains.is_empty() {
routed = routed.child(hint("Nothing routed yet.", cx));
routed = routed.child(hint(tr("Nothing routed yet."), cx));
}
for (i, d) in domains.iter().enumerate() {
let domain = d["domain"].as_str().unwrap_or("").to_owned();
let why = if d["verdict"] == "slow" { Tag::warning().child("slow") } else { Tag::danger().child("blocked") };
let why = if d["verdict"] == "slow" { Tag::warning().child(tr("slow")) } else { Tag::danger().child(tr("blocked")) };
let forget = domain.clone();
routed = routed.child(
row(cx)
.child(div().flex_1().min_w_0().truncate().font_medium().child(domain))
.child(why)
.child(div().w(px(160.)).truncate().text_sm().child(format!("via {}", d["exit"].as_str().unwrap_or(""))))
.child(div().w(px(160.)).truncate().text_sm().child(trf("via {}", &[&d["exit"].as_str().unwrap_or("")])))
.child(Button::new(("ap-forget", i)).small().ghost().icon(IconName::Trash).on_click(cx.listener(move |this, _, _, cx| this.forget(Some(forget.clone()), cx)))),
);
}
let censored = l["censored"].as_array().map_or_else(|| l["censored"].as_u64().unwrap_or(0) as usize, Vec::len);
routed = routed.child(hint(
format!(
"{} site(s) judged; {censored} left to zapret; {} waiting to be probed; {} crawling, to be moved.",
l["hostsJudged"].as_u64().unwrap_or(0),
l["backlog"].as_u64().unwrap_or(0),
l["slowWaiting"].as_u64().unwrap_or(0)
trf(
"{} site(s) judged; {} left to zapret; {} waiting to be probed; {} crawling, to be moved.",
&[&l["hostsJudged"].as_u64().unwrap_or(0), &censored, &l["backlog"].as_u64().unwrap_or(0), &l["slowWaiting"].as_u64().unwrap_or(0)],
),
cx,
));
}
}
let mut exits = card("Exits", None, cx).child(hint("Probed one per network first. One that two sites refused is bad, and probed last.", cx));
let mut exits = card(tr("Exits"), None, cx).child(hint(tr("Probed one per network first. One that two sites refused is bad, and probed last."), cx));
if let Ok(l) = &list {
for e in l["exits"].as_array().into_iter().flatten() {
let bad = e["bad"] == true;
@@ -317,22 +316,69 @@ impl Render for AutoProxyPage {
e["ip"].as_str().unwrap_or(""),
e["asn"].as_str().unwrap_or("")
)))
.child(if bad { Tag::danger().child("bad") } else { Tag::success().child("ok") }),
.child(if bad { Tag::danger().child(tr("bad")) } else { Tag::success().child(tr("ok")) }),
);
}
}
let options = card("Options", Some(Button::new("ap-save").small().label("Save").on_click(cx.listener(|this, _, window, cx| this.save(window, cx))).into_any_element()), cx)
let options = card(tr("Options"), Some(Button::new("ap-save").small().label(tr("Save")).on_click(cx.listener(|this, _, window, cx| this.save(window, cx))).into_any_element()), cx)
.child(
div()
.h_flex()
.gap_4()
.items_start()
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child("Never probe or route (with their subdomains)")).child(Textarea::new(&self.exclude)))
.child(div().v_flex().gap_1().w(px(220.)).child(div().text_sm().child("Move sites slower than (KiB/s, 0: never)")).child(Input::new(&self.slow))),
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child(tr("Never probe or route (with their subdomains)"))).child(Textarea::new(&self.exclude)))
.child(div().v_flex().gap_1().w(px(220.)).child(div().text_sm().child(tr("Move sites slower than (KiB/s, 0: never)"))).child(Input::new(&self.slow))),
)
.child(hint("Everything else (interval, exits, ports) is in Settings, under proxy.autoProxy.", cx));
.child(hint(tr("Everything else (interval, exits, ports) is in Settings, under proxy.autoProxy."), cx));
body.child(about).child(try_card).child(routed).child(exits).child(options)
}
}
/// This page's words, in Russian (i18n).
pub const RU: &[(&str, &str)] = &[
("intranet.example — one per line", "intranet.example — по одному в строке"),
("Type a site first: example.com", "Сначала введите сайт: example.com"),
("{}: probed now, routed if it needs it", "{}: проверен сейчас, будет направлен, если нужно"),
("Everything learned is forgotten", "Всё изученное забыто"),
("{} is forgotten", "{}: забыт"),
("“{}” is not a speed in KiB/s (0 turns it off)", "«{}» — не скорость в КиБ/с (0 отключает)"),
("Waiting for the service…", "Ожидание службы…"),
("autoProxy is on", "autoProxy включён"),
("autoProxy is off", "autoProxy выключен"),
("off", "выкл."),
("waiting for the local proxy", "ждёт локальный прокси"),
("running", "работает"),
("It probes the sites your apps reach directly through each exit, direct first. A site blocked directly but reached through an exit is routed through it; one that crawls directly can move to an exit that carries it faster. Blocks zapret can fix stay direct.", "Проверяет сайты, к которым ваши приложения обращаются напрямую, через каждый выход, начиная с прямого. Сайт, заблокированный напрямую, но доступный через выход, направляется через него; сайт, который напрямую открывается медленно, можно перенести на выход, где он быстрее. Блокировки, которые под силу zapret, остаются напрямую."),
("Probe or learn a site", "Проверить или изучить сайт"),
("Probe: how it answers through each exit, nothing changed. Learn: probe it now and route it if it needs it.", "Проверить: как сайт отвечает через каждый выход, ничего не меняется. Изучить: проверить сейчас и направить через выход, если нужно."),
("Probing…", "Проверка…"),
("Probe", "Проверить"),
("Learn", "Изучить"),
("Reachable directly: nothing to do", "Доступен напрямую: делать ничего не нужно"),
("Blocked directly: routed through {}", "Заблокирован напрямую: направлен через {}"),
("an exit", "выход"),
("Cut on the way: zapret's to fix, left direct", "Обрывается по пути: это для zapret, оставлен напрямую"),
("Fails through every exit: not a block", "Не открывается ни через один выход: это не блокировка"),
("No exit reaches it at all", "Ни один выход до него не доходит"),
("{}, {} bytes{}", "{}, байт: {}{}"),
(", {} page", ", страница: {}"),
("no answer ({})", "нет ответа ({})"),
("Routed sites", "Направленные сайты"),
("Forget all", "Забыть все"),
("Nothing routed yet.", "Пока ничего не направлено."),
("slow", "медленный"),
("blocked", "заблокирован"),
("via {}", "через {}"),
("{} site(s) judged; {} left to zapret; {} waiting to be probed; {} crawling, to be moved.", "Оценено сайтов: {}; оставлено zapret: {}; ждут проверки: {}; медленных, будут перенесены: {}."),
("Exits", "Выходы"),
("Probed one per network first. One that two sites refused is bad, and probed last.", "Сначала проверяется по одному выходу из каждой сети. Выход, от которого отказались два сайта, считается плохим и проверяется последним."),
("bad", "плохой"),
("ok", "в порядке"),
("Options", "Параметры"),
("Save", "Сохранить"),
("Never probe or route (with their subdomains)", "Никогда не проверять и не направлять (вместе с поддоменами)"),
("Move sites slower than (KiB/s, 0: never)", "Переносить сайты медленнее (КиБ/с, 0: никогда)"),
("Everything else (interval, exits, ports) is in Settings, under proxy.autoProxy.", "Всё остальное (интервал, выходы, порты) — в настройках, в разделе proxy.autoProxy."),
];
+24 -9
View File
@@ -1,6 +1,7 @@
//! Components: the programs the service runs, the version each should be and the one
//! installed; fetching them again (an administrator's call, which the service enforces).
use crate::i18n::{tr, trf};
use gpui_kit::assets::IconName;
use gpui_kit::component::button::Button;
use gpui_kit::component::tag::Tag;
@@ -41,7 +42,7 @@ impl ComponentsPage {
fn install(&mut self, names: Vec<String>, cx: &mut Context<Self>) {
self.installing = true;
cx.notify();
let what = if names.is_empty() { "Components installed".to_owned() } else { format!("{} installed", names.join(", ")) };
let what = if names.is_empty() { tr("Components installed").to_owned() } else { trf("{} installed", &[&names.join(", ")]) };
let job = self.model.read(cx).bridge().call(Request::ComponentsInstall { names });
let model = self.model.clone();
cx.spawn(async move |this, cx| {
@@ -66,17 +67,17 @@ impl Render for ComponentsPage {
let actions = div()
.h_flex()
.gap_2()
.child(Button::new("comp-reload").small().icon(IconName::RefreshCw).label("Reload").on_click(cx.listener(|this, _, _, cx| this.load(cx))))
.child(Button::new("comp-reload").small().icon(IconName::RefreshCw).label(tr("Reload")).on_click(cx.listener(|this, _, _, cx| this.load(cx))))
.child(
Button::new("comp-install")
.small()
.icon(IconName::Download)
.label(if self.installing { "Installing…" } else { "Fetch all again" })
.label(if self.installing { tr("Installing…") } else { tr("Fetch all again") })
.inactive(self.installing, cx)
.on_click(cx.listener(|this, _, _, cx| this.install(Vec::new(), cx))),
);
let mut list = card("Programs", Some(actions.into_any_element()), cx).child(hint(
"Each is pinned by version and hash, and checked before it runs. Fetching them again needs an administrator: run the app as one, or proxy-ctl components install in an administrator's terminal.",
let mut list = card(tr("Programs"), Some(actions.into_any_element()), cx).child(hint(
tr("Each is pinned by version and hash, and checked before it runs. Fetching them again needs an administrator: run the app as one, or proxy-ctl components install in an administrator's terminal."),
cx,
));
match &self.list {
@@ -86,9 +87,9 @@ impl Render for ComponentsPage {
let want = c["version"].as_str().unwrap_or("");
let have = c["installed"].as_str();
let state = match have {
Some(v) if v == want => Tag::success().child("installed"),
Some(v) => Tag::warning().child(format!("{v} installed")),
None => Tag::danger().child("missing"),
Some(v) if v == want => Tag::success().child(tr("installed")),
Some(v) => Tag::warning().child(trf("{} installed", &[&v])),
None => Tag::danger().child(tr("missing")),
};
list = list.child(
div()
@@ -106,6 +107,20 @@ impl Render for ComponentsPage {
}
}
}
page("Components", cx).child(list)
page(tr("Components"), cx).child(list)
}
}
/// This page's words, in Russian (i18n).
pub const RU: &[(&str, &str)] = &[
("Components installed", "Компоненты установлены"),
("{} installed", "Установлено: {}"),
("Reload", "Перечитать"),
("Installing…", "Устанавливается…"),
("Fetch all again", "Загрузить все заново"),
("Programs", "Программы"),
("Each is pinned by version and hash, and checked before it runs. Fetching them again needs an administrator: run the app as one, or proxy-ctl components install in an administrator's terminal.", "Каждая программа закреплена по версии и хешу и проверяется перед запуском. Для повторной загрузки нужен администратор: запустите приложение от его имени или выполните proxy-ctl components install в терминале администратора."),
("installed", "установлена"),
("missing", "отсутствует"),
("Components", "Компоненты"),
];
+100 -43
View File
@@ -16,6 +16,7 @@ use ps_ipc::Request;
use serde_json::Value;
use super::widgets::{Inactive as _, card, hint, page, state_tag};
use crate::i18n::{tr, trf};
use crate::model::Model;
const ENGINES: [(&str, &str); 2] = [("zapret-discord-youtube", "Flowseal's presets (zapret)"), ("zapret2", "zapret2")];
@@ -50,8 +51,8 @@ pub struct DpiPage {
impl DpiPage {
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let preset = cx.new(|cx| SelectState::new(Vec::<SharedString>::new(), None, window, cx).searchable(true));
let domains = cx.new(|cx| TextareaState::new(window, cx).rows(6).placeholder("example.com — one per line"));
let exclude = cx.new(|cx| TextareaState::new(window, cx).rows(6).placeholder("bank.example — one per line"));
let domains = cx.new(|cx| TextareaState::new(window, cx).rows(6).placeholder(tr("example.com — one per line")));
let exclude = cx.new(|cx| TextareaState::new(window, cx).rows(6).placeholder(tr("bank.example — one per line")));
let subscriptions = vec![
cx.observe_in(&model, window, |this, _, window, cx| this.sync(window, cx)),
cx.subscribe_in(&preset, window, |this, _, event: &SelectEvent<Vec<SharedString>>, _, cx| {
@@ -59,7 +60,7 @@ impl DpiPage {
let name = name.to_string();
this.model.update(cx, |m, cx| {
m.edit(
format!("Preset: {name}"),
trf("Preset: {}", &[&name]),
move |c| {
edits::set_zapret_preset(c, &name);
Ok(())
@@ -91,7 +92,7 @@ impl DpiPage {
let alive = this.update(cx, |this, cx| {
match r {
Ok(v) => this.cutoff = v,
Err(e) if failed => model.update(cx, |_, cx| cx.emit(crate::model::Outcome::Failed(format!("The cutoff probe: {e:#}").into()))),
Err(e) if failed => model.update(cx, |_, cx| cx.emit(crate::model::Outcome::Failed(trf("The cutoff probe: {}", &[&format!("{e:#}")]).into()))),
Err(_) => {}
}
cx.notify();
@@ -112,18 +113,18 @@ impl DpiPage {
let probe = Button::new("cutoff-probe")
.small()
.icon(IconName::Gauge)
.label(if probing { "Probing…" } else { "Probe now" })
.label(if probing { tr("Probing…") } else { tr("Probe now") })
.inactive(probing || !on, cx)
.on_click(cx.listener(|this, _, _, cx| this.follow_cutoff(true, cx)));
let mut card = card("16 KB cutoff", Some(probe.into_any_element()), cx)
let mut card = card(tr("16 KB cutoff"), Some(probe.into_any_element()), cx)
.child(hint(
"Some lines cut TLS to certain hosting networks after about 16 KB, which no strategy fixes. A probe finds them daily (and when the line's network changes) and, with z2k's strategies, a name that gets through for each, which z2k puts into a fake hello. Each probe makes thousands of short direct connections.",
tr("Some lines cut TLS to certain hosting networks after about 16 KB, which no strategy fixes. A probe finds them daily (and when the line's network changes) and, with z2k's strategies, a name that gets through for each, which z2k puts into a fake hello. Each probe makes thousands of short direct connections."),
cx,
))
.child(self.option_switch("cutoff-on", "Probe this line", &["zapret", "zapret2", "cutoff", "enable"], config))
.child(self.option_switch("cutoff-on", tr("Probe this line"), &["zapret", "zapret2", "cutoff", "enable"], config))
.child(self.option_switch(
"cutoff-fallback",
"Send what no name fixes through the proxy (it sees addresses: the TUN, per-app routing)",
tr("Send what no name fixes through the proxy (it sees addresses: the TUN, per-app routing)"),
&["zapret", "zapret2", "cutoff", "proxyFallback"],
config,
));
@@ -131,22 +132,22 @@ impl DpiPage {
return card;
}
if c["installed"] != true {
return card.child(hint("z2k-detect, the probe, is not installed (the zapret2-extras component).", cx));
return card.child(hint(tr("z2k-detect, the probe, is not installed (the zapret2-extras component)."), cx));
}
if let Some(n) = c["note"].as_str().filter(|n| !n.is_empty() && (probing || !n.starts_with("probed"))) {
card = card.child(hint(n.to_owned(), cx));
}
let Some(ts) = c["probed"].as_u64() else {
return card.child(hint("Not probed yet: the first probe runs five minutes after the service starts.", cx));
return card.child(hint(tr("Not probed yet: the first probe runs five minutes after the service starts."), cx));
};
let nets = c["networks"].as_array().cloned().unwrap_or_default();
let named = nets.iter().filter(|n| n["name"].is_string()).count();
let summary = match nets.len() {
0 => format!("Probed {} from {}: no network is cut off on this line.", ps_client::utc(ts), c["egress"].as_str().unwrap_or("?")),
n => format!("Probed {} from {}: {n} network(s) cut off, {named} with a name that gets through.", ps_client::utc(ts), c["egress"].as_str().unwrap_or("?")),
0 => trf("Probed {} from {}: no network is cut off on this line.", &[&ps_client::utc(ts), &c["egress"].as_str().unwrap_or("?")]),
n => trf("Probed {} from {}: {} network(s) cut off, {} with a name that gets through.", &[&ps_client::utc(ts), &c["egress"].as_str().unwrap_or("?"), &n, &named]),
};
card = card.child(div().text_sm().child(summary));
let fallback = if c["proxyFallback"] == true { "through the proxy" } else { "no name" };
let fallback = if c["proxyFallback"] == true { tr("through the proxy") } else { tr("no name") };
const SHOWN: usize = 8;
for n in nets.iter().take(SHOWN) {
card = card.child(
@@ -159,7 +160,7 @@ impl DpiPage {
);
}
if nets.len() > SHOWN {
card = card.child(hint(format!("and {} more (proxy-ctl zapret cutoff).", nets.len() - SHOWN), cx));
card = card.child(hint(trf("and {} more (proxy-ctl zapret cutoff).", &[&(nets.len() - SHOWN)]), cx));
}
card
}
@@ -212,7 +213,7 @@ impl DpiPage {
self.shown.1 = domains_text;
self.shown.2 = exclude_text;
let engine = Self::engine(self.model.read(cx).config());
self.model.update(cx, |m, cx| m.edit("Sites saved", move |c| edits::set_zapret_sites(c, &engine, &domains, &exclude), cx));
self.model.update(cx, |m, cx| m.edit(tr("Sites saved"), move |c| edits::set_zapret_sites(c, &engine, &domains, &exclude), cx));
}
/// A switch for one option of the configuration, by its path.
@@ -226,7 +227,7 @@ impl DpiPage {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
format!("{label}: {}", if on { "on" } else { "off" }),
format!("{label}: {}", tr(if on { "on" } else { "off" })),
move |c| {
edits::set_path(c, path, on.into());
Ok(())
@@ -244,9 +245,9 @@ impl Render for DpiPage {
let status = m.status()["zapret"].clone();
let config = m.config().clone();
let engine = Self::engine(&config);
let body = page("DPI bypass", cx);
let body = page(tr("DPI bypass"), cx);
if config.is_null() {
return body.child(hint("Waiting for the service…", cx));
return body.child(hint(tr("Waiting for the service…"), cx));
}
let model = self.model.clone();
@@ -254,7 +255,7 @@ impl Render for DpiPage {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
if on { "The DPI bypass is on" } else { "The DPI bypass is off" },
tr(if on { "The DPI bypass is on" } else { "The DPI bypass is off" }),
move |c| {
edits::set_zapret_enabled(c, on);
Ok(())
@@ -265,11 +266,11 @@ impl Render for DpiPage {
});
let model = self.model.clone();
let engines = RadioGroup::horizontal("engine")
.children(ENGINES.map(|(_, label)| label))
.children(ENGINES.map(|(_, label)| tr(label)))
.selected_index(ENGINES.iter().position(|(e, _)| *e == engine))
.on_change(move |ix, _, cx| {
let (engine, label) = ENGINES[*ix];
model.update(cx, |m, cx| m.edit(format!("Engine: {label}"), move |c| edits::set_zapret_engine(c, engine), cx));
model.update(cx, |m, cx| m.edit(trf("Engine: {}", &[&tr(label)]), move |c| edits::set_zapret_engine(c, engine), cx));
});
let mut body = body.child(
card("zapret", Some(enable.into_any_element()), cx)
@@ -277,9 +278,9 @@ impl Render for DpiPage {
.child(engines)
.child(hint(
if engine == "zapret2" {
"zapret2 (winws2): it learns which sites are blocked as it goes, rotates each one's strategy until one works, and keeps it across restarts."
tr("zapret2 (winws2): it learns which sites are blocked as it goes, rotates each one's strategy until one works, and keeps it across restarts.")
} else {
"Flowseal's zapret-discord-youtube: winws with one of its presets, for YouTube, Discord and the sites in its lists."
tr("Flowseal's zapret-discord-youtube: winws with one of its presets, for YouTube, Discord and the sites in its lists.")
},
cx,
)),
@@ -289,13 +290,13 @@ impl Render for DpiPage {
let model = self.model.clone();
let source = config["zapret"]["zapret2"]["strategySource"].as_str().unwrap_or("nfqws2-keenetic");
let sources = RadioGroup::horizontal("strategy-source")
.children(SOURCES.map(|(_, label)| label))
.children(SOURCES.map(|(_, label)| tr(label)))
.selected_index(SOURCES.iter().position(|(v, _)| *v == source))
.on_change(move |ix, _, cx| {
let (value, label) = SOURCES[*ix];
model.update(cx, |m, cx| {
m.edit(
format!("Strategies: {label}"),
trf("Strategies: {}", &[&tr(label)]),
move |c| {
edits::set_path(c, &["zapret", "zapret2", "strategySource"], value.into());
Ok(())
@@ -306,17 +307,17 @@ impl Render for DpiPage {
});
body = body.child(
card("zapret2", None, cx)
.child(div().text_sm().child("Strategies"))
.child(div().text_sm().child(tr("Strategies")))
.child(sources)
.child(self.option_switch("autohostlist", "Learn which sites are blocked", &["zapret", "zapret2", "autoHostlist", "enable"], &config))
.child(self.option_switch("autohostlist", tr("Learn which sites are blocked"), &["zapret", "zapret2", "autoHostlist", "enable"], &config))
.child(self.option_switch(
"extended-detection",
"Extended detection: also sites blocked only some of the time, and requests that never get an answer",
tr("Extended detection: also sites blocked only some of the time, and requests that never get an answer"),
&["zapret", "zapret2", "autoHostlist", "extendedDetection"],
&config,
))
.child(self.option_switch("ipv6", "IPv6 too", &["zapret", "zapret2", "ipv6"], &config))
.child(self.option_switch("strategy-log", "Log the strategy each site gets", &["zapret", "zapret2", "strategyLog"], &config)),
.child(self.option_switch("ipv6", tr("IPv6 too"), &["zapret", "zapret2", "ipv6"], &config))
.child(self.option_switch("strategy-log", tr("Log the strategy each site gets"), &["zapret", "zapret2", "strategyLog"], &config)),
);
body = body.child(self.cutoff_card(&config, cx));
} else {
@@ -324,18 +325,18 @@ impl Render for DpiPage {
let filter = config["zapret"]["zapret-discord-youtube"]["gameFilter"].as_str().unwrap_or("null");
body = body
.child(
card("Preset", None, cx)
.child(hint("One of the release's strategies. If a site still does not open, try the next one.", cx))
.child(Select::new(&self.preset).placeholder("Choose a preset").menu_max_h(px(320.))),
card(tr("Preset"), None, cx)
.child(hint(tr("One of the release's strategies. If a site still does not open, try the next one."), cx))
.child(Select::new(&self.preset).placeholder(tr("Choose a preset")).menu_max_h(px(320.))),
)
.child(
card("Game traffic", None, cx).child(hint("Also handle game traffic, on ports above 1023.", cx)).child(
card(tr("Game traffic"), None, cx).child(hint(tr("Also handle game traffic, on ports above 1023."), cx)).child(
RadioGroup::horizontal("game-filter")
.children(GAME_FILTERS.map(|(_, label)| label))
.children(GAME_FILTERS.map(|(_, label)| tr(label)))
.selected_index(GAME_FILTERS.iter().position(|(v, _)| *v == filter))
.on_change(move |ix, _, cx| {
let (value, label) = GAME_FILTERS[*ix];
model.update(cx, |m, cx| m.edit(format!("Game traffic: {label}"), move |c| edits::set_game_filter(c, value), cx));
model.update(cx, |m, cx| m.edit(trf("Game traffic: {}", &[&tr(label)]), move |c| edits::set_game_filter(c, value), cx));
}),
),
);
@@ -343,20 +344,76 @@ impl Render for DpiPage {
body.child(
card(
"Your sites",
Some(Button::new("save-sites").small().label("Save").on_click(cx.listener(|this, _, _, cx| this.save_sites(cx))).into_any_element()),
tr("Your sites"),
Some(Button::new("save-sites").small().label(tr("Save")).on_click(cx.listener(|this, _, _, cx| this.save_sites(cx))).into_any_element()),
cx,
)
.child(hint("Sites to handle besides the engine's own lists, and sites to leave alone.", cx))
.child(hint(tr("Sites to handle besides the engine's own lists, and sites to leave alone."), cx))
.child(
div()
.h_flex()
.gap_4()
.items_start()
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child("Also handle")).child(Textarea::new(&self.domains)))
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child("Leave alone")).child(Textarea::new(&self.exclude))),
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child(tr("Also handle"))).child(Textarea::new(&self.domains)))
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child(tr("Leave alone"))).child(Textarea::new(&self.exclude))),
),
)
.child(card("Windows", None, cx).child(self.option_switch("tcp-timestamps", "TCP timestamps (some strategies need them)", &["zapret", "tcpTimestamps"], &config)))
.child(card("Windows", None, cx).child(self.option_switch("tcp-timestamps", tr("TCP timestamps (some strategies need them)"), &["zapret", "tcpTimestamps"], &config)))
}
}
/// This page's words, in Russian (i18n).
pub const RU: &[(&str, &str)] = &[
("Flowseal's presets (zapret)", "Пресеты Flowseal (zapret)"),
("z2k (per category: YouTube, Discord, QUIC, the RKN list)", "z2k (по категориям: YouTube, Discord, QUIC, список RKN)"),
("Off", "Выкл."),
("TCP and UDP", "TCP и UDP"),
("TCP only", "Только TCP"),
("UDP only", "Только UDP"),
("example.com — one per line", "example.com — по одному в строке"),
("bank.example — one per line", "bank.example — по одному в строке"),
("Preset: {}", "Пресет: {}"),
("The cutoff probe: {}", "Проверка обрыва на 16 КБ: {}"),
("Probing…", "Проверка…"),
("Probe now", "Проверить сейчас"),
("16 KB cutoff", "Обрыв на 16 КБ"),
("Some lines cut TLS to certain hosting networks after about 16 KB, which no strategy fixes. A probe finds them daily (and when the line's network changes) and, with z2k's strategies, a name that gets through for each, which z2k puts into a fake hello. Each probe makes thousands of short direct connections.",
"Некоторые линии обрывают TLS к определённым сетям хостинга примерно после 16 КБ, и никакая стратегия этого не исправляет. Проверка находит такие сети раз в сутки (и при смене сети линии) и, со стратегиями z2k, для каждой подбирает имя, которое проходит; z2k вставляет его в поддельный hello. Каждая проверка устанавливает тысячи коротких прямых соединений."),
("Probe this line", "Проверять эту линию"),
("Send what no name fixes through the proxy (it sees addresses: the TUN, per-app routing)", "Отправлять через прокси то, что не удаётся исправить подбором имени (он видит адреса: TUN, маршрутизация по приложениям)"),
("z2k-detect, the probe, is not installed (the zapret2-extras component).", "z2k-detect, средство проверки, не установлен (компонент zapret2-extras)."),
("Not probed yet: the first probe runs five minutes after the service starts.", "Ещё не проверялось: первая проверка выполняется через пять минут после запуска службы."),
("Probed {} from {}: no network is cut off on this line.", "Проверено {} с {}: на этой линии нет сетей с обрывом."),
("Probed {} from {}: {} network(s) cut off, {} with a name that gets through.", "Проверено {} с {}: сетей с обрывом — {}, из них с именем, которое проходит, — {}."),
("through the proxy", "через прокси"),
("no name", "нет имени"),
("and {} more (proxy-ctl zapret cutoff).", "и ещё {} (proxy-ctl zapret cutoff)."),
("Sites saved", "Сайты сохранены"),
("DPI bypass", "Обход DPI"),
("Waiting for the service…", "Ожидание службы…"),
("The DPI bypass is on", "Обход DPI включён"),
("The DPI bypass is off", "Обход DPI выключен"),
("Engine: {}", "Движок: {}"),
("zapret2 (winws2): it learns which sites are blocked as it goes, rotates each one's strategy until one works, and keeps it across restarts.",
"zapret2 (winws2): по ходу работы узнаёт, какие сайты заблокированы, перебирает для каждого стратегии, пока одна не сработает, и сохраняет её между перезапусками."),
("Flowseal's zapret-discord-youtube: winws with one of its presets, for YouTube, Discord and the sites in its lists.",
"zapret-discord-youtube от Flowseal: winws с одним из его пресетов — для YouTube, Discord и сайтов из его списков."),
("Strategies: {}", "Стратегии: {}"),
("Strategies", "Стратегии"),
("Learn which sites are blocked", "Узнавать, какие сайты заблокированы"),
("Extended detection: also sites blocked only some of the time, and requests that never get an answer", "Расширенное обнаружение: также сайты, заблокированные лишь время от времени, и запросы, на которые так и не приходит ответ"),
("IPv6 too", "Также IPv6"),
("Log the strategy each site gets", "Записывать в журнал стратегию каждого сайта"),
("Preset", "Пресет"),
("One of the release's strategies. If a site still does not open, try the next one.", "Одна из стратегий выпуска. Если сайт всё равно не открывается, попробуйте следующую."),
("Choose a preset", "Выберите пресет"),
("Game traffic", "Игровой трафик"),
("Also handle game traffic, on ports above 1023.", "Обрабатывать также игровой трафик на портах выше 1023."),
("Game traffic: {}", "Игровой трафик: {}"),
("Your sites", "Ваши сайты"),
("Save", "Сохранить"),
("Sites to handle besides the engine's own lists, and sites to leave alone.", "Сайты, которые нужно обрабатывать помимо списков самого движка, и сайты, которые нужно не трогать."),
("Also handle", "Обрабатывать также"),
("Leave alone", "Не трогать"),
("TCP timestamps (some strategies need them)", "Метки времени TCP (нужны некоторым стратегиям)"),
];
+16 -6
View File
@@ -1,5 +1,6 @@
//! Logs: every unit's, as they come, the last few thousand lines kept; one unit's on its own.
use crate::i18n::{tr, trf};
use std::collections::VecDeque;
use gpui_kit::component::button::Button;
@@ -102,7 +103,7 @@ impl LogsPage {
impl Render for LogsPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let shown = self.shown();
let mut choices: Vec<SharedString> = vec!["All".into()];
let mut choices: Vec<SharedString> = vec![tr("All").into()];
choices.extend(self.units.iter().map(|u| SharedString::from(short(u).to_owned())));
let selected = match &self.only {
None => 0,
@@ -113,11 +114,11 @@ impl Render for LogsPage {
this.only = if *ix == 0 { None } else { this.units.get(*ix - 1).cloned() };
cx.notify();
}));
let follow = Switch::new("log-follow").label("Follow").checked(self.follow).on_change(cx.listener(|this, on: &bool, _, cx| {
let follow = Switch::new("log-follow").label(tr("Follow")).checked(self.follow).on_change(cx.listener(|this, on: &bool, _, cx| {
this.follow = *on;
cx.notify();
}));
let clear = Button::new("log-clear").small().label("Clear").on_click(cx.listener(|this, _, _, cx| {
let clear = Button::new("log-clear").small().label(tr("Clear")).on_click(cx.listener(|this, _, _, cx| {
this.lines.clear();
cx.notify();
}));
@@ -143,10 +144,19 @@ impl Render for LogsPage {
.track_scroll(&self.scroll)
.h(px(460.));
let mut body = card("Logs", Some(div().h_flex().gap_3().items_center().child(follow).child(clear).into_any_element()), cx).child(filter);
let mut body = card(tr("Logs"), Some(div().h_flex().gap_3().items_center().child(follow).child(clear).into_any_element()), cx).child(filter);
if let Some(why) = &self.lost {
body = body.child(hint(format!("Not receiving logs: {why}"), cx));
body = body.child(hint(trf("Not receiving logs: {}", &[&why]), cx));
}
page("Logs", cx).child(body.child(div().p_2().rounded_md().bg(cx.theme().muted).child(lines)))
page(tr("Logs"), cx).child(body.child(div().p_2().rounded_md().bg(cx.theme().muted).child(lines)))
}
}
/// This page's words, in Russian (i18n).
pub const RU: &[(&str, &str)] = &[
("All", "Все"),
("Follow", "Следить"),
("Clear", "Очистить"),
("Logs", "Журналы"),
("Not receiving logs: {}", "Журналы не поступают: {}"),
];
+45 -17
View File
@@ -1,18 +1,19 @@
//! The window: a sidebar of pages, the page shown, and what came of each change as a
//! notification.
mod amneziawg;
mod autoproxy;
mod components;
mod dpi;
mod logs;
mod outbounds;
mod overview;
mod settings;
mod telegram;
mod whitelist;
mod widgets;
pub(crate) mod amneziawg;
pub(crate) mod autoproxy;
pub(crate) mod components;
pub(crate) mod dpi;
pub(crate) mod logs;
pub(crate) mod outbounds;
pub(crate) mod overview;
pub(crate) mod settings;
pub(crate) mod telegram;
pub(crate) mod whitelist;
pub(crate) mod widgets;
use crate::i18n::tr;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::notification::Notification;
use gpui_kit::component::sidebar::{Sidebar, SidebarFooter, SidebarGroup, SidebarHeader, SidebarMenu, SidebarMenuItem};
@@ -129,19 +130,28 @@ impl AppView {
Self { model, page: Page::Overview, dpi, telegram, outbounds, whitelist: None, autoproxy: None, amneziawg: None, logs: None, settings: None, components: None, _subscriptions: subscriptions }
}
pub fn page(&self) -> Page {
self.page
}
pub fn show(&mut self, page: Page, cx: &mut Context<Self>) {
self.page = page;
cx.notify();
}
fn sidebar(&self, cx: &mut Context<Self>) -> impl IntoElement {
let items = Page::ALL.map(|page| {
SidebarMenuItem::new(page.title()).icon(page.icon()).active(self.page == page).on_click(cx.listener(move |this, _, _, cx| {
SidebarMenuItem::new(tr(page.title())).icon(page.icon()).active(self.page == page).on_click(cx.listener(move |this, _, _, cx| {
this.page = page;
cx.notify();
}))
});
let m = self.model.read(cx);
let (colour, state) = match m.connection() {
Connection::Up if m.busy() => (cx.theme().warning, "Applying…"),
Connection::Up => (cx.theme().success, "Connected to the service"),
Connection::Connecting => (cx.theme().muted_foreground, "Connecting…"),
Connection::Down(_) => (cx.theme().danger, "The service is not running"),
Connection::Up if m.busy() => (cx.theme().warning, tr("Applying…")),
Connection::Up => (cx.theme().success, tr("Connected to the service")),
Connection::Connecting => (cx.theme().muted_foreground, tr("Connecting…")),
Connection::Down(_) => (cx.theme().danger, tr("The service is not running")),
};
let footer = SidebarFooter::new().child(div().h_flex().gap_2().items_center().text_xs().text_color(cx.theme().muted_foreground).child(div().size_2().rounded_full().bg(colour)).child(state));
// Light or dark at a click; Settings → This app has "as Windows" too.
@@ -150,7 +160,7 @@ impl AppView {
.ghost()
.xsmall()
.icon(if dark { IconName::Sun } else { IconName::Moon })
.tooltip(if dark { "Light theme" } else { "Dark theme" })
.tooltip(if dark { tr("Light theme") } else { tr("Dark theme") })
.on_click(move |_, _, cx| {
let choice = if dark { crate::prefs::ThemeChoice::Light } else { crate::prefs::ThemeChoice::Dark };
crate::prefs::change(cx, |p| p.theme = choice);
@@ -201,3 +211,21 @@ impl Render for AppView {
.child(div().id("page").flex_1().min_w_0().h_full().overflow_y_scroll().child(page))
}
}
/// The window's words (the pages' names), in Russian (i18n).
pub const RU: &[(&str, &str)] = &[
("Overview", "Обзор"),
("DPI bypass", "Обход DPI"),
("Telegram proxy", "Прокси для Telegram"),
("Whitelist bypass", "Обход белых списков"),
("Outbounds", "Выходы"),
("Logs", "Журналы"),
("Settings", "Настройки"),
("Components", "Компоненты"),
("Applying…", "Применяется…"),
("Connected to the service", "Служба на связи"),
("Connecting…", "Подключение…"),
("The service is not running", "Служба не запущена"),
("Light theme", "Светлая тема"),
("Dark theme", "Тёмная тема"),
];
+78 -32
View File
@@ -17,6 +17,7 @@ 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] = [
@@ -40,8 +41,8 @@ pub struct OutboundsPage {
impl OutboundsPage {
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> 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 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 }
@@ -55,7 +56,7 @@ impl OutboundsPage {
let source = match OutboundSource::parse(&text) {
Ok(s) => s,
Err(e) => {
window.push_notification(Notification::error(format!("Not an outbound: {e:#}")).autohide(false), cx);
window.push_notification(Notification::error(trf("Not an outbound: {}", &[&format!("{e:#}")])).autohide(false), cx);
return;
}
};
@@ -63,7 +64,7 @@ impl OutboundsPage {
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}");
let what = trf("Added {}", &[&tag]);
self.model.update(cx, |m, cx| m.edit(what, move |c| edits::add_outbound(c, &tag, &source, None), cx));
}
@@ -74,7 +75,7 @@ impl OutboundsPage {
}
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));
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<String>, cx: &mut Context<Self>) {
@@ -89,7 +90,7 @@ impl OutboundsPage {
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());
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);
}
}
@@ -115,11 +116,11 @@ impl OutboundsPage {
notes.push(r.to_owned());
}
if let Some(h) = inv["detours"][tag].as_str() {
notes.push(format!("through {h}"));
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(format!("failed: {e}")).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(),
};
@@ -137,25 +138,25 @@ impl OutboundsPage {
.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().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("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| {
.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 { "Back to automatic selection".to_owned() } else { format!("Pinned to {t_pin}") };
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 { "Use it again" } else { "Leave it out" }).on_click(move |_, _, cx| {
let what = format!("{t_dis} {}", if disabled { "is back" } else { "is left out" });
.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("Remove it").on_click(move |_, _, cx| {
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(format!("Removed {tag}"), move |c| edits::remove_outbound(c, &tag), cx));
model_rm.update(cx, |m, cx| m.edit(trf("Removed {}", &[&tag]), move |c| edits::remove_outbound(c, &tag), cx));
}))
})
}
@@ -169,44 +170,44 @@ impl Render for OutboundsPage {
let subs: Vec<String> = m.config()["proxy"]["subscriptions"].as_array().into_iter().flatten().filter_map(|s| s["tag"].as_str().map(str::to_owned)).collect();
let tags: Vec<String> = 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))
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(
format!("Outbounds ({})", tags.len()),
Some(Button::new("test-all").small().icon(IconName::Gauge).label(if self.testing { "Testing…" } else { "Test all" }).inactive(self.testing || tags.is_empty(), cx).on_click(cx.listener(|this, _, _, cx| this.test(Vec::new(), cx))).into_any_element()),
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(format!("Testing failed: {e}")));
list = list.child(div().text_sm().text_color(cx.theme().danger).child(trf("Testing failed: {}", &[&e])));
}
if tags.is_empty() {
list = list.child(hint("None yet: add a link above, or a subscription below.", cx));
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("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 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(format!("Mode: {label}"), req, cx));
model.update(cx, |m, cx| m.request(trf("Mode: {}", &[&tr(label)]), req, cx));
}),
);
let model = self.model.clone();
let mut subscriptions = card(
"Subscriptions",
tr("Subscriptions"),
Some(
Button::new("subs-update")
.small()
.icon(IconName::RefreshCw)
.label("Update all")
.label(tr("Update all"))
.inactive(subs.is_empty(), cx)
.on_click(move |_, _, cx| model.update(cx, |m, cx| m.request("Subscriptions updated", Request::SubsUpdate { tag: None }, cx)))
.on_click(move |_, _, cx| model.update(cx, |m, cx| m.request(tr("Subscriptions updated"), Request::SubsUpdate { tag: None }, cx)))
.into_any_element(),
),
cx,
@@ -216,7 +217,7 @@ impl Render for OutboundsPage {
.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)))),
.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();
@@ -229,13 +230,58 @@ impl Render for OutboundsPage {
.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| {
.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(format!("Removed subscription {tag}"), move |c| edits::remove_subscription(c, &tag), cx));
model.update(cx, |m, cx| m.edit(trf("Removed subscription {}", &[&tag]), move |c| edits::remove_subscription(c, &tag), cx));
})),
);
}
page("Outbounds", cx).child(add).child(list).child(modes).child(subscriptions)
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", "Выходы"),
];
+67 -33
View File
@@ -1,6 +1,7 @@
//! The overview: the local proxy, the DPI bypass and the Telegram proxy, each with its state
//! and a switch; what the service warns of; Proxy Suite's version, and a newer one to install.
use crate::i18n::{tr, trf};
use gpui_kit::assets::IconName;
use gpui_kit::component::alert::Alert;
use gpui_kit::component::button::{Button, ButtonVariants as _};
@@ -27,23 +28,23 @@ pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>)
let m = model.read(cx);
let s = m.status().clone();
let connection = m.connection().clone();
let mut body = page("Overview", cx);
let mut body = page(tr("Overview"), cx);
match &connection {
Connection::Down(why) => {
body = body.child(Alert::error("service-down", why.clone()).title("Not connected")).child(hint(
"The service runs everything; this app only controls it. Install it with install.cmd from the release, or start it as an administrator: sc start ProxySuite.",
body = body.child(Alert::error("service-down", why.clone()).title(tr("Not connected"))).child(hint(
tr("The service runs everything; this app only controls it. Install it with install.cmd from the release, or start it as an administrator: sc start ProxySuite."),
cx,
));
}
Connection::Connecting => body = body.child(Alert::info("connecting", "Connecting to the Proxy Suite service…")),
Connection::Connecting => body = body.child(Alert::info("connecting", tr("Connecting to the Proxy Suite service…"))),
Connection::Up => {}
}
if connection != Connection::Up {
return body;
}
if let Some(e) = s["error"].as_str() {
body = body.child(Alert::error("service-error", e.to_owned()).title("The configuration did not apply"));
body = body.child(Alert::error("service-error", e.to_owned()).title(tr("The configuration did not apply")));
}
for (i, w) in s["warnings"].as_array().into_iter().flatten().enumerate() {
body = body.child(Alert::warning(("warning", i), text(w)));
@@ -53,7 +54,7 @@ pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>)
let proxy_on = p["on"] == true;
let model_p = model.clone();
let proxy = card(
"Local proxy",
tr("Local proxy"),
Some(
Switch::new("proxy-on")
.checked(proxy_on)
@@ -62,19 +63,19 @@ pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>)
),
cx,
)
.child(div().h_flex().gap_2().child(state_tag(p["state"].as_str().unwrap_or("unknown"))).when(p["tun"] == true, |d| d.child(tag::Tag::info().child("global TUN"))))
.child(fact("Listening on", text(&p["listener"]), cx))
.child(fact("Backend", text(&p["backend"]), cx))
.child(fact("Mode", p["mode"].as_str().unwrap_or("default").to_owned(), cx))
.child(fact("Outbound", p["pinned"].as_str().map(|t| format!("{t} (pinned)")).unwrap_or_else(|| format!("{} selection", p["selection"].as_str().unwrap_or("?"))), cx))
.child(div().h_flex().gap_2().child(state_tag(p["state"].as_str().unwrap_or("unknown"))).when(p["tun"] == true, |d| d.child(tag::Tag::info().child(tr("global TUN")))))
.child(fact(tr("Listening on"), text(&p["listener"]), cx))
.child(fact(tr("Backend"), text(&p["backend"]), cx))
.child(fact(tr("Mode"), p["mode"].as_str().unwrap_or("default").to_owned(), cx))
.child(fact(tr("Outbound"), p["pinned"].as_str().map(|t| trf("{} (pinned)", &[&t])).unwrap_or_else(|| trf("{} selection", &[&p["selection"].as_str().unwrap_or("?")])), cx))
.child({
let model = model.clone();
let on = m.config()["proxy"]["systemProxy"]["enable"] == true;
Switch::new("system-proxy").label("Use it as the system proxy (browsers and most programs follow it)").checked(on).on_change(move |on, _, cx| {
Switch::new("system-proxy").label(tr("Use it as the system proxy (browsers and most programs follow it)")).checked(on).on_change(move |on, _, cx| {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
if on { "The system proxy follows the local proxy" } else { "The system proxy is left alone" },
if on { tr("The system proxy follows the local proxy") } else { tr("The system proxy is left alone") },
move |c| {
edits::set_path(c, &["proxy", "systemProxy", "enable"], on.into());
Ok(())
@@ -88,7 +89,7 @@ pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>)
let z = &s["zapret"];
let model_z = model.clone();
let dpi = card(
"DPI bypass",
tr("DPI bypass"),
Some(
Switch::new("zapret-on")
.checked(z["enabled"] == true)
@@ -96,7 +97,7 @@ pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>)
let on = *on;
model_z.update(cx, |m, cx| {
m.edit(
if on { "The DPI bypass is on" } else { "The DPI bypass is off" },
if on { tr("The DPI bypass is on") } else { tr("The DPI bypass is off") },
move |c| {
edits::set_zapret_enabled(c, on);
Ok(())
@@ -110,13 +111,13 @@ pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>)
cx,
)
.child(div().h_flex().child(state_tag(z["state"].as_str().unwrap_or("unknown"))))
.child(fact("Engine", text(&z["engine"]), cx))
.when(z["engine"] == "zapret-discord-youtube", |d| d.child(fact("Preset", text(&z["preset"]), cx)));
.child(fact(tr("Engine"), text(&z["engine"]), cx))
.when(z["engine"] == "zapret-discord-youtube", |d| d.child(fact(tr("Preset"), text(&z["preset"]), cx)));
let t = &s["tgWsProxy"];
let model_t = model.clone();
let telegram = card(
"Telegram proxy",
tr("Telegram proxy"),
Some(
Switch::new("tg-on")
.checked(t["enabled"] == true)
@@ -124,7 +125,7 @@ pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>)
let on = *on;
model_t.update(cx, |m, cx| {
m.edit(
if on { "The Telegram proxy is on" } else { "The Telegram proxy is off" },
if on { tr("The Telegram proxy is on") } else { tr("The Telegram proxy is off") },
move |c| {
edits::set_tg_ws_proxy_enabled(c, on);
Ok(())
@@ -138,7 +139,7 @@ pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>)
cx,
)
.child(div().h_flex().child(state_tag(t["state"].as_str().unwrap_or("unknown"))))
.child(fact("Listening on", text(&t["listener"]), cx));
.child(fact(tr("Listening on"), text(&t["listener"]), cx));
body.child(proxy).child(div().h_flex().gap_4().items_start().child(dpi.flex_1()).child(telegram.flex_1())).child(updates(model, cx))
}
@@ -154,18 +155,18 @@ fn updates(model: &Entity<Model>, cx: &mut Context<AppView>) -> Div {
.small()
.ghost()
.icon(IconName::RefreshCw)
.label("Check for updates")
.label(tr("Check for updates"))
.inactive(busy, cx)
.on_click(move |_, _, cx| model.update(cx, |m, cx| m.check_update(cx)))
};
let card = card(format!("Proxy Suite {}", m.version()), Some(check.into_any_element()), cx);
let explain = "The service fetches its setup program from the project's releases, checks its SHA-256 and runs it: the service and this app close for a moment and start again, new. Settings stay.";
let card = card(trf("Proxy Suite {}", &[&m.version()]), Some(check.into_any_element()), cx);
let explain = tr("The service fetches its setup program from the project's releases, checks its SHA-256 and runs it: the service and this app close for a moment and start again, new. Settings stay.");
match update {
Update::Unknown if !cx.global::<crate::prefs::Prefs>().check_updates => card.child(hint("Updates are not looked for by themselves (Settings → This app).", cx)),
Update::Unknown => card.child(hint("Updates are looked for when the app starts, and daily.", cx)),
Update::Checking => card.child(hint("Looking for a newer release…", cx)),
Update::Newest => card.child(hint("This is the newest release.", cx)),
Update::Failed(e) => card.child(div().text_sm().text_color(cx.theme().danger).child(format!("Could not look for updates: {e}"))),
Update::Unknown if !cx.global::<crate::prefs::Prefs>().check_updates => card.child(hint(tr("Updates are not looked for by themselves (Settings → This app)."), cx)),
Update::Unknown => card.child(hint(tr("Updates are looked for when the app starts, and daily."), cx)),
Update::Checking => card.child(hint(tr("Looking for a newer release…"), cx)),
Update::Newest => card.child(hint(tr("This is the newest release."), cx)),
Update::Failed(e) => card.child(div().text_sm().text_color(cx.theme().danger).child(trf("Could not look for updates: {}", &[&e]))),
Update::Available { version, page } => {
let install = {
let model = model.clone();
@@ -173,15 +174,48 @@ fn updates(model: &Entity<Model>, cx: &mut Context<AppView>) -> Div {
.small()
.primary()
.icon(IconName::Download)
.label(format!("Install {version}"))
.label(trf("Install {}", &[&version]))
.on_click(move |_, _, cx| model.update(cx, |m, cx| m.install_update(cx)))
};
let notes = Button::new("update-notes").small().ghost().icon(IconName::ExternalLink).label("What's new").on_click(move |_, _, cx| cx.open_url(&page));
card.child(div().h_flex().gap_3().items_center().child(div().text_sm().font_semibold().child(format!("{version} is out."))).child(install).child(notes)).child(hint(explain, cx))
let notes = Button::new("update-notes").small().ghost().icon(IconName::ExternalLink).label(tr("What's new")).on_click(move |_, _, cx| cx.open_url(&page));
card.child(div().h_flex().gap_3().items_center().child(div().text_sm().font_semibold().child(trf("{} is out.", &[&version]))).child(install).child(notes)).child(hint(explain, cx))
}
Update::Installing { version, started: false, .. } => card.child(Alert::info("update-fetching", format!("Fetching {version} and checking it…"))),
Update::Installing { version, started: false, .. } => card.child(Alert::info("update-fetching", trf("Fetching {} and checking it…", &[&version]))),
Update::Installing { version, started: true, .. } => {
card.child(Alert::info("update-running", format!("Installing {version}: this app closes, and opens again in a moment.")))
card.child(Alert::info("update-running", trf("Installing {}: this app closes, and opens again in a moment.", &[&version])))
}
}
}
/// This page's words, in Russian (i18n).
pub const RU: &[(&str, &str)] = &[
("Not connected", "Нет связи со службой"),
("The service runs everything; this app only controls it. Install it with install.cmd from the release, or start it as an administrator: sc start ProxySuite.", "Всё работает в службе, а это приложение лишь управляет ею. Установите её с помощью install.cmd из выпуска или запустите от имени администратора: sc start ProxySuite."),
("Connecting to the Proxy Suite service…", "Подключение к службе Proxy Suite…"),
("The configuration did not apply", "Конфигурация не применилась"),
("global TUN", "глобальный TUN"),
("Listening on", "Слушает на"),
("Backend", "Бэкенд"),
("Mode", "Режим"),
("Outbound", "Выход"),
("{} (pinned)", "{} (закреплён)"),
("{} selection", "выбор: {}"),
("Use it as the system proxy (browsers and most programs follow it)", "Использовать как системный прокси (ему следуют браузеры и большинство программ)"),
("The system proxy follows the local proxy", "Системный прокси следует за локальным прокси"),
("The system proxy is left alone", "Системный прокси не затрагивается"),
("Engine", "Движок"),
("Preset", "Пресет"),
("Check for updates", "Проверить обновления"),
("Proxy Suite {}", "Proxy Suite {}"),
("The service fetches its setup program from the project's releases, checks its SHA-256 and runs it: the service and this app close for a moment and start again, new. Settings stay.", "Служба загружает установщик из выпусков проекта, проверяет его SHA-256 и запускает: служба и это приложение на мгновение закроются и запустятся снова, уже новые. Настройки сохранятся."),
("Updates are not looked for by themselves (Settings → This app).", "Обновления сами не ищутся (Настройки → Это приложение)."),
("Updates are looked for when the app starts, and daily.", "Обновления ищутся при запуске приложения и раз в сутки."),
("Looking for a newer release…", "Поиск более нового выпуска…"),
("This is the newest release.", "Это самый новый выпуск."),
("Could not look for updates: {}", "Не удалось проверить обновления: {}"),
("Install {}", "Установить {}"),
("What's new", "Что нового"),
("{} is out.", "Вышла версия {}."),
("Fetching {} and checking it…", "Загрузка {} и проверка…"),
("Installing {}: this app closes, and opens again in a moment.", "Установка {}: приложение закроется и через мгновение откроется снова."),
];
+58 -21
View File
@@ -15,8 +15,9 @@ 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;
use crate::prefs::{self, Prefs, ThemeChoice};
use crate::prefs::{self, Language, Prefs, ThemeChoice};
/// What the service shows in place of a secret the caller may not read; saved back as it is,
/// the secret keeps its value.
@@ -54,7 +55,7 @@ impl SettingsPage {
}
fn reload(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.verdict = Verdict::Working("Loading…");
self.verdict = Verdict::Working(tr("Loading…"));
cx.notify();
let job = self.model.read(cx).bridge().call(Request::ConfigGet);
cx.spawn_in(window, async move |this, cx| {
@@ -78,7 +79,7 @@ impl SettingsPage {
/// The editor's text as JSON, or where it is not.
fn parsed(&self, cx: &App) -> Result<Value, String> {
serde_json::from_str(&self.editor.read(cx).value()).map_err(|e| format!("Not valid JSON: {e}"))
serde_json::from_str(&self.editor.read(cx).value()).map_err(|e| trf("Not valid JSON: {}", &[&e]))
}
fn validate(&mut self, cx: &mut Context<Self>) {
@@ -89,7 +90,7 @@ impl SettingsPage {
return cx.notify();
}
};
self.verdict = Verdict::Working("Checking…");
self.verdict = Verdict::Working(tr("Checking…"));
cx.notify();
let job = self.model.read(cx).bridge().call(Request::ConfigValidate { config });
cx.spawn(async move |this, cx| {
@@ -115,7 +116,7 @@ impl SettingsPage {
}
};
let base = self.loaded.as_ref().map(|(_, r)| *r);
self.verdict = Verdict::Working("Saving…");
self.verdict = Verdict::Working(tr("Saving…"));
cx.notify();
let job = self.model.read(cx).bridge().call(Request::ConfigSet { config, base });
let model = self.model.clone();
@@ -130,7 +131,7 @@ impl SettingsPage {
Verdict::Saved { revision, issues: ps_client::issues(&r), apply_error: r["error"].as_str().map(str::to_owned) }
}
Err(e) if e.to_string().contains("changed since revision") => {
Verdict::Failed("The configuration was changed elsewhere since it was loaded. Reload to see it (your edits here are then lost; copy them first).".into())
Verdict::Failed(tr("The configuration was changed elsewhere since it was loaded. Reload to see it (your edits here are then lost; copy them first).").into())
}
Err(e) => Verdict::Failed(format!("{e:#}")),
};
@@ -159,23 +160,32 @@ fn issue_list(issues: &[Issue], cx: &App) -> Div {
fn this_app(cx: &App) -> Div {
let p = cx.global::<Prefs>().clone();
let theme = RadioGroup::horizontal("app-theme")
.children(ThemeChoice::ALL.map(|(_, label)| label))
.children(ThemeChoice::ALL.map(|(_, label)| tr(label)))
.selected_index(ThemeChoice::ALL.iter().position(|(t, _)| *t == p.theme))
.on_change(|ix, _, cx| {
let choice = ThemeChoice::ALL[*ix].0;
prefs::change(cx, |p| p.theme = choice);
});
let language = RadioGroup::horizontal("app-language")
.children(Language::ALL.map(|(_, label)| tr(label)))
.selected_index(Language::ALL.iter().position(|(l, _)| *l == p.language))
.on_change(|ix, _, cx| {
let language = Language::ALL[*ix].0;
prefs::change(cx, |p| p.language = language);
});
let updates = Switch::new("app-check-updates")
.label("Look for a newer release when the app starts, and daily")
.label(tr("Look for a newer release when the app starts, and daily"))
.checked(p.check_updates)
.on_change(|on, _, cx| {
let on = *on;
prefs::change(cx, |p| p.check_updates = on);
});
card("This app", None, cx)
.child(div().h_flex().gap_4().items_center().child(div().text_sm().w(px(110.)).text_color(cx.theme().muted_foreground).child("Theme")).child(theme))
let row = |label: &'static str, control: AnyElement| div().h_flex().gap_4().items_center().child(div().text_sm().w(px(110.)).text_color(cx.theme().muted_foreground).child(label)).child(control);
card(tr("This app"), None, cx)
.child(row(tr("Language"), language.into_any_element()))
.child(row(tr("Theme"), theme.into_any_element()))
.child(updates)
.child(hint("Yours alone, kept with your Windows account; the service's configuration is below.", cx))
.child(hint(tr("Yours alone, kept with your Windows account; the service's configuration is below."), cx))
}
impl Render for SettingsPage {
@@ -187,30 +197,57 @@ impl Render for SettingsPage {
let actions = div()
.h_flex()
.gap_2()
.child(Button::new("cfg-reload").small().ghost().icon(IconName::RefreshCw).label("Reload").on_click(cx.listener(|this, _, window, cx| this.reload(window, cx))))
.child(Button::new("cfg-validate").small().label("Check").on_click(cx.listener(|this, _, _, cx| this.validate(cx))))
.child(Button::new("cfg-save").small().primary().icon(IconName::Save).label("Save").inactive(!changed, cx).on_click(cx.listener(|this, _, _, cx| this.save(cx))));
.child(Button::new("cfg-reload").small().ghost().icon(IconName::RefreshCw).label(tr("Reload")).on_click(cx.listener(|this, _, window, cx| this.reload(window, cx))))
.child(Button::new("cfg-validate").small().label(tr("Check")).on_click(cx.listener(|this, _, _, cx| this.validate(cx))))
.child(Button::new("cfg-save").small().primary().icon(IconName::Save).label(tr("Save")).inactive(!changed, cx).on_click(cx.listener(|this, _, _, cx| this.save(cx))));
let verdict = match &self.verdict {
Verdict::None => div(),
Verdict::Working(what) => hint(*what, cx),
Verdict::Failed(e) => div().text_sm().text_color(cx.theme().danger).child(e.clone()),
Verdict::Issues(issues) if issues.is_empty() => div().text_sm().text_color(cx.theme().success).child("It is valid."),
Verdict::Issues(issues) if issues.is_empty() => div().text_sm().text_color(cx.theme().success).child(tr("It is valid.")),
Verdict::Issues(issues) => issue_list(issues, cx),
Verdict::Saved { revision, issues, apply_error } => div()
.v_flex()
.gap_1()
.child(div().text_sm().text_color(cx.theme().success).child(format!("Saved as revision {revision}.")))
.when_some(apply_error.clone(), |d, e| d.child(div().text_sm().text_color(cx.theme().danger).child(format!("Saved, but not applied: {e}"))))
.child(div().text_sm().text_color(cx.theme().success).child(trf("Saved as revision {}.", &[&revision])))
.when_some(apply_error.clone(), |d, e| d.child(div().text_sm().text_color(cx.theme().danger).child(trf("Saved, but not applied: {}", &[&e]))))
.child(issue_list(issues, cx)),
};
page("Settings", cx).child(this_app(cx)).child(
card("Configuration", Some(actions.into_any_element()), cx)
.child(hint("Upstream's options (services.proxy-suite…) as JSON, as proxy-ctl config get prints them. The service checks them before taking them; options that run programs or read files need an administrator.", cx))
.when(redacted, |d| d.child(hint("Values shown as •••redacted••• are secrets you may not read here; left as they are, they keep their values.", cx)))
page(tr("Settings"), cx).child(this_app(cx)).child(
card(tr("Configuration"), Some(actions.into_any_element()), cx)
.child(hint(tr("Upstream's options (services.proxy-suite…) as JSON, as proxy-ctl config get prints them. The service checks them before taking them; options that run programs or read files need an administrator."), cx))
.when(redacted, |d| d.child(hint(tr("Values shown as •••redacted••• are secrets you may not read here; left as they are, they keep their values."), cx)))
.child(div().h(px(480.)).border_1().border_color(cx.theme().border).rounded_md().child(Editor::new(&self.editor).h_full()))
.child(verdict),
)
}
}
/// This page's words, in Russian (i18n).
pub const RU: &[(&str, &str)] = &[
("Loading…", "Загрузка…"),
("Checking…", "Проверка…"),
("Saving…", "Сохранение…"),
("Not valid JSON: {}", "Некорректный JSON: {}"),
("The configuration was changed elsewhere since it was loaded. Reload to see it (your edits here are then lost; copy them first).", "Конфигурация была изменена в другом месте после загрузки. Перечитайте её, чтобы увидеть изменения (ваши правки здесь при этом пропадут; сначала скопируйте их)."),
("As Windows", "Как в Windows"),
("Light", "Светлая"),
("Dark", "Тёмная"),
("Look for a newer release when the app starts, and daily", "Искать новый выпуск при запуске приложения и раз в сутки"),
("This app", "Это приложение"),
("Language", "Язык"),
("Theme", "Тема"),
("Yours alone, kept with your Windows account; the service's configuration is below.", "Только ваши, хранятся в вашей учётной записи Windows; конфигурация службы ниже."),
("Reload", "Перечитать"),
("Check", "Проверить"),
("Save", "Сохранить"),
("It is valid.", "Конфигурация корректна."),
("Saved as revision {}.", "Сохранено как ревизия {}."),
("Saved, but not applied: {}", "Сохранено, но не применено: {}"),
("Settings", "Настройки"),
("Configuration", "Конфигурация"),
("Upstream's options (services.proxy-suite…) as JSON, as proxy-ctl config get prints them. The service checks them before taking them; options that run programs or read files need an administrator.", "Параметры upstream (services.proxy-suite…) в виде JSON, как их выводит proxy-ctl config get. Служба проверяет их, прежде чем принять; параметры, запускающие программы или читающие файлы, требуют прав администратора."),
("Values shown as •••redacted••• are secrets you may not read here; left as they are, they keep their values.", "Значения вида •••redacted••• — секреты, которые вам здесь читать нельзя; если оставить их как есть, они сохранят свои значения."),
];
+43 -18
View File
@@ -1,6 +1,7 @@
//! The Telegram proxy (Flowseal's tg-ws-proxy): on or off, the links to open in Telegram, and
//! where it listens.
use crate::i18n::{tr, trf};
use gpui_kit::assets::IconName;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputState};
@@ -26,7 +27,7 @@ pub struct TelegramPage {
impl TelegramPage {
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let port = cx.new(|cx| InputState::new(window, cx).placeholder("1443"));
let fake_tls = cx.new(|cx| InputState::new(window, cx).placeholder("none"));
let fake_tls = cx.new(|cx| InputState::new(window, cx).placeholder(tr("none")));
let subscriptions = vec![cx.observe_in(&model, window, |this, _, window, cx| this.sync(window, cx))];
let mut this = Self { model, port, fake_tls, shown: Default::default(), _subscriptions: subscriptions };
this.sync(window, cx);
@@ -55,14 +56,14 @@ impl TelegramPage {
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let port_text = self.port.read(cx).value().trim().to_owned();
let Ok(port) = port_text.parse::<u16>() else {
window.push_notification(Notification::error(format!("“{port_text}” is not a port (1–65535)")), cx);
window.push_notification(Notification::error(trf("“{}” is not a port (1–65535)", &[&port_text])), cx);
return;
};
let domain = self.fake_tls.read(cx).value().trim().to_owned();
self.shown = (self.port.read(cx).value().to_string(), self.fake_tls.read(cx).value().to_string());
self.model.update(cx, |m, cx| {
m.edit(
"Telegram proxy saved",
tr("Telegram proxy saved"),
move |c| {
edits::set_path(c, &["tgWsProxy", "listener", "port"], port.into());
edits::set_path(c, &["tgWsProxy", "fakeTlsDomain"], if domain.is_empty() { Value::Null } else { domain.clone().into() });
@@ -80,9 +81,9 @@ impl Render for TelegramPage {
let status = m.status()["tgWsProxy"].clone();
let t = m.config()["tgWsProxy"].clone();
let links = m.tg_links().to_vec();
let body = page("Telegram proxy", cx);
let body = page(tr("Telegram proxy"), cx);
if t.is_null() {
return body.child(hint("Waiting for the service…", cx));
return body.child(hint(tr("Waiting for the service…"), cx));
}
let model = self.model.clone();
@@ -90,7 +91,7 @@ impl Render for TelegramPage {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
if on { "The Telegram proxy is on" } else { "The Telegram proxy is off" },
if on { tr("The Telegram proxy is on") } else { tr("The Telegram proxy is off") },
move |c| {
edits::set_tg_ws_proxy_enabled(c, on);
Ok(())
@@ -100,9 +101,9 @@ impl Render for TelegramPage {
})
});
let mut link_card = card("Links", None, cx).child(hint("Open one in Telegram, or copy it to a phone: Telegram then connects through this proxy.", cx));
let mut link_card = card(tr("Links"), None, cx).child(hint(tr("Open one in Telegram, or copy it to a phone: Telegram then connects through this proxy."), cx));
if links.is_empty() {
link_card = link_card.child(hint("No links: reading them needs the secrets scope (userControl).", cx));
link_card = link_card.child(hint(tr("No links: reading them needs the secrets scope (userControl)."), cx));
}
for (i, link) in links.into_iter().enumerate() {
let (copy, open) = (link.clone(), link.clone());
@@ -112,21 +113,21 @@ impl Render for TelegramPage {
.gap_2()
.items_center()
.child(div().flex_1().min_w_0().truncate().text_sm().font_family("monospace").child(link))
.child(Button::new(("copy-link", i)).small().icon(IconName::Copy).label("Copy").on_click(move |_, window, cx| {
.child(Button::new(("copy-link", i)).small().icon(IconName::Copy).label(tr("Copy")).on_click(move |_, window, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(copy.to_string()));
window.push_notification(Notification::success("Copied"), cx);
window.push_notification(Notification::success(tr("Copied")), cx);
}))
.child(Button::new(("open-link", i)).small().primary().icon(IconName::Send).label("Open in Telegram").on_click(move |_, _, cx| cx.open_url(&open))),
.child(Button::new(("open-link", i)).small().primary().icon(IconName::Send).label(tr("Open in Telegram")).on_click(move |_, _, cx| cx.open_url(&open))),
);
}
let shared = t["listener"]["address"] == "0.0.0.0";
let model = self.model.clone();
let lan = Switch::new("tg-lan").label("Let other devices on this network connect (phones, other computers)").checked(shared).on_change(move |on, _, cx| {
let lan = Switch::new("tg-lan").label(tr("Let other devices on this network connect (phones, other computers)")).checked(shared).on_change(move |on, _, cx| {
let address = if *on { "0.0.0.0" } else { "127.0.0.1" };
model.update(cx, |m, cx| {
m.edit(
if address == "0.0.0.0" { "Other devices may connect" } else { "Only this computer may connect" },
if address == "0.0.0.0" { tr("Other devices may connect") } else { tr("Only this computer may connect") },
move |c| {
edits::set_path(c, &["tgWsProxy", "listener", "address"], json!(address));
Ok(())
@@ -139,13 +140,13 @@ impl Render for TelegramPage {
body.child(
card("tg-ws-proxy", Some(enable.into_any_element()), cx)
.child(div().h_flex().child(state_tag(status["state"].as_str().unwrap_or("unknown"))))
.child(hint("Telegram over WebSocket to its own servers, for networks that block its usual connections.", cx)),
.child(hint(tr("Telegram over WebSocket to its own servers, for networks that block its usual connections."), cx)),
)
.child(link_card)
.child(
card(
"Listening",
Some(Button::new("tg-save").small().label("Save").on_click(cx.listener(|this, _, window, cx| this.save(window, cx))).into_any_element()),
tr("Listening"),
Some(Button::new("tg-save").small().label(tr("Save")).on_click(cx.listener(|this, _, window, cx| this.save(window, cx))).into_any_element()),
cx,
)
.child(lan)
@@ -153,9 +154,33 @@ impl Render for TelegramPage {
div()
.h_flex()
.gap_4()
.child(div().v_flex().gap_1().w(px(160.)).child(div().text_sm().child("Port")).child(Input::new(&self.port)))
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child("Fake-TLS domain (ee links)")).child(Input::new(&self.fake_tls))),
.child(div().v_flex().gap_1().w(px(160.)).child(div().text_sm().child(tr("Port"))).child(Input::new(&self.port)))
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child(tr("Fake-TLS domain (ee links)"))).child(Input::new(&self.fake_tls))),
),
)
}
}
/// This page's words, in Russian (i18n).
pub const RU: &[(&str, &str)] = &[
("none", "нет"),
("“{}” is not a port (1–65535)", "«{}» — не порт (1–65535)"),
("Telegram proxy saved", "Прокси для Telegram сохранён"),
("Waiting for the service…", "Ожидание службы…"),
("The Telegram proxy is on", "Прокси для Telegram включён"),
("The Telegram proxy is off", "Прокси для Telegram выключен"),
("Links", "Ссылки"),
("Open one in Telegram, or copy it to a phone: Telegram then connects through this proxy.", "Откройте ссылку в Telegram или скопируйте её на телефон: Telegram будет подключаться через этот прокси."),
("No links: reading them needs the secrets scope (userControl).", "Ссылок нет: чтобы их прочитать, нужна область секретов (userControl)."),
("Copy", "Копировать"),
("Copied", "Скопировано"),
("Open in Telegram", "Открыть в Telegram"),
("Let other devices on this network connect (phones, other computers)", "Разрешить подключаться другим устройствам этой сети (телефонам, другим компьютерам)"),
("Other devices may connect", "Другим устройствам подключаться можно"),
("Only this computer may connect", "Подключаться может только этот компьютер"),
("Telegram over WebSocket to its own servers, for networks that block its usual connections.", "Telegram через WebSocket к его собственным серверам — для сетей, где обычные подключения заблокированы."),
("Listening", "Прослушивание"),
("Save", "Сохранить"),
("Port", "Порт"),
("Fake-TLS domain (ee links)", "Домен Fake-TLS (ссылки ee)"),
];
+76 -35
View File
@@ -16,6 +16,7 @@ use ps_client::edits;
use ps_ipc::Request;
use serde_json::Value;
use crate::i18n::{tr, trf};
use super::widgets::{card, hint, page, state_tag};
use crate::model::Model;
@@ -57,7 +58,7 @@ impl WhitelistPage {
let joiners: Vec<String> = w["joiners"].as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default();
self.joins.retain(|n, _| joiners.contains(n));
for n in joiners {
self.joins.entry(n).or_insert_with(|| cx.new(|cx| InputState::new(window, cx).placeholder("the creator's call link")));
self.joins.entry(n).or_insert_with(|| cx.new(|cx| InputState::new(window, cx).placeholder(tr("the creator's call link"))));
}
let creators: Vec<(String, String)> =
w["creators"].as_object().map(|o| o.iter().map(|(n, c)| (n.clone(), c["platform"].as_str().unwrap_or("").to_owned())).collect()).unwrap_or_default();
@@ -65,8 +66,8 @@ impl WhitelistPage {
for (n, platform) in creators {
if matches!(platform.as_str(), "dion" | "bitrix") && !self.logins.contains_key(&n) {
let login = PasswordLogin {
email: cx.new(|cx| InputState::new(window, cx).placeholder("email")),
password: cx.new(|cx| InputState::new(window, cx).placeholder("password").masked(true)),
email: cx.new(|cx| InputState::new(window, cx).placeholder(tr("email"))),
password: cx.new(|cx| InputState::new(window, cx).placeholder(tr("password")).masked(true)),
portal: (platform == "bitrix").then(|| cx.new(|cx| InputState::new(window, cx).placeholder("portal.bitrix24.ru"))),
};
self.logins.insert(n, login);
@@ -83,7 +84,7 @@ impl WhitelistPage {
return;
}
self.name.update(cx, |s, cx| s.set_value("", window, cx));
let what = format!("{} '{name}' added", if role == "joiners" { "Joiner" } else { "Creator" });
let what = if role == "joiners" { trf("Joiner '{}' added", &[&name]) } else { trf("Creator '{}' added", &[&name]) };
self.model.update(cx, |m, cx| m.edit(what, move |c| edits::add_wl(c, role, &name, platform), cx));
}
@@ -91,11 +92,11 @@ impl WhitelistPage {
let Some(input) = self.joins.get(&name) else { return };
let link = input.read(cx).value().trim().to_owned();
if link.is_empty() {
window.push_notification(Notification::error("Paste the link the creator's side gave (its proxy-ctl wl link)"), cx);
window.push_notification(Notification::error(tr("Paste the link the creator's side gave (its proxy-ctl wl link)")), cx);
return;
}
input.update(cx, |s, cx| s.set_value("", window, cx));
self.model.update(cx, |m, cx| m.request(format!("'{name}' joins the call"), Request::WlJoin { name, link }, cx));
self.model.update(cx, |m, cx| m.request(trf("'{}' joins the call", &[&name]), Request::WlJoin { name, link }, cx));
}
fn link(&mut self, name: String, cx: &mut Context<Self>) {
@@ -113,15 +114,15 @@ impl WhitelistPage {
/// A cookies export, chosen: read here, as the signed-in user, and handed to the service.
fn cookies(&mut self, name: String, cx: &mut Context<Self>) {
let paths = cx.prompt_for_paths(PathPromptOptions { files: true, directories: false, multiple: false, prompt: Some("Log in".into()) });
let paths = cx.prompt_for_paths(PathPromptOptions { files: true, directories: false, multiple: false, prompt: Some(tr("Log in").into()) });
let model = self.model.clone();
cx.spawn(async move |_, cx| {
let Ok(Ok(Some(paths))) = paths.await else { return };
let Some(path) = paths.into_iter().next() else { return };
let login = std::fs::read_to_string(&path);
model.update(cx, |m, cx| match login {
Ok(login) => m.request(format!("'{name}' has its login"), Request::WlAuth { name, login }, cx),
Err(e) => m.track(format!("Reading {}", path.display()), async move { Err(e.into()) }, cx),
Ok(login) => m.request(trf("'{}' has its login", &[&name]), Request::WlAuth { name, login }, cx),
Err(e) => m.track(trf("Reading {}", &[&path.display()]), async move { Err(e.into()) }, cx),
});
})
.detach();
@@ -137,16 +138,16 @@ impl WhitelistPage {
login.insert("portal".into(), if portal.contains("://") { portal } else { format!("https://{portal}") }.into());
}
if login.values().any(|v| v.as_str().is_none_or(str::is_empty) || v == "https://") {
window.push_notification(Notification::error("Fill in every field"), cx);
window.push_notification(Notification::error(tr("Fill in every field")), cx);
return;
}
l.password.update(cx, |s, cx| s.set_value("", window, cx));
let login = Value::Object(login).to_string();
self.model.update(cx, |m, cx| m.request(format!("'{name}' has its login"), Request::WlAuth { name, login }, cx));
self.model.update(cx, |m, cx| m.request(trf("'{}' has its login", &[&name]), Request::WlAuth { name, login }, cx));
}
fn remove(&mut self, role: &'static str, name: String, cx: &mut Context<Self>) {
self.model.update(cx, |m, cx| m.edit(format!("'{name}' removed"), move |c| edits::remove_wl(c, role, &name), cx));
self.model.update(cx, |m, cx| m.edit(trf("'{}' removed", &[&name]), move |c| edits::remove_wl(c, role, &name), cx));
}
}
@@ -167,9 +168,9 @@ impl Render for WhitelistPage {
let m = self.model.read(cx);
let w = m.config()["whitelistBypass"].clone();
let status = m.status().clone();
let body = page("Whitelist bypass", cx);
let body = page(tr("Whitelist bypass"), cx);
if m.config().is_null() {
return body.child(hint("Waiting for the service…", cx));
return body.child(hint(tr("Waiting for the service…"), cx));
}
let on = w["enable"] == true;
@@ -178,7 +179,7 @@ impl Render for WhitelistPage {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
if on { "Whitelist bypass is on" } else { "Whitelist bypass is off" },
if on { tr("Whitelist bypass is on") } else { tr("Whitelist bypass is off") },
move |c| {
edits::set_path(c, &["whitelistBypass", "enable"], on.into());
Ok(())
@@ -188,15 +189,15 @@ impl Render for WhitelistPage {
})
});
let about = card("whitelist-bypass", Some(enable.into_any_element()), cx).child(hint(
"For networks that let only a whitelist through, video calls among it: a joiner here tunnels the proxy's traffic through a call that a creator, on a machine with normal internet, holds open. Pin the joiner's outbound (Outbounds) to send traffic through it.",
tr("For networks that let only a whitelist through, video calls among it: a joiner here tunnels the proxy's traffic through a call that a creator, on a machine with normal internet, holds open. Pin the joiner's outbound (Outbounds) to send traffic through it."),
cx,
));
let mut joiners = card("Joiners", None, cx).child(hint("Each is an outbound of the proxy, named as here. It joins the call whose link its creator gives.", cx));
let mut joiners = card(tr("Joiners"), None, cx).child(hint(tr("Each is an outbound of the proxy, named as here. It joins the call whose link its creator gives."), cx));
let joiner_list: Vec<(String, String)> =
w["joiners"].as_object().map(|o| o.iter().map(|(n, j)| (n.clone(), j["platform"].as_str().unwrap_or("").to_owned())).collect()).unwrap_or_default();
if joiner_list.is_empty() {
joiners = joiners.child(hint("None yet: add one below.", cx));
joiners = joiners.child(hint(tr("None yet: add one below."), cx));
}
for (i, (name, platform)) in joiner_list.into_iter().enumerate() {
let Some(input) = self.joins.get(&name) else { continue };
@@ -225,19 +226,19 @@ impl Render for WhitelistPage {
.h_flex()
.gap_2()
.child(div().flex_1().min_w_0().child(Input::new(input)))
.child(Button::new(("wl-join", i)).small().primary().label("Join").on_click(cx.listener(move |this, _, window, cx| this.join(n2.clone(), window, cx)))),
.child(Button::new(("wl-join", i)).small().primary().label(tr("Join")).on_click(cx.listener(move |this, _, window, cx| this.join(n2.clone(), window, cx)))),
),
);
}
let mut creators = card("Creators", None, cx).child(hint(
"On the machine with normal internet. Each logs in to its platform (a cookies export from the desktop Creator app or a browser; DION and Bitrix take an email and password), starts a call and keeps it: give its link to the joiner.",
let mut creators = card(tr("Creators"), None, cx).child(hint(
tr("On the machine with normal internet. Each logs in to its platform (a cookies export from the desktop Creator app or a browser; DION and Bitrix take an email and password), starts a call and keeps it: give its link to the joiner."),
cx,
));
let creator_list: Vec<(String, String)> =
w["creators"].as_object().map(|o| o.iter().map(|(n, c)| (n.clone(), c["platform"].as_str().unwrap_or("").to_owned())).collect()).unwrap_or_default();
if creator_list.is_empty() {
creators = creators.child(hint("None here.", cx));
creators = creators.child(hint(tr("None here."), cx));
}
for (i, (name, platform)) in creator_list.into_iter().enumerate() {
let state = unit_state(&status, &format!("proxy-suite-wb-creator-{name}"), on);
@@ -257,13 +258,13 @@ impl Render for WhitelistPage {
.child(div().text_sm().text_color(cx.theme().muted_foreground).child(platform_label(&platform).to_owned()))
.child(state_tag(&state))
.child(div().flex_1())
.child(Button::new(("wl-link", i)).small().icon(IconName::Link).label("Call link").on_click(cx.listener(move |this, _, _, cx| this.link(n1.clone(), cx))))
.child(Button::new(("wl-new", i)).small().icon(IconName::RefreshCw).label("New call").on_click(cx.listener(move |this, _, _, cx| {
.child(Button::new(("wl-link", i)).small().icon(IconName::Link).label(tr("Call link")).on_click(cx.listener(move |this, _, _, cx| this.link(n1.clone(), cx))))
.child(Button::new(("wl-new", i)).small().icon(IconName::RefreshCw).label(tr("New call")).on_click(cx.listener(move |this, _, _, cx| {
this.links.remove(&n2);
let name = n2.clone();
this.model.update(cx, |m, cx| m.request(format!("'{name}' starts a new call"), Request::WlNew { name }, cx));
this.model.update(cx, |m, cx| m.request(trf("'{}' starts a new call", &[&name]), Request::WlNew { name }, cx));
})))
.child(Button::new(("wl-cookies", i)).small().icon(IconName::FileUp).label("Cookies file…").on_click(cx.listener(move |this, _, _, cx| this.cookies(n3.clone(), cx))))
.child(Button::new(("wl-cookies", i)).small().icon(IconName::FileUp).label(tr("Cookies file…")).on_click(cx.listener(move |this, _, _, cx| this.cookies(n3.clone(), cx))))
.child(Button::new(("wl-remove-creator", i)).small().ghost().icon(IconName::Trash).on_click(cx.listener(move |this, _, _, cx| this.remove("creators", n4.clone(), cx)))),
);
match self.links.get(&name) {
@@ -275,9 +276,9 @@ impl Render for WhitelistPage {
.gap_2()
.items_center()
.child(div().flex_1().min_w_0().truncate().text_sm().font_family("monospace").child(link.clone()))
.child(Button::new(("wl-copy", i)).small().icon(IconName::Copy).label("Copy").on_click(move |_, window, cx| {
.child(Button::new(("wl-copy", i)).small().icon(IconName::Copy).label(tr("Copy")).on_click(move |_, window, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(copy.clone()));
window.push_notification(Notification::success("Copied"), cx);
window.push_notification(Notification::success(tr("Copied")), cx);
})),
);
}
@@ -289,30 +290,70 @@ impl Render for WhitelistPage {
if let Some(p) = &l.portal {
fields = fields.child(div().flex_1().min_w_0().child(Input::new(p)));
}
row = row.child(fields.child(Button::new(("wl-login", i)).small().primary().label("Log in").on_click(cx.listener(move |this, _, window, cx| this.password_login(n5.clone(), window, cx)))));
row = row.child(fields.child(Button::new(("wl-login", i)).small().primary().label(tr("Log in")).on_click(cx.listener(move |this, _, window, cx| this.password_login(n5.clone(), window, cx)))));
}
creators = creators.child(row);
}
let platforms = RadioGroup::horizontal("wl-platform")
.children(PLATFORMS.map(|(_, label)| label))
.children(PLATFORMS.map(|(_, label)| tr(label)))
.selected_index(Some(self.platform))
.on_change(cx.listener(|this, ix: &usize, _, cx| {
this.platform = *ix;
cx.notify();
}));
let add = card("Add", None, cx)
.child(div().v_flex().gap_1().child(div().text_sm().child("Name (letters, digits, '.', '_', '-')")).child(Input::new(&self.name)))
let add = card(tr("Add"), None, cx)
.child(div().v_flex().gap_1().child(div().text_sm().child(tr("Name (letters, digits, '.', '_', '-')"))).child(Input::new(&self.name)))
.child(platforms)
.child(
div()
.h_flex()
.gap_2()
.child(Button::new("wl-add-joiner").small().icon(IconName::Plus).label("Add a joiner").on_click(cx.listener(|this, _, window, cx| this.add("joiners", window, cx))))
.child(Button::new("wl-add-creator").small().icon(IconName::Plus).label("Add a creator").on_click(cx.listener(|this, _, window, cx| this.add("creators", window, cx)))),
.child(Button::new("wl-add-joiner").small().icon(IconName::Plus).label(tr("Add a joiner")).on_click(cx.listener(|this, _, window, cx| this.add("joiners", window, cx))))
.child(Button::new("wl-add-creator").small().icon(IconName::Plus).label(tr("Add a creator")).on_click(cx.listener(|this, _, window, cx| this.add("creators", window, cx)))),
)
.child(hint("Their other options (linkFile, cookiesFile, upstream, resources) are in Settings, under whitelistBypass.", cx));
.child(hint(tr("Their other options (linkFile, cookiesFile, upstream, resources) are in Settings, under whitelistBypass."), cx));
body.child(about).child(joiners).child(creators).child(add)
}
}
/// This page's words, in Russian (i18n).
pub const RU: &[(&str, &str)] = &[
("the creator's call link", "ссылка на звонок от создателя"),
("email", "эл. почта"),
("password", "пароль"),
("Joiner '{}' added", "Участник «{}» добавлен"),
("Creator '{}' added", "Создатель «{}» добавлен"),
("Paste the link the creator's side gave (its proxy-ctl wl link)", "Вставьте ссылку от стороны создателя (её ссылка из proxy-ctl wl link)"),
("'{}' joins the call", "«{}» подключается к звонку"),
("Log in", "Войти"),
("'{}' has its login", "Для «{}» заданы данные для входа"),
("Reading {}", "Чтение {}"),
("Fill in every field", "Заполните все поля"),
("'{}' removed", "Удалено: «{}»"),
("Whitelist bypass", "Обход белых списков"),
("Waiting for the service…", "Ожидание службы…"),
("Whitelist bypass is on", "Обход белых списков включён"),
("Whitelist bypass is off", "Обход белых списков выключен"),
("For networks that let only a whitelist through, video calls among it: a joiner here tunnels the proxy's traffic through a call that a creator, on a machine with normal internet, holds open. Pin the joiner's outbound (Outbounds) to send traffic through it.", "Для сетей, пропускающих только белый список, в котором есть видеозвонки: участник здесь пускает трафик прокси через звонок, который держит открытым создатель на машине с обычным интернетом. Закрепите выход участника (раздел «Выходы»), чтобы направить трафик через него."),
("Joiners", "Участники"),
("Each is an outbound of the proxy, named as here. It joins the call whose link its creator gives.", "Каждый участник — выход прокси с тем же именем. Он подключается к звонку по ссылке, которую даёт его создатель."),
("None yet: add one below.", "Пока нет: добавьте ниже."),
("Join", "Подключиться"),
("Creators", "Создатели"),
("On the machine with normal internet. Each logs in to its platform (a cookies export from the desktop Creator app or a browser; DION and Bitrix take an email and password), starts a call and keeps it: give its link to the joiner.", "На машине с обычным интернетом. Каждый создатель входит на свою платформу (экспорт cookies из настольного приложения Creator или из браузера; DION и Bitrix принимают эл. почту и пароль), запускает звонок и держит его: передайте его ссылку участнику."),
("None here.", "Пока нет."),
("Call link", "Ссылка на звонок"),
("New call", "Новый звонок"),
("'{}' starts a new call", "«{}» начинает новый звонок"),
("Cookies file…", "Файл cookies…"),
("Copy", "Копировать"),
("Copied", "Скопировано"),
("Add", "Добавить"),
("Name (letters, digits, '.', '_', '-')", "Имя (буквы, цифры, «.», «_», «-»)"),
("Add a joiner", "Добавить участника"),
("Add a creator", "Добавить создателя"),
("Their other options (linkFile, cookiesFile, upstream, resources) are in Settings, under whitelistBypass.", "Остальные их параметры (linkFile, cookiesFile, upstream, resources) — в «Настройках», в разделе whitelistBypass."),
("VK (creators only)", "VK (только создатели)"),
];
+28 -2
View File
@@ -3,6 +3,8 @@
use gpui_kit::component::button::Button;
use gpui_kit::component::tag::Tag;
use gpui_kit::prelude::FluentBuilder as _;
use crate::i18n::tr;
use gpui_kit::assets::IconName;
use gpui_kit::component::*;
use gpui_kit::*;
@@ -30,7 +32,7 @@ pub fn card(title: impl Into<SharedString>, action: Option<AnyElement>, cx: &App
.child(div().h_flex().justify_between().items_center().child(div().font_semibold().child(title.into())).children(action))
}
/// A unit's state, as the service says it, coloured by what it means.
/// A unit's state, as the service says it, coloured by what it means, in the user's words.
pub fn state_tag(state: &str) -> Tag {
let tag = match state {
"active" => Tag::success(),
@@ -38,7 +40,16 @@ pub fn state_tag(state: &str) -> Tag {
"failed" => Tag::danger(),
_ => Tag::secondary(),
};
tag.child(state.to_owned())
tag.child(state_word(state))
}
/// The service's word for a state, in the user's language.
pub fn state_word(state: &str) -> SharedString {
const KNOWN: [&str; 11] = ["active", "inactive", "activating", "deactivating", "reloading", "failed", "unknown", "off", "on", "outbound", "waiting"];
match KNOWN.iter().find(|k| **k == state) {
Some(k) => tr(k).into(),
None => state.to_owned().into(),
}
}
/// A quieter line of explanation.
@@ -64,3 +75,18 @@ impl Inactive for Button {
self.disabled(disabled).when(disabled, |b| b.text_color(cx.theme().muted_foreground))
}
}
/// The shared pieces' words (units' states), in Russian (i18n).
pub const RU: &[(&str, &str)] = &[
("active", "работает"),
("inactive", "остановлено"),
("activating", "запускается"),
("deactivating", "останавливается"),
("reloading", "перезапускается"),
("failed", "сбой"),
("unknown", "неизвестно"),
("off", "выкл."),
("on", "вкл."),
("outbound", "выход прокси"),
("waiting", "ожидает"),
];
Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

+1
View File
@@ -11,4 +11,5 @@ Each has its SHA-256 in the `.sha256` file next to it. SmartScreen may warn of a
### New
- **Updates from the app**: its Overview says when a newer release is out and installs it. The service fetches the setup program from this project's releases, checks its SHA-256 against the one published beside it and runs it silently; the service and the app close for a moment and start again, new, settings kept. Also `proxy-ctl update` and `proxy-ctl update install`. It looks at start and daily (Settings → This app turns that off). This is the first release that has it: from 0.2.0-pre.1, update by running the new setup.
- **zapret2's 16 KB cutoff probe** (`zapret2.cutoff`, on by default, as upstream's): some lines cut TLS to certain hosting networks after about 16 KB, which no strategy fixes. z2k's probe finds those networks daily (or when the line's network changes) and, with z2k's strategies, a name that gets through for each, which z2k puts into a fake hello; what no name fixes goes through the proxy, by address (`cutoff.proxyFallback`). The probe's connections leave from ports winws2 leaves alone. On the DPI bypass page, or `proxy-ctl zapret cutoff [probe]`.
- **The app in Russian**: every page, the tray's menu and the notifications, as Windows' display language is (or chosen in Settings → This app). What the service itself says (its warnings and errors) and `proxy-ctl` stay English.
- **A dark theme**: light, dark, or as Windows is set (the default), in Settings → This app or at the sun/moon in the sidebar; the window's title bar follows it.
+5 -3
View File
@@ -4,7 +4,7 @@
# whitelist-bypass, the Telegram proxy), the app on a virtual display (tools/gui-shot.sh).
# In the dev shell, after tools/package.sh:
#
# tools/screenshots.sh [OUT_DIR] (OUT_DIR: docs/screenshots)
# [SHOT_LANGUAGE=ru] tools/screenshots.sh [OUT_DIR] (OUT_DIR: docs/screenshots)
set -euo pipefail
cd "$(dirname "$0")/.."
OUT=$(realpath -m "${1:-docs/screenshots}")
@@ -52,8 +52,10 @@ release=$(ls -d dist/ProxySuite-*-windows-x64/components 2>/dev/null | tail -1 |
cargo build -q -p ps-service -p ps-gui
# The app's own preferences for the shots: the light theme (one dark shot below).
mkdir -p "$WORK/prefs/light/proxy-suite" "$WORK/prefs/dark/proxy-suite"
echo '{"theme":"light","checkUpdates":false}' >"$WORK/prefs/light/proxy-suite/app.json"
echo '{"theme":"dark","checkUpdates":false}' >"$WORK/prefs/dark/proxy-suite/app.json"
# SHOT_LANGUAGE: the app's language (en, ru).
lang=${SHOT_LANGUAGE:-en}
echo "{\"language\":\"$lang\",\"theme\":\"light\",\"checkUpdates\":false}" >"$WORK/prefs/light/proxy-suite/app.json"
echo "{\"language\":\"$lang\",\"theme\":\"dark\",\"checkUpdates\":false}" >"$WORK/prefs/dark/proxy-suite/app.json"
export XDG_CONFIG_HOME="$WORK/prefs/light"
target/debug/proxy-suite-service --console --state-dir "$STATE" --socket "$SOCK" >"$WORK/service.log" 2>&1 &
SERVICE=$!