Merge commit '8fb4356c91' into work/integration-verified

This commit is contained in:
omar committed 2026-11-28 08:02:09 +03:00
commit f9ae872168
24 files changed
+316 -77

No files matched your search

+7 -3
View File
@@ -1,6 +1,8 @@
# Localization
TeamsPeach defaults to **English**, independently of the operating-system language. Settings → Appearance → Language selects English or Russian. The native preference is persisted by the Rust preferences service; catalog presentation belongs to the UI, not the protocol or capture worker.
TeamsPeach defaults to **English**, independently of the operating-system language. Settings → Appearance → Language saves English or Russian as the language for the next launch. The picker shows the saved value immediately; the running catalog changes only when the app starts again. On desktop, a successful change away from the running language offers a restart. Cancel dismisses the prompt without undoing the save, and the warning remains under the picker. A failed save keeps the previous value and does not open a prompt. Mobile uses the saved language at the next launch without a desktop relaunch prompt.
The manifest-pinned TeamSpeak 6.0.0.5232 `main.js` initializes its catalog from `navigator.language` (character offsets 1424854 and 1445824). Its Appearance setter saves via `application.language`, then offers a restart only when the selection differs from the running language (4597988). The Cancel callback does not write the preference. These observations come from the pinned bundle, not a live TeamSpeak relaunch.
## Native files and boundaries
@@ -19,9 +21,9 @@ Use `Catalog::new(Language::En)` or the current snapshot's catalog, then `text(k
The formatter performs one substitution pass: inserted content containing braces is not interpreted as another template. Plural messages use language-specific categories and `other`; Russian integer suffixes are not English suffix rules. Fractions use `other`. Catalog key and placeholder parity remain required. The native formatter's English/key fallback and retained unresolved placeholders are not evidence that missing translations are acceptable: missing keys/parameters need authoring coverage and must never be mistaken for success.
Bind Slint text, accessibility names, tooltips and placeholders from the current catalog/model. Dynamic messages must be regenerated from stable keys and raw values when language changes, not translated by matching previously painted wording. Avoid rebuilding forms in ways that discard unsaved input, selection, undo state or focus.
Bind Slint text, accessibility names, tooltips and placeholders from the running catalog/model. The settings selection displays the stored language while the rest of the application continues using its startup catalog. Avoid rebuilding forms in ways that discard unsaved input, selection, undo state or focus.
Language changes never translate server/channel names, nicknames, OS device names, chat content, media or descriptions. App-created notices are localized separately from incoming data. Error explanations are selected by stable machine code, with verbatim server/OS/backend detail after the explanation where useful. Unknown codes remain visible errors. Native chooser titles, filters and application-owned confirmation labels use the current saved language; OS-owned controls follow the OS language.
Language changes never translate server/channel names, nicknames, OS device names, chat content, media or descriptions. App-created notices are localized separately from incoming data. Error explanations are selected by stable machine code, with verbatim server/OS/backend detail after the explanation where useful. Unknown codes remain visible errors. Native chooser titles, filters and application-owned confirmation labels use the running language; OS-owned controls follow the OS language.
## Adding a language
@@ -38,6 +40,8 @@ Language changes never translate server/channel names, nicknames, OS device name
The native report `target/evidence/native-offline-ui-03/result.json` records EN/RU, dark/light and 390/800/1280 logical-pixel settings coverage, controlled combobox values and profile restarts. See FEATURE_COMPATIBILITY.md for the complete scope and limitations. No additional execution is claimed by this documentation update.
The focused Windows Slint test `language_applies_and_survives_process_restart` clicks real dropdown options at 900×800 (English to Russian in dark mode and Russian to English in light mode). It checks that only `language` changes on disk, the selected caption changes before the restart prompt is answered, and the surrounding labels remain in the running language. Cancel keeps the saved choice. Confirm reaches the desktop relaunch policy gate, which refuses OS actions in the smoke runtime. A separate process opens the same disposable profile and renders the saved language; a blocked reverse write returns `io` with no prompt and preserves the selector, active catalog and exact preference bytes. The test does not spawn a production replacement process or establish live voice/chat continuity. Native uses the shared confirmation dialog, not the reference’s anchored popup geometry.
### Historical development runs, 2026-10-24
The removed browser implementation passed 14 targeted localization tests and its Windows x64 hidden-runtime scenario on Electron 44.9.3. Evidence is retained in `docs/evidence/runtime/i18n-2026-10-24/`: fresh English, seven categories and both real-device context menus in both languages, live notice translation, Russian persistence, return to English, no capture, unchanged UID/nickname/audio/unrelated preferences, preserved connection draft, and no horizontal overflow at 880×560. Temporary profiles were deleted. This is historical evidence, not a native pass.
+3 -3
View File
@@ -106,7 +106,7 @@ pub async fn handle(ctx:Arc<RuntimeServices>,action:ChatAction)->Result<Workflow
validate(&ctx,&target)?;let shell=shell_target(&target);if !matches!(shell.entity,Entity::Client{..}){return Err(bad("Choose a private conversation"))}
let command=crate::app::server_actions::prepare(&shell,Operation::ClientInfo,&Values::new())?.ok_or_else(||bad("Client info command unavailable"))?;
let reply=ctx.request(&target.session,command).await?;validate(&ctx,&target)?;
let prefs=ctx.profile()?.prefs.get();let catalog=crate::ui::i18n::Catalog::new(crate::ui::i18n::Language::from_code(prefs["language"].as_str().unwrap_or("en")));
let catalog=ctx.catalog;
let detail=crate::app::server_actions::project(&shell,Operation::ClientInfo,&reply,&catalog)?;
Ok(WorkflowResult::effect(UiEffect::Detail{target:shell,detail}))
},
@@ -199,8 +199,8 @@ pub async fn project(ctx:&RuntimeServices)->Result<ChatPresentation>{
let server=active.and_then(|c|snapshots.get(&c.target.session.connection_id).filter(|s|s.key==c.target.session&&s.is_connected())).and_then(|s|s.server.as_deref());
let media_mode=server.map(|s|file_actions::StorageMode::from_server(s,None));
let media_supported=media_mode==Some(file_actions::StorageMode::Legacy);
let language=prefs["language"].as_str().unwrap_or("en");
let catalog=crate::ui::i18n::Catalog::new(crate::ui::i18n::Language::from_code(language));
let catalog=ctx.catalog;
let language=catalog.language.code();
let server_image_unavailable=media_mode.and_then(|mode|mode.unavailable(0,file_actions::FileAccess::InlineImage,&catalog));
let conversation=active.map(|c|{
let can_send=!c.sending&&sendable(ctx,&c.target);
@@ -16,7 +16,7 @@ pub async fn on_control(ctx:Arc<RuntimeServices>,key:SessionKey,value:Value)->Re
async fn snapshot(ctx:Arc<RuntimeServices>,key:SessionKey,value:Value)->Result<()> {
let server=Arc::new(value);ctx.chat_workflows.lock().await.snapshots.insert(key.connection_id.clone(),(key.clone(),server.clone()));
let base=event_target(&server,&key,ChatTarget::Server)?;let channel=server["own_channel_id"].as_u64().filter(|n|*n>0).map(|id|event_target(&server,&key,ChatTarget::Channel(id))).transpose()?;
let prefs=ctx.profile()?.prefs.get();let language=crate::ui::i18n::Language::from_code(prefs["language"].as_str().unwrap_or("en"));let catalog=crate::ui::i18n::Catalog::new(language);
let catalog=ctx.catalog;
let restore={let mut state=ctx.chat_workflows.lock().await;
let previous_channel=state.conversations.iter().find(|c|c.target.session.connection_id==key.connection_id&&matches!(c.target.target,ChatTarget::Channel(_))&&state.selected.get(&key.connection_id)==Some(&c.target.scope)).map(|c|c.target.scope.clone());
if state.selected.get(&key.connection_id).is_some_and(|scope|scope.base!=base.scope.base){state.selected.remove(&key.connection_id);}
@@ -65,7 +65,7 @@ async fn text(ctx:Arc<RuntimeServices>,key:SessionKey,value:Value)->Result<()> {
},_=>return Err(bad("Unknown text message target")),
};
let target=event_target(&server,&key,target)?;
let title:String=match &target.target{ChatTarget::Server=>if prefs["language"]=="ru"{"Сервер".into()}else{"Server".into()},ChatTarget::Channel(id)=>server["channels"].as_array().and_then(|a|a.iter().find(|c|c["id"].as_u64()==Some(*id))).and_then(|c|c["name"].as_str()).unwrap_or("").into(),ChatTarget::Client{uid,..}=>server["clients"].as_array().and_then(|a|a.iter().find(|c|c["uid"].as_str()==Some(uid))).and_then(|c|c["nickname"].as_str()).or_else(||value["from_nickname"].as_str()).unwrap_or("?").into()};
let title:String=match &target.target{ChatTarget::Server=>ctx.catalog.text("ui.server"),ChatTarget::Channel(id)=>server["channels"].as_array().and_then(|a|a.iter().find(|c|c["id"].as_u64()==Some(*id))).and_then(|c|c["name"].as_str()).unwrap_or("").into(),ChatTarget::Client{uid,..}=>server["clients"].as_array().and_then(|a|a.iter().find(|c|c["uid"].as_str()==Some(uid))).and_then(|c|c["nickname"].as_str()).or_else(||value["from_nickname"].as_str()).unwrap_or("?").into()};
let reveal=own||prefs["chatOpenIncoming"]!=false;
{let mut state=ctx.chat_workflows.lock().await;let exists=state.conversations.iter().any(|c|same(&c.target,&target));ensure(&mut state,target.clone(),title.clone())?;let c=find(&mut state,&target)?;if reveal{c.open=true;}else if !exists{c.open=!matches!(target.target,ChatTarget::Client{..});}}
let record=ChatRecord{time:crate::services::media::now_ms(),message_type:if value["target"]=="poke"{MessageType::Poke}else{MessageType::Text},from_uid:from_uid.map(str::to_owned),from_name:limit_utf16(value["from_nickname"].as_str().unwrap_or("?"),128),own,text:limit_utf16(value["message"].as_str().unwrap_or(""),32768)};
@@ -75,9 +75,8 @@ async fn text(ctx:Arc<RuntimeServices>,key:SessionKey,value:Value)->Result<()> {
}
async fn moderation(ctx:Arc<RuntimeServices>,key:SessionKey,event:Value)->Result<()> {
if !matches!(event["kind"].as_str(),Some("client_enter"|"client_leave"|"client_move"))||event["kind"]=="client_enter"&&event["is_self"]==true{return Ok(())}
let prefs=ctx.profile()?.prefs.get();
let server={let state=ctx.chat_workflows.lock().await;state.snapshots.get(&key.connection_id).filter(|(current,_)|*current==key).map(|(_,snapshot)|snapshot.clone())};let Some(server)=server else{return Ok(())};
let catalog=crate::ui::i18n::Catalog::new(crate::ui::i18n::Language::from_code(prefs["language"].as_str().unwrap_or("en")));
let catalog=ctx.catalog;
let victim=event["nickname"].as_str().or_else(||server["clients"].as_array().and_then(|a|a.iter().find(|c|c["id"]==event["client_id"])).and_then(|c|c["nickname"].as_str())).unwrap_or("");
let invoker=event["invoker"]["name"].as_str().unwrap_or(victim);let by_invoker=event["invoker"]["name"].as_str().is_some();let reason=event["message"].as_str().unwrap_or("");
let targets={let state=ctx.chat_workflows.lock().await;state.conversations.iter().filter(|c|c.target.session==key).map(|c|c.target.clone()).collect::<Vec<_>>()};
+2
View File
@@ -52,6 +52,8 @@ pub struct IdentityImprovement {
}
pub struct RuntimeServices {
pub root:PathBuf,
/// The catalog loaded for this launch; saving a locale selects the next launch's catalog.
pub catalog: crate::ui::i18n::Catalog,
pub profile:Mutex<ProfileServices>,
pub connected:Arc<ConnectedServices>,
pub audio:AudioHandle,
+1 -1
View File
@@ -229,7 +229,7 @@ impl RuntimeServices {
pub async fn show_whisper_overlay(&self,key:SessionKey)->Result<WorkflowResult>{
self.require_key(&key,true)?;
let (targets,pending)={let status=lock(&self.settings_status)?;(status.whisper_targets.clone(),status.pending_whisper.clone())};
let prefs=self.profile()?.prefs.get();let catalog=crate::ui::i18n::Catalog::new(crate::ui::i18n::Language::from_code(prefs["language"].as_str().unwrap_or("en")));
let catalog=self.catalog;
let mut rows=targets.into_iter().map(|(label,value)|InfoRow{label,value}).collect::<Vec<_>>();
if let Some((pending_key,entry))=pending.filter(|(pending_key,_)|pending_key==&key){self.require_key(&pending_key,true)?;rows.push(InfoRow{label:catalog.text("clientMenu.whisper"),value:entry.name});}
let detail=Detail{title:catalog.text("settings.whisper.live_preview"),rows,..Detail::default()};
+1 -1
View File
@@ -180,7 +180,7 @@ pub async fn dispatch(ctx:Arc<RuntimeServices>,target:Target,operation:Operation
}ctx.changed().await?;Ok(result)
}
fn operation_for_refresh(operation:Operation)->Operation{use Operation::*;match operation{BanCreate|BanDelete|ClientBan=>ServerBans,KeyCreate|KeyDelete=>ServerKeys,PasswordCreate|PasswordDelete=>ServerPasswords,ClientDatabaseDelete=>ServerClients,PermissionSet|PermissionRemove|ClientChannelPermissionSet|ClientChannelPermissionRemove=>GroupPermissions,_=>operation}}
pub fn catalog(ctx:&RuntimeServices)->Result<crate::ui::i18n::Catalog>{Ok(crate::ui::i18n::Catalog::new(crate::ui::i18n::Language::from_code(ctx.profile()?.prefs.get()["language"].as_str().unwrap_or("en"))))}
pub fn catalog(ctx:&RuntimeServices)->Result<crate::ui::i18n::Catalog>{Ok(ctx.catalog)}
fn fill_server_edit(form: &mut Form, reply: &serde_json::Value, catalog: &crate::ui::i18n::Catalog) -> Result<()> {
let row = reply["rows"].as_array().and_then(|rows| match rows.as_slice() {
[row] => row.as_object(),
+2 -2
View File
@@ -1,7 +1,7 @@
//! Captured, capability-bound file workflows. No UI string is a host filesystem path.
use std::{collections::HashMap, path::PathBuf, sync::Arc};
use serde_json::Value;
use crate::{app::{connections::SessionKey,server_actions}, platform::resources::{DirectoryGrant,DocumentGrant}, services::{Result,ServiceError,files::FilesService,server_icons::IconListing}, ui::{i18n::{Catalog,Language},shell::*}};
use crate::{app::{connections::SessionKey,server_actions}, platform::resources::{DirectoryGrant,DocumentGrant}, services::{Result,ServiceError,files::FilesService,server_icons::IconListing}, ui::{i18n::Catalog,shell::*}};
use super::{context::{RuntimeServices,directory_key},events::{UiEffect,WorkflowResult}};
mod browser;
mod transfers;
@@ -141,7 +141,7 @@ pub async fn handle(ctx:Arc<RuntimeServices>,target:Target,operation:Operation,v
}
fn bad(message:&str)->ServiceError{ServiceError::new("bad_request",message)}
fn key(target:&Target)->Result<SessionKey>{target.session.clone().ok_or_else(||bad("A captured server session is required"))}
fn catalog(ctx:&RuntimeServices)->Result<Catalog>{Ok(Catalog::new(Language::from_code(ctx.profile()?.prefs.get()["language"].as_str().unwrap_or("en"))))}
fn catalog(ctx:&RuntimeServices)->Result<Catalog>{Ok(ctx.catalog)}
fn files(ctx:&RuntimeServices)->Result<Arc<tokio::sync::Mutex<FilesService>>>{Ok(ctx.profile()?.files.clone())}
fn text(values:&Values,id:&str)->Result<String>{match values.get(id){Some(FieldValue::Text(v)|FieldValue::Choice(v))=>Ok(v.clone()),None=>Ok(String::new()),_=>Err(bad("Expected text"))}}
fn number(values:&Values,id:&str)->Result<u64>{match values.get(id){Some(FieldValue::Integer(v))=>u64::try_from(*v).map_err(|_|bad("Expected nonnegative integer")),Some(FieldValue::Choice(v))=>v.parse().map_err(|_|bad("Expected a source identifier")),_=>Err(bad("Missing source identifier"))}}
@@ -131,7 +131,7 @@ mod tests {
#[test]
fn s3_browser_projects_navigation_but_not_file_actions() {
let c=Catalog::new(Language::En);
let c=Catalog::default();
let target=Target{session:Some(SessionKey{connection_id:"c9".into(),session:0,generation:12}),entity:Entity::File{channel_id:4,path:"/docs/".into(),directory:true},..Target::application()};
let mut reply=json!({"channel_id":4,"path":"/docs/","entries":[{"name":"nested","type":"folder"},{"name":"notes.txt","type":"file","size":7}],"capabilities":{"browse":true,"upload":true,"create_directory":true,"download":true,"rename":true,"delete":true}});
let server=json!({"server":{"features":{"file_transfer_s3":true,"file_transfer_http":true}}});
+2 -2
View File
@@ -1,7 +1,7 @@
//! Local application workflows. Inputs are typed form values; no user string is a host path.
use std::sync::Arc;
use serde_json::{Value,json};
use crate::{app::connections::SessionKey,services::{Result,ServiceError,profile::ProfileServices},ui::{i18n::{Catalog,Language},shell::*}};
use crate::{app::connections::SessionKey,services::{Result,ServiceError,profile::ProfileServices},ui::{i18n::Catalog,shell::*}};
use super::{context::{RuntimeServices,changed,connection_error},events::{UiEffect,WorkflowResult}};
mod connections;
mod bookmarks;
@@ -32,7 +32,7 @@ pub async fn handle(ctx:Arc<RuntimeServices>,target:Target,operation:Operation,v
}
fn bad(message:impl Into<String>)->ServiceError{ServiceError::new("bad_request",message)}
fn key(target:&Target)->Result<SessionKey>{target.session.clone().ok_or_else(||bad("A captured server session is required"))}
fn catalog(ctx:&RuntimeServices)->Result<Catalog>{Ok(Catalog::new(Language::from_code(ctx.profile()?.prefs.get()["language"].as_str().unwrap_or("en"))))}
fn catalog(ctx:&RuntimeServices)->Result<Catalog>{Ok(ctx.catalog)}
fn text(values:&Values,id:&str)->Result<String>{match values.get(id){Some(FieldValue::Text(v)|FieldValue::Choice(v))=>Ok(v.clone()),None=>Ok(String::new()),_=>Err(bad(format!("Expected text for {id}")))}}
fn boolean(values:&Values,id:&str)->Result<bool>{match values.get(id){Some(FieldValue::Bool(v))=>Ok(*v),None=>Ok(false),_=>Err(bad(format!("Expected boolean for {id}")))}}
fn optional(value:String)->Option<String>{if value.trim().is_empty(){None}else{Some(value.trim().to_owned())}}
@@ -90,7 +90,7 @@ async fn edit(ctx:&Arc<RuntimeServices>,target:Target,operation:Operation,values
async fn move_item(ctx:&Arc<RuntimeServices>,target:Target,values:Values)->Result<()>{
let id=item_id(&target)?;let original=ctx.profile()?.prefs.get();let current=store::parent_of(&original,&id)?;
let descendants=store::descendants(&original,&id);let mut editor=form(ctx,&target,Operation::BookmarkMove)?;
let c=Catalog::new(Language::from_code(original["language"].as_str().unwrap_or("en")));
let c=ctx.catalog;
let option=|v:&Value|Some(OptionValue{value:v["id"].as_str()?.into(),label:v["name"].as_str().filter(|name|!name.is_empty()).map_or_else(||c.text("bookmarks.folder.empty_name"),str::to_owned)});
let mut folders=vec![OptionValue{value:"root".into(),label:"Root".into()}];folders.extend(original["bookmarkFolders"].as_array().into_iter().flatten().filter(|f|f["id"]!=id&&!f["id"].as_str().is_some_and(|s|descendants.contains(s))).filter_map(option));
choices(&mut editor,"parent_id",folders,current.unwrap_or_else(||"root".into()));
+1
View File
@@ -73,6 +73,7 @@ async fn construct(config:&AppConfig,profile:ProfileServices,runtime:Weak<AppRun
#[cfg(target_os="ios")]apple_call:Default::default(),
#[cfg(target_os="android")]android_notifications:Default::default(),
root:root.clone(),profile:Mutex::new(profile),connected,audio,streams,
catalog: crate::ui::i18n::Catalog::new(crate::ui::i18n::Language::from_code(prefs["language"].as_str().unwrap_or("en"))),
themes:Mutex::new(crate::services::themes::ThemeService::new(root.join("extensions"),prefs["userStyle"].as_str().map(str::to_owned))),
phishing,badges,
notifications:Mutex::new(crate::services::notifications::Notifications::new(serde_json::from_value(prefs.clone())?)?),
+3 -3
View File
@@ -1,6 +1,6 @@
//! Send-only presentation state. Slint Images are created exclusively by the attachment.
use std::{collections::{BTreeSet, HashMap, HashSet},sync::Arc};
use crate::{app::connections::{ConnectionsSnapshot,SessionKey},ui::{shell::*,settings::{SettingsSnapshot,ViewState},chat::ChatPresentation,i18n::{Catalog,Language}}};
use crate::{app::connections::{ConnectionsSnapshot,SessionKey},ui::{shell::*,settings::{SettingsSnapshot,ViewState},chat::ChatPresentation,i18n::Catalog}};
use super::{context::RuntimeServices,events::{SnapshotUpdate,UiEffect}};
use crate::services::snapshots::{CreatedChanges,SnapshotProgress,SnapshotReport,SnapshotTargetKind};
@@ -330,7 +330,7 @@ impl AppState {
super::notification_actions::project_recent_events(&mut self.snapshot.detail,&mut self.recent_events_stamp,target,notifications,catalog,use_24h,epoch_ms);
}
pub async fn project(&mut self,ctx:&RuntimeServices)->crate::services::Result<()> {
let prefs=ctx.profile()?.prefs.get();let c=Catalog::new(Language::from_code(prefs["language"].as_str().unwrap_or("en")));
let prefs=ctx.profile()?.prefs.get();let c=ctx.catalog;
self.snapshot.catalog=c;let connections=ctx.connected.connections.snapshot();
self.expire_snapshot(ctx.current_ui_generation().ok(), &connections);
self.snapshot.tabs=connections.connections.iter().map(|connection|{
@@ -934,7 +934,7 @@ mod tests {
let second=connection("second","Second Server",2);
let mut connections=ConnectionsSnapshot{connections:vec![first.clone(),second.clone()],viewed_id:Some(first.key.connection_id.clone()),..Default::default()};
let en=Catalog::default();
let ru=Catalog::new(Language::Ru);
let ru=Catalog::new(crate::ui::i18n::Language::Ru);
let epoch_ms=1_700_000_000_000;
let prefs=NotificationPrefs::default().with_state("someone_moved_in",0).unwrap();
let mut notifications=Notifications::new(prefs).unwrap();
+1 -1
View File
@@ -94,7 +94,7 @@ async fn open_settings_link(ctx:&Arc<RuntimeServices>,url:&str,package_link:bool
let approved=match prompt.decision {
LinkDecision::Pass if !package_link=>true,
decision=>{
let catalog=crate::ui::i18n::Catalog::new(crate::ui::i18n::Language::from_code(values["language"].as_str().unwrap_or("en")));
let catalog=ctx.catalog;
let description=if decision==LinkDecision::Pass {catalog.format("themes.link.confirm",&[("url",prompt.url())])}else{
let warning=catalog.text(if decision==LinkDecision::WarnMalicious{"url.external.malicious_warning"}else{"url.external.non_official_url_below_warning"});
format!("{warning}\n{}",prompt.url())
@@ -9,6 +9,28 @@ pub(super) async fn edit(ctx:Arc<RuntimeServices>,field:Field,value:SettingValue
patch(&ctx,"outputLevelDb",json!(db)).await?;
audio::set_voice_level(&ctx,db).await?;
},
Field::Preference(Preference::Language) => {
let value = text(value)?;
let restart = value != ctx.catalog.language.code();
patch(&ctx, "language", json!(value)).await?;
if cfg!(not(any(target_os = "android", target_os = "ios"))) && restart {
use crate::ui::shell::{Form, Operation as ShellOperation, Target};
let c = ctx.catalog;
let form = Form {
id: String::new(), target: Target::application(), operation: ShellOperation::ConfirmOverwrite,
title: c.text("language.label"),
description: c.text("settings.appearance.language.warning.restart_required.popup"),
submit_label: c.text("ui.restart.now"),
fields: Vec::new(), confirmation: None, destructive: false, busy: false,
error: String::new(), actions: Vec::new(), acknowledged_revision: 0,
};
match ctx.prompt(form).await {
Ok(_) => ctx.relaunch().await?,
Err(error) if error.code == "cancelled" => (),
Err(error) => return Err(error),
}
}
},
Field::Preference(pref)=>{
let hardware=matches!(pref,Preference::HardwareVideoDecode);let update=matches!(pref,Preference::UpdateChannel);
let audio=matches!(pref,Preference::AutoEnableMicrophone|Preference::AutoReactivateMicOnPreviousTarget);
@@ -6,7 +6,7 @@ pub fn project(ctx:&RuntimeServices,view:&ViewState)->Result<SettingsSnapshot>{
let mut snapshot=lock(&ctx.settings_status)?.clone();
if view.page()==Page::TrustedHosts { snapshot.threat_list=ctx.phishing.availability(); }
let profile=ctx.profile()?;snapshot.prefs=profile.prefs.get();
snapshot.rich_documents=crate::ui::settings::prepare_help(&crate::ui::i18n::Catalog::new(crate::ui::i18n::Language::from_code(snapshot.prefs["language"].as_str().unwrap_or("en"))));
snapshot.rich_documents=crate::ui::settings::prepare_help(&ctx.catalog);
let bookmarks=crate::services::bookmarks::all_bookmarks(&snapshot.prefs,None)?;
let active=lock(&ctx.improvement)?;let progress=lock(&ctx.progress)?;
let identities=profile.identities.list()?.identities;
+2 -2
View File
@@ -1,6 +1,6 @@
//! Stream workflows retain consent/presentation only; StreamHub owns every signaling session.
use std::{collections::HashMap,sync::Arc};
use crate::{app::connections::SessionKey,media::stream::{directory::ChannelOffer,publisher::{PublisherState,StreamPublisher},signal::StreamError,viewer::StreamViewer},services::{Result,ServiceError},ui::{i18n::{Catalog,Language},shell::*}};
use crate::{app::connections::SessionKey,media::stream::{directory::ChannelOffer,publisher::{PublisherState,StreamPublisher},signal::StreamError,viewer::StreamViewer},services::{Result,ServiceError},ui::{i18n::Catalog,shell::*}};
use super::{context::{RuntimeServices,changed},events::{UiEffect,WorkflowResult}};
#[cfg(feature="webrtc")]
use crate::media::stream::publisher::{Privacy,PublisherOptions};
@@ -220,7 +220,7 @@ fn require_owner(ctx:&RuntimeServices,target:&Target,id:u16)->Result<()> {
fn bad(message:&str)->ServiceError{ServiceError::new("bad_request",message)}
fn stream_error(error:StreamError)->ServiceError{ServiceError::new(&error.code,error.message)}
fn key(target:&Target)->Result<SessionKey>{target.session.clone().ok_or_else(||bad("A captured server session is required"))}
fn catalog(ctx:&RuntimeServices)->Result<Catalog>{Ok(Catalog::new(Language::from_code(ctx.profile()?.prefs.get()["language"].as_str().unwrap_or("en"))))}
fn catalog(ctx:&RuntimeServices)->Result<Catalog>{Ok(ctx.catalog)}
fn action(target:&Target,operation:Operation,catalog:&Catalog)->Action{
let id=match &target.entity{
Entity::CaptureFlow{id}=>format!("stream/{operation:?}/{id}"),
+63 -18
View File
@@ -15,6 +15,7 @@ mod focus;
#[cfg(all(test, windows))] mod detached_voice;
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod theme_selection;
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod display_size;
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod language;
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod channel_commander;
#[cfg(all(test,not(any(target_os="android",target_os="ios"))))] mod speaker_gain;
#[cfg(feature="webrtc")] pub mod media;
@@ -66,6 +67,7 @@ struct Driver {
runtime:Arc<AppRuntime>,
chat:Option<chat::ChatFixture>,
output:PathBuf,
restarted_language: Option<&'static str>,
step:Step,
phase_started:Instant,
checks:Vec<Value>,
@@ -81,8 +83,8 @@ struct Driver {
result:Option<SmokeResult<()>>,
}
#[derive(Clone,Copy,Debug)]
enum Step {Boot,Onboarding,Category{index:usize,requested:bool},Variant{index:usize,requested:bool},Markup{requested:bool},Capture{requested:bool},Chat,Done}
const VARIANTS:[(&str,&str,u32);12]=[("en","dark",1280),("en","dark",800),("en","dark",390),("en","light",1280),("en","light",800),("en","light",390),("ru","dark",1280),("ru","dark",800),("ru","dark",390),("ru","light",1280),("ru","light",800),("ru","light",390)];
enum Step {Boot,Onboarding,Category{index:usize,requested:bool},Variant{index:usize,requested:bool},SaveOtherLocale{serial:Option<u64>,dismissed:bool},Markup{requested:bool},Capture{requested:bool},Chat,Done}
const VARIANTS: [(&str,u32);6] = [("dark",1280),("dark",800),("dark",390),("light",1280),("light",800),("light",390)];
#[cfg(not(any(target_os = "android", target_os = "ios")))]
#[derive(Default)]
@@ -204,7 +206,12 @@ impl Driver {
if snapshot.bootstrap==BootstrapState::Ready && snapshot.settings.loaded {
self.uid=Some(default_uid(&snapshot)?);
ui.global::<ShellBridge>().invoke_navigate(3);
self.transition(Step::Category{index:0,requested:false});
if let Some(language) = self.restarted_language {
if snapshot.catalog.language.code() != language { return Err("reopened profile did not apply its saved language".into()); }
self.transition(Step::Variant{index:0,requested:false});
} else {
self.transition(Step::Category{index:0,requested:false});
}
} else if ui.global::<DialogBridge>().get_visible() && ui.global::<DialogBridge>().get_fields().iter().any(|field|field.id=="nickname") {
self.capture("onboarding.png")?;
let dialog=self.attachment.window().global::<DialogBridge>();
@@ -251,8 +258,10 @@ impl Driver {
}
},
Step::Variant{index,requested}=>{
let(language,theme,width)=VARIANTS[index];
let(theme,width)=VARIANTS[index];
let language=snapshot.catalog.language.code();
let settings=ui.global::<SettingsBridge>();
if ui.global::<ShellBridge>().get_destination()!=3 {return Ok(false)}
#[cfg(not(any(target_os="android",target_os="ios")))]
if !requested && ui.window().size().width != width {
ui.window().set_size(slint::PhysicalSize::new(width,800));
@@ -278,7 +287,6 @@ impl Driver {
if !requested {
let row = settings.get_rows().iter().find(|row|row.stable_id=="theme").ok_or("stock theme selector missing")?;
focus::choose_tile(ui, row.title.as_str(), if theme_index == 0 { "Dark" } else { "Light" })?;
choose(ui,"language",language_index as i32)?;
self.variant_check = 0;
self.step=Step::Variant{index,requested:true};return Ok(false)
}
@@ -301,8 +309,32 @@ impl Driver {
self.capture(&format!("{language}-{theme}-{width}.png"))?;
if index+1<VARIANTS.len() {self.transition(Step::Variant{index:index+1,requested:false})}
else {
self.checks.push(json!({"name":"responsive-render","passed":true,"languages":["en","ru"],"themes":["dark","light"],"desktop_widths":if cfg!(any(target_os="android",target_os="ios")){vec![]}else{vec![390,800,1280]},"mobile_scope":"current physical viewport only; device rotation/tablet/accessibility acceptance remains separate"}));
self.checks.push(json!({"name":"responsive-render","passed":true,"languages":[language],"themes":["dark","light"],"desktop_widths":if cfg!(any(target_os="android",target_os="ios")){vec![]}else{vec![390,800,1280]},"mobile_scope":"current physical viewport only; device rotation/tablet/accessibility acceptance remains separate"}));
self.transition(if self.restarted_language.is_some() { Step::Done }
else { Step::SaveOtherLocale { serial: None, dismissed: false } });
}
},
Step::SaveOtherLocale{serial,dismissed}=>{
let active=snapshot.catalog.language.code();
let alternate=if active=="en"{"ru"}else{"en"};
let dialog=ui.global::<DialogBridge>();
if let Some(serial)=serial {
if snapshot.settings_completed < serial {
if !dismissed && dialog.get_visible() {
if dialog.get_title()!=snapshot.catalog.text("language.label") {return Err("unexpected language restart dialog".into());}
dialog.invoke_cancel();
self.step=Step::SaveOtherLocale{serial:Some(serial),dismissed:true};
}
return Ok(false)
}
if snapshot.last_error.is_some() || snapshot.settings.prefs["language"]!=alternate || dialog.get_visible() {
return Err("language restart handoff did not preserve the alternate preference".into());
}
self.transition(Step::Markup{requested:false});
} else {
let choice=ui.global::<SettingsBridge>().get_rows().iter().find(|row|row.stable_id=="language"&&row.enabled).ok_or("language selector unavailable before restart")?;
ui.global::<SettingsBridge>().invoke_choice_value(choice.token,i32::from(alternate=="ru"));
self.step=Step::SaveOtherLocale{serial:Some(snapshot.settings_completed+1),dismissed:false};
}
},
Step::Markup{requested}=>{
@@ -360,11 +392,6 @@ impl Driver {
Ok(false)
}
}
fn choose(ui:&AppWindow,id:&str,index:i32)->SmokeResult<()> {
let settings=ui.global::<SettingsBridge>();
let row=settings.get_rows().iter().find(|row|row.stable_id==id&&row.enabled).ok_or_else(||format!("setting {id} is not reachable"))?;
settings.invoke_choice_value(row.token,index);Ok(())
}
fn default_uid(snapshot:&crate::app::runtime::model::Snapshot)->SmokeResult<String> {
snapshot.settings.identities.iter().find(|identity|identity.is_default).map(|identity|identity.uid.clone()).ok_or_else(||"ready native profile has no default identity".into())
}
@@ -378,12 +405,10 @@ fn screenshot(ui:&AppWindow,output:&std::path::Path,name:&str)->SmokeResult<Valu
Ok(json!({"path":name,"width":size.width,"height":size.height}))
}
pub(crate) fn run_prepared(runtime:Arc<AppRuntime>,generation:u64,prepared:Prepared)->Result<(),AppError> {
if runtime.config.allow_os_actions || runtime.config.network_enabled || runtime.config.profile_dir.as_ref()!=Some(&prepared.profile) {return Err(error("smoke runtime isolation mismatch"))}
let config=runtime.config.clone();
fn drive(runtime: Arc<AppRuntime>, generation: u64, output: PathBuf, restarted_language: Option<&'static str>) -> Result<(Driver, SmokeResult<()>), AppError> {
let attachment=crate::ui::application::bind(runtime.clone(),generation)?;
let chat=chat::ChatFixture::new(prepared.output.clone()).map_err(error)?;
let driver=Rc::new(RefCell::new(Driver {attachment,runtime:runtime.clone(),chat:Some(chat),output:prepared.output.clone(),step:Step::Boot,phase_started:Instant::now(),checks:vec![],screenshots:vec![],uid:None,capture_completed:0,navigation_target:None,settings_scroll:Default::default(),variant_check:0,requested_assets:Default::default(),result:None,
let chat=if restarted_language.is_none(){Some(chat::ChatFixture::new(output.clone()).map_err(error)?)}else{None};
let driver=Rc::new(RefCell::new(Driver {attachment,runtime,chat,output,restarted_language,step:Step::Boot,phase_started:Instant::now(),checks:vec![],screenshots:vec![],uid:None,capture_completed:0,navigation_target:None,settings_scroll:Default::default(),variant_check:0,requested_assets:Default::default(),result:None,
#[cfg(not(any(target_os = "android", target_os = "ios")))]
unavailable_notifications: Default::default(),
}));
@@ -395,11 +420,18 @@ pub(crate) fn run_prepared(runtime:Arc<AppRuntime>,generation:u64,prepared:Prepa
let event_result=slint::run_event_loop().map_err(|error|error.to_string());
timer.stop();drop(timer);
let mut driver=Rc::try_unwrap(driver).map_err(|_|error("smoke UI state retained after timer shutdown"))?.into_inner();
let mut result=event_result.and_then(|_|driver.result.take().unwrap_or_else(||Err("native event loop exited before smoke completed".into())));
let result=event_result.and_then(|_|driver.result.take().unwrap_or_else(||Err("native event loop exited before smoke completed".into())));
Ok((driver,result))
}
pub(crate) fn run_prepared(runtime:Arc<AppRuntime>,generation:u64,prepared:Prepared)->Result<(),AppError> {
if runtime.config.allow_os_actions || runtime.config.network_enabled || runtime.config.profile_dir.as_ref()!=Some(&prepared.profile) { return Err(error("smoke runtime isolation mismatch")); }
let config=runtime.config.clone();
let (mut driver,mut result)=drive(runtime.clone(),generation,prepared.output.clone(),None)?;
if let Some(chat)=driver.chat.take(){if let Err(error)=chat.finish(){result=Err(error)}}
let uid=driver.uid.take();
let mut previous_ui_generation=driver.attachment.generation();
let mut checks=std::mem::take(&mut driver.checks);let screenshots=std::mem::take(&mut driver.screenshots);
let mut checks=std::mem::take(&mut driver.checks);let mut screenshots=std::mem::take(&mut driver.screenshots);
drop(driver); // release UI attachment before joining the services
let worker=tokio::runtime::Builder::new_current_thread().enable_all().build()?;
if let Err(error)=worker.block_on(runtime.shutdown()){result=Err(error.to_string())}
@@ -446,6 +478,19 @@ pub(crate) fn run_prepared(runtime:Arc<AppRuntime>,generation:u64,prepared:Prepa
Ok(())
});
}
if result.is_ok() {
let language=if final_snapshot.catalog.language.code()=="en"{"ru"}else{"en"};
let reopened=AppRuntime::start(config)?;
let rendered=drive(reopened.clone(),0,prepared.output.clone(),Some(language)).map_err(|e|e.to_string());
result=rendered.and_then(|(mut driver,outcome)| {
checks.append(&mut driver.checks);
screenshots.append(&mut driver.screenshots);
outcome
});
if let Err(error)=worker.block_on(reopened.shutdown()){result=Err(error.to_string())}
let state=reopened.snapshot();
if state.audio_input_starts!=0 || state.audio_output_starts!=0 {result=Err("reopened UI activated a physical endpoint".into())}
}
let report=json!({"schema":1,"engine":"rust-slint","version":env!("CARGO_PKG_VERSION"),"target":env!("TEAMSPEACH_BUILD_TARGET"),"scenario":prepared.scenario,"passed":result.is_ok(),"error":result.as_ref().err(),"profile_dir":prepared.profile,"network_enabled":false,"os_actions_enabled":false,"physical_capture_enabled":false,"local_peer_transport":prepared.scenario=="media-loopback","renderer":if cfg!(any(target_os="android",target_os="ios")){"native-device"}else{"Slint software offscreen"},"checks":checks,"screenshots":screenshots});
let bytes=serde_json::to_vec_pretty(&report).map_err(error)?;
fs::write(prepared.output.join("result.json.tmp"),bytes)?;
+172
View File
@@ -0,0 +1,172 @@
use super::{SmokeResult, focus, headless, identities::{ack, row, run_ui, wait}, screenshot,
whisper::{click, find_label}};
use crate::{AppConfig, AppRuntime, AppWindow, DialogBridge, Theme,
app::runtime::model::BootstrapState,
services::{profile::ProfileServices, profile_import::initialize_native_root}, ui::settings::Category};
use i_slint_core::{accessibility::AccessibleStringProperty as Prop, item_tree::ItemRc,
items::{AccessibleRole, ComplexText, SimpleText}, window::WindowInner};
use serde_json::{Value, json};
use slint::{ComponentHandle, PhysicalSize};
use std::{fs, path::Path, process::Command};
const TEST: &str = "smoke::language::language_applies_and_survives_process_restart";
const PHASE: &str = "TEAMSPEACH_LANGUAGE_TEST_PHASE";
const ROOT: &str = "TEAMSPEACH_LANGUAGE_TEST_ROOT";
#[derive(Clone, Copy)]
struct Locale { code: &'static str, option: &'static str, settings: &'static str, page: &'static str, label: &'static str }
const EN: Locale = Locale { code: "en", option: "English", settings: "Settings", page: "Appearance", label: "Language" };
const RU: Locale = Locale { code: "ru", option: "Русский", settings: "Настройки", page: "Внешний вид", label: "Язык" };
async fn select(runtime: &AppRuntime, ui: &AppWindow, before: Locale, after: Locale) -> SmokeResult<u64> {
let selector = focus::visible_selector(ui, before.label, AccessibleRole::Combobox)?;
click(ui, &selector)?;
let choice = wait(runtime, after.option, |_| {
WindowInner::from_pub(ui.window()).active_popups().iter().rev().find_map(|popup| {
find_label(ui, ItemRc::new_root(popup.component.clone()), after.option, |_| true)
})
}).await?;
let serial = runtime.snapshot().settings_completed + 1;
click(ui, &choice)?;
Ok(serial)
}
async fn observe(runtime: &AppRuntime, ui: &AppWindow, locale: Locale, selected: Locale, expected: &Value, evidence: &Path, tag: &str) -> SmokeResult<()> {
let page = wait(runtime, "localized Appearance panel", |s| {
(s.catalog.language.code() == locale.code).then(|| focus::visible_selector(ui, locale.page, AccessibleRole::Groupbox).ok()).flatten()
}).await?;
let combo = focus::visible_selector(ui, locale.label, AccessibleRole::Combobox)?;
assert_eq!(combo.accessible_string_property(Prop::Value).unwrap().as_str(), selected.option);
let warning = runtime.snapshot().catalog.text("settings.appearance.language.warning.restart_required");
assert_eq!(focus::visible_selector(ui, &warning, AccessibleRole::Text).is_ok(), locale.code != selected.code);
focus::visible_selector(ui, locale.settings, AccessibleRole::Button)?;
assert_eq!(runtime.snapshot().settings.prefs, *expected);
let mut caption = None;
headless::visit_named_items(ui.window(), |id, item| {
if id != "parity-appearance-select-caption" { return; }
let value = item.downcast::<SimpleText>().map(|t| t.as_pin_ref().text())
.or_else(|| item.downcast::<ComplexText>().map(|t| t.as_pin_ref().text()));
if value.is_some_and(|text| text == selected.option) {
caption = headless::visible_bounds(ui.window(), item);
}
})?;
let caption = caption.ok_or("selected caption not rendered")?;
let width = ui.invoke_measure_chat(selected.option.into(), ui.global::<Theme>().get_font_size(), 400, false, false).width;
let panel = headless::visible_bounds(ui.window(), &page).ok_or("Appearance panel not rendered")?;
assert!(caption.size.width >= width && panel.contains(caption.center()), "selected caption is clipped: {caption:?}, text width {width}");
let snapshot = screenshot(ui, evidence, &format!("{tag}.png"))?;
println!("pid={} {tag}: {} / {} / {} ({:.0}px caption for {:.0}px text), {:?}", std::process::id(), locale.page, locale.label, selected.option, caption.size.width, width, snapshot);
Ok(())
}
fn phase(suite: &Path, initial: Locale, target: Locale, phase: &str) -> SmokeResult<()> {
headless::install()?;
let dir = suite.to_path_buf();
let profile = dir.join("profile");
let prefs = profile.join("prefs.json");
let baseline: Value = serde_json::from_slice(&fs::read(dir.join("baseline.json")).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
let mut expected = baseline.clone();
expected["language"] = target.code.into();
let write = phase == "save";
let start = if write { initial } else { target };
let config = AppConfig::isolated(profile);
run_ui(&config, async move |runtime, ui| {
ui.window().set_size(PhysicalSize::new(900, 800));
let settings = wait(runtime, "localized Settings button at startup", |s| {
if s.bootstrap != BootstrapState::Ready || !s.settings.loaded || s.catalog.language.code() != start.code { return None; }
focus::visible_selector(ui, start.settings, AccessibleRole::Button).ok()
}).await?;
click(ui, &settings)?;
let appearance = wait(runtime, "localized Appearance category at startup", |s| {
if s.destination != crate::ui::shell::Destination::Settings { return None; }
focus::visible_selector(ui, start.page, AccessibleRole::Button).ok()
}).await?;
let serial = runtime.snapshot().settings_completed + 1;
click(ui, &appearance)?;
ack(runtime, serial, "open Appearance", None).await?;
wait(runtime, "rendered Appearance rows", |_| row(ui, "language").filter(|r| r.title == start.label)).await?;
assert!(runtime.snapshot().settings_view.category == Category::Appearance);
let disk = || -> SmokeResult<Value> { serde_json::from_slice(&fs::read(&prefs).map_err(|e| e.to_string())?).map_err(|e| e.to_string()) };
if write {
observe(runtime, ui, initial, initial, &baseline, &dir, "initial").await?;
let mut expected_disk = disk()?;
expected_disk["language"] = target.code.into();
let serial = select(runtime, ui, initial, target).await?;
let dialog = ui.global::<DialogBridge>();
let c = runtime.snapshot().catalog;
let restart = c.text("ui.restart.now");
let cancel = c.text("native.action.cancel");
let description = c.text("settings.appearance.language.warning.restart_required.popup");
let (accept, decline) = wait(runtime, "visible localized restart prompt after save", |s| {
if s.settings.prefs != expected || !dialog.get_visible() || dialog.get_description() != description { return None; }
focus::visible_selector(ui, initial.label, AccessibleRole::Form).ok()?;
Some((focus::visible_selector(ui, &restart, AccessibleRole::Button).ok()?,
focus::visible_selector(ui, &cancel, AccessibleRole::Button).ok()?))
}).await?;
assert!(focus::visible_selector(ui, &c.text("native.form.advanced"), AccessibleRole::Button).is_err());
assert_eq!(disk()?, expected_disk);
observe(runtime, ui, initial, target, &expected, &dir, "restart-prompt").await?;
let confirm = initial.code == "ru";
click(ui, if confirm { &accept } else { &decline })?;
ack(runtime, serial, "restart dialog response", confirm.then_some("os_actions_disabled")).await?;
wait(runtime, "restart prompt dismissed", |_| (!dialog.get_visible()).then_some(())).await?;
observe(runtime, ui, initial, target, &expected, &dir, if confirm { "isolated-confirm" } else { "declined" }).await?;
assert_eq!(disk()?, expected_disk);
} else {
assert_eq!(disk()?["language"], target.code);
observe(runtime, ui, target, target, &expected, &dir, "reopened").await?;
let before = fs::read(&prefs).map_err(|e| e.to_string())?;
let blocker = prefs.with_extension("json.tmp");
fs::create_dir(&blocker).map_err(|e| e.to_string())?;
let refused = async {
let serial = select(runtime, ui, target, initial).await?;
ack(runtime, serial, "blocked language save", Some("io")).await?;
Ok::<(), String>(())
}.await;
fs::remove_dir(blocker).map_err(|e| e.to_string())?;
refused?;
assert_eq!(fs::read(&prefs).map_err(|e| e.to_string())?, before);
assert!(!ui.global::<DialogBridge>().get_visible());
observe(runtime, ui, target, target, &expected, &dir, "rejected").await?;
}
Ok(())
})
}
#[test]
fn language_applies_and_survives_process_restart() {
let variants = [("en-dark", EN, RU, "dark"), ("ru-light", RU, EN, "light")];
if let Some(phase_name) = std::env::var_os(PHASE) {
let suite = std::path::PathBuf::from(std::env::var_os(ROOT).unwrap());
let (_, initial, target, _) = variants.into_iter().find(|&(name, ..)| suite.ends_with(name)).unwrap();
phase(&suite, initial, target, phase_name.to_str().unwrap()).unwrap();
return;
}
let temp = std::env::var_os("TEAMSPEACH_LANGUAGE_EVIDENCE").is_none().then(|| tempfile::tempdir().unwrap());
let output = temp.as_ref().map(|dir| dir.path().to_owned())
.unwrap_or_else(|| std::path::PathBuf::from(std::env::var_os("TEAMSPEACH_LANGUAGE_EVIDENCE").unwrap()));
for (name, initial, target, theme) in variants {
let suite = output.join(name);
fs::create_dir(&suite).unwrap();
let root = suite.join("profile");
initialize_native_root(&root).unwrap();
let baseline = {
let mut profile = ProfileServices::open(&root).unwrap();
profile.identities.onboard("Language QA").unwrap();
profile.prefs.set(json!({"language": initial.code, "theme": theme, "displaySize": "large"})).unwrap();
profile.prefs.get()
};
fs::write(suite.join("baseline.json"), serde_json::to_vec_pretty(&baseline).unwrap()).unwrap();
for step in ["save", "reopen"] {
let result = Command::new(std::env::current_exe().unwrap()).args(["--exact", TEST, "--nocapture"])
.env(PHASE, step).env(ROOT, &suite).output().unwrap();
let stdout = String::from_utf8_lossy(&result.stdout);
let stderr = String::from_utf8_lossy(&result.stderr);
fs::write(suite.join(format!("{step}.log")), format!("{stdout}{stderr}")).unwrap();
assert!(result.status.success() && stdout.contains("1 passed"), "{name} {step}: {stdout}{stderr}");
print!("{stdout}");
}
fs::remove_dir_all(suite.join("profile")).unwrap();
println!("{name}: {} -> {} saved, reopened in a new process and rejected reverse write preserved disk and UI", initial.code, target.code);
}
}
+3 -3
View File
@@ -35,7 +35,7 @@ fn seed(root: &Path, bytes: &[u8]) -> SmokeResult<()> {
}
// Accessible containers do not enumerate their own descendants through the shallow role iterator.
fn find_label(ui: &AppWindow, root: ItemRc, label: &str, matches: impl Fn(&ItemRc) -> bool) -> Option<ItemRc> {
pub(super) fn find_label(ui: &AppWindow, root: ItemRc, label: &str, matches: impl Fn(&ItemRc) -> bool) -> Option<ItemRc> {
let mut stack = vec![root];
for _ in 0..16_384 {
let item = stack.pop()?;
@@ -68,8 +68,8 @@ fn dispatch(ui: &AppWindow, event: WindowEvent) -> SmokeResult<()> {
ui.window().dispatch_event_with_result(event).map(|_| ()).map_err(|e| e.to_string())
}
fn click(ui: &AppWindow, item: &ItemRc) -> SmokeResult<()> {
headless::visible_bounds(ui.window(), item).ok_or("Whisper control is not visible")?;
pub(super) fn click(ui: &AppWindow, item: &ItemRc) -> SmokeResult<()> {
headless::visible_bounds(ui.window(), item).ok_or("Control is not visible")?;
// Slint's embedded ComboBox popup has its own coordinate space.
let center = item.map_to_native_window(item.geometry().center());
let position = LogicalPosition::new(center.x, center.y);
+4 -9
View File
@@ -95,12 +95,7 @@ pub fn bind(ui:&AppWindow,emit:Arc<dyn Fn(SettingsAction)+Send+Sync>)->Binding{
{let emit=emit.clone();bridge.on_back(move ||emit(SettingsAction::Invoke(Operation::Navigate(Navigation::Back))));}
{let state=state.clone();let emit=emit.clone();bridge.on_invoke(move |token|{
let Some(r)=row(&state,token.as_str())else{return;};
let op = match r.intent {
Intent::Invoke(op) => op,
Intent::Edit(Field::Preference(Preference::Language))
if matches!(r.control, Control::AppearanceChoice { style: AppearanceChoice::Language { .. }, .. }) => Operation::Relaunch,
_ => return,
};
let Intent::Invoke(op) = r.intent else { return; };
// Submit companion draft before the operation, in the same ordered action stream. The host
// reducer stores these local command parameters, not a preference or a claim of persistence.
let companion=match &op{Operation::IdentityCreate=>Some(("identity-new-name".to_owned(),Field::NewIdentityName)),Operation::KeyProfileCreate=>Some(("key-new-name".to_owned(),Field::NewKeyProfileName)),Operation::WhisperCreate=>Some(("whisper-new-name".to_owned(),Field::NewWhisperName)),Operation::IdentityImprove(uid)=>Some((format!("identity-target:{uid}"),Field::IdentityTarget(uid.clone()))),_=>None};
@@ -216,11 +211,11 @@ pub fn present(ui:&AppWindow,binding:&Binding,p:Presentation){
if state.drafts.get(&r.id)==Some(&value){state.drafts.remove(&r.id);}
let value=state.drafts.get(&r.id).cloned().unwrap_or(value);
let rich=if let Control::Rich{source,document}=&r.control{crate::ui::chat::preview_document(ui,source,document,ui.window().size().width as f32/ui.window().scale_factor()).into_iter().collect()}else{Vec::new()};
let command_label = match &r.control {
Control::AppearanceChoice { style: AppearanceChoice::Language { restart }, .. } => restart.as_str().into(),
let restart_notice = match &r.control {
Control::AppearanceChoice { style: AppearanceChoice::Language { restart_notice }, .. } => restart_notice.as_str().into(),
_ => SharedString::default(),
};
let rendered = SettingsRow{token:token.clone().into(),stable_id:r.id.clone().into(),title:r.title.clone().into(),subtitle:r.subtitle.clone().into(),kind,checked,value:value.into(),options:model(options),selected,enabled:r.enabled,destructive:r.destructive,inset:r.inset,error:r.error.clone().into(),meter,decrease:p.decrease_template.replace("{name}",&r.title).into(),increase:p.increase_template.replace("{name}",&r.title).into(),rich:model(rich),section_start,section_end,stacked:r.stacks_desktop_control(),command_label};
let rendered = SettingsRow{token:token.clone().into(),stable_id:r.id.clone().into(),title:r.title.clone().into(),subtitle:r.subtitle.clone().into(),kind,checked,value:value.into(),options:model(options),selected,enabled:r.enabled,destructive:r.destructive,inset:r.inset,error:r.error.clone().into(),meter,decrease:p.decrease_template.replace("{name}",&r.title).into(),increase:p.increase_template.replace("{name}",&r.title).into(),rich:model(rich),section_start,section_end,stacked:r.stacks_desktop_control(),restart_notice};
if let Some(column) = appearance_page.then(|| r.appearance_server_column()).flatten() {
if server_user_rows.is_empty() && server_channel_rows.is_empty() {
rows.push(SettingsRow { stable_id: "appearance-server-grid".into(), kind: 12, ..SettingsRow::default() });
+4 -1
View File
@@ -110,8 +110,11 @@ impl<'a> Builder<'a> {
self.appearance_choice(Preference::DisplaySize, "appearance.displaySize", "settings.display_size.info",
&[("small", "appearance.small"), ("medium", "appearance.medium"), ("large", "appearance.large")], AppearanceChoice::DisplaySize);
let restart_notice = if self.s.prefs["language"].as_str().is_some_and(|code| code != self.c.language.code()) {
self.text("settings.appearance.language.warning.restart_required")
} else { String::new() };
self.appearance_choice(Preference::Language, "language.label", "settings.appearance.language.info",
&[("en", "English"), ("ru", "Русский")], AppearanceChoice::Language { restart: self.text("ui.restart.now") });
&[("en", "English"), ("ru", "Русский")], AppearanceChoice::Language { restart_notice });
self.appearance_choice(Preference::SidebarIconMode, "settings.appearance.sidebar.icon_view_mode", "settings.appearance.sidebar.icon_view_mode.info",
&[("small", "appearance.small"), ("large", "appearance.large"), ("adaptive", "settings.appearance.sidebar.icon_view_mode.large_collapsed")], AppearanceChoice::SidebarIcons);
self.heading("ui.server");
+1 -1
View File
@@ -177,7 +177,7 @@ pub struct SettingsSnapshot {
#[derive(Clone,Debug)]
pub enum Intent { None, Edit(Field), Invoke(Operation), Select(Vec<Operation>), Secret(SecretBinding) }
#[derive(Clone, Debug)]
pub enum AppearanceChoice { Theme, DisplaySize, Language { restart: String }, SidebarIcons }
pub enum AppearanceChoice { Theme, DisplaySize, Language { restart_notice: String }, SidebarIcons }
#[derive(Clone,Debug)]
pub enum Control { Heading, Note, Toggle(bool), Choice{options:Vec<(String,String)>,selected:usize}, AppearanceChoice{style:AppearanceChoice,options:Vec<(String,String)>,selected:usize}, Text(String), Number{value:f64,min:f64,max:f64,step:f64}, Action, Meter(f32), Secret, Rich{source:String,document:std::sync::Arc<crate::ui::chat::prepared::PreparedDocument>} }
#[derive(Clone,Debug)]
+1 -1
View File
@@ -202,7 +202,7 @@ export component ShellDialog inherits Rectangle {
}
}
for action in DialogBridge.actions: ActionButton { text: action.label; enabled: action.enabled && !DialogBridge.busy; destructive: action.destructive; clicked => { ShellBridge.invoke(action.id); } }
if !DialogBridge.speaker: ActionButton { text: DialogBridge.advanced-label; clicked => { dialog.advanced = !dialog.advanced; } }
if !DialogBridge.speaker && DialogBridge.fields.length > 0: ActionButton { text: DialogBridge.advanced-label; clicked => { dialog.advanced = !dialog.advanced; } }
if DialogBridge.confirmation-label != "": VerticalLayout {
padding-top: 16px;
spacing: 4px;
+15 -19
View File
@@ -8,8 +8,8 @@ export struct SettingsRow {
checked: bool, value: string, options: [string], selected: int,
enabled: bool, destructive: bool, inset: bool, error: string,
meter: float, decrease: string, increase: string, rich: [ChatVisual],
command-label: string,
section-start: bool, section-end: bool, stacked: bool,
restart-notice: string,
}
export global SettingsBridge {
in-out property <[string]> categories;
@@ -208,7 +208,7 @@ component AppearanceSelect inherits Rectangle {
private property <bool> locale: setting.kind == 13;
private property <length> leading: locale ? 44px : 45px;
min-width: 0px;
min-height: max(control-height, caption.preferred-height + 12px);
min-height: max(control-height, parity-appearance-select-caption.preferred-height + 12px);
preferred-height: self.min-height;
background: Theme.bg;
border-radius: 10px;
@@ -233,7 +233,7 @@ component AppearanceSelect inherits Rectangle {
height: root.setting.selected == 1 ? 5px : 3px;
border-radius: self.height / 2; background: Theme.fg;
}
caption := Text {
parity-appearance-select-caption := Text {
x: root.leading; width: max(0px, parent.width - self.x - 22px);
text: root.setting.selected >= 0 ? root.setting.options[root.setting.selected] : "";
color: Theme.fg; font-family: Theme.font-family; font-size: Theme.font-size;
@@ -317,8 +317,9 @@ component SettingCell inherits Rectangle {
private property <length> content-height: inline ? max(details.height, editor.height) : details.height + label-spacing + editor.height;
private property <length> body-height: grid-item ? max(64px, content-height) : content-height;
private property <length> bottom-padding: grid-item ? 0px : compact ? (heading ? 8px : 24px) : (setting.section-end ? 8px : heading ? (appearance ? 16px : 20px) : setting.kind == 11 ? 28px : 24px);
private property <length> notice-height: setting.restart-notice == "" ? 0px : restart-notice.preferred-height + 4px;
private property <length> error-height: setting.error == "" ? 0px : error-message.preferred-height + (compact ? 8px : 4px);
private property <length> card-height: top-padding + body-height + error-height + bottom-padding;
private property <length> card-height: top-padding + body-height + notice-height + error-height + bottom-padding;
private property <length> control-height: touch ? max(48px, Theme.touch-target) : appearance-select ? 34px : (setting.stacked ? 33px : 26px);
min-height: compact && heading ? max(48px, card-height) : card-height + (!compact && setting.section-end ? 12px : 0px);
preferred-height: self.min-height;
@@ -357,8 +358,7 @@ component SettingCell inherits Rectangle {
x: root.inline ? root.width - root.right-inset - self.width : root.left-inset;
y: root.top-padding + (root.inline ? (root.body-height - self.height) / 2 : details.height + root.label-spacing);
width: !root.inline ? root.available : root.setting.kind == 2 ? (root.touch ? 48px : (root.appearance ? 40px : 44px)) :
root.appearance-select ? min(root.available * 0.55, max(root.setting.kind == 13 ? 135px : 160px, choice-measure.preferred-width + 80px)
+ (root.setting.command-label != "" ? command-measure.preferred-width + 8px : 0px)) :
root.appearance-select ? min(root.available * 0.55, max(root.setting.kind == 13 ? 135px : 160px, choice-measure.preferred-width + 80px)) :
root.field ? min(360px, root.available * 0.58) : min(260px, root.available * 0.48);
height: self.preferred-height;
if root.setting.kind == 2: Toggle {
@@ -377,16 +377,7 @@ component SettingCell inherits Rectangle {
selected(index) => { SettingsBridge.choice-value(root.setting.token, index); }
}
if root.setting.kind == 10 || root.setting.kind == 11: AppearancePicker { setting: root.setting; }
if root.setting.kind == 13: HorizontalLayout {
spacing: 8px;
ActionButton {
horizontal-stretch: 0; text: root.setting.command-label; enabled: root.setting.enabled;
min-height: root.control-height; cross-axis-self-alignment: center;
clicked => { SettingsBridge.invoke(root.setting.token); }
}
AppearanceSelect { setting: root.setting; control-height: root.control-height; horizontal-stretch: 1; }
}
if root.setting.kind == 14: AppearanceSelect { setting: root.setting; control-height: root.control-height; }
if root.appearance-select: AppearanceSelect { setting: root.setting; control-height: root.control-height; }
if root.field: SettingEditor { setting: root.setting; control-height: root.control-height; compact: root.compact; }
if root.action: HorizontalLayout {
alignment: root.compact ? stretch : (root.inline ? end : start);
@@ -413,13 +404,18 @@ component SettingCell inherits Rectangle {
text: root.appearance-select && root.setting.selected >= 0 ? root.setting.options[root.setting.selected] : "";
font-family: Theme.font-family; font-size: Theme.font-size;
}
command-measure := Text {
visible: false; text: root.setting.command-label; font-family: Theme.font-family; font-size: Theme.font-size;
restart-notice := Text {
visible: root.setting.restart-notice != "";
x: root.left-inset; y: root.top-padding + root.body-height + 4px;
width: root.available; height: self.preferred-height;
text: root.setting.restart-notice; color: Theme.error; wrap: word-wrap;
font-family: Theme.font-family; font-size: Theme.small-font; font-weight: Theme.bold-weight;
accessible-role: text; accessible-label: self.text;
}
error-message := Text {
visible: root.setting.error != "";
x: root.left-inset;
y: root.top-padding + root.body-height + (root.compact ? 8px : 4px);
y: root.top-padding + root.body-height + root.notice-height + (root.compact ? 8px : 4px);
width: root.available; height: self.preferred-height;
text: root.setting.error; color: Theme.error; wrap: word-wrap;
font-family: Theme.font-family; font-size: Theme.font-size; accessible-role: text; accessible-label: self.text;