From 03d1c3bd0787f20f7af0e5b0d94c2c82d690f402 Mon Sep 17 00:00:00 2001 From: faumaray Date: Wed, 21 Oct 2026 06:30:39 +0300 Subject: [PATCH] Move the state transition of every engine event that the AppState holds into voelin-ui-vm events::apply(state, host, event) changes the AppState for an engine Event and returns an Update: the parts to draw again (Refresh, each once), the status line, the engine commands, what to keep (Persist), pictures to decode again, the password dialog, notices for the bell, the chats that changed, a stream to watch. Host is what a transition asks while it runs (is the chat on screen, the store's read markers, the preview limit); the Slint client answers it in host.rs and carries the update out there, so App::handle_event is social_event, apply_event and social_refresh. The chat transitions (tabs, messages, what is read, pins and topics, files), the pictures linked in chats, the server's name, icon and gateway, joining again and the password prompt, the last place of voice and the stored volumes moved with it; Spot, the notice types, own_uids and peer_name moved to the view model crate. Update::rest hands back the events whose state is not in the AppState yet (the streams we share and watch, the studio's stream, a setting that changed); the friends, pokes and offline messages are still looked at by social.rs before and after. The vm tests replay tapes of events against a fake Host. Co-Authored-By: Claude Sonnet 5.5 --- crates/voelin-ui-vm/src/chat/logic.rs | 574 +++++++++++++ .../voelin-ui-vm/src/{chat.rs => chat/mod.rs} | 33 +- crates/voelin-ui-vm/src/events/gateway.rs | 103 +++ crates/voelin-ui-vm/src/events/mod.rs | 476 +++++++++++ crates/voelin-ui-vm/src/events/tests.rs | 793 ++++++++++++++++++ crates/voelin-ui-vm/src/host.rs | 221 +++++ crates/voelin-ui-vm/src/lib.rs | 3 + crates/voelin-ui-vm/src/previews.rs | 172 ++++ crates/voelin-ui-vm/src/social.rs | 164 +++- crates/voelin-ui-vm/src/state.rs | 19 + crates/voelin-ui/src/app.rs | 275 +----- crates/voelin-ui/src/chat.rs | 523 +----------- crates/voelin-ui/src/dev.rs | 6 +- crates/voelin-ui/src/events.rs | 100 +-- crates/voelin-ui/src/home.rs | 22 - crates/voelin-ui/src/host.rs | 243 ++++++ crates/voelin-ui/src/lib.rs | 1 + crates/voelin-ui/src/messages.rs | 21 +- crates/voelin-ui/src/previews.rs | 174 +--- crates/voelin-ui/src/servers.rs | 124 +-- crates/voelin-ui/src/settings_page.rs | 30 +- crates/voelin-ui/src/settings_pages/bind.rs | 2 +- crates/voelin-ui/src/social.rs | 96 +-- crates/voelin-ui/src/streams.rs | 27 - docs/ui.md | 41 +- 25 files changed, 2903 insertions(+), 1340 deletions(-) create mode 100644 crates/voelin-ui-vm/src/chat/logic.rs rename crates/voelin-ui-vm/src/{chat.rs => chat/mod.rs} (96%) create mode 100644 crates/voelin-ui-vm/src/events/gateway.rs create mode 100644 crates/voelin-ui-vm/src/events/mod.rs create mode 100644 crates/voelin-ui-vm/src/events/tests.rs create mode 100644 crates/voelin-ui-vm/src/host.rs create mode 100644 crates/voelin-ui-vm/src/previews.rs create mode 100644 crates/voelin-ui/src/host.rs diff --git a/crates/voelin-ui-vm/src/chat/logic.rs b/crates/voelin-ui-vm/src/chat/logic.rs new file mode 100644 index 0000000..89ee50f --- /dev/null +++ b/crates/voelin-ui-vm/src/chat/logic.rs @@ -0,0 +1,574 @@ +//! What happens to a session's chats when the engine tells something: tabs +//! open, messages arrive and are read, the gateway adds pins and topics, +//! files move. The functions change the [`AppState`] and say in the +//! [`Cx`]'s update what to draw and send; nothing here touches a toolkit. +//! +//! The engine keeps the history: `Event::ChatHistory` is an upsert of +//! messages by their local id (see `voelin_core::history`), so a tab holds +//! the messages it was given, ordered by `(ts_ms, id)`. Sessions the engine +//! keeps no history for (it does not know the server yet) fall back to +//! `Event::Chat`. +//! +//! Messages are read while their tab is on screen in the focused window +//! ([`track_reading`]). A tab remembers the newest message read +//! (`Tab::read`, kept in the store's `chat_reads`), counts what came after +//! it, and when it comes on screen shows a "New" divider above the first of +//! those until it is left. + +use std::collections::HashMap; + +use voelin_core::gateway::Pin; +use voelin_core::{ + Command, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource, TransferState, +}; +use voelin_gateway_proto::{ErrorCode, TopicInfo, feature}; +use voelin_model::{ChatMessage, ChatTarget}; +use voelin_store::ChatRead; + +use super::{Previous, tab_title}; +use crate::host::Cx; +use crate::previews::{fetch_previews, preview_progress}; +use crate::social::{is_own, own_message, peer_name}; +use crate::state::{AppState, Lines, Msg, PinRow, SessionView, store_target}; + +/// The index of `target`'s tab in session `id`, opened if new (the engine +/// then sends its history). +pub fn chat_tab( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + target: ChatTarget, +) -> usize { + let peer = match &target { + ChatTarget::Private(uid) => peer_name(state, uid, None), + _ => String::new(), + }; + let view = state.sessions.entry(id).or_default(); + if let Some(i) = view.tabs.iter().position(|t| t.target == target) { + return i; + } + let title = tab_title(&view.presence, &target, &peer); + let tab = view.new_tab(target.clone(), title); + view.tabs.push(tab); + let index = view.tabs.len() - 1; + cx.send_real(Command::OpenChat { session: id as u64, target }); + index +} + +/// Open the chat `target` of the current session, and with `focus` show it. +pub fn open_chat( + state: &mut AppState, + cx: &mut Cx<'_>, + target: ChatTarget, + focus: bool, +) { + let Some(id) = state.current else { return }; + let index = chat_tab(state, cx, id, target); + if focus { + state.sessions.entry(id).or_default().focus_tab(index); + prefetch_counts(state, cx); + track_reading(state, cx); + } + cx.update.refresh.chat = true; + cx.update.refresh.servers = true; +} + +/// The index of `target`'s tab, opening one if it is new. +fn tab_for( + view: &mut SessionView, + target: &ChatTarget, + title: impl FnOnce() -> String, +) -> usize { + match view.tabs.iter().position(|t| t.target == *target) { + Some(i) => i, + None => { + let tab = view.new_tab(target.clone(), title()); + view.tabs.push(tab); + view.tabs.len() - 1 + } + } +} + +/// A live message of a session without stored history: appended as it +/// comes, without an id. +pub fn add_message( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + message: ChatMessage, +) { + let current = state.current == Some(id); + let reading = reads_now(state, cx, id); + let new = !is_own(state, id, &message); + let view = state.sessions.entry(id).or_default(); + let title = tab_title(&view.presence, &message.target, &message.author_name); + let index = tab_for(view, &message.target, || title); + let seen = reading && view.current_tab == index; + let tab = &mut view.tabs[index]; + let line = super::line(&message, tab.last.as_ref()); + tab.last = Some(Previous::of(&message)); + tab.lines.push(line); + let counted = new && !seen; + if counted { + tab.unread += 1; + } + if current { + cx.update.refresh.chat = true; + } + if counted { + cx.update.refresh.servers = true; + } + cx.chat_changed(id, &message.target); +} + +/// Messages the engine stored: added or updated by their local id. +pub fn history_batch( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + target: &ChatTarget, + messages: Vec, + source: HistorySource, + complete: bool, +) { + let current = state.current == Some(id); + let reading = reads_now(state, cx, id); + // A private chat is named after the peer, whoever wrote first. + let peer = match target { + ChatTarget::Private(uid) => Some(format!( + "@{}", + peer_name( + state, + uid, + messages.iter().find(|m| m.message.author_uid.as_deref() == Some(uid.as_str())) + ) + )), + _ => None, + }; + let own_uids = &state.own_uids; + let view = 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(|| tab_title(&view.presence, target, author)); + let index = tab_for(view, target, || title); + let seen = reading && view.current_tab == index; + let own_client = view.state.own_client; + let tab = &mut view.tabs[index]; + if source == HistorySource::Gateway { + tab.synced = true; + } + if source != HistorySource::Live { + tab.loading = false; + tab.complete = tab.complete || complete; + } + // Without a marker, what the tab holds was read. + if tab.read.is_none() { + tab.read = tab.newest(); + } + for message in messages { + match tab.messages.iter().position(|m| m.message.id == message.id) { + Some(i) => tab.messages[i].message = message, + None => { + let key = tab.take_key(); + tab.messages.push(Msg { key, message }); + } + } + } + tab.messages.sort_by_key(|m| (m.message.message.ts_ms, m.message.id)); + // ...and so is a first stored page; a first live message is new. + if tab.read.is_none() { + tab.read = match source { + HistorySource::Live => tab + .messages + .first() + .map(|m| (m.message.message.ts_ms, m.message.id.saturating_sub(1))), + _ => tab.newest(), + }; + } + let unread = tab.unread; + let own = |m: &ChatMessage| own_message(own_uids, own_client, m); + if seen && source == HistorySource::Live { + tab.catch_up(); + } else { + tab.count_unread(own); + // What came while away (a stored or gateway page) gets the divider + // also when its chat is on screen already. + if seen { + tab.enter(own); + } + } + let counted = tab.unread != unread; + if current { + fetch_previews(state, cx, id); + cx.update.refresh.chat = true; + } + if counted { + cx.update.refresh.servers = true; + } + cx.chat_changed(id, target); +} + +// What is read. + +/// 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(state: &AppState, cx: &Cx<'_>, id: i64) -> bool { + state.focused && state.current == Some(id) && cx.host.chat_shown() +} + +/// Where the tab of `target` is in session `id`. +fn tab_index(state: &AppState, id: i64, target: &ChatTarget) -> Option { + state.sessions.get(&id)?.tabs.iter().position(|t| t.target == *target) +} + +/// After anything that can change which chat is on screen (a tab, a server, +/// the page, the window's focus): the chat left is stored and 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 fn track_reading(state: &mut AppState, cx: &mut Cx<'_>) -> bool { + let open = state.current.filter(|_| cx.host.chat_shown()).and_then(|id| { + let view = state.sessions.get(&id)?; + Some((id, view.tabs.get(view.current_tab)?.target.clone())) + }); + let mut changed = false; + if open != state.reading { + if let Some((id, target)) = state.reading.take() + && let Some(index) = tab_index(state, id, &target) + { + let tab = &mut state.sessions.entry(id).or_default().tabs[index]; + changed |= tab.divider.take().is_some(); + save_read(state, cx, id, index); + } + state.reading = open.clone(); + } + if let (true, Some((id, target))) = (state.focused, open) + && let Some(index) = tab_index(state, id, &target) + { + let own_uids = &state.own_uids; + let view = 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); + tab.enter(|m| own_message(own_uids, own_client, m)); + changed |= (tab.unread, tab.divider) != before; + } + changed +} + +/// Store where tab `index` of session `id` was read, if that moved (not for +/// the sample data of `VOELIN_DEMO_UI`). +pub fn save_read(state: &mut AppState, cx: &mut Cx<'_>, id: i64, index: usize) { + if cx.host.demo_ui() { + return; + } + let Some(view) = 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 { + return; + }; + let read = ChatRead { ts_ms, id: message, updated_ms: chrono::Utc::now().timestamp_millis() }; + let target = store_target(&tab.target); + match cx.host.set_chat_read(server_uid, &target, &read) { + Ok(()) => { + tab.stored_read = tab.read; + // A tab closed and opened again starts from here. + view.reads.insert(target.key(), (ts_ms, message)); + } + Err(e) => cx.warn(format!("could not keep where a chat was read: {e}")), + } +} + +/// Store where every chat of session `id` was read (it ended, or the app +/// exits). +pub fn save_reads(state: &mut AppState, cx: &mut Cx<'_>, id: i64) { + let count = state.sessions.get(&id).map_or(0, |v| v.tabs.len()); + for index in 0..count { + save_read(state, cx, id, index); + } +} + +/// Where the chats of session `id` were read, from the store, once its +/// server is known (or another one: the gateway's id wins): its tabs start +/// from there, now and when they open. +pub fn load_reads(state: &mut AppState, cx: &mut Cx<'_>, id: i64) { + let Some(view) = state.sessions.get_mut(&id) else { return }; + if cx.host.demo_ui() + || view.state.server_uid.is_none() + || view.reads_of == view.state.server_uid + { + return; + } + view.reads_of = view.state.server_uid.clone(); + let server_uid = view.reads_of.as_deref().unwrap_or_default(); + view.reads = match cx.host.chat_reads(server_uid) { + Ok(reads) => reads.into_iter().map(|(t, r)| (t.key(), (r.ts_ms, r.id))).collect(), + Err(e) => { + cx.warn(format!("could not read where the chats were read: {e}")); + HashMap::new() + } + }; + for tab in &mut view.tabs { + tab.read_from(&view.reads); + } +} + +// Gateway features of a chat. + +/// Ask the gateway for the current chat's pins and topics until it sent +/// them, so the header counts them before their drawers are opened. +pub fn prefetch_counts(state: &AppState, cx: &mut Cx<'_>) { + let Some(id) = state.current else { return }; + let Some(view) = state.sessions.get(&id) else { return }; + let Some(tab) = view.tabs.get(view.current_tab) else { return }; + if !tab.pins_loaded && view.gateway_has(feature::PINS) { + cx.gateway_to(id, GatewayRequest::Pins { target: tab.target.clone() }); + } + if !tab.topics_loaded && view.gateway_has(feature::TOPICS) { + let target = tab.target.clone(); + cx.gateway_to(id, GatewayRequest::Topics { target, include_archived: false }); + } +} + +/// What a gateway update says about the chats of session `id`: its +/// features, pins, topics and the viewers of its streams. +pub fn gateway_update( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + update: GatewayUpdate, +) { + let current = state.current == Some(id); + let view = state.sessions.entry(id).or_default(); + match update { + GatewayUpdate::Connected { capabilities, .. } + | GatewayUpdate::Capabilities { capabilities } => { + view.gateway_caps = capabilities; + if current { + prefetch_counts(state, cx); + } + } + GatewayUpdate::Disconnected { .. } => { + view.gateway_caps.clear(); + for tab in &mut view.tabs { + tab.pins_loaded = false; + tab.topics_loaded = false; + } + } + // Answers to our requests: a chat closed while they were on their way + // (prefetch_counts asks on every change of chat) stays closed. + GatewayUpdate::Pins { target, pins } => { + let Some(tab) = view.tabs.iter_mut().find(|t| t.target == target) else { return }; + tab.pins_loaded = true; + tab.pins = pins.into_iter().map(|p| pin_row(tab.take_key(), p)).collect(); + tab.pins.sort_by_key(|p| -p.ts_ms); + } + GatewayUpdate::Pinned { target, pin } => { + let index = tab_for(view, &target, || "Server".into()); + let tab = &mut view.tabs[index]; + let row = pin_row(tab.take_key(), pin); + tab.pins.retain(|p| p.message.id != row.message.id); + tab.pins.insert(0, row); + } + GatewayUpdate::Unpinned { target, message_id, .. } => { + let index = tab_for(view, &target, || "Server".into()); + view.tabs[index].pins.retain(|p| p.message.remote_id != Some(message_id)); + } + GatewayUpdate::Topics { target, topics } => { + let Some(tab) = view.tabs.iter_mut().find(|t| t.target == target) else { return }; + tab.topics = topics; + tab.topics_loaded = true; + } + GatewayUpdate::Topic { topic } => { + let index = tab_for(view, &topic.target.clone(), || "Server".into()); + upsert_topic(&mut view.tabs[index].topics, topic); + } + GatewayUpdate::TopicHistory { target, topic, messages, .. } => { + let index = tab_for(view, &target, || "Server".into()); + let tab = &mut view.tabs[index]; + if tab.topic != Some(topic) { + return; + } + for message in messages { + match tab.topic_messages.iter().position(|m| m.message.id == message.id) { + Some(i) => tab.topic_messages[i].message = message, + None => { + let key = tab.take_key(); + tab.topic_messages.push(Msg { key, message }); + } + } + } + tab.topic_messages.sort_by_key(|m| (m.message.message.ts_ms, m.message.id)); + } + GatewayUpdate::Failed { request, code, message } => { + cx.warn(format!("gateway request {request} failed ({code:?}): {message}")); + if let Some(text) = failure_text(&request, code, &message) { + cx.status(text); + } + return; + } + // The stream directory: how many watch each stream. + GatewayUpdate::Streams { streams } => { + view.stream_viewers = streams.iter().filter_map(viewers_of).collect(); + return stream_viewers_changed(cx, current); + } + GatewayUpdate::StreamStarted { stream } + | GatewayUpdate::StreamUpdated { stream } + | GatewayUpdate::StreamRegistered { stream } => { + if let Some((id, viewers)) = viewers_of(&stream) { + view.stream_viewers.insert(id, viewers); + } + return stream_viewers_changed(cx, current); + } + GatewayUpdate::StreamEnded { id, .. } => { + view.stream_viewers.remove(&id); + return stream_viewers_changed(cx, current); + } + // Posts, pins and reactions also arrive as stored messages. + _ => return, + } + if current { + cx.update.refresh.chat = true; + } +} + +fn stream_viewers_changed(cx: &mut Cx<'_>, current: bool) { + if current { + cx.update.refresh.streams = true; + cx.update.refresh.viewer = true; + } +} + +// Files in chat. + +/// A transfer of a file that was not a picture preview: an upload from the +/// composer posts the file's link once it is up; a download of a message's +/// file shows how far it is. +pub fn transfer_progress( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + transfer: u64, + progress: TransferState, +) { + // An upload from the composer: post the file's link once it is up. + if let Some((_, channel, name)) = state.uploads.get(&transfer).cloned() { + match &progress { + TransferState::Done { size, .. } => { + state.uploads.remove(&transfer); + let file = voelin_model::FileRef { + channel, + path: "/".into(), + name: name.clone(), + size: Some(*size), + ..Default::default() + }; + cx.send(Command::SendChat { + session: id as u64, + target: ChatTarget::Channel(channel), + text: file.to_bbcode(), + }); + cx.status(format!("{name} shared")); + } + TransferState::Failed(e) => { + state.uploads.remove(&transfer); + cx.status(format!("Could not upload {name}: {e}")); + } + TransferState::Cancelled => { + state.uploads.remove(&transfer); + } + _ => {} + } + return; + } + if preview_progress(state, cx, id, transfer, &progress) { + return; + } + let done = matches!(progress, TransferState::Done { .. }); + let current = state.current == Some(id); + let view = state.sessions.entry(id).or_default(); + let Some(entry) = view.downloads.get_mut(&transfer) else { return }; + entry.state = progress; + let name = entry.name.clone(); + if done { + cx.status(format!("{name} downloaded")); + } + if current { + cx.update.refresh.chat = true; + } +} + +/// What a failed gateway request tells the user. What the app asked for by +/// itself (history, lists, subscriptions) fails quietly; what the user did +/// says so in plain words, never the gateway's; the gateway's own +/// administration page shows its message as it is. +pub fn failure_text(request: &str, code: Option, message: &str) -> Option { + if request.starts_with("config_") || request.starts_with("perm_") { + return Some(format!("{request}: {message}")); + } + let done_by_user = matches!( + request, + "post" + | "pin" | "unpin" + | "react" | "unreact" + | "create_topic" + | "update_topic" + | "create_event" + | "update_event" + | "delete_event" + | "rsvp" + ); + if !done_by_user { + return None; + } + let text = match code { + Some(ErrorCode::Forbidden) => "Not allowed on this server.", + Some(ErrorCode::RateLimited) => "Too many requests; try again in a moment.", + Some(ErrorCode::QuotaExceeded) => "This server's limit is reached.", + Some(ErrorCode::NotFound) => "That is no longer there.", + Some(ErrorCode::FeatureDisabled) => "This server does not offer that.", + _ => "That did not work; try again later.", + }; + Some(text.to_owned()) +} + +/// A directory entry's stream id and viewer count, when it has both. +fn viewers_of(entry: &voelin_gateway_proto::StreamEntry) -> Option<(String, u32)> { + Some((entry.stream_id.clone()?, entry.viewers?)) +} + +fn pin_row(key: i32, pin: Pin) -> PinRow { + PinRow { key, message: pin.message, by: pin.by.name, ts_ms: pin.ts_ms } +} + +fn upsert_topic(topics: &mut Vec, topic: TopicInfo) { + match topics.iter().position(|t| t.id == topic.id) { + Some(i) => topics[i] = topic, + None => topics.insert(0, topic), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn failures_say_what_the_user_did_never_the_gateway() { + let lost = "websocket: IO error: Connection refused (os error 111)"; + // The app's own requests fail quietly. + for request in ["history", "sync", "pins", "events", "subscribe_streams"] { + assert_eq!(failure_text(request, None, lost), None, "{request}"); + } + // The user's own, in plain words. + assert_eq!( + failure_text("pin", Some(ErrorCode::Forbidden), "no b_pin").as_deref(), + Some("Not allowed on this server.") + ); + let text = failure_text("post", None, lost).unwrap(); + assert!(!text.contains("websocket") && !text.to_lowercase().contains("gateway"), "{text}"); + // The gateway's administration page shows its message. + assert_eq!( + failure_text("config_set", Some(ErrorCode::BadRequest), "bad value").as_deref(), + Some("config_set: bad value") + ); + } +} diff --git a/crates/voelin-ui-vm/src/chat.rs b/crates/voelin-ui-vm/src/chat/mod.rs similarity index 96% rename from crates/voelin-ui-vm/src/chat.rs rename to crates/voelin-ui-vm/src/chat/mod.rs index 0ff9905..dbc8667 100644 --- a/crates/voelin-ui-vm/src/chat.rs +++ b/crates/voelin-ui-vm/src/chat/mod.rs @@ -1,6 +1,9 @@ //! Chat lines: one [`ChatLine`] per message, with its text in blocks of //! styled runs (`vm::bbcode`), its reactions and the files and pictures it -//! links. +//! links; [`logic`] has what happens to a session's chats when the engine +//! tells something. + +pub mod logic; use std::borrow::Cow; use std::cell::RefCell; @@ -9,7 +12,7 @@ use std::path::PathBuf; use unicode_segmentation::UnicodeSegmentation; use voelin_core::HistoryMessage; -use voelin_model::{ChatMessage, ChatTarget, FileRef, Presence}; +use voelin_model::{ChatMessage, ChatTarget, FileRef, HostMessageMode, Presence, ServerDetails}; use crate::avatar; use crate::bbcode::{self, BlockKind, Doc, Span, Style}; @@ -17,6 +20,32 @@ use crate::bridge::{ChatLine, FileItem, ReactionItem, TextBlock, TextRun}; use crate::color::Rgb; use crate::emoji; use crate::image::ImageRef; +use crate::state::{SessionView, Tab}; + +/// Where the server's welcome and host message keep what their lines were +/// built from (`LineCache`), apart from the messages' ids. +pub const SERVER_LINES: [i64; 2] = [i64::MIN, i64::MIN + 1]; + +/// What the server says to everyone who connects, with where its line keeps +/// its parts: its welcome message, and its host message when that goes to +/// the chat log. +pub fn server_texts(details: &ServerDetails) -> Vec<(&str, i64)> { + let host = details.host_message_mode == HostMessageMode::Log; + [Some(&details.welcome_message), host.then_some(&details.host_message)] + .into_iter() + .zip(SERVER_LINES) + .filter_map(|(text, id)| Some((text.filter(|t| !t.trim().is_empty())?.as_str(), id))) + .collect() +} + +/// The text of the server's line `key` (-1, -2, ...) of a server chat, if +/// `tab` is one. +pub fn server_text<'a, L>(view: &'a SessionView, tab: &Tab, key: i32) -> Option<&'a str> { + if tab.target != ChatTarget::Server || key >= 0 { + return None; + } + server_texts(&view.presence.server).get((-1 - key) as usize).map(|(text, _)| *text) +} /// Lines of the same author within this time are grouped (no header). const GROUP_MS: i64 = 5 * 60 * 1000; diff --git a/crates/voelin-ui-vm/src/events/gateway.rs b/crates/voelin-ui-vm/src/events/gateway.rs new file mode 100644 index 0000000..81f8735 --- /dev/null +++ b/crates/voelin-ui-vm/src/events/gateway.rs @@ -0,0 +1,103 @@ +//! What a server's gateway tells besides chat: its events (the events page, +//! RSVP, reminders), the stream directory and the activity feed (the home +//! page), our permissions there, its configuration (gateway administration). +//! The pins, reactions and topics are in `chat::logic`. + +use voelin_core::{GatewayRequest, GatewayUpdate}; +use voelin_gateway_proto::{EventQuery, feature}; + +use crate::host::Cx; +use crate::social::{NoticeKind, NoticeRequest, NoticeTarget, server_name}; +use crate::state::{AppState, Lines}; + +/// Keep what a gateway update tells the home, events and administration +/// screens (before the chat handles its part), and ask for what a new +/// connection needs. +pub fn extra(state: &mut AppState, cx: &mut Cx<'_>, id: i64, update: &GatewayUpdate) { + use GatewayUpdate as U; + let mut ask: Vec = Vec::new(); + let mut remind = None; + let extra = &mut state.sessions.entry(id).or_default().extra; + match update { + U::Connected { uid, capabilities, .. } => { + extra.gateway_uid = Some(uid.clone()); + let has = |f: &str| capabilities.iter().any(|c| c == f); + ask.push(GatewayRequest::Permissions { channel: None }); + if has(feature::EVENTS) { + ask.push(GatewayRequest::Events { query: EventQuery::default() }); + } + if has(feature::STREAMS) { + ask.push(GatewayRequest::Streams); + } + if has(feature::ACTIVITY) { + ask.push(GatewayRequest::Activity { before: None, limit: Some(30) }); + } + } + U::Disconnected { .. } => { + extra.directory.clear(); + extra.events.clear(); + extra.events_loaded = false; + extra.activity.clear(); + extra.actions.clear(); + extra.config.clear(); + extra.perms.clear(); + } + U::Permissions { channel: None, actions } => extra.actions = actions.clone(), + U::Events { events } => { + extra.events = events.clone(); + extra.events.sort_by_key(|e| e.spec.start_ms); + extra.events_loaded = true; + } + U::Event { event } => { + match extra.events.iter().position(|e| e.id == event.id) { + Some(i) => extra.events[i] = event.clone(), + None => extra.events.push(event.clone()), + } + extra.events.sort_by_key(|e| e.spec.start_ms); + } + U::EventDeleted { id: event } => extra.events.retain(|e| e.id != *event), + U::EventReminder { event, starts_in_ms } => remind = Some((event.clone(), *starts_in_ms)), + U::Streams { streams } => extra.directory = streams.clone(), + U::StreamStarted { stream } + | U::StreamUpdated { stream } + | U::StreamRegistered { stream } => { + extra.directory.retain(|e| e.id != stream.id); + extra.directory.push(stream.clone()); + } + U::StreamEnded { id: stream, .. } => extra.directory.retain(|e| e.id != *stream), + U::Activity { entries, .. } => extra.activity = entries.clone(), + U::ActivityAdded { entry } => { + extra.activity.insert(0, entry.clone()); + extra.activity.truncate(100); + } + U::Config { entries } => extra.config = entries.clone(), + U::ConfigValue { entry } => match extra.config.iter().position(|e| e.key == entry.key) { + Some(i) => extra.config[i] = entry.clone(), + None => extra.config.push(entry.clone()), + }, + U::PermRules { rules } => extra.perms = rules.clone(), + _ => return, + } + for request in ask { + cx.gateway_to(id, request); + } + if let Some((event, starts_in_ms)) = remind { + let minutes = starts_in_ms / 60_000; + let title = if minutes <= 0 { + format!("{} starts now", event.spec.title) + } else { + format!("{} starts in {minutes} min", event.spec.title) + }; + cx.update.notices.push(NoticeRequest { + kind: NoticeKind::Event, + title, + body: format!("on {}", server_name(state, id)), + target: NoticeTarget::Event(id, event.id), + name: event.creator.name.clone(), + uid: Some(event.creator.uid.clone()), + }); + } + cx.update.refresh.home = true; + cx.update.refresh.events = true; + cx.update.refresh.gateways = true; +} diff --git a/crates/voelin-ui-vm/src/events/mod.rs b/crates/voelin-ui-vm/src/events/mod.rs new file mode 100644 index 0000000..a5ef10f --- /dev/null +++ b/crates/voelin-ui-vm/src/events/mod.rs @@ -0,0 +1,476 @@ +//! What the engine's events do to the client's state. [`apply`] takes an +//! [`Event`], changes the [`AppState`] and returns an [`Update`]: what to +//! draw again, the status line, the commands for the engine, what to keep. +//! A front end calls it for every event and then does what the update says; +//! it has no dispatch of its own, so the Slint client and a GPUI one change +//! the state the same way. +//! +//! In [`Update::rest`] come back the events whose state is not in the +//! [`AppState`] yet: a stream we share or watch (`Share` and `Watch` hold +//! the capture and the decoder), the Stream Studio's stream, a setting that +//! changed (the settings service), and the friends, pokes and offline +//! messages that `social.rs` of the Slint client keeps. They move here with +//! their areas (docs/ui.md, "Controllers still to split"). + +mod gateway; + +use voelin_core::{BackendInfo, Command, Event, GatewayUpdate, JoinFailure, Source, VoiceState}; +use voelin_model::{ChannelId, ChatTarget}; +use voelin_store::Bookmark; + +use crate::chat::logic::{ + add_message, gateway_update, history_batch, load_reads, open_chat, save_reads, track_reading, + transfer_progress, +}; +use crate::host::{Cx, Host, Persist, Update}; +use crate::previews::fetch_previews; +use crate::servers::{AfterConnect, JoinStep, after_connect, join_password}; +use crate::settings::LastVoice; +use crate::state::{AppState, Lines, SessionView}; + +/// Apply an event to the state; see the [module](self). +pub fn apply(state: &mut AppState, host: &dyn Host, event: Event) -> Update { + let mut cx = Cx::new(host); + dispatch(state, &mut cx, event); + if let Some(text) = &cx.update.status { + state.status.clone_from(text); + } + cx.update +} + +fn dispatch(state: &mut AppState, cx: &mut Cx<'_>, event: Event) { + match event { + Event::State { session, state: now } => session_state(state, cx, session as i64, now), + Event::ServerInfo { session, name, backend, capabilities } => { + let id = session as i64; + state.sessions.entry(id).or_default().capabilities = capabilities; + adopt_server_name(state, cx, id, &name); + if state.current == Some(id) { + cx.status(connected_status(&name, &backend)); + } + cx.update.refresh.streams = true; + cx.update.autoshare = true; + } + Event::Presence { session, presence } => { + let id = session as i64; + let view = state.sessions.entry(id).or_default(); + // The server chat shows its welcome and host message, with their + // pictures. + let said = crate::chat::server_texts(&view.presence.server) + != crate::chat::server_texts(&presence.server); + // Our channel's path: known only now (a new connection), or + // renamed. + let path = |v: &SessionView| { + v.state.own_channel.map(|c| crate::tree::channel_path(&v.presence, c)) + }; + let path_before = path(view); + view.presence = presence; + let renamed = path(view) != path_before; + apply_client_playback(state, cx, id); + join_after_connect(state, cx, id); + if renamed && remember_voice(state, cx, id) { + cx.update.refresh.servers = true; + } + if state.current == Some(id) { + if said { + fetch_previews(state, cx, id); + } + let r = &mut cx.update.refresh; + (r.toolbar, r.tree, r.chat, r.streams) = (true, true, true, true); + cx.update.first_client = true; + } + } + Event::Talking { session, client, talking } => { + let id = session as i64; + let view = state.sessions.entry(id).or_default(); + if talking { + view.talking.insert(client); + } else { + view.talking.remove(&client); + } + if state.current == Some(id) { + cx.update.refresh.tree = true; + } + } + Event::InputLevel { session, level_db, sending } => { + let shown = match session { + Some(s) => state.current == Some(s as i64), + None => state.mic_test, + }; + if shown { + cx.update.input_level = Some((level_db, sending)); + } + } + Event::MicrophoneTestError { message } => { + cx.status(format!("Microphone test: {message}")); + } + // Only for sessions the engine keeps no history for (it does not + // know the server yet): those get ids and reactions instead. + Event::Chat { session, message } => { + let id = session as i64; + if !state.sessions.entry(id).or_default().has_history() { + add_message(state, cx, id, message); + } + } + Event::ChatHistory { session, target, messages, source, complete } => { + history_batch(state, cx, session as i64, &target, messages, source, complete); + } + Event::Gateway { session, update } => { + let id = session as i64; + if let GatewayUpdate::Connected { url, .. } = &update { + gateway_in_use(state, cx, id, url); + } + gateway::extra(state, cx, id, &update); + gateway_update(state, cx, id, update); + } + Event::Groups { session, server_groups, channel_groups } => { + let id = session as i64; + let view = state.sessions.entry(id).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 state.current == Some(id) { + cx.update.refresh.tree = true; + } + } + Event::ServerDetails { session, address, details } => { + remember_server_icon(state, cx, session as i64, &address, details.icon); + cx.update.refresh.servers = true; + cx.update.refresh.toolbar = true; + } + // Pictures can arrive after the rows were built: draw them again. + Event::AvatarReady { session, client_uid, path, .. } => { + let id = session as i64; + // A file that arrives again is decoded again if it changed. + cx.update.reloaded.push(path.clone()); + state.sessions.entry(id).or_default().avatars.insert(client_uid, path); + if state.current == Some(id) { + let r = &mut cx.update.refresh; + (r.tree, r.chat, r.toolbar, r.member_card, r.streams) = + (true, true, true, true, true); + } + } + Event::IconReady { session, icon, path } => { + let id = session as i64; + cx.update.reloaded.push(path.clone()); + state.sessions.entry(id).or_default().icons.insert(icon, path); + cx.update.refresh.servers = true; + if state.current == Some(id) { + cx.update.refresh.tree = true; + cx.update.refresh.toolbar = true; + } + } + Event::PictureReady { session, url, path } => { + let id = session as i64; + // The host banner reloads into the same file. + cx.update.reloaded.push(path.clone()); + state.sessions.entry(id).or_default().pictures.insert(url, path); + if state.current == Some(id) { + let r = &mut cx.update.refresh; + (r.toolbar, r.tree, r.chat, r.member_card) = (true, true, true, true); + } + } + Event::Transfer { session, transfer, state: progress } => { + transfer_progress(state, cx, session as i64, transfer, progress); + } + // The engine's contacts would replace the sample ones. + Event::ContactsChanged { .. } if cx.host.demo_ui() && !state.contacts.is_empty() => {} + Event::ContactsChanged { contacts } => { + state.contacts = contacts.iter().map(|c| (c.uid.clone(), c.clone())).collect(); + cx.update.refresh.member_card = true; + } + // The sample sessions of VOELIN_DEMO_UI are unknown to the engine. + Event::Error { .. } if cx.host.demo_ui() => {} + Event::Error { message, .. } => cx.status(message), + Event::JoinFailed { session, channel, reason } => { + join_failed(state, cx, session as i64, channel, reason); + } + Event::SettingRejected { key, message } => { + cx.status(format!("Setting {key}: {message}")); + } + Event::StreamsChanged { session, streams } => { + let id = session as i64; + // Development switch: watch the first stream that shows up. + let autowatch = cx.host.autowatch() && !cx.host.watching() && state.current == Some(id); + // A client whose stream was asked for while it was looked up. + let pending = state + .pending_watch + .filter(|(s, _)| *s == id) + .and_then(|(_, client)| streams.iter().find(|s| s.streamer == client)) + .map(|s| s.id.clone()); + let view = state.sessions.entry(id).or_default(); + let first = streams + .iter() + .find(|s| view.state.own_client != Some(s.streamer)) + .map(|s| s.id.clone()); + view.streams = streams; + cx.update.refresh.streams = true; + cx.update.refresh.servers = true; + if let Some(stream) = pending { + state.pending_watch = None; + cx.update.watch = Some(stream); + } else if autowatch && let Some(stream) = first { + cx.update.watch = Some(stream); + } + } + // What a stream we share or watch, the studio's stream and the + // settings service make of the rest, the front end keeps (see the + // module's note). + event => cx.update.rest = Some(event), + } +} + +/// A session's connections changed. +fn session_state( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + now: voelin_core::SessionState, +) { + let view = 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; + view.state = now.clone(); + if now.voice != VoiceState::Connected { + view.focused_own_channel = false; + } + if now.voice == VoiceState::Disconnected && was_voice != VoiceState::Disconnected { + view.channel_passwords.clear(); + view.join_after_connect = None; + } + if now.voice == VoiceState::Connected && was_voice != VoiceState::Connected { + // A new connection: volumes are sent again. + view.applied_playback.clear(); + } + // Where its chats were read, once the server is known; kept when the + // session ends. + load_reads(state, cx, id); + let off = |voice: VoiceState, observe: voelin_core::ObserveState| { + voice == VoiceState::Disconnected && observe == voelin_core::ObserveState::Off + }; + if off(now.voice, now.observe) && !off(was_voice, was_observe) { + save_reads(state, cx, id); + } + let focus = !state.sessions.entry(id).or_default().focused_own_channel; + if now.voice == VoiceState::Connected && was_voice != VoiceState::Connected { + cx.status("Connected"); + } + if state.current == Some(id) { + if track_reading(state, cx) { + cx.update.refresh.chat = true; + } + // The voice channel's chat is always at hand, and focused once per + // connection. + if let (Some(cid), VoiceState::Connected) = (now.own_channel, now.voice) { + open_chat(state, cx, ChatTarget::Channel(cid), focus); + state.sessions.entry(id).or_default().focused_own_channel = true; + } + } + // Where we are with voice, when it changed here: home's last place, + // which the rail's refresh shows (voice on another server does not take + // it back at each of its events). + if (now.voice, now.own_channel) != (was_voice, was_channel) { + remember_voice(state, cx, id); + } + let r = &mut cx.update.refresh; + (r.servers, r.toolbar, r.tree, r.streams) = (true, true, true, true); + cx.update.autoshare = true; + if state.current == Some(id) { + cx.update.first_client = true; + } + join_after_connect(state, cx, id); +} + +/// The status line once a server answered: "Connected to Nightfall Guild +/// (TeamSpeak 6 6.0.0-beta13.1)". +pub fn connected_status(name: &str, backend: &BackendInfo) -> String { + format!("Connected to {name} ({})", backend.label()) +} + +/// The gateway logged in at `url`: it is the one in use from now on. +fn gateway_in_use(state: &mut AppState, cx: &mut Cx<'_>, id: i64, url: &str) { + let Some(b) = state.bookmarks.iter_mut().find(|b| b.id == id) else { return }; + if b.gateway_in_use(url) { + cx.persist(Persist::Bookmark { id, what: "gateway in use" }); + } +} + +/// The server told its name: a server still named by its address takes it, +/// so the address is all a user has to type. +fn adopt_server_name(state: &mut AppState, cx: &mut Cx<'_>, id: i64, name: &str) { + let Some(b) = state.bookmarks.iter_mut().find(|b| b.id == id && b.name == b.address) else { + return; + }; + if name.trim().is_empty() || cx.host.demo_ui() { + return; + } + b.name = name.trim().to_owned(); + cx.persist(Persist::Bookmark { id, what: "server named" }); + cx.update.refresh.servers = true; + cx.update.refresh.toolbar = true; +} + +/// Apply only details originating from the bookmark's current address. +/// Returns whether its persisted metadata changed. +pub fn apply_server_icon( + bookmark: &mut Bookmark, + view: &mut SessionView, + address: &str, + icon: u32, +) -> bool { + if bookmark.address != address { + return false; + } + view.icon_address = Some(address.to_owned()); + view.server_icon = icon; + let before = bookmark.cached_server_icon.clone(); + bookmark.remember_server_icon(icon); + bookmark.cached_server_icon != before +} + +/// Keep only metadata supplied by the bookmark's current server. +fn remember_server_icon( + state: &mut AppState, + cx: &mut Cx<'_>, + id: i64, + address: &str, + icon: u32, +) { + let Some(bookmark) = state.bookmarks.iter_mut().find(|b| b.id == id) else { + return; + }; + let changed = apply_server_icon(bookmark, state.sessions.entry(id).or_default(), address, icon); + if changed && !cx.host.demo_ui() { + cx.persist(Persist::Bookmark { id, what: "server icon" }); + } +} + +/// Keep where we are with voice in `session` as the last place +/// (`ui.last_voice`); whether it changed. Not for the sample sessions. +pub fn remember_voice(state: &mut AppState, cx: &mut Cx<'_>, session: i64) -> bool { + if cx.host.demo_ui() { + return false; + } + let Some(view) = state.sessions.get(&session) else { return false }; + let (VoiceState::Connected, Some(cid)) = (view.state.voice, view.state.own_channel) else { + return false; + }; + let channel = crate::tree::channel_path(&view.presence, cid); + let Some(b) = state.bookmarks.iter().find(|b| b.id == session).filter(|_| !channel.is_empty()) + else { + return false; + }; + let last = LastVoice { bookmark: session, address: b.address.clone(), channel }; + if state.settings.last_voice.as_ref() == Some(&last) { + return false; + } + state.settings.last_voice = Some(last); + cx.persist(Persist::Settings); + true +} + +/// Send the stored volumes of clients that appeared in a voice session. +pub fn apply_client_playback(state: &mut AppState, cx: &mut Cx<'_>, session: i64) { + let Some(view) = state.sessions.get_mut(&session) else { return }; + if view.state.voice != VoiceState::Connected + || view.state.presence_source != Some(Source::Voice) + { + return; + } + let presence = view.presence.clone(); + view.applied_playback.retain(|id| presence.clients.contains_key(id)); + for client in presence.clients.values() { + if !view.applied_playback.insert(client.id) { + continue; + } + let stored = client.uid.as_ref().and_then(|uid| state.playback.get(uid)); + let Some(playback) = stored else { continue }; + let (s, c) = (session as u64, client.id); + cx.send(Command::SetClientVolume { session: s, client: c, volume: playback.volume }); + if playback.muted { + cx.send(Command::SetClientMuted { session: s, client: c, muted: true }); + } + } +} + +/// Connected into another channel than the one asked for +/// (`SessionView::join_after_connect`): the server says nothing when, for +/// one, the password was wrong, so it is joined again, and that move says +/// why. Once the channel shows in the voice connection's presence, which +/// can come after the own channel. +pub fn join_after_connect(state: &mut AppState, cx: &mut Cx<'_>, session: i64) { + let Some(view) = state.sessions.get_mut(&session) else { return }; + let (VoiceState::Connected, Some(asked)) = (view.state.voice, view.join_after_connect) else { + return; + }; + let known = view.presence.channels.contains_key(&asked); + match after_connect(view.state.own_channel, asked, known) { + AfterConnect::Wait => {} + AfterConnect::Joined => view.join_after_connect = None, + AfterConnect::JoinAgain => { + view.join_after_connect = None; + move_into(state, cx, session, asked); + } + } +} + +/// Move into a channel of a session connected with voice: with its +/// password, or asking for one when it is locked and none was given this +/// connection. +fn move_into(state: &mut AppState, cx: &mut Cx<'_>, session: i64, channel: ChannelId) { + let Some(view) = state.sessions.get(&session) else { return }; + let Some(info) = view.presence.channels.get(&channel) else { return }; + let remembered = view.channel_passwords.get(&channel).map(String::as_str); + match join_password(info, remembered) { + JoinStep::Send(password) => { + cx.send_real(Command::MoveToChannel { session: session as u64, channel, password }); + } + JoinStep::Ask => ask_password(state, cx, session, channel, false), + } +} + +/// Open the password dialog for a locked channel; `wrong`: the one given +/// was refused. +pub fn ask_password( + state: &mut AppState, + cx: &mut Cx<'_>, + session: i64, + channel: ChannelId, + wrong: bool, +) { + let Some(info) = state.sessions.get(&session).and_then(|v| v.presence.channels.get(&channel)) + else { + return; + }; + let name = crate::tree::channel_title(info).0.to_owned(); + state.join_target = Some((session, channel)); + cx.ask_password(name, wrong); +} + +/// The server refused a move ([`Event::JoinFailed`]): a password asks again +/// (the one given is forgotten), the rest is a toast. +pub fn join_failed( + state: &mut AppState, + cx: &mut Cx<'_>, + session: i64, + channel: ChannelId, + reason: JoinFailure, +) { + match reason { + JoinFailure::Password => { + let given = state + .sessions + .get_mut(&session) + .and_then(|v| v.channel_passwords.remove(&channel)) + .is_some(); + ask_password(state, cx, session, channel, given); + } + JoinFailure::Full => cx.status("The channel is full"), + JoinFailure::Other(text) => cx.status(text), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/voelin-ui-vm/src/events/tests.rs b/crates/voelin-ui-vm/src/events/tests.rs new file mode 100644 index 0000000..e496511 --- /dev/null +++ b/crates/voelin-ui-vm/src/events/tests.rs @@ -0,0 +1,793 @@ +//! Tapes of engine events replayed through [`apply`] against a fake host: +//! the state they leave, and what each update asks of a front end. + +use std::cell::{Cell, RefCell}; +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::Arc; + +use voelin_core::gateway::Pin; +use voelin_core::stream::StreamInfo; +use voelin_core::{ + AudioSettings, BackendInfo, Command, Event, GatewayRequest, GatewayUpdate, HistoryMessage, + HistorySource, JoinFailure, ObserveState, SessionState, Source, TransferState, VoiceState, +}; +use voelin_gateway_proto::{UserRef, feature}; +use voelin_model::{ + Capabilities, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerDetails, +}; +use voelin_store::{Bookmark, ChatRead, ChatTarget as StoredTarget, MessageSource}; + +use super::*; +use crate::bridge::ChatLine; +use crate::host::Refresh; +use crate::settings::{ClientPlayback, ClientPlaybackMap, LastVoice, UiSettings}; + +type State = AppState>; + +/// The front end of the tests: answers what the transitions ask and keeps +/// what they store. +#[derive(Default)] +struct Fake { + demo: bool, + shown: Cell, + watching: bool, + autowatch: bool, + limit: u64, + /// What the store has: server unique id, its chats' reads. + reads: HashMap>, + /// What was stored. + written: RefCell>, +} + +impl Host for Fake { + fn demo_ui(&self) -> bool { + self.demo + } + + fn chat_shown(&self) -> bool { + self.shown.get() + } + + fn watching(&self) -> bool { + self.watching + } + + fn autowatch(&self) -> bool { + self.autowatch + } + + fn preview_limit(&self) -> u64 { + self.limit + } + + fn fetch_images(&self) -> bool { + false + } + + fn chat_reads(&self, server_uid: &str) -> Result, String> { + Ok(self.reads.get(server_uid).cloned().unwrap_or_default()) + } + + fn set_chat_read( + &self, + server_uid: &str, + target: &StoredTarget, + read: &ChatRead, + ) -> Result<(), String> { + self.written.borrow_mut().push((server_uid.to_owned(), target.clone(), *read)); + Ok(()) + } +} + +fn state() -> State { + let bookmark = Bookmark { + id: 1, + name: "ts.example".into(), + address: "ts.example".into(), + nickname: "Me".into(), + ..Default::default() + }; + AppState::new( + vec![bookmark], + UiSettings::default(), + AudioSettings::default(), + ClientPlaybackMap::new(), + ) +} + +fn session(voice: VoiceState, own_channel: Option) -> SessionState { + let connected = voice == VoiceState::Connected; + SessionState { + voice, + observe: ObserveState::Off, + presence_source: connected.then_some(Source::Voice), + own_channel, + own_client: connected.then_some(10), + server_uid: connected.then(|| "srv=".to_owned()), + ..Default::default() + } +} + +/// Lobby (1) and Games (2), with Me (10, in Games) and Alice (11, in +/// Games). +fn presence() -> Arc { + let mut p = Presence { server_name: "Nightfall Guild".into(), ..Default::default() }; + for (id, order, name) in [(1, 0, "Lobby"), (2, 1, "Games")] { + p.channels.insert(id, ChannelInfo { id, order, name: name.into(), ..Default::default() }); + } + for (id, name, uid) in [(10, "Me", "me="), (11, "Alice", "alice=")] { + p.clients.insert( + id, + ClientInfo { + id, + channel: 2, + nickname: name.into(), + uid: Some(uid.into()), + ..Default::default() + }, + ); + } + p.server = ServerDetails { welcome_message: "Welcome".into(), ..Default::default() }; + Arc::new(p) +} + +/// A message of Games, by Alice unless `mine`. +fn said(id: i64, ts_ms: i64, mine: bool, text: &str) -> HistoryMessage { + HistoryMessage { + id, + message: ChatMessage { + target: ChatTarget::Channel(2), + author_name: if mine { "Me" } else { "Alice" }.into(), + author_uid: Some(if mine { "me=" } else { "alice=" }.into()), + author_id: Some(if mine { 10 } else { 11 }), + text: text.into(), + ts_ms, + via_relay: false, + blocked: false, + }, + source: MessageSource::Voice, + remote_id: Some(id + 1000), + topic_id: None, + reactions: Vec::new(), + pinned: false, + rev: 0, + } +} + +fn games(messages: Vec, source: HistorySource) -> Event { + Event::ChatHistory { + session: 1, + target: ChatTarget::Channel(2), + messages, + source, + complete: true, + } +} + +fn run(state: &mut State, host: &Fake, tape: Vec) -> Vec { + tape.into_iter().map(|event| apply(state, host, event)).collect() +} + +fn gateway(update: GatewayUpdate) -> Event { + Event::Gateway { session: 1, update } +} + +fn open_chats(update: &Update) -> Vec { + update + .commands + .iter() + .filter_map(|c| match c { + Command::OpenChat { target, .. } => Some(target.clone()), + _ => None, + }) + .collect() +} + +/// A first connection to a server, event by event: what the session knows +/// after each, and what the front end is told to do. +#[test] +fn a_first_connection() { + let mut st = state(); + let host = Fake { + reads: HashMap::from([( + "srv=".to_owned(), + vec![(StoredTarget::Channel(2), ChatRead { ts_ms: 200, id: 7, updated_ms: 1 })], + )]), + ..Default::default() + }; + let backend = BackendInfo { product: "TeamSpeak 6".into(), version: "6.0.0".into() }; + let caps = Capabilities { streams: true, file_transfer: true, ..Default::default() }; + + // Connecting: the rail and the bar change, nothing is sent. + let ups = run( + &mut st, + &host, + vec![Event::State { session: 1, state: session(VoiceState::Connecting, None) }], + ); + assert_eq!(st.sessions[&1].state.voice, VoiceState::Connecting); + assert!(ups[0].refresh.servers && ups[0].refresh.toolbar && ups[0].refresh.tree); + assert!(ups[0].commands.is_empty() && ups[0].status.is_none() && ups[0].autoshare); + + // The server answers: it gives its name to a bookmark that has only the + // address, and says what it runs. + let ups = run( + &mut st, + &host, + vec![Event::ServerInfo { + session: 1, + name: " Nightfall Guild ".into(), + backend, + capabilities: caps, + }], + ); + assert_eq!(st.bookmarks[0].name, "Nightfall Guild"); + assert_eq!(ups[0].persist, [Persist::Bookmark { id: 1, what: "server named" }]); + assert_eq!( + ups[0].status.as_deref(), + Some("Connected to Nightfall Guild (TeamSpeak 6 6.0.0)") + ); + assert_eq!(st.status, "Connected to Nightfall Guild (TeamSpeak 6 6.0.0)"); + assert!(st.sessions[&1].capabilities.streams && ups[0].refresh.streams); + + // Its presence: the bar, the tree and the chat are drawn; the stored + // volume of Alice is sent once voice is connected, not before. + st.playback.insert("alice=".into(), ClientPlayback { volume: 0.5, muted: true }); + let ups = run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]); + assert_eq!(st.sessions[&1].presence.clients.len(), 2); + assert!(ups[0].refresh.tree && ups[0].refresh.chat && ups[0].first_client); + assert!(ups[0].commands.is_empty()); + + // Voice connected into Games: its chat opens and is shown, with the + // store's read marker; the place is remembered. + let ups = run( + &mut st, + &host, + vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }], + ); + let view = &st.sessions[&1]; + assert_eq!(view.reads_of.as_deref(), Some("srv=")); + assert_eq!(view.tabs[view.current_tab].target, ChatTarget::Channel(2)); + assert_eq!(view.tabs[view.current_tab].read, Some((200, 7))); + assert_eq!(view.channel_tab, ChatTarget::Channel(2)); + assert!(view.focused_own_channel); + assert_eq!(open_chats(&ups[0]), [ChatTarget::Channel(2)]); + assert_eq!(ups[0].status.as_deref(), Some("Connected")); + assert_eq!( + st.settings.last_voice, + Some(LastVoice { + bookmark: 1, + address: "ts.example".into(), + channel: vec!["Games".into()] + }) + ); + assert!(ups[0].persist.contains(&Persist::Settings)); + assert!(ups[0].refresh.chat && ups[0].refresh.servers); + + // The presence again, now that voice is connected: Alice's volume goes + // to the engine, once. + let ups = run( + &mut st, + &host, + vec![ + Event::Presence { session: 1, presence: presence() }, + Event::Presence { session: 1, presence: presence() }, + ], + ); + assert!(matches!( + ups[0].commands.as_slice(), + [ + Command::SetClientVolume { session: 1, client: 11, volume }, + Command::SetClientMuted { session: 1, client: 11, muted: true }, + ] if *volume == 0.5 + )); + assert!(ups[1].commands.is_empty()); +} + +/// The messages of a chat: a stored page, then live ones, with the chat on +/// screen or not, and what is kept of how far it was read. +#[test] +fn messages_are_counted_read_and_kept() { + let mut st = state(); + let host = Fake::default(); + run( + &mut st, + &host, + vec![ + Event::Presence { session: 1, presence: presence() }, + Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }, + ], + ); + // The stored page: two read before, one new. (Its marker came from the + // store: nothing here, so what the tab held when the page came counts as + // read.) + let ups = run( + &mut st, + &host, + vec![games( + vec![said(6, 190, false, "hi"), said(7, 200, true, "hello"), said(8, 300, false, "x")], + HistorySource::Local, + )], + ); + let tab = &st.sessions[&1].tabs[1]; + assert_eq!(tab.messages.iter().map(|m| m.message.id).collect::>(), [6, 7, 8]); + assert!(tab.complete && !tab.loading); + assert_eq!(tab.unread, 0, "a first page is what was read"); + assert_eq!(ups[0].chats, [(1, ChatTarget::Channel(2))]); + assert!(ups[0].refresh.chat); + + // A live message while the chat is not on screen is new. + let ups = + run(&mut st, &host, vec![games(vec![said(9, 400, false, "new")], HistorySource::Live)]); + assert_eq!(st.sessions[&1].tabs[1].unread, 1); + assert!(ups[0].refresh.servers, "the rail counts it"); + // Our own is not. + st.own_uids.insert("me=".into()); + run(&mut st, &host, vec![games(vec![said(10, 410, true, "mine")], HistorySource::Live)]); + assert_eq!(st.sessions[&1].tabs[1].unread, 1); + + // The chat comes on screen: read up to its end, a divider over the new. + host.shown.set(true); + let mut cx = Cx::new(&host); + assert!(crate::chat::logic::track_reading(&mut st, &mut cx)); + let tab = &st.sessions[&1].tabs[1]; + assert_eq!((tab.unread, tab.divider, tab.read), (0, Some(9), Some((410, 10)))); + assert_eq!(st.reading, Some((1, ChatTarget::Channel(2)))); + // A live one now is read at once. + run(&mut st, &host, vec![games(vec![said(11, 500, false, "seen")], HistorySource::Live)]); + assert_eq!(st.sessions[&1].tabs[1].unread, 0); + assert_eq!(st.sessions[&1].tabs[1].read, Some((500, 11))); + + // The session ends: where the chats were read is stored, and what the + // store has is what the tab then says it has. + let mut ended = session(VoiceState::Disconnected, None); + ended.server_uid = Some("srv=".into()); + let ups = run(&mut st, &host, vec![Event::State { session: 1, state: ended }]); + let written = host.written.borrow(); + assert_eq!(written.len(), 1, "{written:?}"); + assert_eq!(written[0].0, "srv="); + assert_eq!(written[0].1, StoredTarget::Channel(2)); + assert_eq!((written[0].2.ts_ms, written[0].2.id), (500, 11)); + assert_eq!(st.sessions[&1].tabs[1].stored_read, Some((500, 11))); + assert!(ups[0].refresh.servers); +} + +/// Where the chat lines go when the engine keeps no history (it does not +/// know the server yet): one row appended per message. +#[test] +fn a_session_without_history_appends_lines() { + let mut st = state(); + let host = Fake::default(); + let message = |text: &str| ChatMessage { + target: ChatTarget::Server, + author_name: "Alice".into(), + author_uid: Some("alice=".into()), + author_id: Some(11), + text: text.into(), + ts_ms: 1000, + via_relay: false, + blocked: false, + }; + let ups = run( + &mut st, + &host, + vec![ + Event::Chat { session: 1, message: message("one") }, + Event::Chat { session: 1, message: message("two") }, + ], + ); + let tab = &st.sessions[&1].tabs[0]; + assert_eq!(tab.lines.len(), 2); + assert_eq!(tab.unread, 2); + assert_eq!(ups[1].chats, [(1, ChatTarget::Server)]); + assert!(ups[1].refresh.chat && ups[1].refresh.servers); + // With a server unique id the engine has the history, and the live + // message arrives as `ChatHistory`. + st.sessions.get_mut(&1).unwrap().state.server_uid = Some("srv=".into()); + run(&mut st, &host, vec![Event::Chat { session: 1, message: message("three") }]); + assert_eq!(st.sessions[&1].tabs[0].lines.len(), 2); +} + +/// What a gateway brings: capabilities, requests for what the screens +/// show, pins, the stream directory, reminders for the bell. +#[test] +fn a_gateway_connects_and_tells() { + let mut st = state(); + let host = Fake::default(); + run( + &mut st, + &host, + vec![ + Event::Presence { session: 1, presence: presence() }, + Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }, + ], + ); + let caps: Vec = [feature::EVENTS, feature::PINS, feature::TOPICS, feature::STREAMS] + .map(String::from) + .into(); + st.bookmarks[0].gateway_urls = vec!["wss://gw.example/v1".into()]; + let ups = run( + &mut st, + &host, + vec![gateway(GatewayUpdate::Connected { + url: "wss://gw.example/v1".into(), + gateway_id: "g".into(), + server_uid: "srv=".into(), + server_name: "Nightfall Guild".into(), + uid: "me=".into(), + capabilities: caps, + })], + ); + let view = &st.sessions[&1]; + assert!(view.gateway_has(feature::PINS) && view.gateway_has(feature::EVENTS)); + assert_eq!(view.extra.gateway_uid.as_deref(), Some("me=")); + assert_eq!( + st.bookmarks[0].gateway_url.as_deref(), + Some("wss://gw.example/v1"), + "the gateway in use is kept" + ); + assert!(ups[0].persist.contains(&Persist::Bookmark { id: 1, what: "gateway in use" })); + // The permissions, the events and the directory, then the current + // chat's pins and topics. + let asked: Vec<&GatewayRequest> = ups[0] + .commands + .iter() + .filter_map(|c| match c { + Command::Gateway { session: 1, request } => Some(request), + _ => None, + }) + .collect(); + assert!(matches!( + asked.as_slice(), + [ + GatewayRequest::Permissions { channel: None }, + GatewayRequest::Events { .. }, + GatewayRequest::Streams, + GatewayRequest::Pins { target: ChatTarget::Channel(2) }, + GatewayRequest::Topics { target: ChatTarget::Channel(2), .. }, + ] + )); + assert!(ups[0].refresh.home && ups[0].refresh.events && ups[0].refresh.gateways); + + // The answers: pins (newest first), the directory's viewer counts, a + // failed request of the user. + let pin = |id: i64, ts_ms: i64| Pin { + message: said(id, ts_ms, false, "pinned"), + by: UserRef { uid: "alice=".into(), name: "Alice".into() }, + ts_ms, + }; + let ups = run( + &mut st, + &host, + vec![ + gateway(GatewayUpdate::Pins { + target: ChatTarget::Channel(2), + pins: vec![pin(3, 10), pin(4, 20)], + }), + gateway(GatewayUpdate::Failed { + request: "pin".into(), + code: Some(voelin_gateway_proto::ErrorCode::Forbidden), + message: "no".into(), + }), + ], + ); + let tab = &st.sessions[&1].tabs[1]; + assert!(tab.pins_loaded); + assert_eq!(tab.pins.iter().map(|p| p.message.id).collect::>(), [4, 3]); + assert!(ups[0].refresh.chat); + assert_eq!(ups[1].status.as_deref(), Some("Not allowed on this server.")); + + // Gone: nothing of the gateway stays. + run(&mut st, &host, vec![gateway(GatewayUpdate::Disconnected { reason: None })]); + let view = &st.sessions[&1]; + assert!(view.gateway_caps.is_empty() && !view.tabs[1].pins_loaded); +} + +/// A password that was refused asks again, and says so the second time. +#[test] +fn a_locked_channel_asks_for_its_password() { + let mut st = state(); + let host = Fake::default(); + run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]); + let failed = || Event::JoinFailed { session: 1, channel: 1, reason: JoinFailure::Password }; + let ups = run(&mut st, &host, vec![failed()]); + let prompt = ups[0].password.clone().unwrap(); + assert_eq!((prompt.name.as_str(), prompt.wrong), ("Lobby", false)); + assert_eq!(st.join_target, Some((1, 1))); + // A password was given and refused: it is forgotten, the prompt says so. + st.sessions.get_mut(&1).unwrap().channel_passwords.insert(1, "nope".into()); + let ups = run(&mut st, &host, vec![failed()]); + assert!(ups[0].password.as_ref().unwrap().wrong); + assert!(st.sessions[&1].channel_passwords.is_empty()); + // The others are a toast. + let ups = run( + &mut st, + &host, + vec![Event::JoinFailed { session: 1, channel: 1, reason: JoinFailure::Full }], + ); + assert_eq!(ups[0].status.as_deref(), Some("The channel is full")); +} + +/// Connected into another channel than the one asked for: joined again, +/// with the password given this connection. +#[test] +fn a_channel_asked_for_and_not_entered_is_joined_again() { + let mut st = state(); + let host = Fake::default(); + run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]); + let view = st.sessions.get_mut(&1).unwrap(); + view.join_after_connect = Some(1); + view.channel_passwords.insert(1, "pw".into()); + // Connected into Games, not the Lobby that was asked for. + let ups = run( + &mut st, + &host, + vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }], + ); + assert!(ups[0].commands.iter().any(|c| matches!( + c, + Command::MoveToChannel { session: 1, channel: 1, password: Some(p) } if p == "pw" + ))); + assert_eq!(st.sessions[&1].join_after_connect, None); + // The sample sessions send nothing to the engine. + let mut demo = state(); + let host = Fake { demo: true, ..Default::default() }; + run(&mut demo, &host, vec![Event::Presence { session: 1, presence: presence() }]); + demo.sessions.get_mut(&1).unwrap().join_after_connect = Some(1); + let ups = run( + &mut demo, + &host, + vec![Event::State { session: 1, state: session(VoiceState::Connected, Some(2)) }], + ); + assert!(open_chats(&ups[0]).is_empty()); + assert!(!ups[0].commands.iter().any(|c| matches!(c, Command::MoveToChannel { .. }))); +} + +/// Pictures and files: the engine's cache, an upload from the composer, a +/// download that runs, the contacts, errors. +#[test] +fn pictures_files_contacts_and_errors() { + let mut st = state(); + let host = Fake::default(); + run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]); + let path = PathBuf::from("/cache/avatars/ab"); + let ups = run( + &mut st, + &host, + vec![ + Event::AvatarReady { + session: 1, + client_uid: "alice=".into(), + path: path.clone(), + hash: "ab".into(), + }, + Event::IconReady { session: 1, icon: 5, path: "/cache/icons/5".into() }, + Event::PictureReady { + session: 1, + url: "https://e.com/a.png".into(), + path: "/cache/pictures/a".into(), + }, + ], + ); + let view = &st.sessions[&1]; + assert_eq!(view.avatars.get("alice="), Some(&path)); + assert!(view.icons.contains_key(&5) && view.pictures.contains_key("https://e.com/a.png")); + assert_eq!(ups[0].reloaded, [path]); + assert_eq!( + ups[0].refresh, + Refresh { + tree: true, + chat: true, + toolbar: true, + member_card: true, + streams: true, + ..Refresh::default() + } + ); + assert!(ups[1].refresh.servers && ups[1].refresh.tree && !ups[1].refresh.chat); + + // An upload from the composer posts its link once it is up. + st.uploads.insert(7, (1, 2, "notes.txt".into())); + let done = TransferState::Done { size: 12, data: None, path: None }; + let ups = run(&mut st, &host, vec![Event::Transfer { session: 1, transfer: 7, state: done }]); + assert!(st.uploads.is_empty()); + assert_eq!(ups[0].status.as_deref(), Some("notes.txt shared")); + assert!(matches!( + ups[0].commands.as_slice(), + [Command::SendChat { session: 1, target: ChatTarget::Channel(2), text }] if text.contains("notes.txt") + )); + st.uploads.insert(8, (1, 2, "big.iso".into())); + let failed = TransferState::Failed("full".into()); + let ups = run(&mut st, &host, vec![Event::Transfer { session: 1, transfer: 8, state: failed }]); + assert_eq!(ups[0].status.as_deref(), Some("Could not upload big.iso: full")); + + // Errors and rejected settings reach the status line, but not the sample + // sessions' (the engine does not know them). + let ups = run( + &mut st, + &host, + vec![ + Event::Error { session: 1, message: "kicked".into() }, + Event::SettingRejected { key: "audio".into(), message: "no".into() }, + Event::MicrophoneTestError { message: "no device".into() }, + ], + ); + assert_eq!(ups[0].status.as_deref(), Some("kicked")); + assert_eq!(ups[1].status.as_deref(), Some("Setting audio: no")); + assert_eq!(st.status, "Microphone test: no device"); + let demo = Fake { demo: true, ..Default::default() }; + let ups = run(&mut st, &demo, vec![Event::Error { session: 1, message: "kicked".into() }]); + assert!(ups[0].status.is_none()); +} + +/// A client that talks, the meter, the groups in the order TeamSpeak sorts +/// them. +#[test] +fn talking_the_meter_and_groups() { + let mut st = state(); + let host = Fake::default(); + run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]); + let ups = run( + &mut st, + &host, + vec![ + Event::Talking { session: 1, client: 11, talking: true }, + Event::Talking { session: 1, client: 11, talking: false }, + Event::InputLevel { session: Some(1), level_db: -20.0, sending: true }, + Event::InputLevel { session: None, level_db: -30.0, sending: false }, + Event::InputLevel { session: Some(2), level_db: -10.0, sending: true }, + ], + ); + assert!(st.sessions[&1].talking.is_empty()); + assert!(ups[0].refresh.tree); + assert_eq!(ups[2].input_level, Some((-20.0, true))); + assert_eq!(ups[3].input_level, None, "no microphone test is running"); + assert_eq!(ups[4].input_level, None, "another server's"); + st.mic_test = true; + let ups = run( + &mut st, + &host, + vec![Event::InputLevel { session: None, level_db: -30.0, sending: false }], + ); + assert_eq!(ups[0].input_level, Some((-30.0, false))); + + let group = |id, sort_id| voelin_model::GroupInfo { id, sort_id, ..Default::default() }; + run( + &mut st, + &host, + vec![Event::Groups { + session: 1, + server_groups: Arc::new(vec![group(7, 20), group(6, 20), group(9, 10)]), + channel_groups: Arc::new(vec![group(5, 0)]), + }], + ); + let ids: Vec<_> = st.sessions[&1].server_groups.iter().map(|g| g.id).collect(); + assert_eq!(ids, [9, 6, 7]); +} + +/// The streams the voice connection lists: the one a lookup waited for is +/// to be watched; the rest of the stream events are the front end's. +#[test] +fn streams_are_listed_and_the_rest_is_handed_back() { + let mut st = state(); + let host = Fake::default(); + run(&mut st, &host, vec![Event::Presence { session: 1, presence: presence() }]); + let stream = |id: &str, streamer| StreamInfo { + id: id.into(), + streamer, + name: "screen".into(), + kind: voelin_core::stream::StreamKind::Screen, + bitrate: 0, + viewer_limit: 0, + audio: false, + viewers: Some(1), + }; + let ups = run( + &mut st, + &host, + vec![Event::StreamsChanged { session: 1, streams: vec![stream("s1", 11)] }], + ); + assert_eq!(st.sessions[&1].streams.len(), 1); + assert!(ups[0].refresh.streams && ups[0].refresh.servers && ups[0].watch.is_none()); + // A client's stream was asked for before the list knew it. + st.pending_watch = Some((1, 11)); + let ups = run( + &mut st, + &host, + vec![Event::StreamsChanged { session: 1, streams: vec![stream("s2", 11)] }], + ); + assert_eq!(ups[0].watch.as_deref(), Some("s2")); + assert_eq!(st.pending_watch, None); + // The development switch watches the first stream that is not ours. + let host = Fake { autowatch: true, ..Default::default() }; + let ups = run( + &mut st, + &host, + vec![Event::StreamsChanged { session: 1, streams: vec![stream("s3", 11)] }], + ); + assert_eq!(ups[0].watch.as_deref(), Some("s3")); + // What watching and sharing make of the other stream events is the front + // end's (and so is a setting that changed). + let ups = run( + &mut st, + &host, + vec![ + Event::StreamKeyframeRequest { session: 1, layer: 0 }, + Event::SettingChanged { key: "audio".into() }, + ], + ); + assert!(matches!(ups[0].rest, Some(Event::StreamKeyframeRequest { .. }))); + assert!(matches!(&ups[1].rest, Some(Event::SettingChanged { key }) if key == "audio")); + assert!(ups[0].refresh.is_empty() && ups[0].commands.is_empty()); +} + +/// Pictures linked in a chat are downloaded once, up to the limit. +#[test] +fn linked_pictures_are_fetched_once() { + let mut st = state(); + let host = Fake { limit: 100 * 1024, ..Default::default() }; + let mut connected = session(VoiceState::Connected, Some(2)); + connected.server_uid = Some("srv=".into()); + run( + &mut st, + &host, + vec![ + Event::ServerInfo { + session: 1, + name: "S".into(), + backend: BackendInfo::default(), + capabilities: Capabilities { file_transfer: true, ..Default::default() }, + }, + Event::Presence { session: 1, presence: presence() }, + Event::State { session: 1, state: connected }, + ], + ); + let link = "[URL=ts3file://ts.example?port=9987&channel=2&path=%2F&channelpassword=&filename=a.png&isDir=0&size=2048&fileSize=2048]a.png[/URL]"; + let ups = + run(&mut st, &host, vec![games(vec![said(1, 100, false, link)], HistorySource::Live)]); + let downloads: Vec<_> = + ups[0].commands.iter().filter(|c| matches!(c, Command::DownloadChatFile { .. })).collect(); + assert_eq!(downloads.len(), 1, "{:?}", ups[0].commands); + // Asked once: the same page again asks for nothing. + let ups = + run(&mut st, &host, vec![games(vec![said(1, 100, false, link)], HistorySource::Live)]); + assert!(!ups[0].commands.iter().any(|c| matches!(c, Command::DownloadChatFile { .. }))); +} + +#[test] +fn the_status_line_names_the_servers_software() { + let backend = |product: &str, version: &str| BackendInfo { + product: product.into(), + version: version.into(), + }; + assert_eq!( + connected_status("Nightfall Guild", &backend("TeamSpeak 6", "6.0.0-beta13.1")), + "Connected to Nightfall Guild (TeamSpeak 6 6.0.0-beta13.1)" + ); + assert_eq!( + connected_status("Pixel Lounge", &backend("TeamSpeak 3", "3.13.8")), + "Connected to Pixel Lounge (TeamSpeak 3 3.13.8)" + ); + // Not recognised: the version string the server sent. + assert_eq!(connected_status("Home", &backend("", "custom 9")), "Connected to Home (custom 9)"); +} + +#[test] +fn a_server_icon_is_taken_from_the_bookmarks_own_address_only() { + let path = std::env::temp_dir() + .join(format!("voelin-server-icon-provenance-{}.svg", std::process::id())); + std::fs::write( + &path, + r#""#, + ) + .unwrap(); + let mut bookmark = Bookmark { address: "a.test".into(), ..Default::default() }; + let mut view = SessionView::<()>::default(); + view.icons.insert(1234, path.clone()); + assert!(apply_server_icon(&mut bookmark, &mut view, "a.test", 1234)); + assert_eq!(view.server_icon_for(&bookmark.address).size().width, 4); + // Details from another address, queued before an edit, change nothing. + assert!(!apply_server_icon(&mut bookmark, &mut view, "b.test", 77)); + assert_eq!(view.server_icon, 1234); + std::fs::remove_file(path).unwrap(); +} diff --git a/crates/voelin-ui-vm/src/host.rs b/crates/voelin-ui-vm/src/host.rs new file mode 100644 index 0000000..1b19ceb --- /dev/null +++ b/crates/voelin-ui-vm/src/host.rs @@ -0,0 +1,221 @@ +//! What the transitions of the client's state need from the front end and +//! tell it. A transition (`events::apply`, the functions of `chat::logic`) +//! changes the [`AppState`](crate::state::AppState) it is given and puts +//! everything else into an [`Update`]: what to redraw, the status line, the +//! engine commands to send, what to keep; the little it must ask a front end +//! for while it runs (is the chat on screen, what the store knows) goes +//! through [`Host`]. Neither the engine nor the store nor a toolkit is +//! touched here, so the transitions are tested with a fake host +//! (`events::tests`). + +use std::path::PathBuf; + +use voelin_core::{Command, Event, GatewayRequest}; +use voelin_model::ChatTarget; +use voelin_store::{ChatRead, ChatTarget as StoredTarget}; + +use crate::social::NoticeRequest; + +/// What a transition asks of its front end while it runs. +pub trait Host { + /// The sample data of `VOELIN_DEMO_UI` is shown: nothing is sent to the + /// engine or kept in the store. + fn demo_ui(&self) -> bool; + + /// The current chat's messages are on screen (a page shows the chat). + fn chat_shown(&self) -> bool; + + /// A stream is in the viewer. + fn watching(&self) -> bool; + + /// The development switch `VOELIN_AUTOWATCH=1`: watch the first stream + /// that shows up. + fn autowatch(&self) -> bool; + + /// The largest picture previewed in chats, in bytes (0: none), from + /// `ui.image_preview_kb`. + fn preview_limit(&self) -> u64; + + /// Pictures on the web are fetched and shown (`cache.fetch_images`). + fn fetch_images(&self) -> bool; + + /// How far the chats of a server were read, from the store. + fn chat_reads(&self, server_uid: &str) -> Result, String>; + + /// Keep how far a chat of a server was read. + fn set_chat_read( + &self, + server_uid: &str, + target: &StoredTarget, + read: &ChatRead, + ) -> Result<(), String>; +} + +/// The parts of the screen to draw again. Each is a function of the state, +/// so a front end draws each flagged part once, however many events set it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Refresh { + /// The server rail. + pub servers: bool, + /// The top bar of the server page. + pub toolbar: bool, + /// The channel tree and the members. + pub tree: bool, + /// The chat tabs, the lines and what belongs to them (pins, topics). + pub chat: bool, + /// The streams panel and the voice card's streams. + pub streams: bool, + /// The stream viewer's header. + pub viewer: bool, + /// The open member card. + pub member_card: bool, + /// The home page. + pub home: bool, + /// The events page. + pub events: bool, + /// The gateway pages of the settings. + pub gateways: bool, +} + +impl Refresh { + /// Every part. + pub const ALL: Self = Self { + servers: true, + toolbar: true, + tree: true, + chat: true, + streams: true, + viewer: true, + member_card: true, + home: true, + events: true, + gateways: true, + }; + + /// Whether nothing is to be drawn. + pub fn is_empty(&self) -> bool { + *self == Self::default() + } +} + +/// What a transition wants kept. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Persist { + /// The bookmark with this id changed (the store has the old one). + Bookmark { + /// The bookmark. + id: i64, + /// What it was changed for, for the log. + what: &'static str, + }, + /// The UI's own settings changed (`AppState::settings`). + Settings, +} + +/// The password dialog of a locked channel is to open +/// (`AppState::join_target` names the channel). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PasswordPrompt { + /// The channel's name as the tree shows it. + pub name: String, + /// The password given before was refused. + pub wrong: bool, +} + +/// What a transition tells its front end, besides the changed state. +#[derive(Debug, Default)] +pub struct Update { + /// What to draw again. + pub refresh: Refresh, + /// The status line's new text. + pub status: Option, + /// Commands for the engine, in order. + pub commands: Vec, + /// What to keep, in order. + pub persist: Vec, + /// Pictures the engine wrote again: a front end drops what it decoded + /// of them. + pub reloaded: Vec, + /// The microphone meter: level in dBFS, and whether voice is sent. + pub input_level: Option<(f32, bool)>, + /// Open the password dialog. + pub password: Option, + /// Notices for the bell, in order. + pub notices: Vec, + /// What went wrong that nothing else shows, for the log. + pub warnings: Vec, + /// Chats whose messages changed (session, chat): the Stream Studio + /// follows the chat of its channel. + pub chats: Vec<(i64, ChatTarget)>, + /// A stream to watch (its id): the one a lookup was waiting for, or the + /// development switch's. + pub watch: Option, + /// A server connected or answered: the development switch that shares + /// the test pattern may start now. + pub autoshare: bool, + /// The session on screen got its state or its presence: the development + /// switch that opens the volume dialog of the first client may act. + pub first_client: bool, + /// The event, when it is not (only) a matter of this state: a stream we + /// watch or share, the settings service. The front end handles those + /// itself ([`crate::events`] lists them). + pub rest: Option, +} + +/// The host and the update of a transition in progress. +pub struct Cx<'a> { + /// What the front end answers. + pub host: &'a dyn Host, + /// What is collected. + pub update: Update, +} + +impl<'a> Cx<'a> { + /// A transition that starts with nothing to tell. + pub fn new(host: &'a dyn Host) -> Self { + Self { host, update: Update::default() } + } + + /// The status line says this from now on. + pub fn status(&mut self, text: impl Into) { + self.update.status = Some(text.into()); + } + + /// A command for the engine. + pub fn send(&mut self, command: Command) { + self.update.commands.push(command); + } + + /// A command for the engine, but not for the sample sessions of + /// `VOELIN_DEMO_UI`: the engine would open them for real. + pub fn send_real(&mut self, command: Command) { + if !self.host.demo_ui() { + self.send(command); + } + } + + /// A request to a session's gateway (not for the sample sessions). + pub fn gateway_to(&mut self, session: i64, request: GatewayRequest) { + self.send_real(Command::Gateway { session: session as u64, request }); + } + + /// Something went wrong that nothing else shows: it is logged. + pub fn warn(&mut self, text: impl Into) { + self.update.warnings.push(text.into()); + } + + /// Keep this. + pub fn persist(&mut self, what: Persist) { + self.update.persist.push(what); + } + + /// The password dialog of a locked channel opens. + pub fn ask_password(&mut self, channel_name: String, wrong: bool) { + self.update.password = Some(PasswordPrompt { name: channel_name, wrong }); + } + + /// The chat `target` of session `id` changed. + pub fn chat_changed(&mut self, id: i64, target: &ChatTarget) { + self.update.chats.push((id, target.clone())); + } +} diff --git a/crates/voelin-ui-vm/src/lib.rs b/crates/voelin-ui-vm/src/lib.rs index dbf6aff..7ba361a 100644 --- a/crates/voelin-ui-vm/src/lib.rs +++ b/crates/voelin-ui-vm/src/lib.rs @@ -16,9 +16,12 @@ pub mod bridge; pub mod chat; pub mod color; pub mod emoji; +pub mod events; pub mod home; +pub mod host; pub mod image; pub mod list; +pub mod previews; pub mod servers; pub mod settings; pub mod settings_pages; diff --git a/crates/voelin-ui-vm/src/previews.rs b/crates/voelin-ui-vm/src/previews.rs new file mode 100644 index 0000000..406dc92 --- /dev/null +++ b/crates/voelin-ui-vm/src/previews.rs @@ -0,0 +1,172 @@ +//! Pictures linked in chat, shown inline: a link to a PNG, JPEG, GIF or +//! WebP file (by name) up to `ui.image_preview_kb` is downloaded into +//! memory once (`Command::DownloadChatFile` with `DownloadTo::Memory`, +//! voice connections only) and the chat shows it as a picture card, and a +//! click opens it larger. A picture on the web a message shows (`[img]`) +//! comes the way banners do, into the engine's cache (`Command::FetchPicture`, +//! up to the same size, only with `cache.fetch_images`), and until it is +//! there the message shows its address. + +use std::sync::Arc; + +use voelin_core::{Command, DownloadTo, TransferState, VoiceState}; +use voelin_model::{ChatTarget, FileRef}; + +use crate::host::Cx; +use crate::image::{ImageRef, ImageSource}; +use crate::state::{AppState, Preview, SessionView}; + +/// Whether a file name is a picture the chat shows inline. +pub fn is_previewable(name: &str) -> bool { + let lower = name.to_ascii_lowercase(); + [".png", ".jpg", ".jpeg", ".gif", ".webp"].iter().any(|e| lower.ends_with(e)) +} + +/// The key of a link: where the file is. +pub fn link_key(file: &FileRef) -> String { + format!( + "{}/{}{}{}", + file.server_uid.as_deref().unwrap_or(""), + file.channel, + file.path, + file.name + ) +} + +/// The picture of a link, if it is there and shows. +pub fn image_of(view: &SessionView, file: &FileRef) -> Option { + let key = link_key(file); + match view.extra.previews.get(&key)? { + Preview::Ready(bytes) => { + let image = Arc::new(ImageSource::Memory { key: key.into(), bytes: bytes.0.clone() }); + (!image.is_empty()).then_some(image) + } + _ => None, + } +} + +/// Download the pictures linked in the current chat of `session` that are +/// not there yet. +pub fn fetch_previews(state: &mut AppState, cx: &mut Cx<'_>, session: i64) { + if cx.host.demo_ui() { + return; + } + let limit = cx.host.preview_limit(); + if limit == 0 { + return; + } + fetch_web_pictures(state, cx, session, limit); + let Some(view) = state.sessions.get_mut(&session) else { return }; + if view.state.voice != VoiceState::Connected || !view.capabilities.file_transfer { + return; + } + let Some(tab) = view.tabs.get(view.current_tab) else { return }; + // Channel chats only: a link names its channel's file browser. + if matches!(tab.target, ChatTarget::Private(_)) && tab.messages.is_empty() { + return; + } + let wanted: Vec = tab + .messages + .iter() + .rev() + .take(200) + .flat_map(|m| m.message.message.file_refs()) + .filter(|f| is_previewable(&f.name) && f.size.is_some_and(|s| s <= limit)) + .filter(|f| !view.extra.previews.contains_key(&link_key(f))) + .collect(); + for file in wanted { + let transfer = view.next_transfer; + view.next_transfer += 1; + view.extra.previews.insert(link_key(&file), Preview::Loading(transfer)); + cx.send(Command::DownloadChatFile { + session: session as u64, + transfer, + file, + password: None, + to: DownloadTo::Memory, + }); + } +} + +/// Ask the engine for the pictures on the web (`[img]`) of the current chat +/// of `session` that it has not reported; it fetches each once. +fn fetch_web_pictures(state: &AppState, cx: &mut Cx<'_>, session: i64, limit: u64) { + if !cx.host.fetch_images() { + return; + } + let Some(view) = state.sessions.get(&session) else { return }; + let Some(tab) = view.tabs.get(view.current_tab) else { return }; + // The server chat starts with the server's messages. + let server = match tab.target { + ChatTarget::Server => crate::chat::server_texts(&view.presence.server), + _ => Vec::new(), + }; + let wanted: Vec = tab + .messages + .iter() + .rev() + .take(200) + .map(|m| m.message.message.text.as_str()) + .chain(server.into_iter().map(|(text, _)| text)) + .flat_map(crate::chat::web_pictures) + .filter(|url| !view.pictures.contains_key(url)) + .collect(); + for url in wanted { + cx.send(Command::FetchPicture { session: session as u64, url, max_bytes: limit }); + } +} + +/// A transfer of a picture: `true` if it was one. +pub fn preview_progress( + state: &mut AppState, + cx: &mut Cx<'_>, + session: i64, + transfer: u64, + progress: &TransferState, +) -> bool { + let limit = cx.host.preview_limit(); + let current = state.current == Some(session); + let Some(view) = state.sessions.get_mut(&session) else { return false }; + let Some(key) = view + .extra + .previews + .iter() + .find(|(_, p)| matches!(p, Preview::Loading(t) if *t == transfer)) + .map(|(k, _)| k.clone()) + else { + return false; + }; + match progress { + TransferState::Started { size, .. } if *size > limit => { + view.extra.previews.insert(key, Preview::Failed); + cx.send_real(Command::CancelTransfer { session: session as u64, transfer }); + } + TransferState::Done { data: Some(data), .. } => { + view.extra.previews.insert(key, Preview::Ready(data.clone())); + if current { + cx.update.refresh.chat = true; + } + } + TransferState::Done { .. } | TransferState::Failed(_) | TransferState::Cancelled => { + view.extra.previews.insert(key, Preview::Failed); + } + _ => {} + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn previewable_names() { + assert!(is_previewable("Banner.PNG")); + assert!(is_previewable("a.webp")); + assert!(!is_previewable("notes.svg")); + assert!(!is_previewable("route.pdf")); + let file = + FileRef { channel: 2, path: "/".into(), name: "a.png".into(), ..Default::default() }; + assert_eq!(link_key(&file), "/2/a.png"); + } +} diff --git a/crates/voelin-ui-vm/src/social.rs b/crates/voelin-ui-vm/src/social.rs index 8321390..208bf27 100644 --- a/crates/voelin-ui-vm/src/social.rs +++ b/crates/voelin-ui-vm/src/social.rs @@ -3,9 +3,169 @@ //! `vm::bbcode`), mentions, event dates, a poke's message, the private //! chats of the home sidebar; pure, so they are tested here. +use std::collections::HashSet; + use chrono::{DateTime, Local, NaiveDateTime, TimeZone}; -use voelin_core::HistoryMessage; -use voelin_model::ChatTarget; +use voelin_core::{HistoryMessage, VoiceState}; +use voelin_model::{ChatMessage, ChatTarget}; + +use crate::state::AppState; + +/// What a notification of the bell is about. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NoticeKind { + /// Someone mentioned us. + Mention, + /// Someone poked us. + Poke, + /// A private message. + Message, + /// A scheduled event starts soon. + Event, + /// A friend came online. + Friend, +} + +impl NoticeKind { + /// The name the bell's rows carry. + pub fn name(self) -> &'static str { + match self { + Self::Mention => "mention", + Self::Poke => "poke", + Self::Message => "message", + Self::Event => "event", + Self::Friend => "friend", + } + } +} + +/// Where a notification leads. +#[derive(Clone, Debug, PartialEq)] +pub enum NoticeTarget { + /// A chat of a session. + Chat(i64, ChatTarget), + /// A private chat with someone, in a session. + Dm(i64, String), + /// An event of a session's gateway (session, event id). + Event(i64, i64), + /// A contact, by unique id. + Contact(String), +} + +/// A notification a transition asks for; the front end adds it to the bell +/// as the setting of its kind says. +#[derive(Clone, Debug, PartialEq)] +pub struct NoticeRequest { + /// What it is about. + pub kind: NoticeKind, + /// The headline. + pub title: String, + /// The line under it. + pub body: String, + /// Where it leads. + pub target: NoticeTarget, + /// Whose avatar it shows (initials from the name). + pub name: String, + /// Whose avatar picture it shows. + pub uid: Option, +} + +/// Whether a message is ours: by one of our unique ids, or by our client in +/// its session (`own_client`). +pub fn own_message( + own_uids: &HashSet, + own_client: Option, + message: &ChatMessage, +) -> bool { + message.author_uid.as_ref().is_some_and(|u| own_uids.contains(u)) + || (own_client.is_some() && message.author_id == own_client) +} + +/// Whether a message of a session is ours. +pub fn is_own(state: &AppState, session: i64, message: &ChatMessage) -> bool { + let own_client = state.sessions.get(&session).and_then(|v| v.state.own_client); + own_message(&state.own_uids, own_client, message) +} + +/// Where someone is in one session. +#[derive(Clone, Debug, PartialEq)] +pub struct Spot { + /// The session. + pub session: i64, + /// The server's name. + pub server: String, + /// The client's id there. + pub client: u16, + /// The channel it is in. + pub channel: u64, + /// The channel's name as shown (a spacer's text). + pub channel_title: String, + /// Its away message, if it is away. + pub away: Option, + /// It streams. + pub streaming: bool, + /// We are connected with voice there (messages, pokes, moving). + pub voice: bool, +} + +/// A server's name: its bookmark's, else what the session calls it. +pub fn server_name(state: &AppState, session: i64) -> String { + state.bookmarks.iter().find(|b| b.id == session).map(|b| b.name.clone()).unwrap_or_else(|| { + state.sessions.get(&session).map(|v| v.presence.server_name.clone()).unwrap_or_default() + }) +} + +/// Every session where the client with this unique id is, in bookmark +/// order. +pub fn spots_of(state: &AppState, uid: &str) -> Vec { + let mut ids: Vec = state.sessions.keys().copied().collect(); + ids.sort_by_key(|id| state.bookmarks.iter().position(|b| b.id == *id).unwrap_or(usize::MAX)); + let mut spots = Vec::new(); + for id in ids { + let view = &state.sessions[&id]; + let Some(c) = view.presence.clients.values().find(|c| c.uid.as_deref() == Some(uid)) else { + continue; + }; + let channel = view.presence.channels.get(&c.channel); + spots.push(Spot { + session: id, + server: server_name(state, id), + client: c.id, + channel: c.channel, + channel_title: channel + .map(|ch| crate::tree::channel_title(ch).0.to_owned()) + .unwrap_or_default(), + away: c.away.clone(), + streaming: c.streaming == Some(true), + voice: view.state.voice == VoiceState::Connected, + }); + } + spots +} + +/// What we call the peer of a private chat: its contact's nickname, the name +/// it has where it is now, the name on a message of theirs (`last`, or one in +/// any open chat), else the start of its unique id. +pub fn peer_name(state: &AppState, uid: &str, last: Option<&HistoryMessage>) -> String { + if let Some(c) = state.contacts.get(uid).filter(|c| !c.nickname.is_empty()) { + return c.nickname.clone(); + } + if let Some(s) = spots_of(state, uid).first() { + return state.sessions[&s.session].nickname(s.client); + } + let from_peer = |m: &HistoryMessage| { + (m.message.author_uid.as_deref() == Some(uid)).then(|| m.message.author_name.clone()) + }; + last.and_then(from_peer) + .or_else(|| { + state.sessions.values().flat_map(|v| &v.tabs).find_map(|t| { + (t.target == ChatTarget::Private(uid.to_owned())) + .then(|| t.messages.iter().rev().find_map(|m| from_peer(&m.message))) + .flatten() + }) + }) + .unwrap_or_else(|| uid.chars().take(8).collect()) +} /// A chat of any server. #[derive(Clone, Debug, PartialEq)] diff --git a/crates/voelin-ui-vm/src/state.rs b/crates/voelin-ui-vm/src/state.rs index bdc81f2..ea37a4f 100644 --- a/crates/voelin-ui-vm/src/state.rs +++ b/crates/voelin-ui-vm/src/state.rs @@ -21,6 +21,7 @@ use voelin_gateway_proto::{ use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, GroupInfo, Presence}; use voelin_store::Bookmark; +use crate::bridge::ChatLine; use crate::chat::{LineCache, Previous}; use crate::image::ImageRef; use crate::settings::{ClientPlaybackMap, DeviceChoices, UiSettings}; @@ -34,6 +35,20 @@ pub fn store_target(target: &ChatTarget) -> voelin_store::ChatTarget { } } +/// The lines of a chat tab, in the front end's own list type (a Slint model +/// kept in step with them, or a plain `Vec`): what a message that arrives +/// without stored history appends. +pub trait Lines: Default { + /// Append a line. + fn push(&mut self, line: ChatLine); +} + +impl Lines for Vec { + fn push(&mut self, line: ChatLine) { + Vec::push(self, line); + } +} + /// A file being downloaded from a chat message. pub struct Download { /// The message's handle. @@ -550,6 +565,9 @@ pub struct AppState { /// 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, + /// Our unique ids (TeamSpeak 3 and 6 of every identity): messages by + /// them are ours ([`crate::social::own_message`]). + pub own_uids: HashSet, } impl AppState { @@ -589,6 +607,7 @@ impl AppState { stream_volume: 100.0, gateways_looked_up: HashSet::new(), uploads: HashMap::new(), + own_uids: HashSet::new(), } } } diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index dcccfb5..5d645d5 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -23,10 +23,7 @@ use voelin_core::settings::{ AUDIO, CRASH_REPORTS, IDENTITY_IMPORT, STREAM_DECODER_BACKEND, STREAM_HARDWARE_DECODING, Settings, }; -use voelin_core::{ - AudioSettings, BackendInfo, Command, Engine, Event, History, ObserveState, VoiceState, -}; -use voelin_model::ChatTarget; +use voelin_core::{AudioSettings, Command, Engine, Event, History}; use voelin_platform::crash; use voelin_store::{Bookmark, MemorySecrets, Secrets, Store}; @@ -119,6 +116,12 @@ impl Secrets for FallbackSecrets { /// The lines of a chat as the chat view shows them. pub(crate) type ChatRows = Rows; +impl vm::state::Lines for ChatRows { + fn push(&mut self, line: vm::bridge::ChatLine) { + Rows::push(self, line); + } +} + /// A chat of a session (see `voelin_ui_vm::state`). pub(crate) type Tab = vm::state::Tab; @@ -627,7 +630,7 @@ impl App { /// A setting changed, maybe elsewhere (a command, another window): take /// the values the window keeps copies of. The engine applies audio /// settings itself. - fn setting_changed(&mut self, key: &str) { + pub(crate) fn setting_changed(&mut self, key: &str) { if key == AUDIO.name() && !self.state.audio_dirty { self.state.audio = self.prefs.get(&AUDIO); // The voice controls follow the transmit mode. @@ -652,239 +655,16 @@ impl App { self.page_setting_changed(key); } + /// An engine event. What it does to the state is in + /// `voelin_ui_vm::events::apply`; the window, the engine and the store + /// follow what that says ([`App::perform`]). The friends, pokes and offline + /// messages (`social.rs`) look at it before and after. pub(crate) fn handle_event(&mut self, event: Event) { let touched = self.social_event(&event); - self.dispatch(event); + self.apply_event(event); self.social_refresh(touched); } - fn dispatch(&mut self, event: Event) { - match event { - Event::State { session, state } => { - let id = session as i64; - 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; - view.state = state.clone(); - if state.voice != VoiceState::Connected { - view.focused_own_channel = false; - } - if state.voice == VoiceState::Disconnected && was_voice != VoiceState::Disconnected - { - view.channel_passwords.clear(); - view.join_after_connect = None; - } - if state.voice == VoiceState::Connected && was_voice != VoiceState::Connected { - // A new connection: volumes are sent again. - view.applied_playback.clear(); - } - // Where its chats were read, once the server is known; kept - // when the session ends. - self.load_reads(id); - let off = |voice: VoiceState, observe: ObserveState| { - voice == VoiceState::Disconnected && observe == ObserveState::Off - }; - if off(state.voice, state.observe) && !off(was_voice, was_observe) { - self.save_reads(id); - } - 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.state.current == Some(id) { - if self.track_reading() { - self.refresh_chat(); - } - // The voice channel's chat is always at hand, and focused - // once per connection. - if let (Some(cid), VoiceState::Connected) = (state.own_channel, state.voice) { - self.open_chat(ChatTarget::Channel(cid), focus); - self.state.sessions.entry(id).or_default().focused_own_channel = true; - } - } - // Where we are with voice, when it changed here: home's last - // place, which `refresh_servers` shows (voice on another - // server does not take it back at each of its events). - if (state.voice, state.own_channel) != (was_voice, was_channel) { - self.remember_voice(id); - } - self.refresh_servers(); - self.refresh_toolbar(); - self.refresh_tree(); - self.refresh_streams(); - self.autoshare(); - 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.state.sessions.entry(session as i64).or_default().capabilities = capabilities; - self.adopt_server_name(session as i64, &name); - 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.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) - != crate::chat::server_texts(&presence.server); - // Our channel's path: known only now (a new connection), - // or renamed. - let path = |v: &SessionView| { - v.state.own_channel.map(|c| crate::vm::tree::channel_path(&v.presence, c)) - }; - let path_before = path(view); - view.presence = presence; - let renamed = path(view) != path_before; - self.apply_client_playback(session as i64); - self.join_after_connect(session as i64); - if renamed && self.remember_voice(session as i64) { - self.refresh_servers(); - } - if self.state.current == Some(session as i64) { - if said { - self.fetch_previews(session as i64); - } - self.refresh_toolbar(); - self.refresh_tree(); - self.refresh_chat(); - self.refresh_streams(); - if self.open_client_pending { - self.open_first_client(); - } - } - } - Event::Talking { session, client, talking } => { - let view = self.state.sessions.entry(session as i64).or_default(); - if talking { - view.talking.insert(client); - } else { - view.talking.remove(&client); - } - if self.state.current == Some(session as i64) { - self.refresh_tree(); - } - } - Event::InputLevel { session, level_db, sending } => { - let shown = match session { - 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::(); - bridge.set_input_level(level_db); - bridge.set_input_sending(sending); - } - } - Event::MicrophoneTestError { message } => { - self.set_status(format!("Microphone test: {message}")) - } - // Only for sessions the engine keeps no history for (it does not - // know the server yet): those get ids and reactions instead. - Event::Chat { session, message } => { - let id = session as i64; - if !self.state.sessions.entry(id).or_default().has_history() { - self.add_message(id, message); - } - } - Event::ChatHistory { session, target, messages, source, complete } => { - self.history_batch(session as i64, &target, messages, source, complete); - } - Event::Gateway { session, update } => { - if let voelin_core::gateway::GatewayUpdate::Connected { url, .. } = &update { - self.gateway_in_use(session as i64, url); - } - self.gateway_extra(session as i64, &update); - self.gateway_update(session as i64, update); - } - Event::Groups { session, server_groups, channel_groups } => { - 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.state.current == Some(session as i64) { - self.refresh_tree(); - } - } - Event::ServerDetails { session, address, details } => { - self.remember_server_icon(session as i64, &address, details.icon); - self.refresh_servers(); - self.refresh_toolbar(); - } - // Pictures can arrive after the rows were built: draw them again. - Event::AvatarReady { session, client_uid, path, .. } => { - 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.state.current == Some(session as i64) { - self.refresh_tree(); - self.refresh_chat(); - self.refresh_toolbar(); - self.refresh_member_card(); - self.refresh_streams(); - } - } - Event::IconReady { session, icon, path } => { - 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.state.current == Some(session as i64) { - self.refresh_tree(); - self.refresh_toolbar(); - } - } - Event::PictureReady { session, url, path } => { - 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.state.current == Some(session as i64) { - self.refresh_toolbar(); - self.refresh_tree(); - self.refresh_chat(); - self.refresh_member_card(); - } - } - Event::Transfer { session, transfer, state } => { - self.transfer_progress(session as i64, transfer, state); - } - // The engine's contacts would replace the sample ones. - Event::ContactsChanged { .. } if self.demo_ui && !self.state.contacts.is_empty() => {} - Event::ContactsChanged { contacts } => { - 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. - Event::Error { .. } if self.demo_ui => {} - Event::Error { message, .. } => self.set_status(message), - Event::JoinFailed { session, channel, reason } => { - self.join_failed(session as i64, channel, reason); - } - Event::SettingChanged { key } => self.setting_changed(&key), - Event::SettingRejected { key, message } => { - self.set_status(format!("Setting {key}: {message}")); - } - // The Stream Studio's stream (studio/). - Event::StreamState { session, state } if self.studio_streams_to(session as i64) => { - self.studio_stream_state(state); - } - Event::StreamViewers { session, viewers } if self.studio_streams_to(session as i64) => { - self.studio_viewers(viewers); - } - event => self.stream_event(event), - } - } - /// Once a second. fn tick(&mut self) { self.tick_streams(); @@ -903,36 +683,11 @@ impl App { } } -/// The status line once a server answered: "Connected to Nightfall Guild -/// (TeamSpeak 6 6.0.0-beta13.1)". -fn connected_status(name: &str, backend: &BackendInfo) -> String { - format!("Connected to {name} ({})", backend.label()) -} - #[cfg(test)] mod tests { - use super::*; + use voelin_model::ChatTarget; - #[test] - fn the_status_line_names_the_servers_software() { - let backend = |product: &str, version: &str| BackendInfo { - product: product.into(), - version: version.into(), - }; - assert_eq!( - connected_status("Nightfall Guild", &backend("TeamSpeak 6", "6.0.0-beta13.1")), - "Connected to Nightfall Guild (TeamSpeak 6 6.0.0-beta13.1)" - ); - assert_eq!( - connected_status("Pixel Lounge", &backend("TeamSpeak 3", "3.13.8")), - "Connected to Pixel Lounge (TeamSpeak 3 3.13.8)" - ); - // Not recognised: the version string the server sent. - assert_eq!( - connected_status("Home", &backend("", "custom 9")), - "Connected to Home (custom 9)" - ); - } + use super::*; #[test] fn channel_unread_ignores_private_tabs() { diff --git a/crates/voelin-ui/src/chat.rs b/crates/voelin-ui/src/chat.rs index 5cf763a..b85ffe0 100644 --- a/crates/voelin-ui/src/chat.rs +++ b/crates/voelin-ui/src/chat.rs @@ -20,15 +20,12 @@ use std::collections::HashMap; use std::path::PathBuf; use slint::ComponentHandle; -use voelin_core::gateway::Pin; use voelin_core::settings::CACHE_FETCH_IMAGES; use voelin_core::{ - Command, DownloadTo, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource, - TransferState, + Command, DownloadTo, GatewayRequest, HistoryMessage, HistorySource, TransferState, }; -use voelin_gateway_proto::{ErrorCode, TopicInfo, feature}; -use voelin_model::{ChatMessage, ChatTarget, HostMessageMode, ServerDetails}; -use voelin_store::ChatRead; +use voelin_gateway_proto::feature; +use voelin_model::{ChatMessage, ChatTarget}; use crate::app::{App, Bridge, Nav, SessionView, Tab}; use crate::settings::UI_IMAGE_PREVIEW_KB; @@ -36,32 +33,7 @@ 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. -const SERVER_LINES: [i64; 2] = [i64::MIN, i64::MIN + 1]; - -/// What the server says to everyone who connects, with where its line keeps -/// its parts: its welcome message, and its host message when that goes to -/// the chat log. -pub(crate) fn server_texts(details: &ServerDetails) -> Vec<(&str, i64)> { - let host = details.host_message_mode == HostMessageMode::Log; - [Some(&details.welcome_message), host.then_some(&details.host_message)] - .into_iter() - .zip(SERVER_LINES) - .filter_map(|(text, id)| Some((text.filter(|t| !t.trim().is_empty())?.as_str(), id))) - .collect() -} - -/// The text of the server's line `key` (-1, -2, …) of a server chat -/// ([`App::lines_of`]), if `tab` is one. -pub(crate) fn server_text<'a>(view: &'a SessionView, tab: &Tab, key: i32) -> Option<&'a str> { - if tab.target != ChatTarget::Server || key >= 0 { - return None; - } - server_texts(&view.presence.server).get((-1 - key) as usize).map(|(text, _)| *text) -} +use crate::vm::state::Download; /// "3 min ago", "yesterday", "12 Mar". fn ago(ts_ms: i64) -> String { @@ -79,36 +51,16 @@ fn ago(ts_ms: i64) -> String { } impl App { + /// Open the chat `target` of the current session, and with `focus` show + /// it ([`vm::chat::logic::open_chat`]). pub(crate) fn open_chat(&mut self, target: ChatTarget, focus: bool) { - let Some(id) = self.state.current else { return }; - let index = self.chat_tab(id, target); - if focus { - self.state.sessions.entry(id).or_default().focus_tab(index); - self.prefetch_counts(); - self.track_reading(); - } - self.refresh_chat(); - self.refresh_servers(); + self.transition(|state, cx| vm::chat::logic::open_chat(state, cx, target, focus)); } /// The index of `target`'s tab in session `id`, opened if new (the /// engine then sends its history). pub(crate) fn chat_tab(&mut self, id: i64, target: ChatTarget) -> usize { - let peer = match &target { - ChatTarget::Private(uid) => self.peer_name(uid, None), - _ => String::new(), - }; - let view = self.state.sessions.entry(id).or_default(); - if let Some(i) = view.tabs.iter().position(|t| t.target == target) { - return i; - } - let title = vm::chat::tab_title(&view.presence, &target, &peer); - let tab = view.new_tab(target.clone(), title); - view.tabs.push(tab); - if !self.demo_ui { - self.engine.send(Command::OpenChat { session: id as u64, target }); - } - view.tabs.len() - 1 + self.transition(|state, cx| vm::chat::logic::chat_tab(state, cx, id, target)) } /// The session's tab that tab `index` of the chat strip is @@ -155,47 +107,9 @@ impl App { self.engine.send(Command::SendChat { session: id as u64, target, text }); } - /// The index of `target`'s tab, opening one if it is new. - fn tab_for( - view: &mut SessionView, - target: &ChatTarget, - title: impl FnOnce() -> String, - ) -> usize { - match view.tabs.iter().position(|t| t.target == *target) { - Some(i) => i, - None => { - let tab = view.new_tab(target.clone(), title()); - view.tabs.push(tab); - view.tabs.len() - 1 - } - } - } - - /// A live message of a session without stored history: appended as it - /// comes, without an id. + /// A live message of a session without stored history. pub(crate) fn add_message(&mut self, id: i64, message: ChatMessage) { - let current = self.state.current == Some(id); - let reading = self.reads_now(id); - let new = !self.is_own(id, &message); - 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; - let tab = &mut view.tabs[index]; - let line = vm::chat::line(&message, tab.last.as_ref()); - tab.last = Some(Previous::of(&message)); - tab.lines.push(line); - let counted = new && !seen; - if counted { - tab.unread += 1; - } - if current { - self.refresh_chat(); - } - if counted { - self.refresh_servers(); - } - self.studio_chat_changed(id, &message.target); + self.transition(|state, cx| vm::chat::logic::add_message(state, cx, id, message)); } /// Messages the engine stored: added or updated by their local id. @@ -207,79 +121,9 @@ impl App { source: HistorySource, complete: bool, ) { - 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 { - ChatTarget::Private(uid) => Some(format!( - "@{}", - self.peer_name( - uid, - messages.iter().find(|m| m.message.author_uid.as_deref() == Some(uid.as_str())) - ) - )), - _ => None, - }; - 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); - let seen = reading && view.current_tab == index; - let own_client = view.state.own_client; - let tab = &mut view.tabs[index]; - if source == HistorySource::Gateway { - tab.synced = true; - } - if source != HistorySource::Live { - tab.loading = false; - tab.complete = tab.complete || complete; - } - // Without a marker, what the tab holds was read. - if tab.read.is_none() { - tab.read = tab.newest(); - } - for message in messages { - match tab.messages.iter().position(|m| m.message.id == message.id) { - Some(i) => tab.messages[i].message = message, - None => { - let key = tab.take_key(); - tab.messages.push(Msg { key, message }); - } - } - } - tab.messages.sort_by_key(|m| (m.message.message.ts_ms, m.message.id)); - // ...and so is a first stored page; a first live message is new. - if tab.read.is_none() { - tab.read = match source { - HistorySource::Live => tab - .messages - .first() - .map(|m| (m.message.message.ts_ms, m.message.id.saturating_sub(1))), - _ => tab.newest(), - }; - } - let unread = tab.unread; - let own = - |m: &ChatMessage| crate::social::own_message(&self.social.own_uids, own_client, m); - if seen && source == HistorySource::Live { - tab.catch_up(); - } else { - tab.count_unread(own); - // What came while away (a stored or gateway page) gets the - // divider also when its chat is on screen already. - if seen { - tab.enter(own); - } - } - let counted = tab.unread != unread; - if current { - self.fetch_previews(id); - self.refresh_chat(); - } - if counted { - self.refresh_servers(); - } - self.studio_chat_changed(id, target); + self.transition(|state, cx| { + vm::chat::logic::history_batch(state, cx, id, target, messages, source, complete); + }); } /// The page of messages before the oldest one shown. @@ -335,7 +179,7 @@ impl App { .file_refs() .iter() .enumerate() - .filter_map(|(i, f)| crate::previews::image_of(view, f).map(|image| (i, image))) + .filter_map(|(i, f)| vm::previews::image_of(view, f).map(|image| (i, image))) .collect(); let ctx = LineCtx { key: m.key, @@ -356,7 +200,7 @@ impl App { previous = Some(Previous::of(&m.message.message)); } if let Some(cache) = cache { - let ids = messages.iter().map(|m| m.message.id).chain(SERVER_LINES); + let ids = messages.iter().map(|m| m.message.id).chain(vm::chat::SERVER_LINES); cache.keep(ids, messages.len()); } // Pokes of a private chat's peer show among its messages. @@ -384,7 +228,7 @@ impl App { "" => "Server", name => name, }; - server_texts(&view.presence.server) + vm::chat::server_texts(&view.presence.server) .into_iter() .enumerate() .map(|(i, (text, id))| { @@ -621,54 +465,12 @@ impl App { // What is read. - /// The current chat's messages are on screen (`Nav.chat-shown`). - fn chat_shown(&self) -> bool { - self.ui.upgrade().is_some_and(|ui| ui.global::