okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-gh-app: GitHub app and Terminal items for 0.2.73cabb9e3f

main
9.7 KiB238 linesraw
1//! The shell's own choices and the two things the host asks of it besides updates (#3402, #3477).
2//!
3//! `<Strata data folder>/shell-prefs.json` is written by the App Host when the person changes a setting
4//! (`apps/host/server/shell-prefs.mjs`) and read here when Strata starts, before any page exists:
5//!
6//!   { "port": 0 | 1024..65535, "tray": false, "language": "en" }
7//!
8//! * `port`: the port the window's origin uses. 0 is the default, 47831. When the port is busy the shell takes a free one and tells the
9//!   host (`STRATA_PORT_NOTICE=busy:<wanted>:<used>`), which shows the person a warning: the chats and settings of the page are kept per
10//!   port, so a different port starts empty.
11//! * `tray`: closing the window hides it and keeps Strata running in the tray (Windows, macOS). The tray menu follows `language`.
12//! * `/shell/notify` on the loopback bridge shows a desktop notification (an approval is waiting) whether the window is open or hidden.
13
14use std::path::PathBuf;
15
16use serde_json::Value;
17
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct Prefs {
20    pub port: u16,
21    pub tray: bool,
22    pub language: String,
23}
24
25impl Default for Prefs {
26    fn default() -> Self {
27        Prefs { port: 0, tray: false, language: "en".into() }
28    }
29}
30
31pub const LANGUAGES: [&str; 8] = ["en", "zh", "ja", "de", "es", "ru", "pt", "ko"];
32
33pub fn prefs_path() -> PathBuf {
34    crate::desktoplog::data_dir().join("shell-prefs.json")
35}
36
37/// The file's text as choices; anything missing or out of range is the default.
38pub fn parse_prefs(text: &str) -> Prefs {
39    let value: Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).unwrap_or(Value::Null);
40    let port = value.get("port").and_then(Value::as_u64).filter(|p| (1024..=65535).contains(p)).unwrap_or(0) as u16;
41    let tray = value.get("tray").and_then(Value::as_bool).unwrap_or(false);
42    let language = value
43        .get("language")
44        .and_then(Value::as_str)
45        .filter(|l| LANGUAGES.contains(l))
46        .unwrap_or("en")
47        .to_string();
48    Prefs { port, tray, language }
49}
50
51pub fn read_prefs() -> Prefs {
52    std::fs::read_to_string(prefs_path()).map(|t| parse_prefs(&t)).unwrap_or_default()
53}
54
55/// The port to ask for: the person's choice, else the app's usual one.
56pub fn wanted_port(prefs: &Prefs, usual: u16) -> u16 {
57    if prefs.port != 0 { prefs.port } else { usual }
58}
59
60/// The notice the host shows when the wanted port was taken.
61pub fn busy_notice(wanted: u16, used: u16) -> String {
62    format!("busy:{wanted}:{used}")
63}
64
65/// `%41%20b` -> "A b" (a query value from the host). Bad escapes are kept as typed.
66pub fn percent_decode(text: &str) -> String {
67    let bytes = text.as_bytes();
68    let mut out = Vec::with_capacity(bytes.len());
69    let mut i = 0;
70    while i < bytes.len() {
71        if bytes[i] == b'%' && i + 2 < bytes.len() {
72            if let Some(v) = std::str::from_utf8(&bytes[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()) {
73                out.push(v);
74                i += 3;
75                continue;
76            }
77        }
78        out.push(if bytes[i] == b'+' { b' ' } else { bytes[i] });
79        i += 1;
80    }
81    String::from_utf8_lossy(&out).into_owned()
82}
83
84/// The value of `key` in the query of a request path (`/shell/notify?title=..&body=..`).
85pub fn query_value(path: &str, key: &str) -> Option<String> {
86    let query = path.split_once('?')?.1;
87    query.split('&').find_map(|pair| {
88        let (k, v) = pair.split_once('=')?;
89        (k == key).then(|| percent_decode(v))
90    })
91}
92
93/// A short single-line text for a notification: no control characters, bounded.
94pub fn clean_text(text: &str, max: usize) -> String {
95    text.chars().filter(|c| !c.is_control()).take(max).collect::<String>().trim().to_string()
96}
97
98/// The tray menu: (open, quit, tooltip), in the app's language.
99pub fn tray_labels(language: &str) -> (&'static str, &'static str, &'static str) {
100    match language {
101        "zh" => ("打开 Strata", "退出 Strata", "Strata"),
102        "ja" => ("Strata を開く", "Strata を終了", "Strata"),
103        "de" => ("Strata öffnen", "Strata beenden", "Strata"),
104        "es" => ("Abrir Strata", "Salir de Strata", "Strata"),
105        "ru" => ("Открыть Strata", "Выйти из Strata", "Strata"),
106        "pt" => ("Abrir o Strata", "Sair do Strata", "Strata"),
107        "ko" => ("Strata 열기", "Strata 종료", "Strata"),
108        _ => ("Open Strata", "Quit Strata", "Strata"),
109    }
110}
111
112#[cfg(not(target_os = "linux"))]
113mod native {
114    use tauri::menu::{Menu, MenuItem};
115    use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
116    use tauri::{AppHandle, Manager};
117    use tauri_plugin_notification::NotificationExt;
118
119    const TRAY_ID: &str = "strata-tray";
120
121    fn show_main(app: &AppHandle) {
122        if let Some(window) = app.get_webview_window("main") {
123            let _ = window.unminimize();
124            let _ = window.show();
125            let _ = window.set_focus();
126        }
127    }
128
129    /// Hide the window and keep Strata running in the tray (made on the first need, with the menu in the app's language).
130    pub fn hide_to_tray(app: &AppHandle, language: &str) {
131        if app.tray_by_id(TRAY_ID).is_none() {
132            let (open, quit, tip) = super::tray_labels(language);
133            let built = (|| -> tauri::Result<()> {
134                let open_item = MenuItem::with_id(app, "open", open, true, None::<&str>)?;
135                let quit_item = MenuItem::with_id(app, "quit", quit, true, None::<&str>)?;
136                let menu = Menu::with_items(app, &[&open_item, &quit_item])?;
137                let mut builder = TrayIconBuilder::with_id(TRAY_ID)
138                    .tooltip(tip)
139                    .menu(&menu)
140                    .show_menu_on_left_click(false)
141                    .on_menu_event(|app, event| match event.id().as_ref() {
142                        "open" => show_main(app),
143                        "quit" => app.exit(0),
144                        _ => {}
145                    })
146                    .on_tray_icon_event(|tray, event| {
147                        if let TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. } = event {
148                            show_main(tray.app_handle());
149                        }
150                    });
151                if let Some(icon) = app.default_window_icon() {
152                    builder = builder.icon(icon.clone());
153                }
154                builder.build(app)?;
155                Ok(())
156            })();
157            if built.is_err() {
158                // No tray could be made (a desktop without one): do not hide a window nobody could bring back.
159                return;
160            }
161        }
162        if let Some(window) = app.get_webview_window("main") {
163            let _ = window.hide();
164        }
165    }
166
167    pub fn tray_exists(app: &AppHandle) -> bool {
168        app.tray_by_id(TRAY_ID).is_some()
169    }
170
171    /// Show a desktop notification; a hidden or minimised window also asks for attention (the taskbar button flashes).
172    pub fn notify(app: &AppHandle, title: &str, body: &str) -> bool {
173        if title.is_empty() {
174            return false;
175        }
176        if let Some(window) = app.get_webview_window("main") {
177            let hidden = !window.is_visible().unwrap_or(true) || window.is_minimized().unwrap_or(false);
178            if hidden {
179                let _ = window.request_user_attention(Some(tauri::UserAttentionType::Informational));
180            }
181        }
182        app.notification().builder().title(title).body(body).show().is_ok()
183    }
184}
185
186#[cfg(not(target_os = "linux"))]
187pub use native::{hide_to_tray, notify, tray_exists};
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192
193    #[test]
194    fn the_file_gives_choices_and_anything_wrong_is_the_default() {
195        assert_eq!(parse_prefs(""), Prefs::default());
196        assert_eq!(parse_prefs("{ not json"), Prefs::default());
197        let p = parse_prefs(r#"{"port":47900,"tray":true,"language":"de"}"#);
198        assert_eq!((p.port, p.tray, p.language.as_str()), (47900, true, "de"));
199        assert_eq!(parse_prefs("\u{feff}{\"port\":47900}").port, 47900);
200        assert_eq!(parse_prefs(r#"{"port":80}"#).port, 0, "a port below 1024 is not used");
201        assert_eq!(parse_prefs(r#"{"port":70000}"#).port, 0);
202        assert_eq!(parse_prefs(r#"{"port":"47831"}"#).port, 0, "a text is not a number");
203        assert_eq!(parse_prefs(r#"{"tray":"yes","language":"xx"}"#), Prefs::default());
204    }
205
206    #[test]
207    fn the_wanted_port_is_the_choice_or_the_usual_one() {
208        assert_eq!(wanted_port(&Prefs::default(), 47831), 47831);
209        assert_eq!(wanted_port(&Prefs { port: 47900, ..Prefs::default() }, 47831), 47900);
210        assert_eq!(busy_notice(47831, 51234), "busy:47831:51234");
211    }
212
213    #[test]
214    fn query_values_are_decoded_and_bounded() {
215        let path = "/shell/notify?title=Strata%20needs%20your%20answer&body=a%20%26%20b%3F+ok";
216        assert_eq!(query_value(path, "title").as_deref(), Some("Strata needs your answer"));
217        assert_eq!(query_value(path, "body").as_deref(), Some("a & b? ok"));
218        assert_eq!(query_value(path, "missing"), None);
219        assert_eq!(query_value("/shell/notify", "title"), None);
220        assert_eq!(percent_decode("100%"), "100%");
221        assert_eq!(percent_decode("%zz%41"), "%zzA");
222        assert_eq!(percent_decode("%C3%A4"), "ä");
223        assert_eq!(clean_text("a\nb\u{7}c", 10), "abc");
224        assert_eq!(clean_text("abcdef", 3), "abc");
225    }
226
227    #[test]
228    fn every_language_has_tray_labels() {
229        for language in LANGUAGES {
230            let (open, quit, tip) = tray_labels(language);
231            assert!(!open.is_empty() && !quit.is_empty() && !tip.is_empty(), "{language}");
232            if language != "en" {
233                assert_ne!(open, tray_labels("en").0, "{language}");
234            }
235        }
236        assert_eq!(tray_labels("xx"), tray_labels("en"));
237    }
238}