okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3cabb9e3f
main
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 { 20pub port : u16 , 21pub tray : bool , 22pub language : String , 23} 24 25impl Default for Prefs { 26fn default () ->Self { 27Prefs { 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 { 34crate :: 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 { 39let value: Value = serde_json:: from_str ( text. trim_start_matches ( '\u{feff}' )). unwrap_or ( Value :: Null ); 40let port = value. get ( "port" ). and_then ( Value :: as_u64). filter ( |p|( 1024 ..=65535 ). contains ( p)). unwrap_or ( 0 ) as u16 ; 41let tray = value. get ( "tray" ). and_then ( Value :: as_bool). unwrap_or ( false ); 42let language = value 43. get ( "language" ) 44. and_then ( Value :: as_str) 45. filter ( |l|LANGUAGES . contains ( l)) 46. unwrap_or ( "en" ) 47. to_string (); 48Prefs { 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 { 57if 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 { 62format! ( "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 { 67let bytes = text. as_bytes (); 68let mut out =Vec :: with_capacity ( bytes. len ()); 69let mut i =0 ; 70while i < bytes. len () { 71if bytes[ i] ==b'%' && i +2 < bytes. len () { 72if 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 ; 75continue ; 76} 77} 78 out. push ( if bytes[ i] ==b'+' { b' ' } else { bytes[ i] }); 79 i +=1 ; 80} 81String :: 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 > { 86let query = path. split_once ( '?' ) ?. 1 ; 87 query. split ( '&' ). find_map ( |pair|{ 88let ( 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 ) { 100match 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{ 114use tauri:: menu::{ Menu , MenuItem }; 115use tauri:: tray::{ MouseButton , MouseButtonState , TrayIconBuilder , TrayIconEvent }; 116use tauri::{ AppHandle , Manager }; 117use tauri_plugin_notification:: NotificationExt ; 118 119const TRAY_ID : & str ="strata-tray" ; 120 121fn show_main ( app : & AppHandle ) { 122if let Some ( window) = app. get_webview_window ( "main" ) { 123let _ = window. unminimize (); 124let _ = window. show (); 125let _ = 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). 130pub fn hide_to_tray ( app : & AppHandle , language : & str ) { 131if app. tray_by_id ( TRAY_ID ). is_none () { 132let ( open, quit, tip) =super :: tray_labels ( language); 133let built =( || -> tauri:: Result <()> { 134let open_item =MenuItem :: with_id ( app, "open" , open, true , None ::< & str >) ?; 135let quit_item =MenuItem :: with_id ( app, "quit" , quit, true , None ::< & str >) ?; 136let menu =Menu :: with_items ( app, & [ & open_item, & quit_item]) ?; 137let 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|{ 147if let TrayIconEvent :: Click { button : MouseButton :: Left , button_state : MouseButtonState :: Up , ..} = event{ 148show_main ( tray. app_handle ()); 149} 150}); 151if let Some ( icon) = app. default_window_icon () { 152 builder = builder. icon ( icon. clone ()); 153} 154 builder. build ( app) ?; 155Ok (()) 156})(); 157if built. is_err () { 158// No tray could be made (a desktop without one): do not hide a window nobody could bring back. 159return ; 160} 161} 162if let Some ( window) = app. get_webview_window ( "main" ) { 163let _ = window. hide (); 164} 165} 166 167pub 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). 172pub fn notify ( app : & AppHandle , title : & str , body : & str ) ->bool { 173if title. is_empty () { 174return false ; 175} 176if let Some ( window) = app. get_webview_window ( "main" ) { 177let hidden = !window. is_visible (). unwrap_or ( true ) || window. is_minimized (). unwrap_or ( false ); 178if hidden{ 179let _ = 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{ 191use super :: * ; 192 193# [ test ] 194fn the_file_gives_choices_and_anything_wrong_is_the_default () { 195assert_eq! ( parse_prefs ( "" ), Prefs :: default ()); 196assert_eq! ( parse_prefs ( "{ not json" ), Prefs :: default ()); 197let p =parse_prefs ( r#"{"port":47900,"tray":true,"language":"de"}"# ); 198assert_eq! (( p. port , p. tray , p. language . as_str ()), ( 47900 , true , "de" )); 199assert_eq! ( parse_prefs ( "\u{feff}{\"port\":47900}" ). port , 47900 ); 200assert_eq! ( parse_prefs ( r#"{"port":80}"# ). port , 0 , "a port below 1024 is not used" ); 201assert_eq! ( parse_prefs ( r#"{"port":70000}"# ). port , 0 ); 202assert_eq! ( parse_prefs ( r#"{"port":"47831"}"# ). port , 0 , "a text is not a number" ); 203assert_eq! ( parse_prefs ( r#"{"tray":"yes","language":"xx"}"# ), Prefs :: default ()); 204} 205 206# [ test ] 207fn the_wanted_port_is_the_choice_or_the_usual_one () { 208assert_eq! ( wanted_port ( & Prefs :: default (), 47831 ), 47831 ); 209assert_eq! ( wanted_port ( & Prefs { port : 47900 , ..Prefs :: default () }, 47831 ), 47900 ); 210assert_eq! ( busy_notice ( 47831 , 51234 ), "busy:47831:51234" ); 211} 212 213# [ test ] 214fn query_values_are_decoded_and_bounded () { 215let path ="/shell/notify?title=Strata%20needs%20your%20answer&body=a%20%26%20b%3F+ok" ; 216assert_eq! ( query_value ( path, "title" ). as_deref (), Some ( "Strata needs your answer" )); 217assert_eq! ( query_value ( path, "body" ). as_deref (), Some ( "a & b? ok" )); 218assert_eq! ( query_value ( path, "missing" ), None ); 219assert_eq! ( query_value ( "/shell/notify" , "title" ), None ); 220assert_eq! ( percent_decode ( "100%" ), "100%" ); 221assert_eq! ( percent_decode ( "%zz%41" ), "%zzA" ); 222assert_eq! ( percent_decode ( "%C3%A4" ), "ä" ); 223assert_eq! ( clean_text ( "a\nb\u{7}c" , 10 ), "abc" ); 224assert_eq! ( clean_text ( "abcdef" , 3 ), "abc" ); 225} 226 227# [ test ] 228fn every_language_has_tray_labels () { 229for languagein LANGUAGES { 230let ( open, quit, tip) =tray_labels ( language); 231assert! ( !open. is_empty () && !quit. is_empty () && !tip. is_empty (), "{language}" ); 232if language !="en" { 233assert_ne! ( open, tray_labels ( "en" ). 0 , "{language}" ); 234} 235} 236assert_eq! ( tray_labels ( "xx" ), tray_labels ( "en" )); 237} 238}