diff --git a/crates/voelin-ui-vm/src/lib.rs b/crates/voelin-ui-vm/src/lib.rs index 65ba192..7dc0382 100644 --- a/crates/voelin-ui-vm/src/lib.rs +++ b/crates/voelin-ui-vm/src/lib.rs @@ -15,6 +15,7 @@ pub mod list; pub mod servers; pub mod settings; pub mod social; +pub mod state; pub mod streams; pub mod studio; pub mod studio_bridge; diff --git a/crates/voelin-ui-vm/src/state.rs b/crates/voelin-ui-vm/src/state.rs new file mode 100644 index 0000000..cc91fbc --- /dev/null +++ b/crates/voelin-ui-vm/src/state.rs @@ -0,0 +1,719 @@ +//! 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(), + } + } + + /// 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 + } + + /// 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 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() + } + } +} + +/// 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)); + } +} diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 60aa8b0..5aeeef6 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -7,7 +7,6 @@ //! callbacks in `bind/`, development switches in `dev.rs`. use std::cell::RefCell; -use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::rc::Rc; use std::sync::Arc; @@ -22,24 +21,19 @@ use voelin_core::settings::{ AUDIO, CRASH_REPORTS, IDENTITY_IMPORT, STREAM_DECODER_BACKEND, STREAM_HARDWARE_DECODING, Settings, }; -use voelin_core::stream::StreamInfo; use voelin_core::{ - AudioSettings, BackendInfo, Command, Engine, Event, History, HistoryMessage, ObserveState, - SessionState, VoiceState, + AudioSettings, BackendInfo, Command, Engine, Event, History, ObserveState, VoiceState, }; -use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, GroupInfo, Presence}; +use voelin_model::ChatTarget; use voelin_platform::crash; use voelin_store::{Bookmark, MemorySecrets, Secrets, Store}; use crate::bind::rows::Rows; use crate::hotkey::GlobalPtt; -use crate::settings::{ - CLIENT_PLAYBACK, ClientPlaybackMap, DeviceChoices, UI, UiSettings, appearance_keys, -}; +use crate::settings::{CLIENT_PLAYBACK, ClientPlaybackMap, UI, UiSettings, appearance_keys}; use crate::streams::{Share, Watch}; use crate::video::Video; use crate::vm; -use crate::vm::chat::Previous; slint::include_modules!(); @@ -120,363 +114,17 @@ impl Secrets for FallbackSecrets { } } -/// A message of a chat with the handle the UI knows it by: the engine's -/// local ids are 64 bit, a Slint `int` is not. -pub(crate) struct Msg { - pub key: i32, - pub message: HistoryMessage, -} +/// The lines of a chat as the chat view shows them. +pub(crate) type ChatRows = Rows; -/// A chat of a session: its lines are the model the chat view shows while -/// the tab is selected, so a new message is one row appended. -pub(crate) struct Tab { - pub target: ChatTarget, - pub title: String, - pub lines: Rows, - /// 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)>, - 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, - pub pins_loaded: bool, - /// The gateway topics of this chat, and the open one with its messages. - pub topics: Vec, - pub topics_loaded: bool, - pub topic: Option, - pub topic_messages: Vec, - /// The message jumped to from the pins. - pub marked: Option, - /// What the lines of `messages` were built from. - pub cache: crate::vm::chat::LineCache, -} - -impl Tab { - pub fn new(target: ChatTarget, title: String) -> Self { - Self { - target, - title, - lines: Rows::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(), - } - } - - /// 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 - } - - 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::vm::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::vm::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::vm::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(&crate::chat::store_target(&self.target).key()) { - self.read = self.read.max(Some(read)); - self.stored_read = Some(read); - } - } -} +/// A chat of a session (see `voelin_ui_vm::state`). +pub(crate) type Tab = vm::state::Tab; /// What we know about one server session. -pub(crate) struct SessionView { - pub state: SessionState, - pub capabilities: Capabilities, - pub presence: Arc, - pub collapsed: HashSet, - pub talking: HashSet, - pub tabs: Vec, - 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: crate::social::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, - pub reads_of: Option, -} +pub(crate) type SessionView = vm::state::SessionView; -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::vm::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::vm::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 - } - - /// 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 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) -> vm::ImageRef { - vm::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) -> vm::ImageRef { - if self.icon_address.as_deref() == Some(address) { - self.server_icon() - } else { - vm::ImageRef::default() - } - } -} +/// What the screens share, apart from the window and the engine. +pub(crate) type AppState = vm::state::AppState; /// The models the Bridge shows, created once and updated row by row /// ([`Rows::sync`]). @@ -567,75 +215,28 @@ pub(crate) struct App { pub secrets: Box, pub engine: Engine, pub identity: tsclientlib::Identity, - pub bookmarks: Vec, - pub current: Option, - pub sessions: HashMap, + /// The data the screens share (`voelin_ui_vm::state`). + pub state: AppState, pub models: Models, - 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 settings service (shared with the engine); `settings`, `audio` - /// and `playback` are working copies of its keys. + /// The settings service (shared with the engine); `state.settings`, + /// `state.audio` and `state.playback` are working copies of its keys. pub prefs: Settings, - pub settings: UiSettings, - pub audio: AudioSettings, - /// Audio settings changed since they were last stored. - pub audio_dirty: bool, - pub inputs: DeviceChoices, - pub outputs: DeviceChoices, - pub playback: ClientPlaybackMap, - /// The engine's contacts, by unique id ([`Event::ContactsChanged`]). - 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: winit 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 (`App::track_reading`). - pub reading: Option<(i64, ChatTarget)>, - pub mic_test: bool, pub ptt: GlobalPtt, pub video: Video, /// Our stream. pub share: Option, - /// The capture for a share is being started. - pub share_busy: bool, - pub share_error: String, /// The stream in the viewer. pub watch: Option, - /// 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, /// `VOELIN_DEMO_STREAM`: the viewer shows a local test stream. pub demo: bool, /// `VOELIN_DEMO_UI`: sample servers, channels and chat (dev.rs). pub demo_ui: bool, - /// Servers whose gateway was looked up in this run (`discover_gateway`). - pub gateways_looked_up: HashSet, /// `VOELIN_AUTOSHARE=test-pattern`: share the test pattern once streams work. pub autoshare: bool, /// `VOELIN_OPEN=client`: open the volume dialog of the first other client. pub open_client_pending: bool, /// The notices are in the About page's model. pub notices_loaded: bool, - /// 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, /// Home, friends, messages, the bell and the search. pub social: crate::social::Social, /// The settings pages of the new design. @@ -829,44 +430,18 @@ pub fn run(options: RunOptions) -> Result<()> { }), engine: engine.clone(), identity, - current: bookmarks.first().map(|b| b.id), - bookmarks, - sessions: HashMap::new(), + state: AppState::new(bookmarks, settings, audio, playback), models, - status: String::new(), - copy_note: None, - member_filter: String::new(), - topic_filter: String::new(), - voice_view: false, prefs, - 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, ptt, video, share: None, - share_busy: false, - share_error: String::new(), watch: None, - pending_watch: None, - stream_volume: 100.0, demo: switches.demo_stream, demo_ui: switches.demo_ui, - gateways_looked_up: HashSet::new(), autoshare: switches.autoshare, open_client_pending: switches.open_client, notices_loaded: false, - uploads: HashMap::new(), social: Default::default(), pages: Default::default(), studio: Default::default(), @@ -931,18 +506,18 @@ pub fn run(options: RunOptions) -> Result<()> { if let Err(e) = app.prefs.flush() { warn!(%e, "could not store settings"); } - let ids: Vec = app.sessions.keys().copied().collect(); + let ids: Vec = app.state.sessions.keys().copied().collect(); for id in ids { app.save_reads(id); } app.watch = None; app.share = None; if own && !app.demo_ui { - for id in app.sessions.keys() { + for id in app.state.sessions.keys() { app.engine.send(Command::CloseSession { session: *id as u64 }); } } - own && !app.sessions.is_empty() && !app.demo_ui + own && !app.state.sessions.is_empty() && !app.demo_ui }); APP.with(|a| a.borrow_mut().take()); if let Some(runtime) = own_runtime { @@ -1001,30 +576,30 @@ pub(crate) fn model(items: Vec) -> ModelRc { impl App { pub fn view_mut(&mut self) -> Option<&mut SessionView> { - let id = self.current?; - Some(self.sessions.entry(id).or_default()) + let id = self.state.current?; + Some(self.state.sessions.entry(id).or_default()) } pub fn view(&self) -> Option<&SessionView> { - self.current.and_then(|id| self.sessions.get(&id)) + self.state.current.and_then(|id| self.state.sessions.get(&id)) } pub fn bookmark(&self, id: i64) -> Option<&Bookmark> { - self.bookmarks.iter().find(|b| b.id == id) + self.state.bookmarks.iter().find(|b| b.id == id) } /// Send a command for the current session. Not for the sample /// sessions of VOELIN_DEMO_UI: the engine would open them for real. pub fn command(&self, f: impl FnOnce(u64) -> Command) { - if let Some(id) = self.current.filter(|_| !self.demo_ui) { + if let Some(id) = self.state.current.filter(|_| !self.demo_ui) { self.engine.send(f(id as u64)); } } pub fn set_status(&mut self, text: impl Into) { - self.status = text.into(); + self.state.status = text.into(); if let Some(ui) = self.ui.upgrade() { - ui.global::().set_status_text(self.status.clone().into()); + ui.global::().set_status_text(self.state.status.clone().into()); } } @@ -1037,12 +612,12 @@ impl App { /// Nav.copy put text on the clipboard: one toast says so. pub fn copied(&mut self) { - let text = self.copy_note.take().unwrap_or_else(|| "Copied".to_owned()); + let text = self.state.copy_note.take().unwrap_or_else(|| "Copied".to_owned()); self.set_status(text); } pub fn store_settings(&self) { - if let Err(e) = self.prefs.set(&UI, self.settings.clone()) { + if let Err(e) = self.prefs.set(&UI, self.state.settings.clone()) { warn!(%e, "could not store settings"); } } @@ -1051,19 +626,19 @@ impl App { /// the values the window keeps copies of. The engine applies audio /// settings itself. fn setting_changed(&mut self, key: &str) { - if key == AUDIO.name() && !self.audio_dirty { - self.audio = self.prefs.get(&AUDIO); + if key == AUDIO.name() && !self.state.audio_dirty { + self.state.audio = self.prefs.get(&AUDIO); // The voice controls follow the transmit mode. self.refresh_transmit(); } else if key == CRASH_REPORTS.name() { let enabled = self.prefs.get(&CRASH_REPORTS); - if enabled != self.settings.crash_reports { - self.settings.crash_reports = enabled; + if enabled != self.state.settings.crash_reports { + self.state.settings.crash_reports = enabled; crash::set_enabled(enabled); self.refresh_settings_flags(); } } else if key == CLIENT_PLAYBACK.name() { - self.playback = self.prefs.get(&CLIENT_PLAYBACK); + self.state.playback = self.prefs.get(&CLIENT_PLAYBACK); } else if appearance_keys().iter().any(|k| k.name() == key) { self.apply_appearance(); } else if key == voelin_core::settings::STREAM_AUDIO_SOURCES.name() { @@ -1085,7 +660,7 @@ impl App { match event { Event::State { session, state } => { let id = session as i64; - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); let was_voice = view.state.voice; let was_observe = view.state.observe; let was_channel = view.state.own_channel; @@ -1111,12 +686,12 @@ impl App { if off(state.voice, state.observe) && !off(was_voice, was_observe) { self.save_reads(id); } - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); let focus = !view.focused_own_channel; if state.voice == VoiceState::Connected && was_voice != VoiceState::Connected { self.set_status("Connected"); } - if self.current == Some(id) { + if self.state.current == Some(id) { if self.track_reading() { self.refresh_chat(); } @@ -1124,7 +699,7 @@ impl App { // once per connection. if let (Some(cid), VoiceState::Connected) = (state.own_channel, state.voice) { self.open_chat(ChatTarget::Channel(cid), focus); - self.sessions.entry(id).or_default().focused_own_channel = true; + self.state.sessions.entry(id).or_default().focused_own_channel = true; } } // Where we are with voice, when it changed here: home's last @@ -1138,22 +713,22 @@ impl App { self.refresh_tree(); self.refresh_streams(); self.autoshare(); - if self.open_client_pending && self.current == Some(id) { + if self.open_client_pending && self.state.current == Some(id) { self.open_first_client(); } self.join_after_connect(id); } Event::ServerInfo { session, name, backend, capabilities } => { - self.sessions.entry(session as i64).or_default().capabilities = capabilities; + self.state.sessions.entry(session as i64).or_default().capabilities = capabilities; self.adopt_server_name(session as i64, &name); - if self.current == Some(session as i64) { + if self.state.current == Some(session as i64) { self.set_status(connected_status(&name, &backend)); } self.refresh_streams(); self.autoshare(); } Event::Presence { session, presence } => { - let view = self.sessions.entry(session as i64).or_default(); + let view = self.state.sessions.entry(session as i64).or_default(); // The server chat shows its welcome and host message, with // their pictures. let said = crate::chat::server_texts(&view.presence.server) @@ -1171,7 +746,7 @@ impl App { if renamed && self.remember_voice(session as i64) { self.refresh_servers(); } - if self.current == Some(session as i64) { + if self.state.current == Some(session as i64) { if said { self.fetch_previews(session as i64); } @@ -1185,20 +760,20 @@ impl App { } } Event::Talking { session, client, talking } => { - let view = self.sessions.entry(session as i64).or_default(); + let view = self.state.sessions.entry(session as i64).or_default(); if talking { view.talking.insert(client); } else { view.talking.remove(&client); } - if self.current == Some(session as i64) { + if self.state.current == Some(session as i64) { self.refresh_tree(); } } Event::InputLevel { session, level_db, sending } => { let shown = match session { - Some(s) => self.current == Some(s as i64), - None => self.mic_test, + Some(s) => self.state.current == Some(s as i64), + None => self.state.mic_test, }; if shown && let Some(ui) = self.ui.upgrade() { let bridge = ui.global::(); @@ -1213,7 +788,7 @@ impl App { // know the server yet): those get ids and reactions instead. Event::Chat { session, message } => { let id = session as i64; - if !self.sessions.entry(id).or_default().has_history() { + if !self.state.sessions.entry(id).or_default().has_history() { self.add_message(id, message); } } @@ -1228,12 +803,12 @@ impl App { self.gateway_update(session as i64, update); } Event::Groups { session, server_groups, channel_groups } => { - let view = self.sessions.entry(session as i64).or_default(); + let view = self.state.sessions.entry(session as i64).or_default(); view.server_groups = (*server_groups).clone(); // Display order, as TeamSpeak sorts them. view.server_groups.sort_by_key(|g| (g.sort_id, g.id)); view.channel_groups = (*channel_groups).clone(); - if self.current == Some(session as i64) { + if self.state.current == Some(session as i64) { self.refresh_tree(); } } @@ -1244,11 +819,11 @@ impl App { } // Pictures can arrive after the rows were built: draw them again. Event::AvatarReady { session, client_uid, path, .. } => { - let view = self.sessions.entry(session as i64).or_default(); + let view = self.state.sessions.entry(session as i64).or_default(); // A file that arrives again is decoded again if it changed. crate::images::reloaded(&path); view.avatars.insert(client_uid, path); - if self.current == Some(session as i64) { + if self.state.current == Some(session as i64) { self.refresh_tree(); self.refresh_chat(); self.refresh_toolbar(); @@ -1257,21 +832,21 @@ impl App { } } Event::IconReady { session, icon, path } => { - let view = self.sessions.entry(session as i64).or_default(); + let view = self.state.sessions.entry(session as i64).or_default(); crate::images::reloaded(&path); view.icons.insert(icon, path); self.refresh_servers(); - if self.current == Some(session as i64) { + if self.state.current == Some(session as i64) { self.refresh_tree(); self.refresh_toolbar(); } } Event::PictureReady { session, url, path } => { - let view = self.sessions.entry(session as i64).or_default(); + let view = self.state.sessions.entry(session as i64).or_default(); // The host banner reloads into the same file. crate::images::reloaded(&path); view.pictures.insert(url, path); - if self.current == Some(session as i64) { + if self.state.current == Some(session as i64) { self.refresh_toolbar(); self.refresh_tree(); self.refresh_chat(); @@ -1282,9 +857,9 @@ impl App { self.transfer_progress(session as i64, transfer, state); } // The engine's contacts would replace the sample ones. - Event::ContactsChanged { .. } if self.demo_ui && !self.contacts.is_empty() => {} + Event::ContactsChanged { .. } if self.demo_ui && !self.state.contacts.is_empty() => {} Event::ContactsChanged { contacts } => { - self.contacts = contacts.iter().map(|c| (c.uid.clone(), c.clone())).collect(); + self.state.contacts = contacts.iter().map(|c| (c.uid.clone(), c.clone())).collect(); self.refresh_member_card(); } // The sample sessions of VOELIN_DEMO_UI are unknown to the engine. @@ -1312,7 +887,7 @@ impl App { fn tick(&mut self) { self.tick_streams(); self.tick_pages(); - if self.audio_dirty { + if self.state.audio_dirty { self.save_audio(); } } diff --git a/crates/voelin-ui/src/bind/servers.rs b/crates/voelin-ui/src/bind/servers.rs index f237fcf..6425677 100644 --- a/crates/voelin-ui/src/bind/servers.rs +++ b/crates/voelin-ui/src/bind/servers.rs @@ -25,7 +25,7 @@ pub(super) fn wire(ui: &MainWindow) { }); bridge.on_join_channel(|cid| { with_app(|app| { - if let Some(session) = app.current { + if let Some(session) = app.state.current { app.join_channel(session, cid as ChannelId); } }); diff --git a/crates/voelin-ui/src/bind/settings.rs b/crates/voelin-ui/src/bind/settings.rs index 5b05978..d5979bd 100644 --- a/crates/voelin-ui/src/bind/settings.rs +++ b/crates/voelin-ui/src/bind/settings.rs @@ -16,7 +16,7 @@ pub(super) fn wire(ui: &MainWindow) { with_app(|app| app.audio_changed(&form.into())); }); bridge.on_toggle_mic_test(|| { - with_app(|app| app.set_mic_test(!app.mic_test)); + with_app(|app| app.set_mic_test(!app.state.mic_test)); }); bridge.on_apply_ptt(|enabled, key| { with_app(|app| app.apply_ptt(enabled, key.to_string())); diff --git a/crates/voelin-ui/src/chat.rs b/crates/voelin-ui/src/chat.rs index 35f6aaa..518e3b7 100644 --- a/crates/voelin-ui/src/chat.rs +++ b/crates/voelin-ui/src/chat.rs @@ -30,12 +30,13 @@ use voelin_gateway_proto::{ErrorCode, TopicInfo, feature}; use voelin_model::{ChatMessage, ChatTarget, HostMessageMode, ServerDetails}; use voelin_store::ChatRead; -use crate::app::{App, Bridge, Msg, Nav, SessionView, Tab}; +use crate::app::{App, Bridge, Nav, SessionView, Tab}; use crate::settings::UI_IMAGE_PREVIEW_KB; use crate::vm; use crate::vm::bbcode::LinkKind; use crate::vm::bridge::{ChatLine, ChatTab, FileItem, PinItem}; use crate::vm::chat::{LineCache, LineCtx, Previous}; +use crate::vm::state::{Download, Msg, PinRow, store_target}; /// Where the server's welcome and host message keep what their lines were /// built from (`LineCache`), apart from the messages' ids. @@ -62,32 +63,6 @@ pub(crate) fn server_text<'a>(view: &'a SessionView, tab: &Tab, key: i32) -> Opt server_texts(&view.presence.server).get((-1 - key) as usize).map(|(text, _)| *text) } -/// The store's name of a chat. -pub(crate) 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(crate) struct Download { - /// The message's handle and which of its links this is. - pub key: i32, - pub index: usize, - pub name: String, - pub state: TransferState, -} - -/// A pinned message of a chat, with who pinned it. -pub(crate) struct PinRow { - pub key: i32, - pub message: HistoryMessage, - pub by: String, - pub ts_ms: i64, -} - /// "3 min ago", "yesterday", "12 Mar". fn ago(ts_ms: i64) -> String { let Some(then) = chrono::DateTime::from_timestamp_millis(ts_ms) else { return String::new() }; @@ -105,10 +80,10 @@ fn ago(ts_ms: i64) -> String { impl App { pub(crate) fn open_chat(&mut self, target: ChatTarget, focus: bool) { - let Some(id) = self.current else { return }; + let Some(id) = self.state.current else { return }; let index = self.chat_tab(id, target); if focus { - self.sessions.entry(id).or_default().focus_tab(index); + self.state.sessions.entry(id).or_default().focus_tab(index); self.prefetch_counts(); self.track_reading(); } @@ -123,7 +98,7 @@ impl App { ChatTarget::Private(uid) => self.peer_name(uid, None), _ => String::new(), }; - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); if let Some(i) = view.tabs.iter().position(|t| t.target == target) { return i; } @@ -149,7 +124,7 @@ impl App { view.set_current_tab(index); view.tabs[index].topic = None; } - if let Some(id) = self.current { + if let Some(id) = self.state.current { self.fetch_previews(id); } self.prefetch_counts(); @@ -159,13 +134,13 @@ impl App { } pub(crate) fn close_tab(&mut self, index: usize) { - let Some(id) = self.current else { return }; - let view = self.sessions.entry(id).or_default(); + let Some(id) = self.state.current else { return }; + let view = self.state.sessions.entry(id).or_default(); if index == 0 || index >= view.tabs.len() { return; } self.save_read(id, index); - let tab = self.sessions.entry(id).or_default().remove_tab(index); + let tab = self.state.sessions.entry(id).or_default().remove_tab(index); self.engine.send(Command::CloseChat { session: id as u64, target: tab.target }); self.prefetch_counts(); self.track_reading(); @@ -174,8 +149,8 @@ impl App { } pub(crate) fn send_message(&mut self, text: String) { - let Some(id) = self.current else { return }; - let Some(view) = self.sessions.get(&id) else { return }; + let Some(id) = self.state.current else { return }; + let Some(view) = self.state.sessions.get(&id) else { return }; let target = view.tabs[view.current_tab].target.clone(); self.engine.send(Command::SendChat { session: id as u64, target, text }); } @@ -199,10 +174,10 @@ impl App { /// A live message of a session without stored history: appended as it /// comes, without an id. pub(crate) fn add_message(&mut self, id: i64, message: ChatMessage) { - let current = self.current == Some(id); + let current = self.state.current == Some(id); let reading = self.reads_now(id); let new = !self.is_own(id, &message); - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); let title = vm::chat::tab_title(&view.presence, &message.target, &message.author_name); let index = Self::tab_for(view, &message.target, || title); let seen = reading && view.current_tab == index; @@ -232,7 +207,7 @@ impl App { source: HistorySource, complete: bool, ) { - let current = self.current == Some(id); + let current = self.state.current == Some(id); let reading = self.reads_now(id); // A private chat is named after the peer, whoever wrote first. let peer = match target { @@ -245,7 +220,7 @@ impl App { )), _ => None, }; - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); let author = messages.first().map_or("", |m| m.message.author_name.as_str()); let title = peer.unwrap_or_else(|| vm::chat::tab_title(&view.presence, target, author)); let index = Self::tab_for(view, target, || title); @@ -309,8 +284,8 @@ impl App { /// The page of messages before the oldest one shown. pub(crate) fn load_older(&mut self) { - let Some(id) = self.current else { return }; - let Some(view) = self.sessions.get_mut(&id) else { return }; + let Some(id) = self.state.current else { return }; + let Some(view) = self.state.sessions.get_mut(&id) else { return }; let tab = &mut view.tabs[view.current_tab]; if tab.loading || tab.complete { return; @@ -385,7 +360,7 @@ impl App { cache.keep(ids, messages.len()); } // Pokes of a private chat's peer show among its messages. - if let (ChatTarget::Private(uid), Some(session)) = (&tab.target, self.current) { + if let (ChatTarget::Private(uid), Some(session)) = (&tab.target, self.state.current) { lines.extend(self.poke_lines(session, uid)); lines.sort_by_key(|(ts, _)| *ts); } @@ -544,7 +519,7 @@ impl App { .divider .and_then(|d| tab.messages.iter().position(|m| m.message.id == d)) .map_or(&[][..], |i| &tab.messages[i..]); - let session = self.current.unwrap_or_default(); + let session = self.state.current.unwrap_or_default(); let count = new.iter().filter(|m| !self.is_own(session, &m.message.message)).count(); bridge.set_unread_index(divider.map_or(-1, |i| i as i32)); bridge.set_unread_count(count as i32); @@ -585,7 +560,7 @@ impl App { }) .collect(); self.models.pins.sync(&pins); - let filter = self.topic_filter.trim().to_lowercase(); + let filter = self.state.topic_filter.trim().to_lowercase(); let now = chrono::Utc::now().timestamp_millis(); let topics: Vec = tab .topics @@ -654,7 +629,7 @@ impl App { /// New messages of session `id` in its current tab are read as they /// come: they are on screen in the focused window. fn reads_now(&self, id: i64) -> bool { - self.focused && self.current == Some(id) && self.chat_shown() + self.state.focused && self.state.current == Some(id) && self.chat_shown() } /// After anything that can change which chat is on screen (a tab, a @@ -662,26 +637,26 @@ impl App { /// loses its divider; the one on screen, in the focused window, is read /// (its divider above what was new). `true` if a tab changed. pub(crate) fn track_reading(&mut self) -> bool { - let open = self.current.filter(|_| self.chat_shown()).and_then(|id| { - let view = self.sessions.get(&id)?; + let open = self.state.current.filter(|_| self.chat_shown()).and_then(|id| { + let view = self.state.sessions.get(&id)?; Some((id, view.tabs.get(view.current_tab)?.target.clone())) }); let mut changed = false; - if open != self.reading { - if let Some((id, target)) = self.reading.take() + if open != self.state.reading { + if let Some((id, target)) = self.state.reading.take() && let Some(index) = self.tab_index(id, &target) { - let tab = &mut self.sessions.entry(id).or_default().tabs[index]; + let tab = &mut self.state.sessions.entry(id).or_default().tabs[index]; changed |= tab.divider.take().is_some(); self.save_read(id, index); } - self.reading = open.clone(); + self.state.reading = open.clone(); } - if let (true, Some((id, target))) = (self.focused, open) + if let (true, Some((id, target))) = (self.state.focused, open) && let Some(index) = self.tab_index(id, &target) { let own_uids = &self.social.own_uids; - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); let own_client = view.state.own_client; let tab = &mut view.tabs[index]; let before = (tab.unread, tab.divider); @@ -693,7 +668,7 @@ impl App { /// Where the tab of `target` is in session `id`. fn tab_index(&self, id: i64, target: &ChatTarget) -> Option { - self.sessions.get(&id)?.tabs.iter().position(|t| t.target == *target) + self.state.sessions.get(&id)?.tabs.iter().position(|t| t.target == *target) } /// The current chat came on screen or left it (`Nav.chat-shown`). @@ -708,7 +683,7 @@ impl App { /// only). #[cfg(not(target_os = "android"))] pub(crate) fn window_focused(&mut self, focused: bool) { - self.focused = focused; + self.state.focused = focused; if self.track_reading() { self.refresh_chat(); self.refresh_servers(); @@ -718,8 +693,8 @@ impl App { /// The current chat is read (the bar over its messages): the divider /// goes. pub(crate) fn mark_read(&mut self) { - let Some(id) = self.current else { return }; - let Some(view) = self.sessions.get_mut(&id) else { return }; + let Some(id) = self.state.current else { return }; + let Some(view) = self.state.sessions.get_mut(&id) else { return }; let index = view.current_tab; let tab = &mut view.tabs[index]; tab.divider = None; @@ -735,7 +710,7 @@ impl App { if self.demo_ui { return; } - let Some(view) = self.sessions.get_mut(&id) else { return }; + let Some(view) = self.state.sessions.get_mut(&id) else { return }; let Some(server_uid) = view.state.server_uid.as_deref() else { return }; let Some(tab) = view.tabs.get_mut(index) else { return }; let Some((ts_ms, message)) = tab.read.filter(|r| tab.stored_read != Some(*r)) else { @@ -757,7 +732,7 @@ impl App { /// Store where every chat of session `id` was read (it ended, or the /// app exits). pub(crate) fn save_reads(&mut self, id: i64) { - let count = self.sessions.get(&id).map_or(0, |v| v.tabs.len()); + let count = self.state.sessions.get(&id).map_or(0, |v| v.tabs.len()); for index in 0..count { self.save_read(id, index); } @@ -767,7 +742,7 @@ impl App { /// server is known (or another one: the gateway's id wins): its tabs /// start from there, now and when they open. pub(crate) fn load_reads(&mut self, id: i64) { - let Some(view) = self.sessions.get_mut(&id) else { return }; + let Some(view) = self.state.sessions.get_mut(&id) else { return }; if self.demo_ui || view.state.server_uid.is_none() || view.reads_of == view.state.server_uid { return; @@ -794,8 +769,8 @@ impl App { } pub(crate) fn gateway_update(&mut self, id: i64, update: GatewayUpdate) { - let current = self.current == Some(id); - let view = self.sessions.entry(id).or_default(); + let current = self.state.current == Some(id); + let view = self.state.sessions.entry(id).or_default(); match update { GatewayUpdate::Connected { capabilities, .. } | GatewayUpdate::Capabilities { capabilities } => { @@ -976,8 +951,8 @@ impl App { /// The topics drawer's search. pub(crate) fn search_topics(&mut self, text: String) { - if self.topic_filter != text { - self.topic_filter = text; + if self.state.topic_filter != text { + self.state.topic_filter = text; self.refresh_chat(); } } @@ -1024,7 +999,7 @@ impl App { /// Download a file a message links, into the download folder. pub(crate) fn download_file(&mut self, key: i32, index: i32) { - let Some(id) = self.current else { return }; + let Some(id) = self.state.current else { return }; let index = index.max(0) as usize; let Some(file) = self.message_of(key).and_then(|m| m.message.file_refs().into_iter().nth(index)) @@ -1033,7 +1008,7 @@ impl App { }; let dir = dirs::download_dir().unwrap_or_else(|| PathBuf::from(".")); let path = dir.join(&file.name); - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); let transfer = view.next_transfer; view.next_transfer += 1; view.downloads.insert( @@ -1052,10 +1027,10 @@ impl App { pub(crate) fn transfer_progress(&mut self, id: i64, transfer: u64, state: TransferState) { // An upload from the composer: post the file's link once it is up. - if let Some((_, channel, name)) = self.uploads.get(&transfer).cloned() { + if let Some((_, channel, name)) = self.state.uploads.get(&transfer).cloned() { match &state { TransferState::Done { size, .. } => { - self.uploads.remove(&transfer); + self.state.uploads.remove(&transfer); let file = voelin_model::FileRef { channel, path: "/".into(), @@ -1071,11 +1046,11 @@ impl App { self.set_status(format!("{name} shared")); } TransferState::Failed(e) => { - self.uploads.remove(&transfer); + self.state.uploads.remove(&transfer); self.set_status(format!("Could not upload {name}: {e}")); } TransferState::Cancelled => { - self.uploads.remove(&transfer); + self.state.uploads.remove(&transfer); } _ => {} } @@ -1085,14 +1060,14 @@ impl App { return; } let done = matches!(state, TransferState::Done { .. }); - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); let Some(entry) = view.downloads.get_mut(&transfer) else { return }; entry.state = state; let name = entry.name.clone(); if done { self.set_status(format!("{name} downloaded")); } - if self.current == Some(id) { + if self.state.current == Some(id) { self.refresh_chat(); } } @@ -1100,8 +1075,8 @@ impl App { /// Attach a file to the current channel chat: ask for one, upload it /// into the channel and post its link. pub(crate) fn attach_file(&mut self) { - let Some(id) = self.current else { return }; - let Some(view) = self.sessions.get(&id) else { return }; + let Some(id) = self.state.current else { return }; + let Some(view) = self.state.sessions.get(&id) else { return }; let ChatTarget::Channel(channel) = view.tabs[view.current_tab].target else { self.set_status("Files can be attached to a channel's chat."); return; @@ -1124,10 +1099,10 @@ impl App { /// Upload a file into a channel and link it in the chat once it is up. pub(crate) fn upload(&mut self, id: i64, channel: u64, from: PathBuf) { let Some(name) = from.file_name().map(|n| n.to_string_lossy().to_string()) else { return }; - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); let transfer = view.next_transfer; view.next_transfer += 1; - self.uploads.insert(transfer, (id, channel, name.clone())); + self.state.uploads.insert(transfer, (id, channel, name.clone())); self.engine.send(Command::UploadFile { session: id as u64, transfer, diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index 1a2fd1a..a33b438 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -184,7 +184,7 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { } Some("observe") => { with_app(|app| { - if let Some(id) = app.current { + if let Some(id) = app.state.current { app.observe(id); } }); @@ -214,7 +214,7 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running { } // The current server's dialog, Advanced open. "bookmark" if arg == "edit" => { - if let Some(id) = with_app(|app| app.current).flatten() { + if let Some(id) = with_app(|app| app.state.current).flatten() { nav.invoke_edit_server(id as i32); } } @@ -425,9 +425,9 @@ fn late( /// The current chat's read marker `back` messages before its end, as if /// they came while away, its "New" divider shown (`VOELIN_OPEN=unread`). fn open_unread(app: &mut App, back: usize) { - let Some(id) = app.current else { return }; + let Some(id) = app.state.current else { return }; let own_uids = app.social.own_uids.clone(); - let Some(view) = app.sessions.get_mut(&id) else { return }; + let Some(view) = app.state.sessions.get_mut(&id) else { return }; let own_client = view.state.own_client; let own = |m: &ChatMessage| crate::social::own_message(&own_uids, own_client, m); let index = view.current_tab; @@ -483,7 +483,7 @@ fn save_png(image: &SharedPixelBuffer, path: &std::path::Path) -> Re /// channel, which asks for its password; `wrong` as if the server had /// refused one. fn open_channel_password(app: &mut App, wrong: bool) { - let Some(session) = app.current else { return }; + let Some(session) = app.state.current else { return }; let locked = app .view() .and_then(|v| v.presence.channels.values().filter(|c| c.has_password).map(|c| c.id).min()); @@ -549,7 +549,7 @@ fn demo_ui(app: &mut App) { client_version: None, cached_server_icon: None, }; - app.bookmarks = vec![ + app.state.bookmarks = vec![ Bookmark { gateway_url: Some("wss://gw.nightfall.example/v1".into()), ..bookmark(DEMO, "Nightfall Guild", "ts.nightfall.example:9987") @@ -559,12 +559,12 @@ fn demo_ui(app: &mut App) { ]; // Home's "Continue where you left off": a channel of a server without // voice, so it shows Join. - app.settings.last_voice = Some(LastVoice { + app.state.settings.last_voice = Some(LastVoice { bookmark: DEMO + 1, address: "pixel.example".into(), channel: vec!["Art Corner".into()], }); - app.current = Some(DEMO); + app.state.current = Some(DEMO); let session = DEMO as u64; let mut p = Presence { server_name: "Nightfall Guild".into(), ..Default::default() }; @@ -940,7 +940,7 @@ fn demo_social(app: &mut App) { // The samples came one by one, as new ones do: all are read (no "New" // line, which a gateway page on screen gets), but for Mira's and // Lumen's messages, which came while away. - for view in app.sessions.values_mut() { + for view in app.state.sessions.values_mut() { for tab in &mut view.tabs { tab.divider = None; tab.catch_up(); @@ -983,7 +983,7 @@ fn demo_social(app: &mut App) { }); // The pictures of the links, as if downloaded. - if let Some(view) = app.sessions.get_mut(&DEMO) { + if let Some(view) = app.state.sessions.get_mut(&DEMO) { for (channel, name) in [(2, "night-castle.png"), (2, "guild-banner.png"), (2, "map-notes.png")] { @@ -995,7 +995,7 @@ fn demo_social(app: &mut App) { }; view.extra.previews.insert( crate::previews::link_key(&file), - crate::previews::Preview::Ready(voelin_core::Bytes( + crate::vm::state::Preview::Ready(voelin_core::Bytes( demo_picture(640, 360, name.len() as u32).into(), )), ); @@ -1242,7 +1242,7 @@ fn demo_pictures(app: &mut App) { }; let mut events = vec![Event::ServerDetails { session, - address: app.bookmarks.iter().find(|b| b.id == DEMO).unwrap().address.clone(), + address: app.state.bookmarks.iter().find(|b| b.id == DEMO).unwrap().address.clone(), details: Arc::new(voelin_model::ServerDetails { icon: DEMO_SERVER_ICON, ..Default::default() diff --git a/crates/voelin-ui/src/events.rs b/crates/voelin-ui/src/events.rs index b0232b2..96e1256 100644 --- a/crates/voelin-ui/src/events.rs +++ b/crates/voelin-ui/src/events.rs @@ -29,7 +29,7 @@ impl App { use GatewayUpdate as U; let mut ask: Vec = Vec::new(); let mut remind = None; - let extra = &mut self.sessions.entry(id).or_default().extra; + let extra = &mut self.state.sessions.entry(id).or_default().extra; match update { U::Connected { uid, capabilities, .. } => { extra.gateway_uid = Some(uid.clone()); @@ -121,8 +121,8 @@ impl App { /// The events page of the current server was opened. pub(crate) fn open_events(&mut self) { - let Some(id) = self.current else { return }; - let loaded = self.sessions.get(&id).is_some_and(|v| v.extra.events_loaded); + let Some(id) = self.state.current else { return }; + let loaded = self.state.sessions.get(&id).is_some_and(|v| v.extra.events_loaded); if !loaded { self.gateway_to(id, GatewayRequest::Events { query: EventQuery::default() }); } @@ -232,16 +232,16 @@ impl App { /// Answer an event ("" withdraws the answer). pub(crate) fn rsvp(&mut self, event_id: i32, status: &str) { - let Some(id) = self.current else { return }; + let Some(id) = self.state.current else { return }; let status = (!status.is_empty()).then(|| RsvpStatus::parse(status)); self.gateway_to(id, GatewayRequest::Rsvp { event_id: i64::from(event_id), status }); } /// Show or hide who answered (fetching the event with its attendees). pub(crate) fn toggle_event(&mut self, event_id: i32) { - let Some(id) = self.current else { return }; + let Some(id) = self.state.current else { return }; let event_id = i64::from(event_id); - let view = self.sessions.entry(id).or_default(); + let view = self.state.sessions.entry(id).or_default(); if !view.extra.expanded.remove(&event_id) { view.extra.expanded.insert(event_id); self.gateway_to(id, GatewayRequest::GetEvent { id: event_id }); @@ -277,7 +277,7 @@ impl App { /// Create or change an event; the reason when the form is not right. pub(crate) fn save_event(&mut self, form: &EventForm) -> String { - let Some(id) = self.current else { return "No server selected.".into() }; + let Some(id) = self.state.current else { return "No server selected.".into() }; let Some(start_ms) = parse_local(&form.start) else { return "Write the start as YYYY-MM-DD HH:MM.".into(); }; @@ -315,14 +315,14 @@ impl App { } pub(crate) fn delete_event(&mut self, event_id: i32) { - if let Some(id) = self.current { + if let Some(id) = self.state.current { self.gateway_to(id, GatewayRequest::DeleteEvent { id: i64::from(event_id) }); } } /// Watch the stream of a live scheduled stream. pub(crate) fn watch_event(&mut self, event_id: i32) { - let Some(id) = self.current else { return }; + let Some(id) = self.state.current else { return }; let stream = self .view() .and_then(|v| v.extra.events.iter().find(|e| e.id == i64::from(event_id))) diff --git a/crates/voelin-ui/src/home.rs b/crates/voelin-ui/src/home.rs index edf1d4c..532fa41 100644 --- a/crates/voelin-ui/src/home.rs +++ b/crates/voelin-ui/src/home.rs @@ -29,8 +29,10 @@ impl App { /// streaming. fn live_rooms(&self) -> Vec { let mut rooms = Vec::new(); - for (b, backdrop) in self.bookmarks.iter().zip(vm::servers::tints(&self.bookmarks)) { - let Some(view) = self.sessions.get(&b.id) else { continue }; + for (b, backdrop) in + self.state.bookmarks.iter().zip(vm::servers::tints(&self.state.bookmarks)) + { + let Some(view) = self.state.sessions.get(&b.id) else { continue }; let channel_of = |cid: Option| { cid.and_then(|c| view.presence.channels.get(&c)) .map(|c| vm::tree::channel_title(c).0.to_owned()) @@ -123,8 +125,8 @@ impl App { let now = crate::social::now_ms(); let mut events: Vec<(i64, HappeningItem, Happening)> = Vec::new(); let mut news = Vec::new(); - for b in &self.bookmarks { - let Some(view) = self.sessions.get(&b.id) else { continue }; + for b in &self.state.bookmarks { + let Some(view) = self.state.sessions.get(&b.id) else { continue }; for e in &view.extra.events { let ends = e.spec.end_ms.unwrap_or(e.spec.start_ms + 3 * 3_600_000); if ends < now { @@ -192,7 +194,7 @@ impl App { /// server (and the streamer's channel, watching once there). pub(crate) fn watch_live(&mut self, session: i64, id: &str) { self.show_server(session); - let Some(view) = self.sessions.get(&session) else { return }; + let Some(view) = self.state.sessions.get(&session) else { return }; if view.streams_available() && view.streams.iter().any(|s| s.id == id) { self.watch_stream(id.to_owned()); return; @@ -232,8 +234,9 @@ impl App { } fn last_resume(&self) -> Option { - let voice = |id| self.sessions.get(&id).map_or(VoiceState::Disconnected, |v| v.state.voice); - vm::home::resume(self.settings.last_voice.as_ref(), &self.bookmarks, voice) + let voice = + |id| self.state.sessions.get(&id).map_or(VoiceState::Disconnected, |v| v.state.voice); + vm::home::resume(self.state.settings.last_voice.as_ref(), &self.state.bookmarks, voice) } /// Home's "Continue where you left off", its server as the rail shows @@ -272,17 +275,17 @@ impl App { if self.demo_ui { return false; } - let Some(view) = self.sessions.get(&session) else { return false }; + let Some(view) = self.state.sessions.get(&session) else { return false }; let (VoiceState::Connected, Some(cid)) = (view.state.voice, view.state.own_channel) else { return false; }; let channel = vm::tree::channel_path(&view.presence, cid); let Some(b) = self.bookmark(session).filter(|_| !channel.is_empty()) else { return false }; let last = LastVoice { bookmark: session, address: b.address.clone(), channel }; - if self.settings.last_voice.as_ref() == Some(&last) { + if self.state.settings.last_voice.as_ref() == Some(&last) { return false; } - self.settings.last_voice = Some(last); + self.state.settings.last_voice = Some(last); self.store_settings(); true } diff --git a/crates/voelin-ui/src/inbox.rs b/crates/voelin-ui/src/inbox.rs index af7593c..9eaa569 100644 --- a/crates/voelin-ui/src/inbox.rs +++ b/crates/voelin-ui/src/inbox.rs @@ -65,8 +65,8 @@ pub(crate) fn take() { impl App { fn share(&mut self, nav: &Nav<'_>, text: Option, files: Vec) { - let current = self.current.and_then(|id| { - let view = self.sessions.get(&id)?; + let current = self.state.current.and_then(|id| { + let view = self.state.sessions.get(&id)?; let tab = &view.tabs[view.current_tab]; // Files go to the channel of the chat, else to ours. let channel = match tab.target { diff --git a/crates/voelin-ui/src/links.rs b/crates/voelin-ui/src/links.rs index 82570c3..3e73e26 100644 --- a/crates/voelin-ui/src/links.rs +++ b/crates/voelin-ui/src/links.rs @@ -29,9 +29,14 @@ impl App { } }; let in_voice = |id: i64| { - self.sessions.get(&id).is_some_and(|v| v.state.voice == VoiceState::Connected) + self.state.sessions.get(&id).is_some_and(|v| v.state.voice == VoiceState::Connected) }; - match vm::servers::link_server(&self.bookmarks, &link.address(), self.current, in_voice) { + match vm::servers::link_server( + &self.state.bookmarks, + &link.address(), + self.state.current, + in_voice, + ) { Some((id, true)) => self.move_by_link(id, &link), saved => self.open_link_form(saved.map(|(id, _)| id), &link), } @@ -41,7 +46,7 @@ impl App { fn move_by_link(&mut self, session: i64, link: &ServerLink) { self.show_server(session); let Some(path) = &link.channel else { return }; - let Some(view) = self.sessions.get_mut(&session) else { return }; + let Some(view) = self.state.sessions.get_mut(&session) else { return }; let Some(channel) = vm::servers::channel_by_path(&view.presence, path) else { let server = self.bookmark(session).map(|b| b.name.clone()).unwrap_or_default(); self.set_status(format!("{server} has no channel \u{201c}{path}\u{201d}")); diff --git a/crates/voelin-ui/src/members.rs b/crates/voelin-ui/src/members.rs index 95e8f51..b9569ff 100644 --- a/crates/voelin-ui/src/members.rs +++ b/crates/voelin-ui/src/members.rs @@ -46,9 +46,12 @@ impl App { let id = view.member_card?; let client = view.presence.clients.get(&id)?; let uid = client.uid.clone(); - let contact = uid.as_ref().and_then(|u| self.contacts.get(u)); - let playback = - uid.as_ref().and_then(|u| self.playback.get(u)).copied().unwrap_or_default(); + let contact = uid.as_ref().and_then(|u| self.state.contacts.get(u)); + let playback = uid + .as_ref() + .and_then(|u| self.state.playback.get(u)) + .copied() + .unwrap_or_default(); let groups: Vec> = client .server_groups .iter() @@ -83,8 +86,8 @@ impl App { /// The card's buttons: "message", "poke", "friend", "blocked", "mute". pub(crate) fn member_action(&mut self, action: &str) { - let Some(id) = self.current else { return }; - let Some(view) = self.sessions.get(&id) else { return }; + let Some(id) = self.state.current else { return }; + let Some(view) = self.state.sessions.get(&id) else { return }; let Some(client) = view.member_card.and_then(|c| view.presence.clients.get(&c)) else { return; }; @@ -105,18 +108,22 @@ impl App { "friend" | "blocked" => { let Some(uid) = uid else { return }; let wanted = if action == "friend" { Relation::Friend } else { Relation::Blocked }; - let current = self.contacts.get(&uid).map(|c| c.relation); - let mut contact = - self.contacts.get(&uid).cloned().unwrap_or_else(|| Contact::new(uid.clone())); + let current = self.state.contacts.get(&uid).map(|c| c.relation); + let mut contact = self + .state + .contacts + .get(&uid) + .cloned() + .unwrap_or_else(|| Contact::new(uid.clone())); contact.nickname = nickname; contact.relation = if current == Some(wanted) { Relation::Neutral } else { wanted }; - self.contacts.insert(uid, contact.clone()); + self.state.contacts.insert(uid, contact.clone()); self.engine.send(Command::SetContact { contact: Box::new(contact) }); self.refresh_member_card(); } "mute" => { let Some(uid) = uid else { return }; - let mut playback = self.playback.get(&uid).copied().unwrap_or_default(); + let mut playback = self.state.playback.get(&uid).copied().unwrap_or_default(); playback.muted = !playback.muted; self.set_playback(&uid, client_id, playback); } @@ -126,9 +133,9 @@ impl App { /// Open the poke dialog for a client (the member card, a contact). pub(crate) fn ask_poke(&mut self, session: i64, client: u16) { - let Some(view) = self.sessions.get(&session) else { return }; + let Some(view) = self.state.sessions.get(&session) else { return }; let name = view.nickname(client); - self.poke_target = Some((session, client, name.clone())); + self.state.poke_target = Some((session, client, name.clone())); let Some(ui) = self.ui.upgrade() else { return }; let nav = ui.global::