//! What the client knows, apart from how it is shown: the servers' sessions //! with their chat tabs, and the data the screens share. A front end owns //! one [`AppState`] and fills it from the engine's events; the view models //! (`chat`, `tree`, `servers`, ...) turn it into rows. //! //! The lines of a chat tab are the front end's own list type `L`: a Slint //! model (`bind::rows::Rows`), or a plain `Vec` of rows. use std::collections::{HashMap, HashSet}; use std::path::PathBuf; use std::sync::Arc; use voelin_core::stream::StreamInfo; use voelin_core::{ AudioSettings, Bytes, Contact, HistoryMessage, OfflineMessageInfo, SessionState, TransferState, VoiceState, }; use voelin_gateway_proto::{ Action, ActivityEntry, ConfigEntry, EventInfo, PermRuleInfo, StreamEntry, TopicInfo, }; use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, GroupInfo, Presence}; use voelin_store::Bookmark; use crate::chat::{LineCache, Previous}; use crate::image::ImageRef; use crate::settings::{ClientPlaybackMap, DeviceChoices, UiSettings}; /// The store's name of a chat. pub fn store_target(target: &ChatTarget) -> voelin_store::ChatTarget { match target { ChatTarget::Server => voelin_store::ChatTarget::Server, ChatTarget::Channel(cid) => voelin_store::ChatTarget::Channel(*cid), ChatTarget::Private(uid) => voelin_store::ChatTarget::Private(uid.clone()), } } /// A file being downloaded from a chat message. pub struct Download { /// The message's handle. pub key: i32, /// Which of the message's links this is. pub index: usize, /// The file's name. pub name: String, /// How the transfer stands. pub state: TransferState, } /// A pinned message of a chat, with who pinned it. pub struct PinRow { /// The message's handle. pub key: i32, /// The message. pub message: HistoryMessage, /// Who pinned it. pub by: String, /// When it was pinned. pub ts_ms: i64, } /// A linked picture. #[derive(Clone, Debug)] pub enum Preview { /// Downloading (transfer id). Loading(u64), /// Downloaded: the file's bytes. Ready(Bytes), /// Too large, not a picture, or the download failed. Failed, } /// What a session's gateway and voice connection add for these screens. #[derive(Default)] pub struct SessionExtra { /// The gateway's stream directory. pub directory: Vec, /// The gateway's events by start time. pub events: Vec, /// The events were asked for and arrived. pub events_loaded: bool, /// The events whose answers are shown (by event id). pub expanded: HashSet, /// The activity feed, newest first. pub activity: Vec, /// Our unique id at the gateway. pub gateway_uid: Option, /// What we may do at the gateway. pub actions: Vec, /// Gateway administration: its keys. pub config: Vec, /// Gateway administration: its permission rules. pub perms: Vec, /// Offline messages (voice). pub inbox: Vec, /// The offline messages were asked for. pub inbox_asked: bool, /// Pictures linked in chat, by link. pub previews: HashMap, /// When this session's presence first came (ms): friends found in it /// then are not "coming online". pub presence_since: i64, /// "TeamSpeak 6", "TeamSpeak 3" once the server told what it runs; /// empty before that, and for software nobody recognised. pub product: String, } /// A message of a chat with the handle the UI knows it by: the engine's /// local ids are 64 bit, a bridge `int` is not. pub struct Msg { /// The handle (see [`Tab::take_key`]). pub key: i32, /// The message as the engine stored it. pub message: HistoryMessage, } /// A chat of a session: its lines (`L`) are what the chat view shows while /// the tab is selected, so a new message is one row appended. pub struct Tab { /// The chat. pub target: ChatTarget, /// The tab's name. pub title: String, /// The lines the chat view shows. pub lines: L, /// The messages, oldest first, by `(ts_ms, id)`. pub messages: Vec, /// Live messages of a session that keeps no history (no server unique /// id yet): grouped from the message before, without ids. pub last: Option, /// Messages not read, not ours: those after `read` (without stored /// history, those that came while the tab was not on screen). pub unread: i32, /// The newest message read, by `(ts_ms, id)`: kept in the store /// (`chat_reads`) when the tab is left, the session closes and on exit /// (`App::save_read`). `stored_read` is what the store has. pub read: Option<(i64, i64)>, /// What the store has of `read`. pub stored_read: Option<(i64, i64)>, /// The message the "New" divider is above: the first that was new when /// the tab came on screen. It stays until the tab is left. pub divider: Option, /// Nothing older exists as far as the engine can tell. pub complete: bool, /// A gateway page arrived: the chat is not only what we saw. pub synced: bool, /// An older page was asked for. pub loading: bool, /// The next message handle. next_key: i32, /// The pins of this chat, once asked for. pub pins: Vec, /// The pins were asked for and arrived. pub pins_loaded: bool, /// The gateway topics of this chat. pub topics: Vec, /// The topics were asked for and arrived. pub topics_loaded: bool, /// The open topic. pub topic: Option, /// The messages of the open topic. pub topic_messages: Vec, /// The message jumped to from the pins. pub marked: Option, /// What the lines of `messages` were built from. pub cache: LineCache, } impl Tab { /// An empty tab for a chat, nothing read or asked for. pub fn new(target: ChatTarget, title: String) -> Self { Self { target, title, lines: L::default(), messages: Vec::new(), last: None, unread: 0, read: None, stored_read: None, divider: None, complete: false, synced: false, loading: false, next_key: 1, pins: Vec::new(), pins_loaded: false, topics: Vec::new(), topics_loaded: false, topic: None, topic_messages: Vec::new(), marked: None, cache: Default::default(), } } } impl Tab { /// A private chat (on the Direct Messages page, not in the chat strip). pub fn is_private(&self) -> bool { matches!(self.target, ChatTarget::Private(_)) } /// A handle for a message that has none yet. pub fn take_key(&mut self) -> i32 { self.next_key += 1; self.next_key } /// The message with this handle, in the chat or in the open topic. pub fn message(&self, key: i32) -> Option<&HistoryMessage> { self.messages.iter().chain(&self.topic_messages).find(|m| m.key == key).map(|m| &m.message) } /// Where each message is and whether it is ours (`own`), for the read /// markers ([`crate::chat::first_unread`]). pub fn positions(&self, own: impl Fn(&ChatMessage) -> bool) -> Vec<(i64, i64, bool)> { self.messages .iter() .map(|m| (m.message.message.ts_ms, m.message.id, own(&m.message.message))) .collect() } /// Where the newest message is. pub fn newest(&self) -> Option<(i64, i64)> { self.messages.last().map(|m| (m.message.message.ts_ms, m.message.id)) } /// The tab came on screen: the first new message gets the divider /// (unless one shows), and everything is read. pub fn enter(&mut self, own: impl Fn(&ChatMessage) -> bool) { if self.unread > 0 && self.divider.is_none() { let first = crate::chat::first_unread(&self.positions(own), self.read); self.divider = first.map(|i| self.messages[i].message.id); } self.catch_up(); } /// Everything in the tab is read (it is on screen). pub fn catch_up(&mut self) { self.read = self.read.max(self.newest()); self.unread = 0; } /// Count what is not read: what came after `read`, not ours. pub fn count_unread(&mut self, own: impl Fn(&ChatMessage) -> bool) { self.unread = crate::chat::unread_count(&self.positions(own), self.read); } /// Start from where the store says the chat was read (`reads`: by the /// store's name of the chat). pub fn read_from(&mut self, reads: &HashMap) { if let Some(&read) = reads.get(&store_target(&self.target).key()) { self.read = self.read.max(Some(read)); self.stored_read = Some(read); } } } /// What we know about one server session. pub struct SessionView { /// Where the connections stand. pub state: SessionState, /// What the server offers. pub capabilities: Capabilities, /// The server's channels and clients. pub presence: Arc, /// The channels folded in the tree. pub collapsed: HashSet, /// The clients talking now. pub talking: HashSet, /// The chats, the server's first. pub tabs: Vec>, /// The chat on screen (an index of `tabs`). pub current_tab: usize, /// The chat strip's chat last current (the server's or a channel's): a /// private chat is current only on the Direct Messages page, and this /// one is current again when that page is left. pub channel_tab: ChatTarget, /// The own channel's tab was focused for this voice connection. pub focused_own_channel: bool, /// The streams in our channel (TeamSpeak 6). pub streams: Vec, /// Clients whose stored volume was sent for this voice connection. pub applied_playback: HashSet, /// Avatar pictures in the engine's cache, by unique id /// ([`Event::AvatarReady`]). pub avatars: HashMap, /// Icons in the engine's cache, by icon id ([`Event::IconReady`]). pub icons: HashMap, /// Banners and badges in the engine's cache, by address /// ([`Event::PictureReady`]). pub pictures: HashMap, /// The server's icon id as its voice connection last told it /// ([`Event::ServerDetails`]); kept while disconnected, for the rail. pub server_icon: u32, /// Bookmark address that supplied this session's icon. pub icon_address: Option, /// The server groups in display order ([`Event::Groups`]). pub server_groups: Vec, /// The channel groups ([`Event::Groups`]). pub channel_groups: Vec, /// What the session's gateway offers (`voelin_gateway_proto::feature`). pub gateway_caps: Vec, /// The client whose member card is open. pub member_card: Option, /// Passwords given for locked channels, until voice disconnects. pub channel_passwords: HashMap, /// The channel a voice connection was asked into, until it is joined /// or joined again (`App::join_after_connect`). pub join_after_connect: Option, /// Viewers of the streams in the gateway's directory, by stream id. pub stream_viewers: HashMap, /// Downloads started from chat, by transfer id. pub downloads: HashMap, /// The next transfer id. pub next_transfer: u64, /// What the home, messages and events screens keep of the session. pub extra: SessionExtra, /// Where its chats were read, from the store (by the store's name of /// the chat), for the server unique id `reads_of`. pub reads: HashMap, /// The server unique id `reads` are for. pub reads_of: Option, } impl Default for SessionView { fn default() -> Self { Self { state: SessionState::default(), capabilities: Capabilities::default(), presence: Arc::default(), collapsed: HashSet::new(), talking: HashSet::new(), tabs: vec![Tab::new(ChatTarget::Server, "Server".into())], current_tab: 0, channel_tab: ChatTarget::Server, focused_own_channel: false, streams: Vec::new(), applied_playback: HashSet::new(), avatars: HashMap::new(), icons: HashMap::new(), pictures: HashMap::new(), server_icon: 0, icon_address: None, server_groups: Vec::new(), channel_groups: Vec::new(), gateway_caps: Vec::new(), member_card: None, channel_passwords: HashMap::new(), join_after_connect: None, stream_viewers: HashMap::new(), downloads: HashMap::new(), next_transfer: 1, extra: Default::default(), reads: HashMap::new(), reads_of: None, } } } impl SessionView { /// Streams can be watched and shared: TeamSpeak 6, connected with voice. pub fn streams_available(&self) -> bool { self.capabilities.streams && self.state.voice == VoiceState::Connected } /// The channel a client is in. pub fn channel_of(&self, client: u16) -> Option { self.presence.clients.get(&client).map(|c| c.channel) } /// The name of a client's channel when it is not ours; empty in ours. pub fn other_channel_name(&self, client: u16) -> String { self.channel_of(client) .filter(|c| Some(*c) != self.state.own_channel) .and_then(|c| self.presence.channels.get(&c)) .map_or_else(String::new, |c| crate::tree::channel_title(c).0.to_owned()) } /// A client's nickname, or its id. pub fn nickname(&self, client: u16) -> String { self.presence .clients .get(&client) .map_or_else(|| format!("client {client}"), |c| c.nickname.clone()) } /// Unread messages in the server's and the channels' chats (the rail and /// the chat strip count them; private chats count on the Direct /// Messages page). pub fn channel_unread(&self) -> i32 { self.tabs.iter().filter(|t| !t.is_private()).map(|t| t.unread).sum() } /// Unread messages in private chats. pub fn private_unread(&self) -> i32 { self.tabs.iter().filter(|t| t.is_private()).map(|t| t.unread).sum() } /// Make tab `index` the current one; the chat strip remembers it unless /// it is a private chat. pub fn set_current_tab(&mut self, index: usize) { self.current_tab = index; if let Some(tab) = self.tabs.get(index).filter(|t| !t.is_private()) { self.channel_tab = tab.target.clone(); } } /// Focus tab `index`. While a private chat is current (the Direct /// Messages page shows it, and its composer sends there), a chat of the /// strip does not take its place: it is the strip's chat, current once /// that page is left (voice connecting focuses its channel's chat). pub fn focus_tab(&mut self, index: usize) { let Some(tab) = self.tabs.get(index) else { return }; if !tab.is_private() && self.tabs.get(self.current_tab).is_some_and(Tab::is_private) { self.channel_tab = tab.target.clone(); } else { self.set_current_tab(index); } } /// Remove tab `index`. The current tab stays; when it is this one, the /// chat strip's next tab takes its place, else its last. pub fn remove_tab(&mut self, index: usize) -> Tab { let tab = self.tabs.remove(index); if self.current_tab > index { self.current_tab -= 1; } else if self.current_tab == index { let (strip, _) = crate::chat::strip(self.tabs.iter().map(|t| &t.target), 0); let next = strip.iter().find(|&&i| i >= index).or(strip.last()).copied(); self.set_current_tab(next.unwrap_or(0)); } tab } /// Leave a current private chat for the chat strip's last one (the /// Direct Messages page was left); `true` if the current tab changed. pub fn leave_private(&mut self) -> bool { if !self.tabs.get(self.current_tab).is_some_and(Tab::is_private) { return false; } self.current_tab = self.tabs.iter().position(|t| t.target == self.channel_tab).unwrap_or(0); true } /// The session's gateway offers this feature /// (`voelin_gateway_proto::feature`). pub fn gateway_has(&self, feature: &str) -> bool { self.gateway_caps.iter().any(|c| c == feature) } /// The chat history is kept by the engine (it knows the server): its /// messages come with ids, reactions and pins. pub fn has_history(&self) -> bool { self.state.server_uid.is_some() } /// The avatar picture of a client, if the engine fetched one. pub fn avatar(&self, client: u16) -> Option<&PathBuf> { let uid = self.presence.clients.get(&client)?.uid.as_deref()?; self.avatars.get(uid) } /// The server's icon, if it has one and the engine fetched it. pub fn server_icon(&self) -> ImageRef { crate::avatar::image(self.icons.get(&self.server_icon).filter(|_| self.server_icon != 0)) } /// Icons stay associated with the address that supplied them, including /// while a reconnect to an edited bookmark is pending or has failed. pub fn server_icon_for(&self, address: &str) -> ImageRef { if self.icon_address.as_deref() == Some(address) { self.server_icon() } else { ImageRef::default() } } } impl SessionView { /// A new tab for `target`, read as far as the store says. pub fn new_tab(&self, target: ChatTarget, title: String) -> Tab { let mut tab = Tab::new(target, title); tab.read_from(&self.reads); tab } } /// The data the screens share, apart from the engine and the toolkit: the /// servers and what is known of their sessions, the settings the screens /// show and the dialogs' targets. pub struct AppState { /// The saved servers, in the rail's order. pub bookmarks: Vec, /// The server shown (a bookmark id). pub current: Option, /// What is known of each server's session, by bookmark id. pub sessions: HashMap>, /// The line at the bottom: what happened last. pub status: String, /// What the toast of the next copy says instead of "Copied" (an invite /// names its channel and link). pub copy_note: Option, /// The members panel's search. pub member_filter: String, /// The topics drawer's search. pub topic_filter: String, /// The voice channel view is shown (its people come first in the /// members panel). pub voice_view: bool, /// The UI's own settings (a working copy of the `ui` key). pub settings: UiSettings, /// The audio settings (a working copy). pub audio: AudioSettings, /// Audio settings changed since they were last stored. pub audio_dirty: bool, /// The input devices, as the settings list them. pub inputs: DeviceChoices, /// The output devices, as the settings list them. pub outputs: DeviceChoices, /// Local playback of each client, by unique id. pub playback: ClientPlaybackMap, /// The engine's contacts, by unique id. pub contacts: HashMap, /// The client in the volume dialog: session, client id, unique id. pub playback_dialog: Option<(i64, u16, Option)>, /// The locked channel the password dialog is for: session, channel. pub join_target: Option<(i64, ChannelId)>, /// Who the poke dialog pokes: session, client, nickname. pub poke_target: Option<(i64, u16, String)>, /// The window has the focus (desktop: the toolkit tells; elsewhere /// assumed): messages are read only then. pub focused: bool, /// The chat whose messages are on screen (session, target): when it is /// left, it is stored and loses its divider. pub reading: Option<(i64, ChatTarget)>, /// The microphone test runs. pub mic_test: bool, /// The capture for a share is being started. pub share_busy: bool, /// Why the last share did not start. pub share_error: String, /// A client whose stream was asked for before it was known (session, /// client): watched when the lookup brings it. pub pending_watch: Option<(i64, u16)>, /// Stream volume in percent, kept between streams. pub stream_volume: f32, /// Servers whose gateway was looked up in this run. pub gateways_looked_up: HashSet, /// Files being uploaded to a channel from the composer: session, /// channel and name, so the link can be posted when they are up. pub uploads: HashMap, } impl AppState { /// The state at start: the saved servers (the first one shown), the /// stored settings, nothing known of any session yet. pub fn new( bookmarks: Vec, settings: UiSettings, audio: AudioSettings, playback: ClientPlaybackMap, ) -> Self { Self { current: bookmarks.first().map(|b| b.id), bookmarks, sessions: HashMap::new(), status: String::new(), copy_note: None, member_filter: String::new(), topic_filter: String::new(), voice_view: false, settings, audio, audio_dirty: false, inputs: DeviceChoices::default(), outputs: DeviceChoices::default(), playback, contacts: HashMap::new(), playback_dialog: None, join_target: None, poke_target: None, focused: true, reading: None, mic_test: false, share_busy: false, share_error: String::new(), pending_watch: None, stream_volume: 100.0, gateways_looked_up: HashSet::new(), uploads: HashMap::new(), } } } #[cfg(test)] mod tests { use voelin_store::MessageSource; use super::*; fn msg(key: i32, id: i64, ts_ms: i64, own: bool) -> Msg { Msg { key, message: HistoryMessage { id, message: ChatMessage { target: ChatTarget::Server, author_name: if own { "me" } else { "you" }.into(), author_uid: None, author_id: None, text: format!("message {id}"), ts_ms, via_relay: false, blocked: false, }, source: MessageSource::Voice, remote_id: None, topic_id: None, reactions: Vec::new(), pinned: false, rev: 0, }, } } fn is_own(message: &ChatMessage) -> bool { message.author_name == "me" } /// A session with the server's chat and then these. fn session(targets: &[ChatTarget]) -> SessionView<()> { let mut view = SessionView::<()>::default(); for target in targets { view.tabs.push(Tab::new(target.clone(), "chat".into())); } view } #[test] fn a_private_chat_stays_current_until_its_page_is_left() { let mut view = session(&[ChatTarget::Channel(1), ChatTarget::Private("uid".into())]); view.set_current_tab(2); assert_eq!((view.current_tab, &view.channel_tab), (2, &ChatTarget::Server)); // A chat of the strip does not take the private chat's place ... view.focus_tab(1); assert_eq!((view.current_tab, &view.channel_tab), (2, &ChatTarget::Channel(1))); // ... it is current once the page is left, and only once. assert!(view.leave_private()); assert_eq!(view.current_tab, 1); assert!(!view.leave_private()); } #[test] fn removing_a_tab_keeps_the_current_one_or_picks_the_next_of_the_strip() { let mut view = session(&[ChatTarget::Channel(1), ChatTarget::Channel(2)]); view.set_current_tab(2); view.remove_tab(1); assert_eq!(view.current_tab, 1); assert_eq!(view.tabs[1].target, ChatTarget::Channel(2)); // The current tab itself: the strip's next one takes its place. let mut view = session(&[ChatTarget::Channel(1), ChatTarget::Channel(2)]); view.set_current_tab(1); view.remove_tab(1); assert_eq!(view.tabs[view.current_tab].target, ChatTarget::Channel(2)); } #[test] fn unread_messages_are_counted_after_the_read_marker_and_not_ours() { let mut tab = Tab::<()>::new(ChatTarget::Server, "Server".into()); tab.messages = vec![msg(1, 1, 100, false), msg(2, 2, 200, true), msg(3, 3, 300, false)]; tab.count_unread(is_own); assert_eq!(tab.unread, 2); tab.read = Some((100, 1)); tab.count_unread(is_own); assert_eq!(tab.unread, 1); assert_eq!(tab.newest(), Some((300, 3))); } #[test] fn entering_a_tab_puts_the_divider_above_the_first_new_message() { let mut tab = Tab::<()>::new(ChatTarget::Server, "Server".into()); tab.messages = vec![msg(1, 1, 100, false), msg(2, 2, 200, false), msg(3, 3, 300, false)]; tab.read = Some((100, 1)); tab.count_unread(is_own); tab.enter(is_own); assert_eq!(tab.divider, Some(2)); assert_eq!((tab.unread, tab.read), (0, Some((300, 3)))); // A divider that shows stays when the tab is entered again. tab.unread = 1; tab.enter(is_own); assert_eq!(tab.divider, Some(2)); } #[test] fn a_new_tab_starts_from_where_the_store_says_the_chat_was_read() { let mut view = SessionView::<()>::default(); view.reads.insert(store_target(&ChatTarget::Channel(5)).key(), (700, 9)); let tab = view.new_tab(ChatTarget::Channel(5), "five".into()); assert_eq!((tab.read, tab.stored_read), (Some((700, 9)), Some((700, 9)))); let other = view.new_tab(ChatTarget::Channel(6), "six".into()); assert_eq!((other.read, other.stored_read), (None, None)); } #[test] fn handles_are_taken_one_by_one_and_found_in_topics_too() { let mut tab = Tab::<()>::new(ChatTarget::Server, "Server".into()); let (a, b) = (tab.take_key(), tab.take_key()); assert_ne!(a, b); tab.topic_messages.push(msg(a, 4, 400, false)); assert_eq!(tab.message(a).map(|m| m.id), Some(4)); assert!(tab.message(b).is_none()); } #[test] fn unread_counts_split_between_the_strip_and_private_chats() { let mut view = session(&[ChatTarget::Channel(1), ChatTarget::Private("uid".into())]); view.tabs[0].unread = 2; view.tabs[1].unread = 3; view.tabs[2].unread = 4; assert_eq!((view.channel_unread(), view.private_unread()), (5, 4)); } }