diff --git a/crates/voelin-ui-vm/src/image.rs b/crates/voelin-ui-vm/src/image.rs index 31685ad..6854190 100644 --- a/crates/voelin-ui-vm/src/image.rs +++ b/crates/voelin-ui-vm/src/image.rs @@ -59,7 +59,7 @@ impl fmt::Debug for ImageSource { /// What identifies a file's content without reading it: its length and the /// time it was last written. Both zero for a file that is missing. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct Stamp { len: u64, modified: Option, diff --git a/crates/voelin-ui-vm/src/servers/logic.rs b/crates/voelin-ui-vm/src/servers/logic.rs index d184fb7..56ef1c5 100644 --- a/crates/voelin-ui-vm/src/servers/logic.rs +++ b/crates/voelin-ui-vm/src/servers/logic.rs @@ -339,6 +339,16 @@ pub fn search_members(state: &mut AppState, cx: &mut Cx<'_>, text: String) } } +/// Open the card of a client of the server shown over the members panel +/// (`None` closes it). +pub fn open_member(state: &mut AppState, cx: &mut Cx<'_>, client: Option) { + let Some(view) = state.current.and_then(|id| state.sessions.get_mut(&id)) else { return }; + if view.member_card != client { + view.member_card = client; + cx.update.refresh.member_card = true; + } +} + /// The voice channel view was opened or closed: its chat is our channel's, /// and its people lead the members panel. pub fn show_voice_view(state: &mut AppState, cx: &mut Cx<'_>, on: bool) { @@ -863,6 +873,32 @@ mod tests { assert!(st.sessions[&1].collapsed.is_empty()); } + /// The card of a client opens over the members panel of the server shown + /// and closes again; the card is drawn again only when it changed. + #[test] + fn the_member_card_opens_and_closes() { + let (mut st, host) = (state(), Fake::default()); + st.current = Some(1); + st.sessions.insert(1, SessionView::default()); + let mut cx = Cx::new(&host); + open_member(&mut st, &mut cx, Some(11)); + assert_eq!(st.sessions[&1].member_card, Some(11)); + assert!(cx.update.refresh.member_card); + + let mut cx = Cx::new(&host); + open_member(&mut st, &mut cx, Some(11)); + assert!(!cx.update.refresh.member_card, "the same card: nothing to draw"); + open_member(&mut st, &mut cx, None); + assert_eq!(st.sessions[&1].member_card, None); + assert!(cx.update.refresh.member_card); + + // No server on screen: no card. + st.current = None; + let mut cx = Cx::new(&host); + open_member(&mut st, &mut cx, Some(11)); + assert!(cx.update.refresh.is_empty()); + } + /// A chat takes its server's colour only while it is a server chat of a /// server in the list: a chat whose server is gone, and a chat that is a /// channel's or a person's, take the colour of their own title. Black diff --git a/crates/voelin-ui-vm/src/servers/sequence.rs b/crates/voelin-ui-vm/src/servers/sequence.rs index 8acc070..dd2bf58 100644 --- a/crates/voelin-ui-vm/src/servers/sequence.rs +++ b/crates/voelin-ui-vm/src/servers/sequence.rs @@ -25,6 +25,7 @@ use std::time::Instant; use tracing::{debug, info, warn}; use voelin_core::stream::PeerConfig; use voelin_core::{Command, IdentityBlob, ObserveState}; +use voelin_model::ChannelId; use voelin_store::{Bookmark, QueryTransport, Secrets, Store}; use super::logic::{self, CREATED_IDENTITY, GatewayFound, ObservePlan}; @@ -147,6 +148,67 @@ pub fn connect_voice_to( true } +/// Join a channel of a session (a double-click in the tree, joining a friend): +/// move there with voice ([`logic::join_channel`]), ask for the password of a +/// locked channel first, and without voice on that server connect into it. +pub fn join_channel( + state: &mut AppState, + cx: &mut Cx<'_>, + backing: &Backing<'_>, + session: i64, + channel: ChannelId, + stream_peer: Option, +) { + if let Some(password) = logic::join_channel(state, cx, session, channel) { + connect_into(state, cx, backing, session, channel, password, stream_peer); + } +} + +/// The password dialog's Join ([`logic::join_with_password`]): the same, with +/// the password given. +pub fn join_with_password( + state: &mut AppState, + cx: &mut Cx<'_>, + backing: &Backing<'_>, + password: String, + stream_peer: Option, +) { + if let Some((session, channel, password)) = logic::join_with_password(state, cx, password) { + connect_into(state, cx, backing, session, channel, password, stream_peer); + } +} + +/// Connect voice into a channel of a server that has none: the server is +/// shown first, and the channel is named by its id (by its name the server +/// finds only a top-level channel, and a subchannel's name connects into the +/// default channel). Joined again after the connect if the server puts us +/// elsewhere ([`logic::join_after_connect`]). +fn connect_into( + state: &mut AppState, + cx: &mut Cx<'_>, + backing: &Backing<'_>, + session: i64, + channel: ChannelId, + password: Option, + stream_peer: Option, +) { + if state.current != Some(session) { + select_server(state, cx, backing, session); + } + let asked = connect_voice_to( + state, + cx, + backing, + Some(format!("/{channel}")), + password, + None, + stream_peer, + ); + if asked { + logic::join_after_connect(state, session, channel); + } +} + /// Ask for the gateway of a server to be looked up ([`voelin_core::discover`]), /// once a run ([`logic::discover_wanted`]): every one the server publishes is /// kept, best first, and tried in turn; they take the place of a stored one @@ -356,9 +418,13 @@ pub fn delete_bookmark( mod tests { use voelin_store::{MemorySecrets, QueryConfig}; + use std::sync::Arc; + + use voelin_core::VoiceState; + use super::*; use crate::host::Update; - use crate::host::testing::{Fake, State}; + use crate::host::testing::{Fake, State, presence, session}; /// A store, secrets and a front end of the tests' own. struct Rig { @@ -482,6 +548,115 @@ mod tests { assert!(!asked, "no server on screen"); } + /// A state whose first server has a session with `voice` and the channels + /// of `host::testing::presence`: Lobby (1), Games (2, where we are). + fn joined(rig: &Rig, voice: VoiceState, locked: Option) -> (State, i64) { + let mut state = rig.state(&[("Nightfall", "ts.example")]); + let id = state.current.unwrap(); + let mut presence = (*presence()).clone(); + if let Some(channel) = locked { + presence.channels.get_mut(&channel).unwrap().has_password = true; + } + let view = state.sessions.entry(id).or_default(); + view.presence = Arc::new(presence); + view.state = session(voice, Some(2)); + (state, id) + } + + /// A double-click in the tree with voice up asks the engine to move there, + /// and connects nothing. + #[test] + fn joining_a_channel_with_voice_moves_there() { + let rig = Rig::new(); + let (mut state, id) = joined(&rig, VoiceState::Connected, None); + let (_, update) = + rig.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, id, 1, None)); + let [Command::MoveToChannel { session, channel, password }] = &update.commands[..] else { + panic!("{:?}", update.commands) + }; + assert_eq!((*session, *channel, password.as_deref()), (id as u64, 1, None)); + assert!(update.password.is_none()); + } + + /// With no voice on the server the join connects into the channel, named + /// by its id, and remembers to join it again if the server puts us + /// elsewhere; a server that is not the one shown is shown first. + #[test] + fn joining_a_channel_without_voice_connects_into_it() { + let rig = Rig::new(); + let (mut state, id) = joined(&rig, VoiceState::Disconnected, None); + let (_, update) = + rig.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, id, 1, None)); + let [Command::ConnectVoice { session, options }] = &update.commands[..] else { + panic!("{:?}", update.commands) + }; + assert_eq!((*session, options.channel.as_deref()), (id as u64, Some("/1"))); + assert_eq!(state.sessions[&id].join_after_connect, Some(1)); + assert_eq!(update.status.as_deref(), Some("Connecting to ts.example…")); + + // Another server is shown, then connected into the channel. + let other = rig.store.add_bookmark(&Bookmark { + name: "Lounge".into(), + address: "lounge.example".into(), + nickname: "Nova".into(), + ..Default::default() + }); + state.bookmarks = rig.store.bookmarks().unwrap(); + let other = other.unwrap(); + let view = state.sessions.entry(other).or_default(); + view.presence = Arc::new((*presence()).clone()); + let (_, update) = rig + .run(&mut state, |state, cx, backing| join_channel(state, cx, backing, other, 2, None)); + assert_eq!(state.current, Some(other)); + assert!( + update.commands.iter().any(|c| matches!(c, Command::ConnectVoice { session, options } + if *session == other as u64 && options.channel.as_deref() == Some("/2"))), + "{:?}", + update.commands + ); + } + + /// A locked channel asks for its password first (nothing is sent), the + /// dialog's Join sends it with the move, and the same channel does not ask + /// again this connection. + #[test] + fn a_locked_channel_asks_for_its_password_and_joins_with_it() { + let rig = Rig::new(); + let (mut state, id) = joined(&rig, VoiceState::Connected, Some(1)); + let (_, update) = + rig.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, id, 1, None)); + assert!(update.commands.is_empty(), "{:?}", update.commands); + let prompt = update.password.expect("the dialog opens"); + assert_eq!((prompt.name.as_str(), prompt.wrong), ("Lobby", false)); + assert_eq!(state.join_target, Some((id, 1))); + + let (_, update) = rig.run(&mut state, |state, cx, backing| { + join_with_password(state, cx, backing, "secret".into(), None) + }); + let [Command::MoveToChannel { channel, password, .. }] = &update.commands[..] else { + panic!("{:?}", update.commands) + }; + assert_eq!((*channel, password.as_deref()), (1, Some("secret"))); + assert_eq!(state.join_target, None); + + // Remembered for this connection: no dialog the second time. + let (_, update) = + rig.run(&mut state, |state, cx, backing| join_channel(state, cx, backing, id, 1, None)); + assert!(update.password.is_none()); + assert!( + matches!(&update.commands[..], [Command::MoveToChannel { password, .. }] + if password.as_deref() == Some("secret")), + "{:?}", + update.commands + ); + // An empty password joins nothing. + state.join_target = Some((id, 1)); + let (_, update) = rig.run(&mut state, |state, cx, backing| { + join_with_password(state, cx, backing, String::new(), None) + }); + assert!(update.commands.is_empty()); + } + /// A new server is in the store with its password in the secrets, is the /// one on screen, and has its gateway looked up (it has none to observe /// through yet). diff --git a/crates/voelin-ui-vm/src/settings.rs b/crates/voelin-ui-vm/src/settings.rs index 7468912..6c5d589 100644 --- a/crates/voelin-ui-vm/src/settings.rs +++ b/crates/voelin-ui-vm/src/settings.rs @@ -10,6 +10,7 @@ use tracing::warn; use voelin_audio::process::NoiseLevel; use voelin_core::settings::{Key, Kind, Settings}; use voelin_core::{AudioSettings, TransmitMode}; +use voelin_model::ChannelId; use crate::bridge::AudioForm; @@ -173,6 +174,55 @@ pub static UI_WINDOW: Key> = Key::new( ) .validated(valid_window); +/// What the channel tree remembers of one server: the channels folded shut and +/// the channel last selected (a click on its row). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TreeState { + /// The channels folded shut, in ascending order. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub collapsed: Vec, + /// The channel last selected, if one was. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub selected: Option, +} + +impl TreeState { + /// Nothing is remembered. + pub fn is_empty(&self) -> bool { + self.collapsed.is_empty() && self.selected.is_none() + } +} + +/// What the channel tree remembers, by the id of the server's bookmark +/// (as text: a JSON object's keys are). +pub type TreeStates = BTreeMap; + +/// The most channels one server may have folded in [`UI_TREE`]: a server has +/// far fewer channels, so more is a damaged setting. +const TREE_STATE_LIMIT: usize = 10_000; + +fn valid_tree(states: &TreeStates) -> Result<(), String> { + if states.keys().any(|id| id.parse::().is_err()) { + return Err("keyed by the id of a server".into()); + } + if states.values().any(|state| state.collapsed.len() > TREE_STATE_LIMIT) { + return Err(format!("at most {TREE_STATE_LIMIT} folded channels of a server")); + } + Ok(()) +} + +/// `ui.tree`: which channels each server's tree has folded shut, and which +/// channel was selected, by the id of the server's bookmark. The GPUI front +/// end writes it; the Slint one does not read it (its tree forgets both +/// when the app ends). +pub static UI_TREE: Key = Key::new( + "ui.tree", + Kind::Json, + "The channels each server's tree has folded and the channel selected, by server.", + TreeStates::new, +) +.validated(valid_tree); + /// The UI's keys besides [`UI`] and [`CLIENT_PLAYBACK`], for registering. pub fn appearance_keys() -> [&'static dyn voelin_core::settings::Setting; 6] { [ @@ -750,6 +800,35 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); } + /// The tree's memory is a JSON object by server, round-trips through the + /// service, and a damaged value is refused. + #[test] + fn tree_key() { + let settings = voelin_core::settings::Settings::in_memory(); + settings.register(&UI_TREE); + assert!(settings.get(&UI_TREE).is_empty(), "nothing remembered at first"); + let states = TreeStates::from([ + ("3".to_owned(), TreeState { collapsed: vec![4, 9], selected: Some(2) }), + ("5".to_owned(), TreeState { collapsed: Vec::new(), selected: Some(1) }), + ]); + settings.set(&UI_TREE, states.clone()).unwrap(); + assert_eq!(settings.get(&UI_TREE), states); + assert_eq!( + settings.get_json("ui.tree"), + Some( + serde_json::json!({"3": {"collapsed": [4, 9], "selected": 2}, "5": {"selected": 1}}) + ) + ); + // What an older build wrote without a field still loads. + settings.set_json("ui.tree", serde_json::json!({"7": {}})).unwrap(); + assert!(settings.get(&UI_TREE)["7"].is_empty()); + for damaged in + [serde_json::json!({"nope": {}}), serde_json::json!({"1": {"selected": "x"}})] + { + assert!(settings.set_json("ui.tree", damaged).is_err()); + } + } + #[test] fn voice_compact_key() { let settings = voelin_core::settings::Settings::in_memory(); diff --git a/crates/voelin-ui-vm/src/tree.rs b/crates/voelin-ui-vm/src/tree.rs index 031021a..eab8884 100644 --- a/crates/voelin-ui-vm/src/tree.rs +++ b/crates/voelin-ui-vm/src/tree.rs @@ -10,10 +10,13 @@ use voelin_model::{ tree_rows, }; +use voelin_core::{Contact, Relation}; + use crate::avatar; -use crate::bridge::{BadgeItem, MemberItem, TreeItem}; +use crate::bridge::{BadgeItem, MemberCard, MemberItem, TreeItem}; use crate::image::ImageRef; use crate::settings::ClientPlaybackMap; +use crate::state::SessionView; /// A banner mode as the UI takes it (`TreeItem.banner-mode`). pub fn banner_mode(mode: BannerMode) -> i32 { @@ -54,6 +57,47 @@ pub fn badge_items(guids: &[String], pictures: &HashMap) -> Vec .collect() } +/// The card over a member row: everything about the client `id` of a session +/// and what is known of it locally (the contact, the playback settings). +/// None when the presence has no such client (it left). +pub fn member_card( + view: &SessionView, + id: u16, + contacts: &HashMap, + playback: &ClientPlaybackMap, +) -> Option { + let client = view.presence.clients.get(&id)?; + let uid = client.uid.as_ref(); + let contact = uid.and_then(|u| contacts.get(u)); + let local = uid.and_then(|u| playback.get(u)).copied().unwrap_or_default(); + let groups = client + .server_groups + .iter() + .filter_map(|g| view.server_groups.iter().find(|i| i.id == *g)) + .map(|g| g.name.as_str().into()) + .collect(); + Some(MemberCard { + open: true, + id: i32::from(id), + name: client.nickname.as_str().into(), + initials: avatar::initials(&client.nickname).into(), + tint: avatar::tint(&client.nickname), + avatar: avatar::image(view.avatar(id)), + status: status_of(client, view.talking.contains(&id)).into(), + description: client.description.as_deref().unwrap_or_default().into(), + groups, + badges: badge_items(&client.badges, &view.pictures), + country: client.country.as_deref().unwrap_or_default().into(), + talk_power: client.talk_power, + friend: contact.is_some_and(|c| c.relation == Relation::Friend), + blocked: contact.is_some_and(|c| c.relation == Relation::Blocked), + volume: local.volume * 100.0, + muted: local.muted, + known: uid.is_some(), + streaming: client.streaming == Some(true), + }) +} + /// What the tree shows besides the presence. pub struct TreeInput<'a> { /// The channels and clients of the server. @@ -901,6 +945,61 @@ mod tests { ); } + /// The card has what the row has, the groups by name, the badges, the + /// contact's relation and the local playback; a client that left has none. + #[test] + fn the_member_card_is_what_is_known_of_one_client() { + use std::sync::Arc; + + use crate::settings::ClientPlayback; + + let mut p = presence(); + let bob = p.clients.get_mut(&11).unwrap(); + bob.uid = Some("bob=".into()); + bob.server_groups = vec![6, 99]; + bob.description = Some("Raid lead".into()); + bob.country = Some("DE".into()); + bob.talk_power = 75; + bob.badges = vec!["4b27be5a-b92a-4b30-8b2d-14b59653f427".into()]; + bob.streaming = Some(true); + let mut view = SessionView::<()> { + presence: Arc::new(p), + server_groups: vec![GroupInfo { + id: 6, + name: "Moderator".into(), + ..Default::default() + }], + ..Default::default() + }; + view.talking.insert(11); + let mut friend = Contact::new("bob="); + friend.relation = Relation::Friend; + let contacts = HashMap::from([("bob=".to_owned(), friend)]); + let playback = ClientPlaybackMap::from([( + "bob=".to_owned(), + ClientPlayback { volume: 1.5, muted: true }, + )]); + + let card = member_card(&view, 11, &contacts, &playback).expect("bob is there"); + assert!(card.open); + assert_eq!((card.id, &*card.name, &*card.initials), (11, "bob", "BO")); + assert_eq!(card.tint, avatar::tint("bob")); + assert_eq!(&*card.status, "Speaking"); + assert_eq!((&*card.description, &*card.country, card.talk_power), ("Raid lead", "DE", 75)); + let groups: Vec<&str> = card.groups.iter().map(|g| &**g).collect(); + assert_eq!(groups, ["Moderator"], "a group the server did not list is left out"); + assert_eq!(card.badges.len(), 1); + assert_eq!(&*card.badges[0].name, "20th Anniversary"); + assert!(card.friend && !card.blocked && card.known && card.streaming && card.muted); + assert_eq!(card.volume, 150.0); + + // Someone nobody knows: not known, nothing local, listening. + let alice = member_card(&view, 10, &contacts, &playback).unwrap(); + assert!(!alice.known && !alice.friend && !alice.muted && alice.volume == 100.0); + assert_eq!(&*alice.status, "Listening"); + assert!(member_card(&view, 99, &contacts, &playback).is_none(), "a client that left"); + } + #[test] fn channel_paths() { let mut p = presence();