Resolve participant permissions for each opened context menu
This commit is contained in:
1 parent
62bb67b5a3
commit
b266f4f1b7
14 files changed
+747
-65
No files matched your search
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
## Unreleased
|
## Unreleased
|
||||||
|
|
||||||
|
- The participant menu reads the selected client's capabilities on opening. Late replies cannot change a closed or reopened menu, and unavailable server actions stay disabled.
|
||||||
|
|
||||||
- Poke accepts up to 1024 UTF-8 bytes locally. A server refusal keeps the message editable; submitting a draft after the recipient leaves cannot send it to a replacement participant.
|
- Poke accepts up to 1024 UTF-8 bytes locally. A server refusal keeps the message editable; submitting a draft after the recipient leaves cannot send it to a replacement participant.
|
||||||
|
|
||||||
- Participant Connection Info shows localized timing, packet loss and traffic metrics without rounding 64-bit counters. Old statistics cannot populate a replacement tab or participant.
|
- Participant Connection Info shows localized timing, packet loss and traffic metrics without rounding 64-bit counters. Old statistics cannot populate a replacement tab or participant.
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
## Current Windows account-free checkpoint (2026-11-26)
|
## Current Windows account-free checkpoint (2026-11-26)
|
||||||
|
|
||||||
|
**Participant context on Windows:** On private beta14, two muted guests opened the self and peer menus on both tabs. Poke, volume, Connection Info and group availability matched independently queried capabilities for the selected client ID, UID and generation. The test inspected an eligible group choice without submitting it. Escape preserved selection and whisper targeting. A separate popup test verified one request per opening and rejection of stale responses after reopening. Five native and two core checks passed.
|
||||||
|
|
||||||
**Participant Poke on Windows:** Two muted guests used Slint's participant menu on private beta14. The server refused the long message with ParameterInvalidSize; the editor retained it and accepted a shorter correction. The destination recorded the exact literal message with the initiator's UID. Cancelled, locally oversized and stale drafts did not arrive. The replacement guest had the same display name but a different client ID; reused-ID rejection was tested separately. Five native checks and a real stdio byte-boundary test passed. No physical audio was used.
|
**Participant Poke on Windows:** Two muted guests used Slint's participant menu on private beta14. The server refused the long message with ParameterInvalidSize; the editor retained it and accepted a shorter correction. The destination recorded the exact literal message with the initiator's UID. Cancelled, locally oversized and stale drafts did not arrive. The replacement guest had the same display name but a different client ID; reused-ID rejection was tested separately. Five native checks and a real stdio byte-boundary test passed. No physical audio was used.
|
||||||
|
|
||||||
**Participant connection statistics:** The Windows Slint menu displayed the peer's server-assigned client ID and a numeric timing metric with units on private beta14. After changing tabs and reconnecting, the self panel used the new session. Escape dismissed the menu without changing selection or the whisper target. Separate tests checked English and Russian formatting, exact counters, empty and unscoped responses and client-number reuse. Seven native and three core checks passed; no physical audio was used.
|
**Participant connection statistics:** The Windows Slint menu displayed the peer's server-assigned client ID and a numeric timing metric with units on private beta14. After changing tabs and reconnecting, the self panel used the new session. Escape dismissed the menu without changing selection or the whisper target. Separate tests checked English and Russian formatting, exact counters, empty and unscoped responses and client-number reuse. Seven native and three core checks passed; no physical audio was used.
|
||||||
|
|||||||
+4
-4
@@ -194,7 +194,7 @@ fn cap(allowed:Option<bool>,source:&str)->Value {json!({"allowed":allowed,"reaso
|
|||||||
pub fn tapped(name:&[u8])->bool{matches!(name,b"notifypermissionlist"|b"notifyclientneededpermissions"|b"notifyconnectioninfo"|b"notifyclientpermlist"|b"notifychannelclientpermlist")}
|
pub fn tapped(name:&[u8])->bool{matches!(name,b"notifypermissionlist"|b"notifyclientneededpermissions"|b"notifyconnectioninfo"|b"notifyclientpermlist"|b"notifychannelclientpermlist")}
|
||||||
|
|
||||||
fn validate_live_identity(target:&Target,client_id:u16,uid:Option<&tsclientlib::UidBuf>)->Result<(),ErrorObj>{
|
fn validate_live_identity(target:&Target,client_id:u16,uid:Option<&tsclientlib::UidBuf>)->Result<(),ErrorObj>{
|
||||||
if target.client_id!=client_id || uid.is_none_or(|uid|uid.to_string()!=target.uid){return Err(bad("client identity changed; reopen the menu"));}
|
if target.client_id!=client_id || uid.is_none_or(|uid|uid.to_string()!=target.uid){return Err(ErrorObj::new(ErrorCode::TargetChanged,"client identity changed; reopen the menu"));}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
fn target_hint(own:bool,key:&str,hints:Option<u64>,bit:u64)->Value {
|
fn target_hint(own:bool,key:&str,hints:Option<u64>,bit:u64)->Value {
|
||||||
@@ -305,9 +305,9 @@ mod tests {
|
|||||||
let first=tsclientlib::UidBuf(vec![1;20]); let second=tsclientlib::UidBuf(vec![2;20]);
|
let first=tsclientlib::UidBuf(vec![1;20]); let second=tsclientlib::UidBuf(vec![2;20]);
|
||||||
let target=Target{client_id:42,uid:first.to_string()};
|
let target=Target{client_id:42,uid:first.to_string()};
|
||||||
assert!(validate_live_identity(&target,42,Some(&first)).is_ok());
|
assert!(validate_live_identity(&target,42,Some(&first)).is_ok());
|
||||||
assert!(validate_live_identity(&target,42,Some(&second)).is_err());
|
for (id,uid) in [(42,Some(&second)),(43,Some(&first)),(42,None)] {
|
||||||
assert!(validate_live_identity(&target,43,Some(&first)).is_err());
|
assert_eq!(validate_live_identity(&target,id,uid).unwrap_err().code,ErrorCode::TargetChanged);
|
||||||
assert!(validate_live_identity(&target,42,None).is_err());
|
}
|
||||||
let mut persisted=HashMap::new(); persisted.insert(second.0.clone(),-6.0);
|
let mut persisted=HashMap::new(); persisted.insert(second.0.clone(),-6.0);
|
||||||
let mut volumes=LocalVolumes::default(); volumes.set(&first.0,-8.0,true);
|
let mut volumes=LocalVolumes::default(); volumes.set(&first.0,-8.0,true);
|
||||||
assert_eq!(volumes.get(&first.0,&persisted),(-8.0,true)); assert_eq!(volumes.gain(&first.0,&persisted),0.0);
|
assert_eq!(volumes.get(&first.0,&persisted),(-8.0,true)); assert_eq!(volumes.gain(&first.0,&persisted),0.0);
|
||||||
|
|||||||
@@ -260,6 +260,11 @@ fn client_menu_commands_are_validated_and_never_fake_success_offline() {
|
|||||||
let mut core=Core::start(&dir.0);
|
let mut core=Core::start(&dir.0);
|
||||||
let (r,_)=core.request("ctx","client_context",json!({"client_id":42,"uid":"fixture"}));
|
let (r,_)=core.request("ctx","client_context",json!({"client_id":42,"uid":"fixture"}));
|
||||||
assert_eq!(r["error"]["code"],"not_connected");
|
assert_eq!(r["error"]["code"],"not_connected");
|
||||||
|
for args in [json!({"client_id":0,"uid":"fixture"}),json!({"client_id":65536,"uid":"fixture"}),
|
||||||
|
json!({"client_id":42,"uid":""}),json!({"client_id":42,"uid":"fixture","unexpected":true})] {
|
||||||
|
let (reply,_) = core.request("invalid-context","client_context",args);
|
||||||
|
assert_eq!(reply["error"]["code"],"bad_request","{reply}");
|
||||||
|
}
|
||||||
let (r,_)=core.request("invalid-stats","client_action",json!({"client_id":42,"uid":"fixture","generation":9_007_199_254_740_992u64,"action":"connection_info"}));
|
let (r,_)=core.request("invalid-stats","client_action",json!({"client_id":42,"uid":"fixture","generation":9_007_199_254_740_992u64,"action":"connection_info"}));
|
||||||
assert_eq!(r["error"]["code"],"bad_request","{r}");
|
assert_eq!(r["error"]["code"],"bad_request","{r}");
|
||||||
let actions=[
|
let actions=[
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
|
|
||||||
## Возврат к разработке на ПК, 2026-11-26
|
## Возврат к разработке на ПК, 2026-11-26
|
||||||
|
|
||||||
|
Windows, база `62bb67b`: закрыт `command:client_context`. На beta14 доступность действий и групп в меню обоих клиентов совпала с ответами ядра. Повторное открытие и устаревшие ответы проверены отдельно. Прошли пять нативных и две проверки ядра. Права не менялись; стенд остановлен.
|
||||||
|
|
||||||
Windows, база `256e10a`: закрыт `client-action:poke`. На beta14 отказ ParameterInvalidSize сохранил черновик; исправленный текст дошёл с точным UID отправителя. Отмена, превышение 1024 байт и смена адресата не привели к доставке. Прошли пять нативных тестов и тест stdio; стенд остановлен.
|
Windows, база `256e10a`: закрыт `client-action:poke`. На beta14 отказ ParameterInvalidSize сохранил черновик; исправленный текст дошёл с точным UID отправителя. Отмена, превышение 1024 байт и смена адресата не привели к доставке. Прошли пять нативных тестов и тест stdio; стенд остановлен.
|
||||||
|
|
||||||
Windows, база `89a2b21`: закрыт `client-action:connection_info`. На beta14 проверено отображение статистики другого участника и своей после переподключения. Единицы измерения и точные 64-битные счётчики проверены отдельно. Прошли семь нативных и три проверки ядра; стенд остановлен.
|
Windows, база `89a2b21`: закрыт `client-action:connection_info`. На beta14 проверено отображение статистики другого участника и своей после переподключения. Единицы измерения и точные 64-битные счётчики проверены отдельно. Прошли семь нативных и три проверки ядра; стенд остановлен.
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
//! Worker-to-UI requests retain their original target and cannot become current-tab actions.
|
//! Worker-to-UI requests retain their original target and cannot become current-tab actions.
|
||||||
use crate::{services::{Result,ServiceError},ui::{shell::{Target,Values,Form,Detail},settings::Navigation,chat::{ChatAssetResult,ConversationTarget,SendReceipt}}};
|
use crate::{services::{Result,ServiceError},ui::{shell::{Target,Values,Form,Detail},settings::Navigation,chat::{ChatAssetResult,ConversationTarget,SendReceipt}}};
|
||||||
use crate::{app::connections::SessionKey,media::stream::signal::StreamError};
|
use crate::{app::connections::SessionKey,media::stream::signal::StreamError};
|
||||||
|
use crate::app::server_actions::ClientMenuCapabilities;
|
||||||
use tokio::sync::oneshot;
|
use tokio::sync::oneshot;
|
||||||
|
|
||||||
pub struct Prompt {pub form:Form,pub answer:oneshot::Sender<Result<Values>>}
|
pub struct Prompt {pub form:Form,pub answer:oneshot::Sender<Result<Values>>}
|
||||||
@@ -14,6 +15,7 @@ pub enum SnapshotUpdate {
|
|||||||
}
|
}
|
||||||
pub enum UiEffect {
|
pub enum UiEffect {
|
||||||
Detail{target:Target,detail:Detail},
|
Detail{target:Target,detail:Detail},
|
||||||
|
ClientMenuContext { target: Target, menu_epoch: u64, ui_generation: u64, result: Result<ClientMenuCapabilities> },
|
||||||
SnapshotPreviewOpened { target: Target, detail: Detail, ui_generation: u64 },
|
SnapshotPreviewOpened { target: Target, detail: Detail, ui_generation: u64 },
|
||||||
SnapshotPreviewDismissed { target: Target },
|
SnapshotPreviewDismissed { target: Target },
|
||||||
Navigate(crate::ui::shell::Destination),
|
Navigate(crate::ui::shell::Destination),
|
||||||
@@ -46,6 +48,7 @@ pub enum UiEffect {
|
|||||||
pub enum ServiceEvent {
|
pub enum ServiceEvent {
|
||||||
Changed, Prompt(Prompt), Effect(UiEffect), Workflow(Result<WorkflowResult>),
|
Changed, Prompt(Prompt), Effect(UiEffect), Workflow(Result<WorkflowResult>),
|
||||||
ScopedDetailComplete { serial: u64, ui_generation: u64, target: Target, operation: crate::ui::shell::Operation, result: Result<Detail> },
|
ScopedDetailComplete { serial: u64, ui_generation: u64, target: Target, operation: crate::ui::shell::Operation, result: Result<Detail> },
|
||||||
|
ClientMenuComplete { target: Target, menu_epoch: u64, ui_generation: u64, result: Result<ClientMenuCapabilities> },
|
||||||
RecordingChanged(crate::app::connections::SessionKey),
|
RecordingChanged(crate::app::connections::SessionKey),
|
||||||
SnapshotStarted { serial: u64, cancel: std::sync::Weak<crate::services::server_icons::OperationCancellation> },
|
SnapshotStarted { serial: u64, cancel: std::sync::Weak<crate::services::server_icons::OperationCancellation> },
|
||||||
SnapshotUpdated { serial: u64, update: SnapshotUpdate },
|
SnapshotUpdated { serial: u64, update: SnapshotUpdate },
|
||||||
|
|||||||
@@ -214,6 +214,22 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
|
|||||||
match result{Ok(created)=>{if created.is_some(){profile=created}bootstrap.present(&mut state,profile.as_ref())?;if state.snapshot.bootstrap==BootstrapState::Ready{owner=Some(construct(&config,profile.take().unwrap(),runtime.clone(),events.clone(),cancelled.clone(),controls.clone()).await?);}send_effect(&runtime,&effects,UiEffect::FormComplete{id:editor_id,target,result:Ok(())}).await?;},Err(error)=>{state.snapshot.error=error.message.clone();send_effect(&runtime,&effects,UiEffect::FormComplete{id:editor_id,target,result:Err(error)}).await?;}}dirty=true;
|
match result{Ok(created)=>{if created.is_some(){profile=created}bootstrap.present(&mut state,profile.as_ref())?;if state.snapshot.bootstrap==BootstrapState::Ready{owner=Some(construct(&config,profile.take().unwrap(),runtime.clone(),events.clone(),cancelled.clone(),controls.clone()).await?);}send_effect(&runtime,&effects,UiEffect::FormComplete{id:editor_id,target,result:Ok(())}).await?;},Err(error)=>{state.snapshot.error=error.message.clone();send_effect(&runtime,&effects,UiEffect::FormComplete{id:editor_id,target,result:Err(error)}).await?;}}dirty=true;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
RuntimeCommand::Shell(ShellAction::ClientContext{target,menu_epoch})=>{
|
||||||
|
let Some(ui_generation)=attachment_ui else{continue};
|
||||||
|
let Some(owner)=&owner else{continue};
|
||||||
|
let ctx=&owner.ctx;
|
||||||
|
if state.snapshot.destination!=Destination::Servers || !client_menu_target_current(&target,&ctx.connected.connections.snapshot()){continue}
|
||||||
|
if jobs.len()>=64 {
|
||||||
|
let result=Err(ServiceError::new("runtime_busy","Too many pending application actions; reopen the menu to retry"));
|
||||||
|
send_effect(&runtime,&effects,UiEffect::ClientMenuContext{target,menu_epoch,ui_generation,result}).await?;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let ctx=ctx.clone();let sender=events.clone();
|
||||||
|
jobs.spawn(async move {
|
||||||
|
let result=query_client_menu(&ctx,&target,ui_generation).await;
|
||||||
|
let _=sender.send(ServiceEvent::ClientMenuComplete{target,menu_epoch,ui_generation,result}).await;
|
||||||
|
});
|
||||||
|
},
|
||||||
command @ (RuntimeCommand::Shell(ShellAction::DiscoverChannelStreams{..})|RuntimeCommand::DiscoverChannelStreams{..})=>{
|
command @ (RuntimeCommand::Shell(ShellAction::DiscoverChannelStreams{..})|RuntimeCommand::DiscoverChannelStreams{..})=>{
|
||||||
let Some(owner)=&owner else{continue};
|
let Some(owner)=&owner else{continue};
|
||||||
let ctx=&owner.ctx;
|
let ctx=&owner.ctx;
|
||||||
@@ -428,6 +444,14 @@ async fn run(config:AppConfig,runtime:Weak<AppRuntime>,mut commands:mpsc::Receiv
|
|||||||
dirty=true;
|
dirty=true;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
ServiceEvent::ClientMenuComplete{target,menu_epoch,ui_generation,result}=>{
|
||||||
|
let Some(owner)=&owner else{continue};
|
||||||
|
let ctx=&owner.ctx;
|
||||||
|
if ctx.require_ui_generation(ui_generation).is_ok() && state.snapshot.destination==Destination::Servers
|
||||||
|
&& client_menu_target_current(&target,&ctx.connected.connections.snapshot()) {
|
||||||
|
send_effect(&runtime,&effects,UiEffect::ClientMenuContext{target,menu_epoch,ui_generation,result}).await?;
|
||||||
|
}
|
||||||
|
},
|
||||||
ServiceEvent::StreamDiscoveryComplete{key,visit,ui_generation,result}=>{
|
ServiceEvent::StreamDiscoveryComplete{key,visit,ui_generation,result}=>{
|
||||||
// A mixed response can still update valid offers and per-client failures.
|
// A mixed response can still update valid offers and per-client failures.
|
||||||
dirty=true;
|
dirty=true;
|
||||||
@@ -679,6 +703,29 @@ fn spawn_snapshot(jobs:&mut tokio::task::JoinSet<()>,ctx:Arc<RuntimeServices>,ta
|
|||||||
}
|
}
|
||||||
pub(crate) fn scoped_detail_query(operation:Operation)->bool{matches!(operation,Operation::ChannelInfo|Operation::ClientInfo|Operation::ClientConnectionInfo)}
|
pub(crate) fn scoped_detail_query(operation:Operation)->bool{matches!(operation,Operation::ChannelInfo|Operation::ClientInfo|Operation::ClientConnectionInfo)}
|
||||||
|
|
||||||
|
pub(crate) fn client_menu_target_current(target:&Target, connections:&crate::app::connections::ConnectionsSnapshot)->bool {
|
||||||
|
let (Some(key), Entity::Client{id,uid,channel_id})=(&target.session,&target.entity) else{return false};
|
||||||
|
let Some(viewed)=connections.viewed_id.as_deref().and_then(|id|connections.get(id))
|
||||||
|
.filter(|viewed| viewed.key==*key && viewed.is_connected()) else{return false};
|
||||||
|
let Some(server)=viewed.server.as_deref() else{return false};
|
||||||
|
server["own_channel_id"].as_u64()==target.own_channel_id && server["clients"].as_array().is_some_and(|rows|
|
||||||
|
rows.iter().any(|row|row["id"].as_u64()==Some(u64::from(*id)) && row["uid"].as_str()==Some(uid.as_str())
|
||||||
|
&& row["channel_id"].as_u64()==Some(*channel_id)))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn query_client_menu(ctx:&RuntimeServices,target:&Target,ui_generation:u64)->Result<crate::app::server_actions::ClientMenuCapabilities> {
|
||||||
|
ctx.require_ui_generation(ui_generation)?;
|
||||||
|
if !ctx.network_enabled { return Err(ServiceError::new("network_disabled","Network connections are disabled in this isolated runtime")); }
|
||||||
|
if !client_menu_target_current(target,&ctx.connected.connections.snapshot()) { return Err(context::changed()); }
|
||||||
|
let (Some(key), Entity::Client{id,uid,..})=(&target.session,&target.entity) else{return Err(context::changed())};
|
||||||
|
let command=teamspeach_core::protocol::Command::ClientContext(teamspeach_core::menu::Target{client_id:*id,uid:uid.clone()});
|
||||||
|
// A menu read must not trigger the notification side effects of a user command failure.
|
||||||
|
let reply=ctx.connected.connections.request(key,command).await.map_err(context::connection_error)?;
|
||||||
|
ctx.require_ui_generation(ui_generation)?;
|
||||||
|
if !client_menu_target_current(target,&ctx.connected.connections.snapshot()) { return Err(context::changed()); }
|
||||||
|
crate::app::server_actions::client_menu_capabilities(target,&reply)
|
||||||
|
}
|
||||||
|
|
||||||
async fn query_detail(ctx:&Arc<RuntimeServices>,target:&Target,operation:Operation,options:&crate::app::server_actions::QueryOptions)->Result<Detail>{
|
async fn query_detail(ctx:&Arc<RuntimeServices>,target:&Target,operation:Operation,options:&crate::app::server_actions::QueryOptions)->Result<Detail>{
|
||||||
let command=crate::app::server_actions::query(target,operation,options)?;
|
let command=crate::app::server_actions::query(target,operation,options)?;
|
||||||
let key=target.session.as_ref().ok_or_else(context::changed)?;
|
let key=target.session.as_ref().ok_or_else(context::changed)?;
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ use serde_json::{Map, Value};
|
|||||||
mod projection;
|
mod projection;
|
||||||
mod context;
|
mod context;
|
||||||
pub use context::{client_context,group_entries,group_entries_with_context};
|
pub use context::{client_context,group_entries,group_entries_with_context};
|
||||||
|
pub use context::ClientMenuCapabilities;
|
||||||
|
pub(crate) use context::client_menu_capabilities;
|
||||||
pub use projection::{project, project_with_context, query, QueryOptions, Refresh, refresh};
|
pub use projection::{project, project_with_context, query, QueryOptions, Refresh, refresh};
|
||||||
pub(super) mod channel_editor;
|
pub(super) mod channel_editor;
|
||||||
pub(crate) use channel_editor::{populate_choices, populate_move};
|
pub(crate) use channel_editor::{populate_choices, populate_move};
|
||||||
|
|||||||
@@ -1,27 +1,120 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::ui::{i18n::Catalog,shell::{Action,Entry,OptionValue,FieldKind,Form}};
|
use crate::ui::{i18n::Catalog,shell::{Action,Entry,OptionValue,FieldKind,Form}};
|
||||||
|
|
||||||
/// Client context is fetched immediately before displaying the menu. A recycled
|
const CLIENT_CAPABILITIES: &[(Operation, &str)] = &[
|
||||||
/// numeric client ID or a different generation must not inherit these capabilities.
|
(Operation::ClientPoke, "poke"),
|
||||||
|
(Operation::ClientConnectionInfo, "connection_info"),
|
||||||
|
(Operation::ClientCommander, "commander"),
|
||||||
|
(Operation::ClientPermissions, "client_permissions"),
|
||||||
|
(Operation::ClientMove, "move_to_own_channel"),
|
||||||
|
(Operation::ClientKickChannel, "kick_channel"),
|
||||||
|
(Operation::ClientKickServer, "kick_server"),
|
||||||
|
(Operation::ClientBan, "ban"),
|
||||||
|
(Operation::ClientVolume, "volume"),
|
||||||
|
(Operation::ClientAvatarChoose, "avatar"),
|
||||||
|
(Operation::ClientAvatarDelete, "delete_avatar"),
|
||||||
|
(Operation::PermissionSet, "set_client_permission"),
|
||||||
|
(Operation::ClientChannelPermissionSet, "set_channel_permission"),
|
||||||
|
(Operation::ClientChannelPermissionRemove, "set_channel_permission"),
|
||||||
|
];
|
||||||
|
const CLIENT_GROUPS: &[(Operation, &str, &str)] = &[
|
||||||
|
(Operation::ClientServerGroupAdd, "server_groups", "can_add"),
|
||||||
|
(Operation::ClientServerGroupRemove, "server_groups", "can_remove"),
|
||||||
|
(Operation::ClientChannelGroupSet, "channel_groups", "can_set"),
|
||||||
|
];
|
||||||
|
|
||||||
|
pub struct ClientMenuCapabilities {
|
||||||
|
capabilities: [bool; CLIENT_CAPABILITIES.len()],
|
||||||
|
groups: [bool; CLIENT_GROUPS.len()],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ClientMenuCapabilities {
|
||||||
|
pub(crate) fn covers(operation: Operation) -> bool {
|
||||||
|
CLIENT_CAPABILITIES.iter().any(|&(op, _)| op == operation)
|
||||||
|
|| CLIENT_GROUPS.iter().any(|&(op, _, _)| op == operation)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn allows(&self, operation: Operation) -> Option<bool> {
|
||||||
|
CLIENT_CAPABILITIES.iter().position(|&(op, _)| op == operation).map(|i| self.capabilities[i])
|
||||||
|
.or_else(|| CLIENT_GROUPS.iter().position(|&(op, _, _)| op == operation).map(|i| self.groups[i]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client_capabilities<'a>(t: &Target, reply: &'a Value) -> Result<&'a Map<String, Value>> {
|
||||||
|
let client = client(t)?;
|
||||||
|
if reply.get("generation").and_then(Value::as_u64) != Some(generation(t)?)
|
||||||
|
|| reply.get("client_id").and_then(Value::as_u64) != Some(u64::from(client.client_id))
|
||||||
|
|| reply.get("uid").and_then(Value::as_str) != Some(client.uid.as_str()) {
|
||||||
|
return Err(ServiceError::new("target_changed", "Client context changed"));
|
||||||
|
}
|
||||||
|
reply.get("capabilities").and_then(Value::as_object).ok_or_else(|| bad("Missing client capabilities"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// A present null defers to the server; an absent or malformed capability does not.
|
||||||
|
fn allowed(capability: Option<&Value>) -> Option<bool> {
|
||||||
|
match capability.and_then(|capability| capability.get("allowed")) {
|
||||||
|
Some(Value::Bool(allowed)) => Some(*allowed),
|
||||||
|
Some(Value::Null) => Some(true),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn group_rows<'a>(reply: &'a Value, operation: Operation, list: &str, cap: &'static str) -> Result<impl Iterator<Item = Result<(u64, &'a str)>> + 'a> {
|
||||||
|
let rows = reply.get(list).and_then(Value::as_array).ok_or_else(|| bad("Missing client group catalog"))?;
|
||||||
|
Ok(rows.iter().filter(move |row| {
|
||||||
|
let member = row.get("member").and_then(Value::as_bool);
|
||||||
|
let eligible = match operation {
|
||||||
|
Operation::ClientServerGroupAdd => member == Some(false),
|
||||||
|
Operation::ClientServerGroupRemove => member == Some(true),
|
||||||
|
_ => member.is_some(),
|
||||||
|
};
|
||||||
|
eligible && allowed(row.get(cap)) == Some(true)
|
||||||
|
}).map(|row| {
|
||||||
|
let id = row.get("id").and_then(Value::as_u64).filter(|n| *n > 0).ok_or_else(|| bad("Invalid group catalog ID"))?;
|
||||||
|
let name = row.get("name").and_then(Value::as_str).ok_or_else(|| bad("Missing group catalog name"))?;
|
||||||
|
Ok((id, name))
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Menu state deliberately contains no form defaults or server catalogs.
|
||||||
|
pub(crate) fn client_menu_capabilities(t: &Target, reply: &Value) -> Result<ClientMenuCapabilities> {
|
||||||
|
let capabilities = client_capabilities(t, reply)?;
|
||||||
|
let Entity::Client { channel_id, .. } = t.entity else { return Err(bad("Expected a client target")); };
|
||||||
|
if reply.get("channel_id").and_then(Value::as_u64) != Some(channel_id) {
|
||||||
|
return Err(ServiceError::new("target_changed", "Client context changed"));
|
||||||
|
}
|
||||||
|
let capabilities = std::array::from_fn(|i| {
|
||||||
|
let (operation, key) = CLIENT_CAPABILITIES[i];
|
||||||
|
// Playback volume is local; only a known denial can further restrict its own rules.
|
||||||
|
allowed(capabilities.get(key)).unwrap_or(operation == Operation::ClientVolume)
|
||||||
|
});
|
||||||
|
let mut groups = [false; CLIENT_GROUPS.len()];
|
||||||
|
for (i, &(operation, list, cap)) in CLIENT_GROUPS.iter().enumerate() {
|
||||||
|
for row in group_rows(reply, operation, list, cap)? {
|
||||||
|
row?;
|
||||||
|
groups[i] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(ClientMenuCapabilities { capabilities, groups })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A server editor obtains its own fresh context and choices after the menu click.
|
||||||
pub fn client_context(t:&Target,reply:&Value,c:&Catalog)->Result<Vec<Action>> {
|
pub fn client_context(t:&Target,reply:&Value,c:&Catalog)->Result<Vec<Action>> {
|
||||||
let client=client(t)?;
|
let capabilities = client_capabilities(t, reply)?;
|
||||||
if reply.get("generation").and_then(Value::as_u64)!=Some(generation(t)?)||reply.get("client_id").and_then(Value::as_u64)!=Some(u64::from(client.client_id))||reply.get("uid").and_then(Value::as_str)!=Some(client.uid.as_str()){return Err(ServiceError::new("target_changed","Client context changed"))}
|
|
||||||
let capabilities=reply.get("capabilities").and_then(Value::as_object).ok_or_else(||bad("Missing client capabilities"))?;
|
|
||||||
let mut actions=Vec::new();
|
let mut actions=Vec::new();
|
||||||
for(op,key)in [(Operation::ClientPoke,"poke"),(Operation::ClientConnectionInfo,"connection_info"),(Operation::ClientCommander,"commander"),(Operation::ClientPermissions,"client_permissions"),(Operation::ClientMove,"move_to_own_channel"),(Operation::ClientKickChannel,"kick_channel"),(Operation::ClientKickServer,"kick_server"),(Operation::ClientBan,"ban"),(Operation::ClientVolume,"volume"),(Operation::ClientAvatarChoose,"avatar"),(Operation::ClientAvatarDelete,"delete_avatar"),(Operation::PermissionSet,"set_client_permission"),(Operation::ClientChannelPermissionSet,"set_channel_permission")]{
|
for &(op,key) in CLIENT_CAPABILITIES {
|
||||||
let Some(cap)=capabilities.get(key) else{continue};let mut a=Action::new(key,op,t.clone(),c);
|
let mut a=Action::new(key,op,t.clone(),c);
|
||||||
// Null means server decides, not an OS/backend capability promise.
|
a.enabled=allowed(capabilities.get(key))==Some(true);
|
||||||
a.enabled=cap.get("allowed").and_then(Value::as_bool)!=Some(false);
|
|
||||||
if !a.enabled{a.reason=c.text("admin.denied");}
|
if !a.enabled{a.reason=c.text("admin.denied");}
|
||||||
if let Some(form)=&mut a.form{fill_client_choices(form,reply)?;}
|
if a.enabled { if let Some(form)=&mut a.form { fill_client_choices(form,reply)?; } }
|
||||||
actions.push(a);
|
actions.push(a);
|
||||||
}
|
}
|
||||||
for(op,list,cap)in[(Operation::ClientServerGroupAdd,"server_groups","can_add"),(Operation::ClientServerGroupRemove,"server_groups","can_remove"),(Operation::ClientChannelGroupSet,"channel_groups","can_set")]{
|
for &(op,list,cap) in CLIENT_GROUPS {
|
||||||
let mut a=Action::new(format!("{op:?}"),op,t.clone(),c);
|
let mut a=Action::new(format!("{op:?}"),op,t.clone(),c);
|
||||||
let options=reply.get(list).and_then(Value::as_array).ok_or_else(||bad("Missing client group catalog"))?.iter().filter(|row|{
|
let options=group_rows(reply,op,list,cap)?.map(|row| {
|
||||||
let member=row.get("member").and_then(Value::as_bool)==Some(true);
|
let (id,name)=row?;
|
||||||
(op!=Operation::ClientServerGroupAdd||!member)&&(op!=Operation::ClientServerGroupRemove||member)&&row.get(cap).and_then(|v|v.get("allowed")).and_then(Value::as_bool)!=Some(false)
|
Ok(OptionValue{value:id.to_string(),label:name.into()})
|
||||||
}).map(|row|{let id=row.get("id").and_then(Value::as_u64).filter(|n|*n>0).ok_or_else(||bad("Invalid group catalog ID"))?;Ok(OptionValue{value:id.to_string(),label:row.get("name").and_then(Value::as_str).unwrap_or("").into()})}).collect::<Result<Vec<_>>>()?;
|
}).collect::<Result<Vec<_>>>()?;
|
||||||
a.enabled=!options.is_empty();if !a.enabled{a.reason=c.text("admin.denied")}
|
a.enabled=!options.is_empty();if !a.enabled{a.reason=c.text("admin.denied")}
|
||||||
if let Some(form)=&mut a.form{if let Some(field)=form.fields.iter_mut().find(|f|f.id=="group_id"){field.kind=FieldKind::Choice(options);}}
|
if let Some(form)=&mut a.form{if let Some(field)=form.fields.iter_mut().find(|f|f.id=="group_id"){field.kind=FieldKind::Choice(options);}}
|
||||||
actions.push(a);
|
actions.push(a);
|
||||||
@@ -58,3 +151,62 @@ pub fn group_entries_with_context(t:&Target,kind:GroupKind,reply:&Value,context:
|
|||||||
for entry in &mut entries{for(op,suffix)in[(Operation::GroupRename,"rename"),(Operation::GroupDelete,"delete")]{let mut a=Action::new(format!("{op:?}"),op,entry.target.clone(),c);let permission=format!("b_virtualserver_{kind_name}group_{suffix}");a.enabled=context.get("permissions").and_then(|v|v.get(&permission)).and_then(Value::as_i64)!=Some(0);if !a.enabled{a.reason=c.text("admin.denied")}entry.actions.push(a)}}
|
for entry in &mut entries{for(op,suffix)in[(Operation::GroupRename,"rename"),(Operation::GroupDelete,"delete")]{let mut a=Action::new(format!("{op:?}"),op,entry.target.clone(),c);let permission=format!("b_virtualserver_{kind_name}group_{suffix}");a.enabled=context.get("permissions").and_then(|v|v.get(&permission)).and_then(Value::as_i64)!=Some(0);if !a.enabled{a.reason=c.text("admin.denied")}entry.actions.push(a)}}
|
||||||
Ok(entries)
|
Ok(entries)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::app::connections::SessionKey;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
fn target() -> Target {
|
||||||
|
Target {
|
||||||
|
session: Some(SessionKey { connection_id: "fixture".into(), session: 3, generation: 8 }),
|
||||||
|
entity: Entity::Client { id: 42, uid: "peer".into(), channel_id: 4 },
|
||||||
|
name: "Peer".into(), own_channel_id: Some(2),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reply() -> Value {
|
||||||
|
json!({"generation":8,"client_id":42,"uid":"peer","channel_id":4,
|
||||||
|
"capabilities":{"poke":{"allowed":false},"connection_info":{"allowed":null},
|
||||||
|
"set_channel_permission":{"allowed":true},"ban":{"allowed":"true"},
|
||||||
|
"client_permissions":{},"volume":{"allowed":true}},
|
||||||
|
"server_groups":[{"id":9,"name":"Present","member":true,"can_add":{"allowed":true},"can_remove":{"allowed":false}},
|
||||||
|
{"id":10,"name":"Absent","member":false,"can_add":{"allowed":null},"can_remove":{"allowed":true}},
|
||||||
|
{"id":11,"name":"Malformed","can_add":{"allowed":true}}],
|
||||||
|
"channel_groups":[{"id":12,"name":"Unavailable","member":false,"can_set":{}}]})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_menu_uses_only_explicit_capabilities_and_eligible_groups() {
|
||||||
|
use Operation::*;
|
||||||
|
let caps = client_menu_capabilities(&target(), &reply()).unwrap();
|
||||||
|
for op in [ClientConnectionInfo, ClientVolume, ClientChannelPermissionSet, ClientChannelPermissionRemove, ClientServerGroupAdd] {
|
||||||
|
assert_eq!(caps.allows(op), Some(true), "{op:?}");
|
||||||
|
}
|
||||||
|
for op in [ClientPoke, ClientBan, ClientKickServer, ClientPermissions, ClientServerGroupRemove, ClientChannelGroupSet] {
|
||||||
|
assert_eq!(caps.allows(op), Some(false), "{op:?}");
|
||||||
|
}
|
||||||
|
for op in [ClientInfo, ClientPrivateChat, ClientWhisperAdd, ContactAdd, TalkGrant, TalkRevoke] {
|
||||||
|
assert_eq!(caps.allows(op), None, "{op:?}");
|
||||||
|
assert!(!ClientMenuCapabilities::covers(op));
|
||||||
|
}
|
||||||
|
let mut malformed_volume = reply();
|
||||||
|
malformed_volume["capabilities"]["volume"] = json!({});
|
||||||
|
assert_eq!(client_menu_capabilities(&target(), &malformed_volume).unwrap().allows(ClientVolume), Some(true));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_menu_rejects_another_peer_generation_or_channel_and_malformed_catalogs() {
|
||||||
|
for (key, value) in [("generation", json!(9)), ("client_id", json!(43)), ("uid", json!("recycled")), ("channel_id", json!(5))] {
|
||||||
|
let mut wire = reply();
|
||||||
|
wire[key] = value;
|
||||||
|
assert!(matches!(client_menu_capabilities(&target(), &wire), Err(error) if error.code == "target_changed"), "{key}");
|
||||||
|
}
|
||||||
|
for key in ["capabilities", "server_groups", "channel_groups"] {
|
||||||
|
let mut wire = reply();
|
||||||
|
wire[key] = Value::Null;
|
||||||
|
assert!(client_menu_capabilities(&target(), &wire).is_err(), "{key}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -135,7 +135,7 @@ impl Capture {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Only the real attachment consumes this watch stream. It can emit typed UI intents, but
|
/// Only the real attachment consumes this watch stream. It can emit typed UI intents, but
|
||||||
/// there is intentionally no service dispatcher; the harness observes only scene navigation.
|
/// there is intentionally no service dispatcher; the harness supplies fixture-only results.
|
||||||
struct ModelHost {
|
struct ModelHost {
|
||||||
runtime: Arc<AppRuntime>,
|
runtime: Arc<AppRuntime>,
|
||||||
snapshots: watch::Sender<Arc<Snapshot>>,
|
snapshots: watch::Sender<Arc<Snapshot>>,
|
||||||
@@ -236,8 +236,23 @@ impl Active {
|
|||||||
RuntimeCommand::Shell(ShellAction::Navigate(Destination::Settings)) if category.is_some() => {},
|
RuntimeCommand::Shell(ShellAction::Navigate(Destination::Settings)) if category.is_some() => {},
|
||||||
RuntimeCommand::Settings(settings::SettingsAction::Invoke(settings::Operation::Navigate(nav @ Navigation::Category(chosen))))
|
RuntimeCommand::Settings(settings::SettingsAction::Invoke(settings::Operation::Navigate(nav @ Navigation::Category(chosen))))
|
||||||
if category == Some(chosen) => { self.host.publish_settings(nav); self.delivered = true; },
|
if category == Some(chosen) => { self.host.publish_settings(nav); self.delivered = true; },
|
||||||
RuntimeCommand::Shell(ShellAction::Context(target))
|
RuntimeCommand::AttachmentShell { action: ShellAction::ClientContext { target, menu_epoch }, ui_generation }
|
||||||
if scene == Scene::Menu && target.name == "Alex" && matches!(target.entity, Entity::Client { id: 2, .. }) => self.delivered = true,
|
if scene == Scene::Menu && target.name == "Alex" => {
|
||||||
|
let crate::ui::shell::Target { session: Some(session), entity: Entity::Client { id: 2, uid, channel_id }, .. } = &target else {
|
||||||
|
return Err("the menu did not request the captured fixture participant".into());
|
||||||
|
};
|
||||||
|
let wire = json!({"generation": session.generation, "client_id": 2, "uid": uid, "channel_id": channel_id,
|
||||||
|
"capabilities": {"poke": {"allowed": true}, "connection_info": {"allowed": null},
|
||||||
|
"commander": {"allowed": false}, "client_permissions": {"allowed": null},
|
||||||
|
"move_to_own_channel": {"allowed": target.own_channel_id != Some(*channel_id)},
|
||||||
|
"kick_channel": {"allowed": null}, "kick_server": {"allowed": null}, "ban": {"allowed": null},
|
||||||
|
"volume": {"allowed": true}, "avatar": {"allowed": false}, "delete_avatar": {"allowed": null},
|
||||||
|
"set_client_permission": {"allowed": null}, "set_channel_permission": {"allowed": null}},
|
||||||
|
"server_groups": [], "channel_groups": []});
|
||||||
|
let capabilities = crate::app::server_actions::client_menu_capabilities(&target,&wire).map_err(|error|error.message)?;
|
||||||
|
self.attachment.fixture_client_menu_context(&target,menu_epoch,ui_generation,capabilities);
|
||||||
|
self.delivered = true;
|
||||||
|
},
|
||||||
RuntimeCommand::Chat(_) => {}, // Native editor/layout notices; never dispatched to services.
|
RuntimeCommand::Chat(_) => {}, // Native editor/layout notices; never dispatched to services.
|
||||||
_ => return Err("unexpected action during the isolated screenshot scenario".into()),
|
_ => return Err("unexpected action during the isolated screenshot scenario".into()),
|
||||||
}
|
}
|
||||||
@@ -259,7 +274,8 @@ impl Active {
|
|||||||
&& chat.get_content_width() > 0.0 && chat.get_can_info() == is_private
|
&& chat.get_content_width() > 0.0 && chat.get_can_info() == is_private
|
||||||
&& chat.get_tabs().iter().any(|tab| tab.active && tab.label == title)
|
&& chat.get_tabs().iter().any(|tab| tab.active && tab.label == title)
|
||||||
&& (count == 0) == is_private && shell.get_menu_visible() == (scene == Scene::Menu)
|
&& (count == 0) == is_private && shell.get_menu_visible() == (scene == Scene::Menu)
|
||||||
&& (scene != Scene::Menu || (shell.get_menu_title() == "Alex" && shell.get_menu_actions().row_count() > 0))
|
&& (scene != Scene::Menu || (shell.get_menu_title() == "Alex" && shell.get_menu_actions().iter().any(|action|
|
||||||
|
action.enabled && action.label.as_str() == self.capture.snapshot.catalog.text("clientMenu.poke"))))
|
||||||
};
|
};
|
||||||
if ready && self.delivered && self.activated.elapsed() >= SETTLE { return Ok(true) }
|
if ready && self.delivered && self.activated.elapsed() >= SETTLE { return Ok(true) }
|
||||||
if self.started.elapsed() >= DEADLINE {
|
if self.started.elapsed() >= DEADLINE {
|
||||||
|
|||||||
+232
-25
@@ -667,9 +667,17 @@ fn participant_poke_menu_delivers_literal_message_to_muted_beta14_guest() {
|
|||||||
run_muted_beta14_participant_fixture(ParticipantFixture::Poke);
|
run_muted_beta14_participant_fixture(ParticipantFixture::Poke);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
#[test]
|
||||||
|
#[ignore = "requires exclusive use of private beta14 at 127.0.0.1:19987"]
|
||||||
|
fn participant_context_menu_projects_muted_beta14_capabilities() {
|
||||||
|
headless::install().unwrap();
|
||||||
|
run_muted_beta14_participant_fixture(ParticipantFixture::Context);
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
enum ParticipantFixture { Info, Statistics, Poke }
|
enum ParticipantFixture { Info, Statistics, Poke, Context }
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
fn run_muted_beta14_participant_fixture(scenario: ParticipantFixture) {
|
fn run_muted_beta14_participant_fixture(scenario: ParticipantFixture) {
|
||||||
@@ -719,6 +727,7 @@ fn run_muted_beta14_participant_fixture(scenario: ParticipantFixture) {
|
|||||||
ParticipantFixture::Statistics => return exercise_beta14_connection_info(runtime, ui, &owner, &mut tabs, clients, &uids, &identities[1]).await,
|
ParticipantFixture::Statistics => return exercise_beta14_connection_info(runtime, ui, &owner, &mut tabs, clients, &uids, &identities[1]).await,
|
||||||
ParticipantFixture::Poke => return exercise_beta14_poke(runtime, ui, &owner, &mut tabs, clients, &uids,
|
ParticipantFixture::Poke => return exercise_beta14_poke(runtime, ui, &owner, &mut tabs, clients, &uids,
|
||||||
replacement.as_deref().ok_or("missing replacement guest identity")?).await,
|
replacement.as_deref().ok_or("missing replacement guest identity")?).await,
|
||||||
|
ParticipantFixture::Context => return exercise_beta14_participant_context(runtime, ui, &owner, &tabs, clients, &uids).await,
|
||||||
ParticipantFixture::Info => {},
|
ParticipantFixture::Info => {},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -901,6 +910,161 @@ async fn await_beta14_participant(runtime: &AppRuntime, key: &SessionKey, peer:
|
|||||||
})).await
|
})).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
async fn exercise_beta14_participant_context(runtime: &AppRuntime, ui: &AppWindow, owner: &crate::app::runtime::context::RuntimeServices,
|
||||||
|
tabs: &[SessionKey; 2], clients: [u16; 2], uids: &[String; 2]) -> SmokeResult<()> {
|
||||||
|
use super::{focus, key_profiles::until};
|
||||||
|
use crate::ui::shell::{Entity, Operation::*, forms};
|
||||||
|
use i_slint_core::items::AccessibleRole;
|
||||||
|
use serde_json::Value;
|
||||||
|
use teamspeach_core::menu::Target;
|
||||||
|
|
||||||
|
let shell = ui.global::<ShellBridge>();
|
||||||
|
let dialog = ui.global::<crate::DialogBridge>();
|
||||||
|
let catalog = runtime.snapshot().catalog;
|
||||||
|
let label = |operation| catalog.text(forms::label_key(operation));
|
||||||
|
let loading = catalog.text("native.status.loading");
|
||||||
|
let denied = catalog.text("admin.denied");
|
||||||
|
let mut previous_poke = None;
|
||||||
|
let mut checked_group_choices = false;
|
||||||
|
for (view, peer) in [(0, 0), (0, 1), (1, 1), (1, 0)] {
|
||||||
|
let key = &tabs[view];
|
||||||
|
let own = view == peer;
|
||||||
|
let name = BETA14_PARTICIPANTS[peer];
|
||||||
|
let client_id = clients[peer];
|
||||||
|
let uid = &uids[peer];
|
||||||
|
let scope = format!("tab {} {}", view + 1, if own { "self" } else { "peer" });
|
||||||
|
view_muted_beta14_tab(runtime, ui, key, view).await?;
|
||||||
|
await_beta14_participant(runtime, key, peer, client_id, uid, own).await?;
|
||||||
|
let other = BETA14_PARTICIPANTS[1 - peer];
|
||||||
|
until("both participant rows are visible in the rendered tree", || {
|
||||||
|
[name, other].into_iter().all(|name| focus::visible_selector(ui, name, AccessibleRole::ListItem).is_ok())
|
||||||
|
}).await?;
|
||||||
|
focus::activate(focus::visible_selector(ui, other, AccessibleRole::ListItem)?)?;
|
||||||
|
until("the other participant is rendered as selected", || {
|
||||||
|
shell.get_tree().iter().any(|row| row.title == other && row.selected)
|
||||||
|
}).await?;
|
||||||
|
|
||||||
|
// Read the exact guest-to-participant context without using native menu projection.
|
||||||
|
pace_beta14().await?;
|
||||||
|
let reply = owner.request(key, Command::ClientContext(Target { client_id, uid: uid.clone() }))
|
||||||
|
.await.map_err(|e| format!("{scope}: independent client context failed ({})", e.code))?;
|
||||||
|
if reply["generation"].as_u64() != Some(key.generation) || reply["client_id"].as_u64() != Some(u64::from(client_id))
|
||||||
|
|| reply["uid"].as_str() != Some(uid.as_str()) || reply["is_self"].as_bool() != Some(own) {
|
||||||
|
return Err(format!("{scope}: client context had the wrong UID, generation, client ID, or self flag"));
|
||||||
|
}
|
||||||
|
let allowed = |capability: &str| match reply["capabilities"][capability].get("allowed") {
|
||||||
|
Some(Value::Bool(value)) => Ok(Some(*value)),
|
||||||
|
Some(Value::Null) => Ok(None),
|
||||||
|
_ => Err(format!("{scope}: client context omitted the {capability} decision")),
|
||||||
|
};
|
||||||
|
let poke = allowed("poke")?;
|
||||||
|
if (own && poke != Some(false)) || allowed("volume")? != Some(!own)
|
||||||
|
|| reply["capabilities"]["volume"]["source"] != "local" {
|
||||||
|
return Err(format!("{scope}: client context did not distinguish local volume from Poke"));
|
||||||
|
}
|
||||||
|
let mut states = vec![(ClientPoke, poke != Some(false)), (ClientVolume, !own),
|
||||||
|
(ClientConnectionInfo, allowed("connection_info")? != Some(false))];
|
||||||
|
let mut group_preview = None;
|
||||||
|
for (operation, list, capability, membership) in [
|
||||||
|
(ClientServerGroupAdd, "server_groups", "can_add", Some(false)),
|
||||||
|
(ClientServerGroupRemove, "server_groups", "can_remove", Some(true)),
|
||||||
|
(ClientChannelGroupSet, "channel_groups", "can_set", None),
|
||||||
|
] {
|
||||||
|
let groups = reply[list].as_array().ok_or_else(|| format!("{scope}: missing {list} catalog"))?;
|
||||||
|
let mut eligible = groups.iter().filter(|group| {
|
||||||
|
membership.is_none_or(|member| group["member"].as_bool() == Some(member))
|
||||||
|
&& group[capability]["allowed"] != false
|
||||||
|
}).peekable();
|
||||||
|
let enabled = eligible.peek().is_some();
|
||||||
|
states.push((operation, enabled));
|
||||||
|
if enabled && !checked_group_choices && group_preview.is_none() {
|
||||||
|
let options = eligible.map(|group| {
|
||||||
|
let id = group["id"].as_u64().filter(|id| *id != 0).ok_or("missing eligible group ID")?;
|
||||||
|
let name = group["name"].as_str().ok_or("missing eligible group label")?;
|
||||||
|
Ok((id.to_string(), name))
|
||||||
|
}).collect::<SmokeResult<Vec<_>>>()?;
|
||||||
|
group_preview = Some((operation, options));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pace_beta14().await?;
|
||||||
|
|
||||||
|
let before = runtime.snapshot();
|
||||||
|
let previous_error = shell.get_error();
|
||||||
|
let unchanged = || {
|
||||||
|
let after = runtime.snapshot();
|
||||||
|
after.connections.viewed_id.as_deref() == Some(key.connection_id.as_str())
|
||||||
|
&& after.connections.get(&key.connection_id).is_some_and(|tab| tab.key == *key)
|
||||||
|
&& before.tree.iter().filter(|entry| entry.row.selected).map(|entry| &entry.row.target)
|
||||||
|
.eq(after.tree.iter().filter(|entry| entry.row.selected).map(|entry| &entry.row.target))
|
||||||
|
&& shell.get_tree().iter().any(|row| row.title == other && row.selected)
|
||||||
|
&& after.settings.pending_whisper == before.settings.pending_whisper
|
||||||
|
&& after.settings.whisper_targets == before.settings.whisper_targets
|
||||||
|
&& shell.get_error() == previous_error && !dialog.get_visible()
|
||||||
|
};
|
||||||
|
|
||||||
|
open_tree_info_menu(ui, name)?;
|
||||||
|
let actions = shell.get_menu_actions();
|
||||||
|
let pending = actions.iter().find(|row| row.label.as_str() == label(ClientPoke))
|
||||||
|
.ok_or_else(|| format!("{scope}: missing initial Poke row"))?;
|
||||||
|
if !shell.get_menu_visible() || shell.get_menu_title() != name || pending.enabled || pending.reason.as_str() != loading
|
||||||
|
|| previous_poke.as_ref() == Some(&pending.id) || !unchanged() {
|
||||||
|
return Err(format!("{scope}: initial menu was not a fresh, non-selecting loading menu"));
|
||||||
|
}
|
||||||
|
let volume = actions.iter().find(|row| row.label.as_str() == label(ClientVolume))
|
||||||
|
.ok_or_else(|| format!("{scope}: missing initial volume row"))?;
|
||||||
|
if volume.enabled == own || volume.reason.as_str() == loading {
|
||||||
|
return Err(format!("{scope}: local volume depended on pending server context"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let loaded = await_tree_menu_action(ui, name, &label(ClientPoke), &loading).await
|
||||||
|
.map_err(|e| format!("{scope}: {e}"))?;
|
||||||
|
previous_poke = Some(pending.id);
|
||||||
|
if previous_poke.as_ref() != Some(&loaded.id) {
|
||||||
|
return Err(format!("{scope}: context did not update the original popup"));
|
||||||
|
}
|
||||||
|
for (operation, enabled) in states {
|
||||||
|
let label = label(operation);
|
||||||
|
let (flag, reason) = if enabled { ("true", "") } else { ("false", denied.as_str()) };
|
||||||
|
let row = rendered_tree_menu_action(ui, name, &label).await.map_err(|e| format!("{scope}: {e}"))?;
|
||||||
|
if row.accessible_string_property(Property::Enabled).as_deref() != Some(flag)
|
||||||
|
|| row.accessible_string_property(Property::Description).unwrap_or_default().as_str() != reason {
|
||||||
|
return Err(format!("{scope}: rendered {operation:?} did not match the client context (expected enabled={enabled})"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !unchanged() { return Err(format!("{scope}: loading context changed selection, whisper state, or dialog state")); }
|
||||||
|
dismiss_tree_menu(ui).await?;
|
||||||
|
if !unchanged() { return Err(format!("{scope}: dismissing context changed selection, whisper state, or dialog state")); }
|
||||||
|
|
||||||
|
// Inspect one offered group editor, if the guest has any choices. Never submit it.
|
||||||
|
if let Some((operation, options)) = group_preview {
|
||||||
|
pace_beta14().await?;
|
||||||
|
let title = label(operation);
|
||||||
|
invoke_tree_info_menu(runtime, ui, name, operation).await?;
|
||||||
|
until("visible participant group editor", || dialog.get_visible() && dialog.get_title() == title
|
||||||
|
&& focus::visible_selector(ui, &title, AccessibleRole::Form).is_ok()).await?;
|
||||||
|
let correct_target_and_ids = runtime.snapshot().dialog.as_ref().is_some_and(|form| {
|
||||||
|
form.operation == operation && form.target.session.as_ref() == Some(key)
|
||||||
|
&& matches!(&form.target.entity, Entity::Client { id, uid: captured, .. } if *id == client_id && captured == uid)
|
||||||
|
&& form.fields.iter().find(|field| field.id == "group_id").and_then(|field| field.kind.choices(None))
|
||||||
|
.is_some_and(|choices| choices.iter().map(|choice| (choice.value.as_str(), choice.label.as_str()))
|
||||||
|
.eq(options.iter().map(|(id, name)| (id.as_str(), *name))))
|
||||||
|
});
|
||||||
|
let correct_labels = dialog.get_fields().iter().find(|field| field.id == "group_id").is_some_and(|field| {
|
||||||
|
field.enabled && field.choices.iter().map(|name| name.to_string()).eq(options.iter().map(|(_, name)| *name))
|
||||||
|
});
|
||||||
|
rendered_form_button(ui, &title, dialog.get_cancel_label().as_str())?;
|
||||||
|
until("participant group editor closed without submission", || !dialog.get_visible()).await?;
|
||||||
|
if !correct_target_and_ids || !correct_labels {
|
||||||
|
return Err(format!("{scope}: group editor target or choices did not match client context"));
|
||||||
|
}
|
||||||
|
checked_group_choices = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
eprintln!("beta14 Slint participant context: exact self and peer on both tabs; Poke, local volume, Connection Info and group availability matched; Escape preserved selection and whisper state; group choices inspected={checked_group_choices}");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
async fn exercise_beta14_poke(runtime: &AppRuntime, ui: &AppWindow, owner: &crate::app::runtime::context::RuntimeServices,
|
async fn exercise_beta14_poke(runtime: &AppRuntime, ui: &AppWindow, owner: &crate::app::runtime::context::RuntimeServices,
|
||||||
tabs: &mut [SessionKey; 2], mut clients: [u16; 2], uids: &[String; 2], replacement_identity: &str) -> SmokeResult<()> {
|
tabs: &mut [SessionKey; 2], mut clients: [u16; 2], uids: &[String; 2], replacement_identity: &str) -> SmokeResult<()> {
|
||||||
@@ -947,10 +1111,10 @@ async fn exercise_beta14_poke(runtime: &AppRuntime, ui: &AppWindow, owner: &crat
|
|||||||
&& focus::visible_selector(ui, &title, AccessibleRole::Form).is_ok()).await
|
&& focus::visible_selector(ui, &title, AccessibleRole::Form).is_ok()).await
|
||||||
};
|
};
|
||||||
let cancel = async || {
|
let cancel = async || {
|
||||||
poke_form_button(ui, &title, dialog.get_cancel_label().as_str())?;
|
rendered_form_button(ui, &title, dialog.get_cancel_label().as_str())?;
|
||||||
until("Poke form closed on cancellation", || !dialog.get_visible()).await
|
until("Poke form closed on cancellation", || !dialog.get_visible()).await
|
||||||
};
|
};
|
||||||
let submit = || poke_form_button(ui, &title, dialog.get_submit_label().as_str());
|
let submit = || rendered_form_button(ui, &title, dialog.get_submit_label().as_str());
|
||||||
|
|
||||||
open().await?;
|
open().await?;
|
||||||
edit_poke_input(ui, &title, &field, "", CANCELLED, CANCELLED)?;
|
edit_poke_input(ui, &title, &field, "", CANCELLED, CANCELLED)?;
|
||||||
@@ -1044,14 +1208,14 @@ async fn exercise_beta14_poke(runtime: &AppRuntime, ui: &AppWindow, owner: &crat
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
fn poke_form_button(ui: &AppWindow, title: &str, label: &str) -> SmokeResult<()> {
|
fn rendered_form_button(ui: &AppWindow, title: &str, label: &str) -> SmokeResult<()> {
|
||||||
use super::focus;
|
use super::focus;
|
||||||
use i_slint_core::{accessibility::accessible_descendents, items::AccessibleRole};
|
use i_slint_core::{accessibility::accessible_descendents, items::AccessibleRole};
|
||||||
|
|
||||||
let form = focus::visible_selector(ui, title, AccessibleRole::Form)?;
|
let form = focus::visible_selector(ui, title, AccessibleRole::Form)?;
|
||||||
let button = accessible_descendents(&form).filter(|item| item.accessible_role() == AccessibleRole::Button
|
let button = accessible_descendents(&form).filter(|item| item.accessible_role() == AccessibleRole::Button
|
||||||
&& item.accessible_string_property(Property::Label).is_some_and(|text| text == label)
|
&& item.accessible_string_property(Property::Label).is_some_and(|text| text == label)
|
||||||
&& headless::visible_bounds(ui.window(), item).is_some()).last().ok_or_else(|| format!("missing Poke form button {label:?}"))?;
|
&& headless::visible_bounds(ui.window(), item).is_some()).last().ok_or_else(|| format!("missing {title} form button {label:?}"))?;
|
||||||
focus::activate(button)
|
focus::activate(button)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1116,7 +1280,6 @@ async fn exercise_beta14_connection_info(runtime: &AppRuntime, ui: &AppWindow, o
|
|||||||
use super::{focus, key_profiles::until};
|
use super::{focus, key_profiles::until};
|
||||||
use crate::app::connections::ConnectionState;
|
use crate::app::connections::ConnectionState;
|
||||||
use i_slint_core::items::AccessibleRole;
|
use i_slint_core::items::AccessibleRole;
|
||||||
use slint::platform::Key;
|
|
||||||
|
|
||||||
let shell = ui.global::<ShellBridge>();
|
let shell = ui.global::<ShellBridge>();
|
||||||
let catalog = runtime.snapshot().catalog;
|
let catalog = runtime.snapshot().catalog;
|
||||||
@@ -1132,14 +1295,10 @@ async fn exercise_beta14_connection_info(runtime: &AppRuntime, ui: &AppWindow, o
|
|||||||
let before = runtime.snapshot();
|
let before = runtime.snapshot();
|
||||||
let previous_error = shell.get_error();
|
let previous_error = shell.get_error();
|
||||||
open_tree_info_menu(ui, BETA14_PARTICIPANTS[1])?;
|
open_tree_info_menu(ui, BETA14_PARTICIPANTS[1])?;
|
||||||
until("the rendered participant context menu offers Connection Info", || {
|
let loading = catalog.text("native.status.loading");
|
||||||
focus::visible_selector(ui, BETA14_PARTICIPANTS[1], AccessibleRole::List).is_ok()
|
await_tree_menu_action(ui, BETA14_PARTICIPANTS[1], &subtitle, &loading).await?;
|
||||||
&& shell.get_menu_actions().iter().any(|a| a.label.as_str() == subtitle && a.enabled)
|
focus::visible_selector(ui, BETA14_PARTICIPANTS[1], AccessibleRole::List)?;
|
||||||
}).await?;
|
dismiss_tree_menu(ui).await?;
|
||||||
for event in [WindowEvent::KeyPressed { text: Key::Escape.into() }, WindowEvent::KeyReleased { text: Key::Escape.into() }] {
|
|
||||||
ui.window().dispatch_event_with_result(event).map_err(|e| e.to_string())?;
|
|
||||||
}
|
|
||||||
until("Escape closes the participant menu", || !shell.get_menu_visible()).await?;
|
|
||||||
pace_beta14().await?;
|
pace_beta14().await?;
|
||||||
let after = runtime.snapshot();
|
let after = runtime.snapshot();
|
||||||
for (unchanged, property) in [(clear(), "details"), (shell.get_error() == previous_error, "error"),
|
for (unchanged, property) in [(clear(), "details"), (shell.get_error() == previous_error, "error"),
|
||||||
@@ -1195,7 +1354,7 @@ async fn exercise_beta14_connection_info(runtime: &AppRuntime, ui: &AppWindow, o
|
|||||||
async fn read_beta14_connection_info(runtime: &AppRuntime, ui: &AppWindow, owner: &crate::app::runtime::context::RuntimeServices,
|
async fn read_beta14_connection_info(runtime: &AppRuntime, ui: &AppWindow, owner: &crate::app::runtime::context::RuntimeServices,
|
||||||
key: &SessionKey, peer: usize, client_id: u16, uid: &str, own: bool) -> SmokeResult<bool> {
|
key: &SessionKey, peer: usize, client_id: u16, uid: &str, own: bool) -> SmokeResult<bool> {
|
||||||
use super::key_profiles::until;
|
use super::key_profiles::until;
|
||||||
use crate::ui::{i18n::Language, shell::Operation};
|
use crate::ui::i18n::Language;
|
||||||
use teamspeach_core::menu::{Action, ActionRequest, Target};
|
use teamspeach_core::menu::{Action, ActionRequest, Target};
|
||||||
|
|
||||||
let shell = ui.global::<ShellBridge>();
|
let shell = ui.global::<ShellBridge>();
|
||||||
@@ -1226,7 +1385,21 @@ async fn read_beta14_connection_info(runtime: &AppRuntime, ui: &AppWindow, owner
|
|||||||
target: Target { client_id, uid: uid.into() }, generation: key.generation, action: Action::ConnectionInfo {},
|
target: Target { client_id, uid: uid.into() }, generation: key.generation, action: Action::ConnectionInfo {},
|
||||||
})).await;
|
})).await;
|
||||||
pace_beta14().await?;
|
pace_beta14().await?;
|
||||||
invoke_tree_info_menu(runtime, ui, name, Operation::ClientConnectionInfo).await?;
|
open_tree_info_menu(ui, name)?;
|
||||||
|
let action = await_tree_menu_action(ui, name, &subtitle, &catalog.text("native.status.loading")).await?;
|
||||||
|
if !action.enabled {
|
||||||
|
if own || !readback.as_ref().is_err_and(|error| error.code == "server_error"
|
||||||
|
&& error.message == "server permission hint denies this action") || action.reason.as_str() != catalog.text("admin.denied") {
|
||||||
|
return Err("Connection Info disabled without a matching peer permission denial".into());
|
||||||
|
}
|
||||||
|
let rendered = rendered_tree_menu_action(ui, name, &subtitle).await?;
|
||||||
|
if rendered.accessible_string_property(Property::Enabled).as_deref() != Some("false") {
|
||||||
|
return Err("denied peer Connection Info was not rendered as disabled".into());
|
||||||
|
}
|
||||||
|
dismiss_tree_menu(ui).await?;
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
super::focus::activate(rendered_tree_menu_action(ui, name, &subtitle).await?)?;
|
||||||
match readback {
|
match readback {
|
||||||
Ok(reply) => {
|
Ok(reply) => {
|
||||||
let rows = reply["rows"].as_array().filter(|rows| !rows.is_empty()).ok_or("missing scoped beta14 statistics")?;
|
let rows = reply["rows"].as_array().filter(|rows| !rows.is_empty()).ok_or("missing scoped beta14 statistics")?;
|
||||||
@@ -1309,7 +1482,8 @@ fn participant_info_menu_rejects_a_previous_session_target() {
|
|||||||
assert!(!shown());
|
assert!(!shown());
|
||||||
}
|
}
|
||||||
shell.invoke_context(own_row().unwrap().id,20.,20.);
|
shell.invoke_context(own_row().unwrap().id,20.,20.);
|
||||||
let action=shell.get_menu_actions().iter().find(|a|a.enabled && a.label.as_str()==info_label).ok_or("missing participant information action")?;
|
let action = await_tree_menu_action(ui, nick, &info_label, &labels.text("native.status.loading")).await?;
|
||||||
|
if !action.enabled { return Err("participant information action was disabled".into()); }
|
||||||
let captured=runtime.snapshot().tree.iter().find(|e|e.row.title==nick).ok_or("participant disappeared")?.row.target.clone();
|
let captured=runtime.snapshot().tree.iter().find(|e|e.row.title==nick).ok_or("participant disappeared")?.row.target.clone();
|
||||||
shell.invoke_invoke(action.id);
|
shell.invoke_invoke(action.id);
|
||||||
until("participant information",||shell.get_title()==nick && shown()).await.map_err(|e|format!("{e}: {}",shell.get_error()))?;
|
until("participant information",||shell.get_title()==nick && shown()).await.map_err(|e|format!("{e}: {}",shell.get_error()))?;
|
||||||
@@ -1448,16 +1622,38 @@ fn open_tree_info_menu(ui: &AppWindow, title: &str) -> SmokeResult<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn invoke_tree_info_menu(runtime: &AppRuntime, ui: &AppWindow, title: &str, operation: crate::ui::shell::Operation) -> SmokeResult<()> {
|
#[cfg(target_os = "windows")]
|
||||||
|
async fn dismiss_tree_menu(ui: &AppWindow) -> SmokeResult<()> {
|
||||||
|
use super::key_profiles::until;
|
||||||
|
use slint::platform::Key;
|
||||||
|
|
||||||
|
for event in [WindowEvent::KeyPressed { text: Key::Escape.into() }, WindowEvent::KeyReleased { text: Key::Escape.into() }] {
|
||||||
|
ui.window().dispatch_event_with_result(event).map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
until("Escape closes the participant menu", || !ui.global::<ShellBridge>().get_menu_visible()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn await_tree_menu_action(ui: &AppWindow, title: &str, label: &str, loading: &str) -> SmokeResult<crate::ShellCommand> {
|
||||||
|
use super::key_profiles::until;
|
||||||
|
|
||||||
|
let shell = ui.global::<ShellBridge>();
|
||||||
|
let mut result = None;
|
||||||
|
until(&format!("{label} ready in {title}'s context menu"), || {
|
||||||
|
if shell.get_menu_visible() && shell.get_menu_title() == title {
|
||||||
|
result = shell.get_menu_actions().iter().find(|action| action.label.as_str() == label && action.reason.as_str() != loading);
|
||||||
|
}
|
||||||
|
result.is_some()
|
||||||
|
}).await?;
|
||||||
|
result.ok_or_else(|| format!("missing ready {label} action"))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn rendered_tree_menu_action(ui: &AppWindow, title: &str, label: &str) -> SmokeResult<i_slint_core::item_tree::ItemRc> {
|
||||||
use super::{focus, key_profiles::until};
|
use super::{focus, key_profiles::until};
|
||||||
use crate::ui::shell::forms;
|
|
||||||
use i_slint_core::{accessibility::accessible_descendents, items::AccessibleRole};
|
use i_slint_core::{accessibility::accessible_descendents, items::AccessibleRole};
|
||||||
|
|
||||||
open_tree_info_menu(ui, title)?;
|
|
||||||
let label = runtime.snapshot().catalog.text(forms::label_key(operation));
|
|
||||||
let mut result = None;
|
let mut result = None;
|
||||||
let mut scrolls = 0;
|
let mut scrolls = 0;
|
||||||
until(&format!("{label} in {title}'s context menu"), || {
|
until(&format!("rendered {label} in {title}'s context menu"), || {
|
||||||
let Ok(popup) = focus::visible_selector(ui, title, AccessibleRole::List) else { return false; };
|
let Ok(popup) = focus::visible_selector(ui, title, AccessibleRole::List) else { return false; };
|
||||||
let Some(bounds) = headless::visible_bounds(ui.window(), &popup) else { return false; };
|
let Some(bounds) = headless::visible_bounds(ui.window(), &popup) else { return false; };
|
||||||
let action = accessible_descendents(&popup).find(|item| item.accessible_role() == AccessibleRole::Button
|
let action = accessible_descendents(&popup).find(|item| item.accessible_role() == AccessibleRole::Button
|
||||||
@@ -1467,11 +1663,11 @@ async fn invoke_tree_info_menu(runtime: &AppRuntime, ui: &AppWindow, title: &str
|
|||||||
y >= bounds.origin.y + 30.0 && y < bounds.origin.y + bounds.size.height
|
y >= bounds.origin.y + 30.0 && y < bounds.origin.y + bounds.size.height
|
||||||
}));
|
}));
|
||||||
if let Some(action) = action {
|
if let Some(action) = action {
|
||||||
result = Some(focus::activate(action));
|
result = Some(Ok(action));
|
||||||
} else if scrolls == 10 {
|
} else if scrolls == 10 {
|
||||||
result = Some(Err(format!("missing visible {label} action for {title}")));
|
result = Some(Err(format!("missing visible {label} action for {title}")));
|
||||||
} else {
|
} else {
|
||||||
// Participant menus can place Info below the clipped menu viewport.
|
// Participant menus can place actions below the clipped viewport.
|
||||||
let position = LogicalPosition::new(bounds.center().x, bounds.center().y);
|
let position = LogicalPosition::new(bounds.center().x, bounds.center().y);
|
||||||
if let Err(e) = ui.window().dispatch_event_with_result(WindowEvent::PointerScrolled { position, delta_x: 0.0, delta_y: -160.0 }) {
|
if let Err(e) = ui.window().dispatch_event_with_result(WindowEvent::PointerScrolled { position, delta_x: 0.0, delta_y: -160.0 }) {
|
||||||
result = Some(Err(e.to_string()));
|
result = Some(Err(e.to_string()));
|
||||||
@@ -1480,7 +1676,18 @@ async fn invoke_tree_info_menu(runtime: &AppRuntime, ui: &AppWindow, title: &str
|
|||||||
}
|
}
|
||||||
result.is_some()
|
result.is_some()
|
||||||
}).await?;
|
}).await?;
|
||||||
result.ok_or("missing menu activation result")?
|
result.ok_or("missing rendered menu action")?
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn invoke_tree_info_menu(runtime: &AppRuntime, ui: &AppWindow, title: &str, operation: crate::ui::shell::Operation) -> SmokeResult<()> {
|
||||||
|
use crate::ui::shell::forms;
|
||||||
|
|
||||||
|
open_tree_info_menu(ui, title)?;
|
||||||
|
let catalog = runtime.snapshot().catalog;
|
||||||
|
let label = catalog.text(forms::label_key(operation));
|
||||||
|
let action = await_tree_menu_action(ui, title, &label, &catalog.text("native.status.loading")).await?;
|
||||||
|
if !action.enabled { return Err(format!("{label} is disabled in {title}'s context menu")); }
|
||||||
|
super::focus::activate(rendered_tree_menu_action(ui, title, &label).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn rendered_detail_text(ui: &AppWindow) -> SmokeResult<Vec<slint::SharedString>> {
|
fn rendered_detail_text(ui: &AppWindow) -> SmokeResult<Vec<slint::SharedString>> {
|
||||||
|
|||||||
@@ -22,6 +22,13 @@ impl UiAttachment{
|
|||||||
pub fn window(&self)->&AppWindow{&self.window}
|
pub fn window(&self)->&AppWindow{&self.window}
|
||||||
pub fn generation(&self)->u64{self.generation}
|
pub fn generation(&self)->u64{self.generation}
|
||||||
pub fn take_startup_error(&self)->Option<crate::services::ServiceError>{self.startup_error.borrow_mut().take()}
|
pub fn take_startup_error(&self)->Option<crate::services::ServiceError>{self.startup_error.borrow_mut().take()}
|
||||||
|
#[cfg(all(feature="test-harness",not(any(target_os="android",target_os="ios"))))]
|
||||||
|
pub(crate) fn fixture_client_menu_context(&self,target:&shell::Target,menu_epoch:u64,ui_generation:u64,
|
||||||
|
capabilities:crate::app::server_actions::ClientMenuCapabilities) {
|
||||||
|
if self.generation==ui_generation && self.runtime.is_ui_current(ui_generation) {
|
||||||
|
self._bindings.borrow().shell.client_menu_context(&self.window,target,menu_epoch,Ok(capabilities));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
impl Drop for UiAttachment{fn drop(&mut self){
|
impl Drop for UiAttachment{fn drop(&mut self){
|
||||||
#[cfg(not(any(target_os="android",target_os="ios")))]
|
#[cfg(not(any(target_os="android",target_os="ios")))]
|
||||||
@@ -33,6 +40,8 @@ pub fn bind(runtime:Arc<AppRuntime>,generation:u64)->Result<UiAttachment,AppErro
|
|||||||
if !runtime.is_ui_current(generation){return Err(crate::services::ServiceError::new("ui_destroyed","The UI attachment was replaced").into())}
|
if !runtime.is_ui_current(generation){return Err(crate::services::ServiceError::new("ui_destroyed","The UI attachment was replaced").into())}
|
||||||
let window=AppWindow::new()?;
|
let window=AppWindow::new()?;
|
||||||
let weak=Arc::downgrade(&runtime);
|
let weak=Arc::downgrade(&runtime);
|
||||||
|
let client_menu_error=Arc::new(std::sync::Mutex::new(None));
|
||||||
|
let menu_error=client_menu_error.clone();
|
||||||
let shell=shell::bind(&window,Arc::new(move|action|{
|
let shell=shell::bind(&window,Arc::new(move|action|{
|
||||||
let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)) else{return};
|
let Some(runtime)=weak.upgrade().filter(|r|r.is_ui_current(generation)) else{return};
|
||||||
let result=match action {
|
let result=match action {
|
||||||
@@ -47,6 +56,13 @@ pub fn bind(runtime:Arc<AppRuntime>,generation:u64)->Result<UiAttachment,AppErro
|
|||||||
Ok(())
|
Ok(())
|
||||||
},
|
},
|
||||||
shell::ShellAction::DiscoverChannelStreams{key,visit}=>runtime.enqueue(crate::app::runtime::RuntimeCommand::DiscoverChannelStreams{key,visit,ui_generation:generation}),
|
shell::ShellAction::DiscoverChannelStreams{key,visit}=>runtime.enqueue(crate::app::runtime::RuntimeCommand::DiscoverChannelStreams{key,visit,ui_generation:generation}),
|
||||||
|
shell::ShellAction::ClientContext{ref target,menu_epoch}=>{
|
||||||
|
let target=target.clone();
|
||||||
|
if let Err(error)=runtime.enqueue(crate::app::runtime::RuntimeCommand::AttachmentShell{action,ui_generation:generation}) {
|
||||||
|
*menu_error.lock().expect("client menu error")=Some((target,menu_epoch,error));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
},
|
||||||
action if matches!(&action,shell::ShellAction::Invoke{operation,..}
|
action if matches!(&action,shell::ShellAction::Invoke{operation,..}
|
||||||
if crate::app::runtime::scoped_detail_query(*operation))
|
if crate::app::runtime::scoped_detail_query(*operation))
|
||||||
|| matches!(&action,shell::ShellAction::Invoke{operation:shell::Operation::ClientPoke,..})
|
|| matches!(&action,shell::ShellAction::Invoke{operation:shell::Operation::ClientPoke,..})
|
||||||
@@ -85,7 +101,15 @@ pub fn bind(runtime:Arc<AppRuntime>,generation:u64)->Result<UiAttachment,AppErro
|
|||||||
#[cfg(target_os="android")]
|
#[cfg(target_os="android")]
|
||||||
let accessibility=crate::platform::android::accessibility::attach_accessibility(window.window(),generation);
|
let accessibility=crate::platform::android::accessibility::attach_accessibility(window.window(),generation);
|
||||||
let ui=window.as_weak();let weak=Arc::downgrade(&runtime);let state=bindings.clone();
|
let ui=window.as_weak();let weak=Arc::downgrade(&runtime);let state=bindings.clone();
|
||||||
let update=Rc::new(move||{if let(Some(ui),Some(runtime))=(ui.upgrade(),weak.upgrade()){if runtime.is_ui_current(generation){update(&ui,&runtime,&mut state.borrow_mut());}}});
|
let update=Rc::new(move||{
|
||||||
|
let(Some(ui),Some(runtime))=(ui.upgrade(),weak.upgrade())else{return};
|
||||||
|
if !runtime.is_ui_current(generation){return}
|
||||||
|
let mut state=state.borrow_mut();
|
||||||
|
update(&ui,&runtime,&mut state);
|
||||||
|
if let Some((target,menu_epoch,error))=client_menu_error.lock().expect("client menu error").take(){
|
||||||
|
if client_menu_target_current(&runtime,&target){state.shell.client_menu_context(&ui,&target,menu_epoch,Err(error.message));}
|
||||||
|
}
|
||||||
|
});
|
||||||
let ui=window.as_weak();let weak=Arc::downgrade(&runtime);
|
let ui=window.as_weak();let weak=Arc::downgrade(&runtime);
|
||||||
// At most one queued wake per immutable snapshot batch; the timer also consumes latest video
|
// At most one queued wake per immutable snapshot batch; the timer also consumes latest video
|
||||||
// independently from model revisions, so decode never accumulates behind UI work.
|
// independently from model revisions, so decode never accumulates behind UI work.
|
||||||
@@ -141,6 +165,11 @@ fn update(ui:&AppWindow,runtime:&AppRuntime,bindings:&mut Bindings){
|
|||||||
{let shell=ui.global::<ShellBridge>();let compact=ui.window().size().width as f32/ui.window().scale_factor()<600.;let visible=(shell.get_destination()==1||shell.get_destination()==0&&shell.get_stage()==1&&(!compact||shell.get_depth()>0))&&!ui.global::<crate::MarkupBridge>().get_visible();chat::set_visibility(&bindings.chat,visible);}
|
{let shell=ui.global::<ShellBridge>();let compact=ui.window().size().width as f32/ui.window().scale_factor()<600.;let visible=(shell.get_destination()==1||shell.get_destination()==0&&shell.get_stage()==1&&(!compact||shell.get_depth()>0))&&!ui.global::<crate::MarkupBridge>().get_visible();chat::set_visibility(&bindings.chat,visible);}
|
||||||
for effect in runtime.drain_effects(){match effect{
|
for effect in runtime.drain_effects(){match effect{
|
||||||
UiEffect::FormComplete{id,target,result}=>bindings.shell.complete(ui,&id,&target,result.map_err(|error|error.message)),
|
UiEffect::FormComplete{id,target,result}=>bindings.shell.complete(ui,&id,&target,result.map_err(|error|error.message)),
|
||||||
|
UiEffect::ClientMenuContext{target,menu_epoch,ui_generation,result}=>{
|
||||||
|
if runtime.is_ui_current(ui_generation) && client_menu_target_current(runtime,&target) {
|
||||||
|
bindings.shell.client_menu_context(ui,&target,menu_epoch,result.map_err(|error|error.message));
|
||||||
|
}
|
||||||
|
},
|
||||||
UiEffect::SettingsAcknowledge(id)=>bindings.settings.acknowledge(&id),
|
UiEffect::SettingsAcknowledge(id)=>bindings.settings.acknowledge(&id),
|
||||||
UiEffect::Asset(asset)=>chat::present_asset(ui,&bindings.chat,asset),
|
UiEffect::Asset(asset)=>chat::present_asset(ui,&bindings.chat,asset),
|
||||||
UiEffect::ChatPreview{target,revision,preview}=>chat::present_preview(ui,&bindings.chat,&target,revision,preview),
|
UiEffect::ChatPreview{target,revision,preview}=>chat::present_preview(ui,&bindings.chat,&target,revision,preview),
|
||||||
@@ -169,6 +198,10 @@ fn update(ui:&AppWindow,runtime:&AppRuntime,bindings:&mut Bindings){
|
|||||||
_=>{}
|
_=>{}
|
||||||
}}
|
}}
|
||||||
}
|
}
|
||||||
|
fn client_menu_target_current(runtime:&AppRuntime,target:&shell::Target)->bool {
|
||||||
|
let ctx=runtime.services.lock().expect("runtime services").upgrade();
|
||||||
|
ctx.is_some_and(|ctx|crate::app::runtime::client_menu_target_current(target,&ctx.connected.connections.snapshot()))
|
||||||
|
}
|
||||||
fn apply_theme(ui:&AppWindow,snapshot:&Snapshot){
|
fn apply_theme(ui:&AppWindow,snapshot:&Snapshot){
|
||||||
use crate::services::themes::TokenValue;
|
use crate::services::themes::TokenValue;
|
||||||
let theme=ui.global::<Theme>();let prefs=&snapshot.settings.prefs;let dark=if prefs["theme"]=="system"{snapshot.theme.as_ref().and_then(|resolved|resolved.base_values.get("--tsv-bg")).and_then(|value|if let TokenValue::Color(color)=value{super::theme::color(color)}else{None}).is_none_or(|color|u32::from(color.red())+u32::from(color.green())+u32::from(color.blue())<384)}else{prefs["theme"]!="light"};theme.set_dark(dark);theme.set_high_contrast(snapshot.high_contrast);theme.set_reduced_motion(snapshot.reduced_motion);
|
let theme=ui.global::<Theme>();let prefs=&snapshot.settings.prefs;let dark=if prefs["theme"]=="system"{snapshot.theme.as_ref().and_then(|resolved|resolved.base_values.get("--tsv-bg")).and_then(|value|if let TokenValue::Color(color)=value{super::theme::color(color)}else{None}).is_none_or(|color|u32::from(color.red())+u32::from(color.green())+u32::from(color.blue())<384)}else{prefs["theme"]!="light"};theme.set_dark(dark);theme.set_high_contrast(snapshot.high_contrast);theme.set_reduced_motion(snapshot.reduced_motion);
|
||||||
|
|||||||
+226
-16
@@ -5,6 +5,7 @@ pub use types::*;
|
|||||||
use crate::{AppWindow, ShellBridge, DialogBridge, ShellRow, ShellTab, ShellCommand, ShellInfo, ShellStream, ShellField};
|
use crate::{AppWindow, ShellBridge, DialogBridge, ShellRow, ShellTab, ShellCommand, ShellInfo, ShellStream, ShellField};
|
||||||
use slint::{ComponentHandle, Model, ModelExt, ModelRc, SharedString, VecModel};
|
use slint::{ComponentHandle, Model, ModelExt, ModelRc, SharedString, VecModel};
|
||||||
use crate::app::connections::SessionKey;
|
use crate::app::connections::SessionKey;
|
||||||
|
use crate::app::server_actions::ClientMenuCapabilities;
|
||||||
use std::{cell::RefCell, collections::BTreeMap, rc::Rc, sync::Arc};
|
use std::{cell::RefCell, collections::BTreeMap, rc::Rc, sync::Arc};
|
||||||
|
|
||||||
struct Editor { form: Form, raw: BTreeMap<String,String>, dirty: BTreeMap<String,bool>, confirmation: String }
|
struct Editor { form: Form, raw: BTreeMap<String,String>, dirty: BTreeMap<String,bool>, confirmation: String }
|
||||||
@@ -22,6 +23,28 @@ const STREAMS_STAGE: i32 = 2;
|
|||||||
|
|
||||||
struct StreamDiscovery { key: SessionKey, visit: u64, error: Option<String> }
|
struct StreamDiscovery { key: SessionKey, visit: u64, error: Option<String> }
|
||||||
|
|
||||||
|
struct ClientMenu {
|
||||||
|
row: String,
|
||||||
|
own: bool,
|
||||||
|
// None is pending. Only this opening may replace it with a result.
|
||||||
|
result: Option<Result<ClientMenuCapabilities, String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ClientMenu {
|
||||||
|
fn disabled_reason(&self, operation: Operation, catalog: &super::i18n::Catalog) -> Option<String> {
|
||||||
|
if !ClientMenuCapabilities::covers(operation) { return None; }
|
||||||
|
if operation == Operation::ClientVolume && self.own {
|
||||||
|
return Some(catalog.text("admin.denied"));
|
||||||
|
}
|
||||||
|
match &self.result {
|
||||||
|
Some(Ok(capabilities)) => (capabilities.allows(operation) != Some(true)).then(|| catalog.text("admin.denied")),
|
||||||
|
_ if operation == Operation::ClientVolume => None, // This workflow adjusts local playback.
|
||||||
|
Some(Err(error)) => Some(error.clone()),
|
||||||
|
None => Some(catalog.text("native.status.loading")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn selected_connected_session(presentation: &ShellPresentation) -> Option<&SessionKey> {
|
fn selected_connected_session(presentation: &ShellPresentation) -> Option<&SessionKey> {
|
||||||
presentation.tabs.iter().find(|tab| tab.selected && tab.connected)?.target.session.as_ref()
|
presentation.tabs.iter().find(|tab| tab.selected && tab.connected)?.target.session.as_ref()
|
||||||
}
|
}
|
||||||
@@ -33,6 +56,7 @@ struct State {
|
|||||||
fields:Rc<VecModel<ShellField>>, tree:Rc<VecModel<ShellRow>>, bookmarks:Rc<VecModel<ShellRow>>, contacts:Rc<VecModel<ShellRow>>, entries:Rc<VecModel<ShellRow>>,
|
fields:Rc<VecModel<ShellField>>, tree:Rc<VecModel<ShellRow>>, bookmarks:Rc<VecModel<ShellRow>>, contacts:Rc<VecModel<ShellRow>>, entries:Rc<VecModel<ShellRow>>,
|
||||||
held_target:Option<Target>, menu_target:Option<Target>,
|
held_target:Option<Target>, menu_target:Option<Target>,
|
||||||
menu_epoch:u64, menu_actions:BTreeMap<String,Action>,
|
menu_epoch:u64, menu_actions:BTreeMap<String,Action>,
|
||||||
|
client_menu: Option<ClientMenu>,
|
||||||
bookmark_menu:bool,
|
bookmark_menu:bool,
|
||||||
press_epoch:u64, pressed_row:Option<String>, suppress_click:Option<String>,
|
press_epoch:u64, pressed_row:Option<String>, suppress_click:Option<String>,
|
||||||
bookmark_drag:Option<Target>,
|
bookmark_drag:Option<Target>,
|
||||||
@@ -41,9 +65,21 @@ struct State {
|
|||||||
stream_discovery: Option<StreamDiscovery>,
|
stream_discovery: Option<StreamDiscovery>,
|
||||||
}
|
}
|
||||||
impl Default for State {
|
impl Default for State {
|
||||||
fn default()->Self { Self {presentation:ShellPresentation::default(),targets:BTreeMap::new(),actions:BTreeMap::new(),contexts:BTreeMap::new(),editor:None,stack:vec![],destination:Destination::Servers,fields:Rc::new(VecModel::default()),tree:Rc::new(VecModel::default()),bookmarks:Rc::new(VecModel::default()),contacts:Rc::new(VecModel::default()),entries:Rc::new(VecModel::default()),held_target:None,menu_target:None,menu_epoch:0,menu_actions:BTreeMap::new(),bookmark_menu:false,press_epoch:0,pressed_row:None,suppress_click:None,bookmark_drag:None,popouts:BTreeMap::new(),streams_visit:0,stream_discovery:None} }
|
fn default()->Self { Self {presentation:ShellPresentation::default(),targets:BTreeMap::new(),actions:BTreeMap::new(),contexts:BTreeMap::new(),editor:None,stack:vec![],destination:Destination::Servers,fields:Rc::new(VecModel::default()),tree:Rc::new(VecModel::default()),bookmarks:Rc::new(VecModel::default()),contacts:Rc::new(VecModel::default()),entries:Rc::new(VecModel::default()),held_target:None,menu_target:None,menu_epoch:0,menu_actions:BTreeMap::new(),client_menu:None,bookmark_menu:false,press_epoch:0,pressed_row:None,suppress_click:None,bookmark_drag:None,popouts:BTreeMap::new(),streams_visit:0,stream_discovery:None} }
|
||||||
}
|
}
|
||||||
impl State {
|
impl State {
|
||||||
|
fn cancel_row_press(&mut self) {
|
||||||
|
self.press_epoch = self.press_epoch.wrapping_add(1);
|
||||||
|
self.pressed_row = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client_menu_current(&self, presentation: &ShellPresentation) -> bool {
|
||||||
|
let (Some(menu), Some(target)) = (&self.client_menu, &self.menu_target) else { return false; };
|
||||||
|
self.destination == Destination::Servers && target.session.is_some()
|
||||||
|
&& target.session.as_ref() == selected_connected_session(presentation)
|
||||||
|
&& self.targets.get(&menu.row) == Some(target)
|
||||||
|
}
|
||||||
|
|
||||||
fn clear_stream_discovery(&mut self, bridge: &ShellBridge<'_>) {
|
fn clear_stream_discovery(&mut self, bridge: &ShellBridge<'_>) {
|
||||||
if self.stream_discovery.take().is_some_and(|discovery| discovery.error.is_some()) {
|
if self.stream_discovery.take().is_some_and(|discovery| discovery.error.is_some()) {
|
||||||
bridge.set_error(self.presentation.error.as_str().into());
|
bridge.set_error(self.presentation.error.as_str().into());
|
||||||
@@ -73,6 +109,13 @@ fn menu_commands(state:&mut State,actions:&[Action])->ModelRc<ShellCommand> {
|
|||||||
let mut rows=Vec::with_capacity(actions.len());
|
let mut rows=Vec::with_capacity(actions.len());
|
||||||
let mut section="";
|
let mut section="";
|
||||||
for (index,action) in actions.iter().enumerate() {
|
for (index,action) in actions.iter().enumerate() {
|
||||||
|
let mut action = action.clone();
|
||||||
|
if action.enabled && state.menu_target.as_ref() == Some(&action.target) {
|
||||||
|
if let Some(reason) = state.client_menu.as_ref().and_then(|menu| menu.disabled_reason(action.operation, &state.presentation.catalog)) {
|
||||||
|
action.enabled = false;
|
||||||
|
action.reason = reason;
|
||||||
|
}
|
||||||
|
}
|
||||||
let (next,glyph)=match action.operation {
|
let (next,glyph)=match action.operation {
|
||||||
ClientPoke=>("",20), ClientVolume=>("",10), ClientConnectionInfo=>("",21),
|
ClientPoke=>("",20), ClientVolume=>("",10), ClientConnectionInfo=>("",21),
|
||||||
ClientInfo|ChannelInfo|ServerInfo=>("",16), ClientPrivateChat|ServerChat=>("",3),
|
ClientInfo|ChannelInfo|ServerInfo=>("",16), ClientPrivateChat|ServerChat=>("",3),
|
||||||
@@ -90,13 +133,13 @@ fn menu_commands(state:&mut State,actions:&[Action])->ModelRc<ShellCommand> {
|
|||||||
}
|
}
|
||||||
section=next;
|
section=next;
|
||||||
let id=format!("popup/{}/{index}/{}",state.menu_epoch,action.id);
|
let id=format!("popup/{}/{index}/{}",state.menu_epoch,action.id);
|
||||||
let mut row=command(action,id.clone());row.glyph=glyph;
|
let mut row=command(&action,id.clone());row.glyph=glyph;
|
||||||
state.menu_actions.insert(id,action.clone());rows.push(row);
|
state.menu_actions.insert(id,action);rows.push(row);
|
||||||
}
|
}
|
||||||
model(rows)
|
model(rows)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn open_menu(ui:&AppWindow,state:&mut State,target:Option<Target>,title:&str,actions:&[Action],x:f32,y:f32) {
|
fn open_menu(ui:&AppWindow,state:&mut State,target:Option<Target>,title:&str,actions:&[Action],client_menu:Option<ClientMenu>,x:f32,y:f32) {
|
||||||
let bridge=ui.global::<ShellBridge>();
|
let bridge=ui.global::<ShellBridge>();
|
||||||
bridge.set_menu_glyph(match target.as_ref().map(|target|&target.entity) {
|
bridge.set_menu_glyph(match target.as_ref().map(|target|&target.entity) {
|
||||||
Some(Entity::Server{..}|Entity::Connection)=>0, Some(Entity::Channel{..})=>1, Some(Entity::Client{..}|Entity::Contact(_))=>2,
|
Some(Entity::Server{..}|Entity::Connection)=>0, Some(Entity::Channel{..})=>1, Some(Entity::Client{..}|Entity::Contact(_))=>2,
|
||||||
@@ -104,14 +147,32 @@ fn open_menu(ui:&AppWindow,state:&mut State,target:Option<Target>,title:&str,act
|
|||||||
});
|
});
|
||||||
// Identical operations on separately opened menus are different captures.
|
// Identical operations on separately opened menus are different captures.
|
||||||
state.menu_epoch=state.menu_epoch.wrapping_add(1);
|
state.menu_epoch=state.menu_epoch.wrapping_add(1);
|
||||||
|
state.cancel_row_press();
|
||||||
state.menu_target=target;
|
state.menu_target=target;
|
||||||
|
state.client_menu=client_menu;
|
||||||
state.bookmark_menu=false;
|
state.bookmark_menu=false;
|
||||||
bridge.set_menu_title(title.into());
|
bridge.set_menu_title(title.into());
|
||||||
bridge.set_menu_actions(menu_commands(state,actions));
|
bridge.set_menu_actions(menu_commands(state,actions));
|
||||||
bridge.set_menu_x(x);bridge.set_menu_y(y);bridge.set_menu_visible(true);
|
bridge.set_menu_x(x);bridge.set_menu_y(y);bridge.set_menu_visible(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn open_row_menu(ui:&AppWindow,state:&mut State,row:&str,target:Target,x:f32,y:f32)->ShellAction {
|
||||||
|
let client_menu=matches!(target.entity,Entity::Client{..}).then(|| ClientMenu {
|
||||||
|
row: row.into(),
|
||||||
|
own: state.presentation.tree.iter().any(|entry| entry.row.target == target
|
||||||
|
&& matches!(entry.appearance,TreeAppearance::Client { own:true,.. })),
|
||||||
|
result: None,
|
||||||
|
});
|
||||||
|
let live=client_menu.is_some();
|
||||||
|
let actions=state.contexts.get(row).cloned().unwrap_or_default();
|
||||||
|
open_menu(ui,state,Some(target.clone()),&target.name,&actions,client_menu,x,y);
|
||||||
|
if live { ShellAction::ClientContext { target,menu_epoch:state.menu_epoch } }
|
||||||
|
else { ShellAction::Context(target) }
|
||||||
|
}
|
||||||
fn close_menu(bridge:&ShellBridge,state:&mut State) {
|
fn close_menu(bridge:&ShellBridge,state:&mut State) {
|
||||||
state.menu_target=None;
|
state.menu_target=None;
|
||||||
|
state.client_menu=None;
|
||||||
|
state.cancel_row_press();
|
||||||
state.menu_actions.clear();
|
state.menu_actions.clear();
|
||||||
bridge.set_menu_visible(false);
|
bridge.set_menu_visible(false);
|
||||||
}
|
}
|
||||||
@@ -212,7 +273,7 @@ pub fn bind(ui:&AppWindow,emit:Arc<dyn Fn(ShellAction)+Send+Sync>)->ShellBinding
|
|||||||
b.set_tree(s.tree.clone().into());b.set_bookmarks(s.bookmarks.clone().into());b.set_contacts(s.contacts.clone().into());b.set_entries(s.entries.clone().into());ui.global::<DialogBridge>().set_fields(s.fields.clone().into());
|
b.set_tree(s.tree.clone().into());b.set_bookmarks(s.bookmarks.clone().into());b.set_contacts(s.contacts.clone().into());b.set_entries(s.entries.clone().into());ui.global::<DialogBridge>().set_fields(s.fields.clone().into());
|
||||||
}
|
}
|
||||||
let b=ui.global::<ShellBridge>();
|
let b=ui.global::<ShellBridge>();
|
||||||
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();b.on_navigate(move|index|{let destination=match index{1=>Destination::Chats,2=>Destination::Contacts,3=>Destination::Settings,_=>Destination::Servers};let mut s=s.borrow_mut();release_hold(&mut s,&e);s.destination=destination;s.stack.clear();if let Some(ui)=weak.upgrade(){let bridge=ui.global::<ShellBridge>();if destination!=Destination::Servers{s.clear_stream_discovery(&bridge);}bridge.set_destination(destination_index(destination));bridge.set_depth(0);}e(ShellAction::Navigate(destination));});}
|
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();b.on_navigate(move|index|{let destination=match index{1=>Destination::Chats,2=>Destination::Contacts,3=>Destination::Settings,_=>Destination::Servers};let mut s=s.borrow_mut();release_hold(&mut s,&e);s.destination=destination;s.stack.clear();if let Some(ui)=weak.upgrade(){let bridge=ui.global::<ShellBridge>();close_menu(&bridge,&mut s);if destination!=Destination::Servers{s.clear_stream_discovery(&bridge);}bridge.set_destination(destination_index(destination));bridge.set_depth(0);}e(ShellAction::Navigate(destination));});}
|
||||||
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();b.on_select_stage(move|index|{
|
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();b.on_select_stage(move|index|{
|
||||||
let Some(ui)=weak.upgrade()else{return};
|
let Some(ui)=weak.upgrade()else{return};
|
||||||
let bridge=ui.global::<ShellBridge>();
|
let bridge=ui.global::<ShellBridge>();
|
||||||
@@ -221,6 +282,7 @@ pub fn bind(ui:&AppWindow,emit:Arc<dyn Fn(ShellAction)+Send+Sync>)->ShellBinding
|
|||||||
bridge.set_stage(index);
|
bridge.set_stage(index);
|
||||||
let discover={
|
let discover={
|
||||||
let mut state=s.borrow_mut();
|
let mut state=s.borrow_mut();
|
||||||
|
close_menu(&bridge,&mut state);
|
||||||
state.clear_stream_discovery(&bridge);
|
state.clear_stream_discovery(&bridge);
|
||||||
if index==STREAMS_STAGE && state.destination==Destination::Servers {
|
if index==STREAMS_STAGE && state.destination==Destination::Servers {
|
||||||
selected_connected_session(&state.presentation).cloned().map(|key| {
|
selected_connected_session(&state.presentation).cloned().map(|key| {
|
||||||
@@ -240,6 +302,7 @@ pub fn bind(ui:&AppWindow,emit:Arc<dyn Fn(ShellAction)+Send+Sync>)->ShellBinding
|
|||||||
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();b.on_select(move|id|{
|
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();b.on_select(move|id|{
|
||||||
let mut s=s.borrow_mut();if s.suppress_click.take().as_deref()==Some(id.as_str()){return}
|
let mut s=s.borrow_mut();if s.suppress_click.take().as_deref()==Some(id.as_str()){return}
|
||||||
let Some(target)=s.targets.get(id.as_str()).cloned()else{return};
|
let Some(target)=s.targets.get(id.as_str()).cloned()else{return};
|
||||||
|
if let Some(ui)=weak.upgrade(){close_menu(&ui.global::<ShellBridge>(),&mut s);}
|
||||||
let bookmark_operation=match target.entity{Entity::BookmarkFolder(_)=>Some(Operation::BookmarkFolderOpen),Entity::Bookmark(_)=>Some(Operation::BookmarkConnect),_=>None};
|
let bookmark_operation=match target.entity{Entity::BookmarkFolder(_)=>Some(Operation::BookmarkFolderOpen),Entity::Bookmark(_)=>Some(Operation::BookmarkConnect),_=>None};
|
||||||
if let Some(operation)=bookmark_operation{
|
if let Some(operation)=bookmark_operation{
|
||||||
if operation==Operation::BookmarkFolderOpen{if let Some(ui)=weak.upgrade(){let bridge=ui.global::<ShellBridge>();bridge.set_sidebar_search("".into());filter_sidebar(&bridge);}}
|
if operation==Operation::BookmarkFolderOpen{if let Some(ui)=weak.upgrade(){let bridge=ui.global::<ShellBridge>();bridge.set_sidebar_search("".into());filter_sidebar(&bridge);}}
|
||||||
@@ -256,7 +319,11 @@ pub fn bind(ui:&AppWindow,emit:Arc<dyn Fn(ShellAction)+Send+Sync>)->ShellBinding
|
|||||||
e(ShellAction::Select(target));
|
e(ShellAction::Select(target));
|
||||||
});}
|
});}
|
||||||
{let s=state.clone();let e=emit.clone();b.on_expand(move|id|{if let Some(target)=s.borrow().targets.get(id.as_str()).cloned(){e(ShellAction::Expand(target));}});}
|
{let s=state.clone();let e=emit.clone();b.on_expand(move|id|{if let Some(target)=s.borrow().targets.get(id.as_str()).cloned(){e(ShellAction::Expand(target));}});}
|
||||||
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();b.on_context(move|id,x,y|{let mut s=s.borrow_mut();let Some(target)=s.targets.get(id.as_str()).cloned()else{return};let actions=s.contexts.get(id.as_str()).cloned().unwrap_or_default();if let Some(ui)=weak.upgrade(){open_menu(&ui,&mut s,Some(target.clone()),&target.name,&actions,x,y);}e(ShellAction::Context(target));});}
|
{let s=state.clone();let e=emit.clone();let weak=ui.as_weak();b.on_context(move|id,x,y|{
|
||||||
|
let Some(ui)=weak.upgrade()else{return};
|
||||||
|
let mut s=s.borrow_mut();let Some(target)=s.targets.get(id.as_str()).cloned()else{return};
|
||||||
|
e(open_row_menu(&ui,&mut s,id.as_str(),target,x,y));
|
||||||
|
});}
|
||||||
{
|
{
|
||||||
let state=state.clone();let emit=emit.clone();let weak=ui.as_weak();
|
let state=state.clone();let emit=emit.clone();let weak=ui.as_weak();
|
||||||
b.on_row_press(move|id,held,x,y|{
|
b.on_row_press(move|id,held,x,y|{
|
||||||
@@ -268,14 +335,12 @@ pub fn bind(ui:&AppWindow,emit:Arc<dyn Fn(ShellAction)+Send+Sync>)->ShellBinding
|
|||||||
slint::Timer::single_shot(std::time::Duration::from_millis(550),move||{
|
slint::Timer::single_shot(std::time::Duration::from_millis(550),move||{
|
||||||
let mut s=state.borrow_mut();if s.press_epoch!=epoch||s.pressed_row.as_deref()!=Some(id.as_str())||s.targets.get(id.as_str())!=Some(&target){return}
|
let mut s=state.borrow_mut();if s.press_epoch!=epoch||s.pressed_row.as_deref()!=Some(id.as_str())||s.targets.get(id.as_str())!=Some(&target){return}
|
||||||
s.suppress_click=Some(id.to_string());
|
s.suppress_click=Some(id.to_string());
|
||||||
let actions=s.contexts.get(id.as_str()).cloned().unwrap_or_default();
|
if let Some(ui)=weak.upgrade(){emit(open_row_menu(&ui,&mut s,id.as_str(),target,x,y));}
|
||||||
if let Some(ui)=weak.upgrade(){open_menu(&ui,&mut s,Some(target.clone()),&target.name,&actions,x,y);}
|
|
||||||
emit(ShellAction::Context(target));
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
{let s=state.clone();let weak=ui.as_weak();b.on_menu(move|x,y|{if let Some(ui)=weak.upgrade(){let mut s=s.borrow_mut();let actions=s.presentation.actions.clone();let title=s.presentation.catalog.text("native.shell.actions");open_menu(&ui,&mut s,None,&title,&actions,x,y);}});}
|
{let s=state.clone();let weak=ui.as_weak();b.on_menu(move|x,y|{if let Some(ui)=weak.upgrade(){let mut s=s.borrow_mut();let actions=s.presentation.actions.clone();let title=s.presentation.catalog.text("native.shell.actions");open_menu(&ui,&mut s,None,&title,&actions,None,x,y);}});}
|
||||||
{let s=state.clone();let weak=ui.as_weak();b.on_bookmark_menu(move|x,y|{if let Some(ui)=weak.upgrade(){let mut s=s.borrow_mut();let actions=s.presentation.actions.iter().filter(|action|matches!(action.operation,Operation::BookmarkCreate|Operation::BookmarkFolderCreate)).cloned().collect::<Vec<_>>();let title=s.presentation.catalog.text("ui.saved.servers");open_menu(&ui,&mut s,None,&title,&actions,x,y);s.bookmark_menu=true;}});}
|
{let s=state.clone();let weak=ui.as_weak();b.on_bookmark_menu(move|x,y|{if let Some(ui)=weak.upgrade(){let mut s=s.borrow_mut();let actions=s.presentation.actions.iter().filter(|action|matches!(action.operation,Operation::BookmarkCreate|Operation::BookmarkFolderCreate)).cloned().collect::<Vec<_>>();let title=s.presentation.catalog.text("ui.saved.servers");open_menu(&ui,&mut s,None,&title,&actions,None,x,y);s.bookmark_menu=true;}});}
|
||||||
{let s=state.clone();b.on_bookmark_drag_start(move|id|{let mut s=s.borrow_mut();s.bookmark_drag=s.targets.get(id.as_str()).filter(|target|matches!(target.entity,Entity::Channel{..})).cloned();});}
|
{let s=state.clone();b.on_bookmark_drag_start(move|id|{let mut s=s.borrow_mut();s.bookmark_drag=s.targets.get(id.as_str()).filter(|target|matches!(target.entity,Entity::Channel{..})).cloned();});}
|
||||||
{let s=state.clone();let e=emit.clone();b.on_bookmark_drag_end(move|id,drop_in_sidebar|{let mut s=s.borrow_mut();if let Some(target)=s.bookmark_drag.take().filter(|_|drop_in_sidebar&&s.suppress_click.is_none()){s.suppress_click=Some(id.to_string());e(ShellAction::Invoke{target,operation:Operation::BookmarkCreate});}});}
|
{let s=state.clone();let e=emit.clone();b.on_bookmark_drag_end(move|id,drop_in_sidebar|{let mut s=s.borrow_mut();if let Some(target)=s.bookmark_drag.take().filter(|_|drop_in_sidebar&&s.suppress_click.is_none()){s.suppress_click=Some(id.to_string());e(ShellAction::Invoke{target,operation:Operation::BookmarkCreate});}});}
|
||||||
{let s=state.clone();let weak=ui.as_weak();b.on_close_menu(move||{if let Some(ui)=weak.upgrade(){close_menu(&ui.global::<ShellBridge>(),&mut s.borrow_mut());}});}
|
{let s=state.clone();let weak=ui.as_weak();b.on_close_menu(move||{if let Some(ui)=weak.upgrade(){close_menu(&ui.global::<ShellBridge>(),&mut s.borrow_mut());}});}
|
||||||
@@ -367,6 +432,7 @@ fn cancel_editor(ui:&AppWindow,state:&mut State,emit:&Arc<dyn Fn(ShellAction)+Se
|
|||||||
fn back(ui:&AppWindow,state:&mut State,emit:&Arc<dyn Fn(ShellAction)+Send+Sync>){
|
fn back(ui:&AppWindow,state:&mut State,emit:&Arc<dyn Fn(ShellAction)+Send+Sync>){
|
||||||
release_hold(state,emit);
|
release_hold(state,emit);
|
||||||
if ui.global::<ShellBridge>().get_menu_visible(){close_menu(&ui.global::<ShellBridge>(),state);return}
|
if ui.global::<ShellBridge>().get_menu_visible(){close_menu(&ui.global::<ShellBridge>(),state);return}
|
||||||
|
state.cancel_row_press();
|
||||||
if !ui.global::<ShellBridge>().get_fullscreen_stream().is_empty(){ui.global::<ShellBridge>().set_fullscreen_stream("".into());return}
|
if !ui.global::<ShellBridge>().get_fullscreen_stream().is_empty(){ui.global::<ShellBridge>().set_fullscreen_stream("".into());return}
|
||||||
if cancel_editor(ui,state,emit){return}
|
if cancel_editor(ui,state,emit){return}
|
||||||
state.stack.pop();if state.stack.is_empty(){state.destination=Destination::Servers;}
|
state.stack.pop();if state.stack.is_empty(){state.destination=Destination::Servers;}
|
||||||
@@ -420,7 +486,7 @@ fn submit(ui:&AppWindow,state:&mut State,emit:&Arc<dyn Fn(ShellAction)+Send+Sync
|
|||||||
project_editor(ui,state);
|
project_editor(ui,state);
|
||||||
}
|
}
|
||||||
impl ShellBinding {
|
impl ShellBinding {
|
||||||
pub fn navigate(&self,ui:&AppWindow,destination:Destination){let mut state=self.state.borrow_mut();state.destination=destination;state.stack.clear();let bridge=ui.global::<ShellBridge>();if destination!=Destination::Servers{state.clear_stream_discovery(&bridge);}bridge.set_destination(destination_index(destination));bridge.set_depth(0);}
|
pub fn navigate(&self,ui:&AppWindow,destination:Destination){let mut state=self.state.borrow_mut();state.destination=destination;state.stack.clear();let bridge=ui.global::<ShellBridge>();close_menu(&bridge,&mut state);if destination!=Destination::Servers{state.clear_stream_discovery(&bridge);}bridge.set_destination(destination_index(destination));bridge.set_depth(0);}
|
||||||
pub(super) fn stream_discovery_error(&self,ui:&AppWindow,key:&SessionKey,visit:u64,error:String){
|
pub(super) fn stream_discovery_error(&self,ui:&AppWindow,key:&SessionKey,visit:u64,error:String){
|
||||||
let bridge=ui.global::<ShellBridge>();
|
let bridge=ui.global::<ShellBridge>();
|
||||||
if bridge.get_stage()!=STREAMS_STAGE{return}
|
if bridge.get_stage()!=STREAMS_STAGE{return}
|
||||||
@@ -430,12 +496,25 @@ impl ShellBinding {
|
|||||||
discovery.error=Some(error);
|
discovery.error=Some(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
pub(super) fn client_menu_context(&self,ui:&AppWindow,target:&Target,menu_epoch:u64,result:Result<ClientMenuCapabilities,String>) {
|
||||||
|
let bridge=ui.global::<ShellBridge>();
|
||||||
|
let mut state=self.state.borrow_mut();
|
||||||
|
let state=&mut *state;
|
||||||
|
if !bridge.get_menu_visible() || state.menu_epoch!=menu_epoch || state.menu_target.as_ref()!=Some(target)
|
||||||
|
|| !state.client_menu_current(&state.presentation) { return; }
|
||||||
|
let menu=state.client_menu.as_mut().expect("matching client menu");
|
||||||
|
if menu.result.is_some() { return; }
|
||||||
|
menu.result=Some(result);
|
||||||
|
let actions=state.contexts.get(&menu.row).cloned().unwrap_or_default();
|
||||||
|
bridge.set_menu_actions(menu_commands(state,&actions));
|
||||||
|
}
|
||||||
pub fn stream_effect(&self,ui:&AppWindow,target:&Target,popout:bool,close:bool)->Result<(),String>{let mut state=self.state.borrow_mut();let Some(stream)=state.presentation.streams.iter().find(|stream|&stream.target==target).cloned()else{return Ok(())};if close{if let Some((_,window))=state.popouts.remove(&stream.id){window.hide().map_err(|e|e.to_string())?;}if ui.global::<ShellBridge>().get_fullscreen_stream()==stream.id{ui.global::<ShellBridge>().set_fullscreen_stream("".into());}return Ok(())}if popout{open_popout(ui,&mut state,&stream)}else{ui.global::<ShellBridge>().set_fullscreen_stream(stream.id.into());Ok(())}}
|
pub fn stream_effect(&self,ui:&AppWindow,target:&Target,popout:bool,close:bool)->Result<(),String>{let mut state=self.state.borrow_mut();let Some(stream)=state.presentation.streams.iter().find(|stream|&stream.target==target).cloned()else{return Ok(())};if close{if let Some((_,window))=state.popouts.remove(&stream.id){window.hide().map_err(|e|e.to_string())?;}if ui.global::<ShellBridge>().get_fullscreen_stream()==stream.id{ui.global::<ShellBridge>().set_fullscreen_stream("".into());}return Ok(())}if popout{open_popout(ui,&mut state,&stream)}else{ui.global::<ShellBridge>().set_fullscreen_stream(stream.id.into());Ok(())}}
|
||||||
pub fn update_frames(&self,ui:&AppWindow,frames:&[(String,slint::Image)]){let mut state=self.state.borrow_mut();let model=ui.global::<ShellBridge>().get_streams();for(id,image)in frames{if let Some(stream)=state.presentation.streams.iter_mut().find(|stream|stream.id==*id){stream.frame=image.clone();stream.has_frame=true;}for row in 0..model.row_count(){if let Some(mut stream)=model.row_data(row){if stream.id.as_str()==id{stream.frame=image.clone();stream.has_frame=true;model.set_row_data(row,stream.clone());if let Some((_,window))=state.popouts.get(id){window.set_item(stream);}break}}}}}
|
pub fn update_frames(&self,ui:&AppWindow,frames:&[(String,slint::Image)]){let mut state=self.state.borrow_mut();let model=ui.global::<ShellBridge>().get_streams();for(id,image)in frames{if let Some(stream)=state.presentation.streams.iter_mut().find(|stream|stream.id==*id){stream.frame=image.clone();stream.has_frame=true;}for row in 0..model.row_count(){if let Some(mut stream)=model.row_data(row){if stream.id.as_str()==id{stream.frame=image.clone();stream.has_frame=true;model.set_row_data(row,stream.clone());if let Some((_,window))=state.popouts.get(id){window.set_item(stream);}break}}}}}
|
||||||
/// Call on the Slint event loop after runtime has coalesced a snapshot.
|
/// Call on the Slint event loop after runtime has coalesced a snapshot.
|
||||||
pub fn present(&self,ui:&AppWindow,p:ShellPresentation){
|
pub fn present(&self,ui:&AppWindow,p:ShellPresentation){
|
||||||
let mut s=self.state.borrow_mut();
|
let mut s=self.state.borrow_mut();
|
||||||
if s.held_target.as_ref().is_some_and(|target|p.voice.as_ref().is_none_or(|v|&v.target!=target||!v.ptt_enabled)){release_hold(&mut s,&self.emit);}
|
if s.held_target.as_ref().is_some_and(|target|p.voice.as_ref().is_none_or(|v|&v.target!=target||!v.ptt_enabled)){release_hold(&mut s,&self.emit);}
|
||||||
|
if selected_connected_session(&p)!=selected_connected_session(&s.presentation) { s.cancel_row_press(); }
|
||||||
s.targets.clear();s.actions.clear();s.contexts.clear();
|
s.targets.clear();s.actions.clear();s.contexts.clear();
|
||||||
let b=ui.global::<ShellBridge>();let c=p.catalog;
|
let b=ui.global::<ShellBridge>();let c=p.catalog;
|
||||||
let tree=tree_rows(&mut s,&p.tree);reconcile(&s.tree,tree);
|
let tree=tree_rows(&mut s,&p.tree);reconcile(&s.tree,tree);
|
||||||
@@ -533,7 +612,11 @@ impl ShellBinding {
|
|||||||
s.editor = None;
|
s.editor = None;
|
||||||
}
|
}
|
||||||
if b.get_menu_visible(){
|
if b.get_menu_visible(){
|
||||||
if let Some(target)=&s.menu_target {
|
if let Some(menu)=&s.client_menu {
|
||||||
|
if s.client_menu_current(&p) {
|
||||||
|
if let Some(actions)=s.contexts.get(&menu.row).cloned() { b.set_menu_actions(menu_commands(&mut s,&actions)); }
|
||||||
|
} else { close_menu(&b,&mut s); }
|
||||||
|
}else if let Some(target)=&s.menu_target {
|
||||||
if let Some(actions)=s.targets.iter().find_map(|(id,current)|if current==target{s.contexts.get(id)}else{None}).cloned(){b.set_menu_actions(menu_commands(&mut s,&actions));}
|
if let Some(actions)=s.targets.iter().find_map(|(id,current)|if current==target{s.contexts.get(id)}else{None}).cloned(){b.set_menu_actions(menu_commands(&mut s,&actions));}
|
||||||
else{close_menu(&b,&mut s);}
|
else{close_menu(&b,&mut s);}
|
||||||
}else if s.bookmark_menu{let actions=p.actions.iter().filter(|action|matches!(action.operation,Operation::BookmarkCreate|Operation::BookmarkFolderCreate)).cloned().collect::<Vec<_>>();b.set_menu_actions(menu_commands(&mut s,&actions));}
|
}else if s.bookmark_menu{let actions=p.actions.iter().filter(|action|matches!(action.operation,Operation::BookmarkCreate|Operation::BookmarkFolderCreate)).cloned().collect::<Vec<_>>();b.set_menu_actions(menu_commands(&mut s,&actions));}
|
||||||
@@ -598,18 +681,145 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(any(target_os="android",target_os="ios")))]
|
#[cfg(not(any(target_os="android",target_os="ios")))]
|
||||||
fn headless_shell_window() -> AppWindow {
|
fn headless_shell_window() -> AppWindow { headless_shell_window_with_clock(None) }
|
||||||
|
|
||||||
|
#[cfg(not(any(target_os="android",target_os="ios")))]
|
||||||
|
fn headless_shell_window_with_clock(clock:Option<Rc<std::cell::Cell<std::time::Duration>>>) -> AppWindow {
|
||||||
use slint::platform::{Platform, WindowAdapter, software_renderer::{MinimalSoftwareWindow, RepaintBufferType}};
|
use slint::platform::{Platform, WindowAdapter, software_renderer::{MinimalSoftwareWindow, RepaintBufferType}};
|
||||||
struct Headless;
|
struct Headless(Option<Rc<std::cell::Cell<std::time::Duration>>>,std::time::Instant);
|
||||||
impl Platform for Headless {
|
impl Platform for Headless {
|
||||||
fn create_window_adapter(&self) -> Result<Rc<dyn WindowAdapter>, slint::PlatformError> {
|
fn create_window_adapter(&self) -> Result<Rc<dyn WindowAdapter>, slint::PlatformError> {
|
||||||
Ok(MinimalSoftwareWindow::new(RepaintBufferType::NewBuffer))
|
Ok(MinimalSoftwareWindow::new(RepaintBufferType::NewBuffer))
|
||||||
}
|
}
|
||||||
|
fn duration_since_start(&self) -> std::time::Duration {
|
||||||
|
self.0.as_ref().map_or_else(||self.1.elapsed(),|clock|clock.get())
|
||||||
}
|
}
|
||||||
slint::platform::set_platform(Box::new(Headless)).unwrap();
|
}
|
||||||
|
slint::platform::set_platform(Box::new(Headless(clock,std::time::Instant::now()))).unwrap();
|
||||||
AppWindow::new().unwrap()
|
AppWindow::new().unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(not(any(target_os="android",target_os="ios")))]
|
||||||
|
#[test]
|
||||||
|
fn client_popup_loads_once_and_never_retargets_a_reopened_menu() {
|
||||||
|
use Operation::*;
|
||||||
|
use serde_json::json;
|
||||||
|
use std::{cell::Cell,sync::Mutex,time::Duration};
|
||||||
|
|
||||||
|
let clock=Rc::new(Cell::new(Duration::ZERO));
|
||||||
|
let ui=headless_shell_window_with_clock(Some(clock.clone()));
|
||||||
|
let bridge=ui.global::<ShellBridge>();
|
||||||
|
let events=Arc::new(Mutex::new(Vec::new()));
|
||||||
|
let sent=events.clone();
|
||||||
|
let shell=bind(&ui,Arc::new(move|action|sent.lock().unwrap().push(action)));
|
||||||
|
let take=||std::mem::take(&mut *events.lock().unwrap());
|
||||||
|
let key=SessionKey{connection_id:"fixture".into(),session:1,generation:2};
|
||||||
|
let catalog=ShellPresentation::default().catalog;
|
||||||
|
let present=|key:&SessionKey,uid:&str,own| {
|
||||||
|
let target=Target{session:Some(key.clone()),entity:Entity::Client{id:42,uid:uid.into(),channel_id:4},name:"Peer".into(),own_channel_id:Some(2)};
|
||||||
|
let mut actions=crate::app::runtime::model::actions(&target,&[ClientPoke,ClientVolume,ClientServerGroupAdd,
|
||||||
|
ClientKickServer,ClientMove,ClientPrivateChat,ContactAdd,ClientWhisperAdd,TalkGrant],&catalog);
|
||||||
|
let locally_disabled=actions.iter_mut().find(|action|action.operation==ClientMove).unwrap();
|
||||||
|
locally_disabled.enabled=false;
|
||||||
|
locally_disabled.reason="Local restriction".into();
|
||||||
|
shell.present(&ui,ShellPresentation{catalog,
|
||||||
|
tabs:vec![Tab{target:Target{entity:Entity::Connection,..target.clone()},title:"Fixture".into(),
|
||||||
|
selected:true,microphone_owner:false,connected:true,unread:0,actions:vec![]}],
|
||||||
|
tree:vec![TreeEntry{row:Entry{id:"peer".into(),target:target.clone(),title:"Peer".into(),subtitle:String::new(),
|
||||||
|
actions,depth:0,selected:false,expanded:false,expandable:false,talking:false,muted:false,unread:0,waveform:vec![]},
|
||||||
|
appearance:TreeAppearance::Client{own,contact:false,deafened:false,away:false,recording:false,streaming:false}}],
|
||||||
|
..ShellPresentation::default()});
|
||||||
|
target
|
||||||
|
};
|
||||||
|
let reply=|target:&Target| {
|
||||||
|
let Entity::Client{id,uid,channel_id}=&target.entity else{panic!("client target required")};
|
||||||
|
crate::app::server_actions::client_menu_capabilities(target,&json!({
|
||||||
|
"generation": target.session.as_ref().unwrap().generation, "client_id": id, "uid": uid, "channel_id": channel_id,
|
||||||
|
"capabilities":{"poke":{"allowed":true},"kick_server":{"allowed":false},
|
||||||
|
"move_to_own_channel":{"allowed":true},"volume":{"allowed":true}},
|
||||||
|
"server_groups":[{"id":9,"name":"Available","member":false,"can_add":{"allowed":null}}], "channel_groups":[]
|
||||||
|
})).unwrap()
|
||||||
|
};
|
||||||
|
let command=|op| bridge.get_menu_actions().iter().find(|row|row.id.as_str().ends_with(format!("/{op:?}").as_str())).unwrap();
|
||||||
|
let pending=|| {
|
||||||
|
assert!(bridge.get_menu_visible());
|
||||||
|
assert!(!command(ClientPoke).enabled);
|
||||||
|
assert_eq!(command(ClientPoke).reason.as_str(),catalog.text("native.status.loading"));
|
||||||
|
};
|
||||||
|
let capture=||match take().as_slice() {
|
||||||
|
[ShellAction::ClientContext{target,menu_epoch}] => (target.clone(),*menu_epoch),
|
||||||
|
_ => panic!("one client menu request expected"),
|
||||||
|
};
|
||||||
|
let open=|| {bridge.invoke_context("tree/peer".into(),8.,12.);capture()};
|
||||||
|
|
||||||
|
let target=present(&key,"peer",false);
|
||||||
|
bridge.invoke_row_press("tree/peer".into(),true,8.,12.);
|
||||||
|
assert!(take().is_empty());
|
||||||
|
clock.set(Duration::from_millis(551));
|
||||||
|
slint::platform::update_timers_and_animations();
|
||||||
|
let (captured,first)=capture();
|
||||||
|
assert_eq!(captured,target);
|
||||||
|
bridge.invoke_row_press("tree/peer".into(),false,8.,12.);
|
||||||
|
bridge.invoke_select("tree/peer".into());
|
||||||
|
present(&key,"peer",false);
|
||||||
|
assert!(take().is_empty());
|
||||||
|
pending();
|
||||||
|
for op in [ClientVolume,ClientPrivateChat,ContactAdd,ClientWhisperAdd,TalkGrant] {assert!(command(op).enabled,"{op:?}");}
|
||||||
|
let stale_id=command(ClientPoke).id;
|
||||||
|
bridge.invoke_invoke(stale_id.clone());
|
||||||
|
assert!(take().is_empty());
|
||||||
|
|
||||||
|
shell.client_menu_context(&ui,&target,first,Err("Server refused this read".into()));
|
||||||
|
present(&key,"peer",false);
|
||||||
|
assert!(!command(ClientPoke).enabled);
|
||||||
|
assert_eq!(command(ClientPoke).reason.as_str(),"Server refused this read");
|
||||||
|
bridge.invoke_invoke(command(ClientWhisperAdd).id);
|
||||||
|
assert!(matches!(take().as_slice(),[ShellAction::Invoke{target:captured,operation:ClientWhisperAdd}] if captured==&target));
|
||||||
|
shell.client_menu_context(&ui,&target,first,Ok(reply(&target)));
|
||||||
|
assert!(!bridge.get_menu_visible());
|
||||||
|
|
||||||
|
let (_,second)=open();
|
||||||
|
assert_ne!(first,second);
|
||||||
|
shell.client_menu_context(&ui,&target,first,Err("Late refusal".into()));
|
||||||
|
shell.client_menu_context(&ui,&target,first,Ok(reply(&target)));
|
||||||
|
bridge.invoke_invoke(stale_id);
|
||||||
|
assert!(take().is_empty());
|
||||||
|
pending();
|
||||||
|
|
||||||
|
let reused=present(&key,"recycled",true);
|
||||||
|
assert!(!bridge.get_menu_visible());
|
||||||
|
let (captured,third)=open();
|
||||||
|
assert_eq!(captured,reused);
|
||||||
|
assert!(!command(ClientVolume).enabled);
|
||||||
|
shell.client_menu_context(&ui,&target,second,Ok(reply(&target)));
|
||||||
|
shell.client_menu_context(&ui,&target,third,Err("Wrong UID for this epoch".into()));
|
||||||
|
pending();
|
||||||
|
|
||||||
|
let new_target=present(&SessionKey{session:2,generation:3,..key},"recycled",false);
|
||||||
|
assert!(!bridge.get_menu_visible());
|
||||||
|
let (_,fourth)=open();
|
||||||
|
shell.client_menu_context(&ui,&reused,third,Err("Refusal from replaced session".into()));
|
||||||
|
pending();
|
||||||
|
bridge.invoke_select_stage(1);
|
||||||
|
assert!(matches!(take().as_slice(),[ShellAction::LeaveRecordingDetail]));
|
||||||
|
shell.client_menu_context(&ui,&new_target,fourth,Ok(reply(&new_target)));
|
||||||
|
assert!(!bridge.get_menu_visible() && bridge.get_error().is_empty());
|
||||||
|
|
||||||
|
let (_,fifth)=open();
|
||||||
|
let add=command(ClientServerGroupAdd).id;
|
||||||
|
shell.client_menu_context(&ui,&new_target,fifth,Ok(reply(&new_target)));
|
||||||
|
assert!(command(ClientPoke).enabled);
|
||||||
|
assert!(!command(ClientKickServer).enabled);
|
||||||
|
assert!(!command(ClientMove).enabled);
|
||||||
|
assert_eq!(command(ClientMove).reason.as_str(),"Local restriction");
|
||||||
|
assert!(command(TalkGrant).enabled);
|
||||||
|
assert!(command(ClientServerGroupAdd).enabled);
|
||||||
|
assert_eq!(command(ClientServerGroupAdd).id,add);
|
||||||
|
bridge.invoke_invoke(add);
|
||||||
|
assert!(matches!(take().as_slice(),[ShellAction::Invoke{target:captured,operation:ClientServerGroupAdd}] if captured==&new_target));
|
||||||
|
assert!(!ui.global::<DialogBridge>().get_visible());
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(not(any(target_os="android",target_os="ios")))]
|
#[cfg(not(any(target_os="android",target_os="ios")))]
|
||||||
#[test]
|
#[test]
|
||||||
fn streams_stage_discovers_only_on_entry_for_selected_connected_session() {
|
fn streams_stage_discovers_only_on_entry_for_selected_connected_session() {
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ pub type Values = BTreeMap<String, FieldValue>;
|
|||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub enum ShellAction {
|
pub enum ShellAction {
|
||||||
Navigate(Destination), Back, Select(Target), Expand(Target), Context(Target),
|
Navigate(Destination), Back, Select(Target), Expand(Target), Context(Target),
|
||||||
|
ClientContext { target: Target, menu_epoch: u64 },
|
||||||
LeaveRecordingDetail,
|
LeaveRecordingDetail,
|
||||||
DiscoverChannelStreams { key: SessionKey, visit: u64 },
|
DiscoverChannelStreams { key: SessionKey, visit: u64 },
|
||||||
Invoke { target: Target, operation: Operation },
|
Invoke { target: Target, operation: Operation },
|
||||||
|
|||||||
Reference in new issue
Block a user