From f92a14fc84038a30f08846c9dc564978aaded55e Mon Sep 17 00:00:00 2001 From: faumaray Date: Wed, 21 Oct 2026 05:31:35 +0300 Subject: [PATCH 01/24] Fall back to the name's colour for a chat whose server is gone server_tint answered opaque black for a server that is not in the list, where the Slint version answered transparent. It now answers none, and the direct-message list picks the colour of the chat's own title, as it does for every chat that is not a server's. Co-Authored-By: Claude Sonnet 5.5 --- crates/voelin-ui/src/messages.rs | 8 +++++--- crates/voelin-ui/src/servers.rs | 8 +++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/voelin-ui/src/messages.rs b/crates/voelin-ui/src/messages.rs index 7d377a5..3325e5a 100644 --- a/crates/voelin-ui/src/messages.rs +++ b/crates/voelin-ui/src/messages.rs @@ -220,11 +220,13 @@ impl App { ago: ago(ts).into(), unread: chat.unread, initials: vm::avatar::initials(&title).into(), - // A server's chat in the server's colour. + // A server's chat in the server's colour; a name's own colour + // when the server is gone. tint: match (kind, session) { (0, Some(s)) => self.server_tint(s), - _ => vm::avatar::tint(&title), - }, + _ => None, + } + .unwrap_or_else(|| vm::avatar::tint(&title)), avatar, online, selected: open.is_some_and(|o| { diff --git a/crates/voelin-ui/src/servers.rs b/crates/voelin-ui/src/servers.rs index 93853ee..a2fa32e 100644 --- a/crates/voelin-ui/src/servers.rs +++ b/crates/voelin-ui/src/servers.rs @@ -450,10 +450,12 @@ impl App { } } - /// A server's colour, as the rail shows it ([`vm::servers::tints`]). - pub(crate) fn server_tint(&self, id: i64) -> vm::Rgb { + /// A server's colour, as the rail shows it ([`vm::servers::tints`]); none + /// for a server that is not in the list (a chat that outlived its + /// bookmark), where the caller picks a colour of its own. + pub(crate) fn server_tint(&self, id: i64) -> Option { let tints = vm::servers::tints(&self.state.bookmarks); - self.state.bookmarks.iter().position(|b| b.id == id).map(|i| tints[i]).unwrap_or_default() + self.state.bookmarks.iter().position(|b| b.id == id).map(|i| tints[i]) } /// The rail: servers with their state, unread count (without private From d9de95b9856919a03ddc89aac0e6c85772a094cb Mon Sep 17 00:00:00 2001 From: faumaray Date: Wed, 21 Oct 2026 05:52:16 +0300 Subject: [PATCH 02/24] Make a picture's size mean it shows, and keep pixels the size they say ImageSource::size() read a raster file's header, so a cache file that was cut short or garbled after the header counted as showable, where the Slint version's decoded image was empty. A raster picture is now decoded to tell (the first frame, with the limits the Slint side uses) and an SVG must parse as XML with an svg root (roxmltree, already in the tree through the vector renderer); the answer is kept per file stamp, and per key and content hash for a downloaded picture, and decoding runs outside the lock. The size check of the pixel count no longer overflows on a header that claims u32::MAX. ImageSource::Rgba holds a Pixels value that can only be made with the right length, so the Slint conversion cannot hand clone_from_slice bytes that do not fit (it panics on that). Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 1 + crates/voelin-ui-vm/Cargo.toml | 7 +- crates/voelin-ui-vm/src/image.rs | 283 ++++++++++++++++++++------- crates/voelin-ui-vm/src/lib.rs | 2 +- crates/voelin-ui/src/bind/convert.rs | 10 +- 5 files changed, 224 insertions(+), 79 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bf6d35f..cd38c6b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9764,6 +9764,7 @@ dependencies = [ "image", "miniz_oxide 0.8.9", "png", + "roxmltree", "serde", "serde_json", "unicode-segmentation", diff --git a/crates/voelin-ui-vm/Cargo.toml b/crates/voelin-ui-vm/Cargo.toml index 6d903b0..17f3587 100644 --- a/crates/voelin-ui-vm/Cargo.toml +++ b/crates/voelin-ui-vm/Cargo.toml @@ -16,12 +16,15 @@ path = "src/lib.rs" # must show neither. The front ends convert these types (docs/ui.md). [dependencies] chrono = { version = "0.4.45", default-features = false, features = ["clock"] } -# Picture sizes (the header of a file); PNG and JPEG are listed as the -# front end's toolkit used to bring them. +# Whether a picture file decodes, and its size; PNG and JPEG are listed as +# the front end's toolkit used to bring them. image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "ico"] } serde = { version = "1", features = ["derive"] } # JSON values of the settings and the gateway's configuration keys. serde_json = "1" +# Whether an SVG document is XML with an svg root (the vector renderers read +# it with this parser too). +roxmltree = { version = "0.21", default-features = false, features = ["std"] } # The Twemoji archive's blocks (raw deflate). miniz_oxide = "0.8" # Grapheme clusters for emoji in chat text. diff --git a/crates/voelin-ui-vm/src/image.rs b/crates/voelin-ui-vm/src/image.rs index e92f464..31685ad 100644 --- a/crates/voelin-ui-vm/src/image.rs +++ b/crates/voelin-ui-vm/src/image.rs @@ -4,6 +4,8 @@ use std::collections::HashMap; use std::fmt; +use std::hash::{DefaultHasher, Hasher}; +use std::io::Cursor; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use std::time::SystemTime; @@ -28,15 +30,8 @@ pub enum ImageSource { /// What the file was when the reference was made. stamp: Stamp, }, - /// Decoded pixels, 4 bytes per pixel in the order red, green, blue, alpha. - Rgba { - /// Width in pixels. - w: u32, - /// Height in pixels. - h: u32, - /// `w * h * 4` bytes. - bytes: Arc<[u8]>, - }, + /// Decoded pixels; [`ImageSource::rgba`] makes them. + Rgba(Pixels), /// An SVG document. Svg(Arc<[u8]>), /// A picture file held in memory (a chat picture downloaded for its @@ -55,7 +50,7 @@ impl fmt::Debug for ImageSource { match self { Self::None => f.write_str("None"), Self::File { path, .. } => f.debug_tuple("File").field(path).finish(), - Self::Rgba { w, h, .. } => write!(f, "Rgba({w}x{h})"), + Self::Rgba(pixels) => write!(f, "Rgba({}x{})", pixels.width(), pixels.height()), Self::Svg(bytes) => write!(f, "Svg({} bytes)", bytes.len()), Self::Memory { key, bytes } => write!(f, "Memory({key}, {} bytes)", bytes.len()), } @@ -88,6 +83,39 @@ pub struct Size { pub height: u32, } +/// Decoded pixels, 4 bytes per pixel in the order red, green, blue, alpha. +/// The length always fits the size (`width * height * 4`), so a front end +/// can hand the bytes to its toolkit without checking them. +#[derive(Clone, PartialEq, Eq)] +pub struct Pixels { + w: u32, + h: u32, + bytes: Arc<[u8]>, +} + +impl Pixels { + /// The pixels `bytes` hold, if there are `w * h * 4` of them. + pub fn new(w: u32, h: u32, bytes: impl Into>) -> Option { + let bytes = bytes.into(); + (bytes.len() as u128 == u128::from(w) * u128::from(h) * 4).then_some(Self { w, h, bytes }) + } + + /// Width in pixels. + pub fn width(&self) -> u32 { + self.w + } + + /// Height in pixels. + pub fn height(&self) -> u32 { + self.h + } + + /// `width * height * 4` bytes: red, green, blue, alpha of each pixel, row by row. + pub fn bytes(&self) -> &[u8] { + &self.bytes + } +} + impl ImageSource { /// A reference to no picture. pub fn none() -> ImageRef { @@ -104,27 +132,24 @@ impl ImageSource { /// A reference to decoded pixels (`bytes`: `w * h * 4`, red, green, blue, /// alpha); no picture if the length does not fit. pub fn rgba(w: u32, h: u32, bytes: impl Into>) -> ImageRef { - let bytes = bytes.into(); - if bytes.len() as u64 == u64::from(w) * u64::from(h) * 4 { - Arc::new(Self::Rgba { w, h, bytes }) - } else { - Self::none() - } + Pixels::new(w, h, bytes).map_or_else(Self::none, |pixels| Arc::new(Self::Rgba(pixels))) } /// The size the picture shows with; 0 by 0 when there is none or it can - /// not be shown: a file that is missing, is not a picture, or is too - /// large to decode (a front end drops those, as it would show nothing). - /// A file's size is read from its header, once while it stays as it is; - /// a vector picture has none of its own: its stated width and height, - /// else 1 by 1. + /// not be shown: a file that is missing, does not decode, or is too large + /// to decode (a front end drops those, as it would show nothing). So a + /// picture that has a size shows: a raster picture is decoded to tell + /// (its first frame, as a front end would show it), an SVG document must + /// parse. A file or a downloaded picture is checked once while it stays + /// as it is; a vector picture has no size of its own: its stated width + /// and height, else 1 by 1. pub fn size(&self) -> Size { match self { Self::None => Size::default(), Self::File { path, stamp } => file_size(path, *stamp), - Self::Rgba { w, h, .. } => Size { width: *w, height: *h }, + Self::Rgba(pixels) => Size { width: pixels.width(), height: pixels.height() }, Self::Svg(bytes) => svg_size(bytes), - Self::Memory { bytes, .. } => bytes_size(bytes), + Self::Memory { key, bytes } => memory_size(key, bytes), } } @@ -138,24 +163,38 @@ impl ImageSource { const MAX_DECODED_BYTES: u64 = 128 << 20; fn checked(width: u32, height: u32) -> Size { - if width == 0 || height == 0 || u64::from(width) * u64::from(height) * 4 > MAX_DECODED_BYTES { + let bytes = u128::from(width) * u128::from(height) * 4; + if width == 0 || height == 0 || bytes > u128::from(MAX_DECODED_BYTES) { Size::default() } else { Size { width, height } } } -/// The size of a picture file's bytes, told by content. +/// What a picture file's bytes show as, told by content: a raster picture is +/// decoded (its first frame; the size comes from the header, the decoding +/// tells whether the rest of the file is a picture too), an SVG document +/// must parse. Anything else, or anything that does not decode, shows +/// nothing. fn bytes_size(bytes: &[u8]) -> Size { let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes); - let Ok(reader) = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format() - else { + let Ok(mut reader) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format() else { return Size::default(); }; if reader.format().is_none() { return if voelin_core::is_svg(bytes) { svg_size(bytes) } else { Size::default() }; } - reader.into_dimensions().map_or_else(|_| Size::default(), |(w, h)| checked(w, h)) + // What a front end allows itself: 16 bits a channel take twice the bytes. + let mut limits = image::Limits::default(); + limits.max_alloc = Some(2 * MAX_DECODED_BYTES + (64 << 20)); + reader.limits(limits); + let Ok(decoder) = reader.into_decoder() else { return Size::default() }; + let (width, height) = image::ImageDecoder::dimensions(&decoder); + let size = checked(width, height); + if size == Size::default() || image::DynamicImage::from_decoder(decoder).is_err() { + return Size::default(); + } + size } /// The number at the start of an attribute's value ("48", "48px", "4.5em"). @@ -164,34 +203,25 @@ fn number(value: &str) -> Option { value[..end].parse::().ok().filter(|v| *v >= 1.0).map(|v| v as u32) } -/// The value of `name="…"` in the root tag of an SVG. -fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> { - let mut rest = tag; - while let Some(at) = rest.find(name) { - let before = rest[..at].chars().next_back(); - let after = &rest[at + name.len()..]; - let after = after.trim_start(); - if before.is_none_or(char::is_whitespace) - && let Some(value) = after.strip_prefix('=') - { - let value = value.trim_start(); - let quote = value.chars().next().filter(|q| matches!(q, '"' | '\''))?; - return value[1..].split(quote).next(); - } - rest = &rest[at + name.len()..]; - } - None -} - +/// The size of an SVG document: none unless it is XML (as the vector +/// renderers read it, a doctype allowed) whose root is an `svg` element. fn svg_size(bytes: &[u8]) -> Size { - let text = String::from_utf8_lossy(bytes); - let Some(start) = text.find("').unwrap_or(tag.len())]; + const NAMESPACE: &str = "http://www.w3.org/2000/svg"; + let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes); + let Ok(text) = std::str::from_utf8(bytes) else { return Size::default() }; + let options = roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() }; + let Ok(document) = roxmltree::Document::parse_with_options(text, options) else { + return Size::default(); + }; + let root = document.root_element(); + let name = root.tag_name(); + if name.name() != "svg" || name.namespace().is_some_and(|ns| ns != NAMESPACE) { + return Size::default(); + } let stated = - attribute(tag, "width").and_then(number).zip(attribute(tag, "height").and_then(number)); + root.attribute("width").and_then(number).zip(root.attribute("height").and_then(number)); let boxed = || { - let mut parts = attribute(tag, "viewBox")?.split([' ', ',']).filter(|p| !p.is_empty()); + let mut parts = root.attribute("viewBox")?.split([' ', ',']).filter(|p| !p.is_empty()); let (_, _, w, h) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?); number(w).zip(number(h)) }; @@ -199,34 +229,66 @@ fn svg_size(bytes: &[u8]) -> Size { checked(width, height) } -/// What a probe of a file found, and what the file was then. -type Probe = (Stamp, Size); +/// What identifies the bytes a probe looked at. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Seen { + /// A file as it was (length and time). + File(Stamp), + /// A picture in memory: its length and a hash of its bytes. + Bytes(usize, u64), +} -/// Probed files, so a picture shown in many rows is read once; entries are -/// checked against the file's length and time before use. -static PROBES: Mutex>> = Mutex::new(None); +/// Where a probed picture is. +#[derive(Clone, PartialEq, Eq, Hash)] +enum Probed { + File(PathBuf), + Memory(Arc), +} + +/// Probed pictures with what they were then, so a picture shown in many +/// rows is decoded once; an entry is checked against the picture's length +/// and time (or bytes) before use. +static PROBES: Mutex>> = Mutex::new(None); /// Probes kept at most; the picture cache is far smaller than this. const MAX_PROBES: usize = 4096; +/// The size of the picture at `at`, from the cache when it is still the +/// same, else from `probe` (run without the lock: it decodes). +fn probed(at: Probed, seen: Seen, probe: impl FnOnce() -> Size) -> Size { + { + let guard = PROBES.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((was, size)) = guard.as_ref().and_then(|probes| probes.get(&at)) + && *was == seen + { + return *size; + } + } + let size = probe(); + let mut guard = PROBES.lock().unwrap_or_else(|e| e.into_inner()); + let probes = guard.get_or_insert_with(HashMap::new); + if probes.len() >= MAX_PROBES { + probes.clear(); + } + probes.insert(at, (seen, size)); + size +} + fn file_size(path: &Path, stamp: Stamp) -> Size { if stamp == Stamp::default() { return Size::default(); } - let mut guard = PROBES.lock().unwrap_or_else(|e| e.into_inner()); - let probes = guard.get_or_insert_with(HashMap::new); - if let Some((was, size)) = probes.get(path) - && *was == stamp - { - return *size; - } - // The file is read with the lock held; probes are short and rare. - let size = std::fs::read(path).map_or_else(|_| Size::default(), |bytes| bytes_size(&bytes)); - if probes.len() >= MAX_PROBES { - probes.clear(); - } - probes.insert(path.to_owned(), (stamp, size)); - size + probed(Probed::File(path.to_owned()), Seen::File(stamp), || { + std::fs::read(path).map_or_else(|_| Size::default(), |bytes| bytes_size(&bytes)) + }) +} + +fn memory_size(key: &Arc, bytes: &[u8]) -> Size { + let mut hasher = DefaultHasher::new(); + hasher.write(bytes); + probed(Probed::Memory(key.clone()), Seen::Bytes(bytes.len(), hasher.finish()), || { + bytes_size(bytes) + }) } #[cfg(test)] @@ -239,7 +301,15 @@ mod tests { let mut encoder = ::png::Encoder::new(&mut bytes, width, height); encoder.set_color(::png::ColorType::Rgba); encoder.set_depth(::png::BitDepth::Eight); - let pixels = vec![200; width as usize * height as usize * 4]; + // Pixels that do not compress to nothing, so cutting the file short + // cuts into the picture. + let mut seed = 0x2545_f491_u32; + let pixels: Vec = (0..width as usize * height as usize * 4) + .map(|_| { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 24) as u8 + }) + .collect(); encoder.write_header().unwrap().write_image_data(&pixels).unwrap(); bytes } @@ -257,8 +327,13 @@ mod tests { let pixels = ImageSource::rgba(2, 3, vec![0u8; 24]); assert_eq!(pixels.size(), Size { width: 2, height: 3 }); assert!(!pixels.is_empty()); - // The wrong length is no picture. + // The wrong length is no picture, and no pixels either. assert!(ImageSource::rgba(2, 3, vec![0u8; 23]).is_empty()); + assert!(ImageSource::rgba(2, 3, vec![0u8; 25]).is_empty()); + assert!(Pixels::new(2, 3, vec![0u8; 23]).is_none()); + assert!(Pixels::new(u32::MAX, u32::MAX, vec![0u8; 4]).is_none()); + let ImageSource::Rgba(inner) = &*pixels else { panic!("pixels") }; + assert_eq!((inner.width(), inner.height(), inner.bytes().len()), (2, 3, 24)); assert_eq!(format!("{pixels:?}"), "Rgba(2x3)"); } @@ -284,6 +359,48 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + #[test] + fn a_file_that_does_not_decode_shows_nothing() { + let dir = temp("corrupt"); + let whole = png(32, 32); + // The header is fine, the picture is cut short (a download that + // stopped, a cache file written halfway). + let cut = dir.join("cut"); + std::fs::write(&cut, &whole[..whole.len() * 2 / 3]).unwrap(); + assert!(ImageSource::file(&cut).is_empty()); + // The header is fine, the data is not: flipped bytes in the image + // data, from the middle of the file to its end. + let mut flipped = whole.clone(); + let from = flipped.len() / 2; + for byte in &mut flipped[from..] { + *byte = !*byte; + } + let garbled = dir.join("garbled"); + std::fs::write(&garbled, &flipped).unwrap(); + assert!(ImageSource::file(&garbled).is_empty()); + // The whole file shows, and the answer is kept while it stays so. + let good = dir.join("good"); + std::fs::write(&good, &whole).unwrap(); + assert_eq!(ImageSource::file(&good).size(), Size { width: 32, height: 32 }); + // A file that is made whole shows (another stamp: another answer). + std::fs::write(&cut, &whole).unwrap(); + assert_eq!(ImageSource::file(&cut).size(), Size { width: 32, height: 32 }); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn a_downloaded_picture_is_checked_too() { + let whole = png(16, 16); + let memory = + |key: &str, bytes: &[u8]| ImageSource::Memory { key: key.into(), bytes: bytes.into() }; + assert_eq!(memory("whole", &whole).size(), Size { width: 16, height: 16 }); + assert!(memory("cut", &whole[..whole.len() / 2]).is_empty()); + // The same key with other bytes is another picture. + assert!(memory("same", &whole[..whole.len() / 2]).is_empty()); + assert_eq!(memory("same", &whole).size(), Size { width: 16, height: 16 }); + assert!(memory("none", b"").is_empty()); + } + #[test] fn vector_pictures() { let size = |svg: &str| ImageSource::Svg(svg.as_bytes().into()).size(); @@ -296,6 +413,24 @@ mod tests { ImageSource::Svg(b"".as_slice().into()) .is_empty() ); + // Not an SVG document: cut off, a sibling of the root, other roots, + // not text. + assert!(size("").width == 0); + assert!(size("").width == 0); + assert!(size("").width == 0); + assert!(size("").width == 0); + assert_eq!( + size("").height, + 9 + ); + assert!( + ImageSource::Svg(b"\xff".as_slice().into()).is_empty() + ); + // A doctype, as editors write it. + let doctype = ""; + assert_eq!(size(doctype), Size { width: 5, height: 6 }); // An SVG file with a byte order mark and a prolog, and in memory. let svg: &[u8] = b"\xef\xbb\xbf"; let dir = temp("svg"); diff --git a/crates/voelin-ui-vm/src/lib.rs b/crates/voelin-ui-vm/src/lib.rs index fa25c8f..66e5969 100644 --- a/crates/voelin-ui-vm/src/lib.rs +++ b/crates/voelin-ui-vm/src/lib.rs @@ -23,4 +23,4 @@ pub mod studio_bridge; pub mod tree; pub use color::Rgb; -pub use image::{ImageRef, ImageSource, Size}; +pub use image::{ImageRef, ImageSource, Pixels, Size}; diff --git a/crates/voelin-ui/src/bind/convert.rs b/crates/voelin-ui/src/bind/convert.rs index 3cddcbb..61cfd84 100644 --- a/crates/voelin-ui/src/bind/convert.rs +++ b/crates/voelin-ui/src/bind/convert.rs @@ -37,8 +37,14 @@ pub(crate) fn image(picture: &ImageRef) -> Image { match &**picture { ImageSource::None => Image::default(), ImageSource::File { path, .. } => crate::images::file(path), - ImageSource::Rgba { w, h, bytes } => { - Image::from_rgba8(SharedPixelBuffer::::clone_from_slice(bytes, *w, *h)) + // `Pixels` holds `width * height * 4` bytes, which `clone_from_slice` + // needs (it panics otherwise). + ImageSource::Rgba(pixels) => { + Image::from_rgba8(SharedPixelBuffer::::clone_from_slice( + pixels.bytes(), + pixels.width(), + pixels.height(), + )) } ImageSource::Svg(data) => Image::load_from_svg_data(data).unwrap_or_default(), ImageSource::Memory { key, bytes } => crate::images::picture(key, bytes), From 12b277379112b83ac595ce17aea3ce07f12c30f0 Mon Sep 17 00:00:00 2001 From: faumaray Date: Wed, 21 Oct 2026 05:55:24 +0300 Subject: [PATCH 03/24] Say what docs/ui.md counts, with the true share and the studio's base The table of controllers still to split now states its measure (every .set_ call, the status line's included), the share of Bridge writes as counted (four fifths with the status line, two thirds without), the base counts before the work on voelin-ui-vm (studio.rs 64, settings_pages.rs 52), why the studio went before streams.rs, and what ImageSource::size() does now. Co-Authored-By: Claude Sonnet 5.5 --- docs/ui.md | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/docs/ui.md b/docs/ui.md index 58c7dd9..081e056 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -87,7 +87,8 @@ this file is `voelin_ui_vm::chat`. The boundary: - **Values.** A picture is an `ImageRef` (`Arc`: a file of the engine's cache with its stamp, decoded RGBA pixels, SVG or memory bytes, - or none; `size()` reads a file's header). A colour is an `Rgb(u32)`, a + or none; `size()` decodes a raster file once to tell it shows, and parses an SVG, so a + picture with a size is one a front end can draw). A colour is an `Rgb(u32)`, a shared string an `Arc`, a list a `Vec`. The bridge structs (51 in `bridge.rs`, 10 in `studio_bridge.rs`) are plain `Clone + PartialEq + Debug` structs with the field names of the Slint structs in `bridge.slint` and @@ -118,10 +119,15 @@ no display); the Slint crate's tests are what needs the window types. ### Controllers still to split -Counted as `.set_` calls per file (`grep -c '\.set_'`, the status line's -`set_status` included) before this round's splits; Bridge writes alone are -about four fifths of each. Each one is a slice of the same shape as -`settings_pages` and `studio`: move the decisions into +The measure is the number of `.set_` calls in the file (`grep -c '\.set_'`): +every setter counts, those of the Bridge, `Nav`, the window, models and the +engine, and the status line's `self.set_status(…)`, which writes the Bridge's +status text too. In the seven largest files (230 calls) 150 are direct +`bridge.set_…` writes and 37 go through the status line, so Bridge writes +are about four fifths of those files and direct ones about two thirds; the +rest are `Nav`, window and engine setters (in `dev.rs` mostly those). The +numbers are those of the files as they stand. Each controller is a slice of +the same shape as `settings_pages` and `studio`: move the decisions into `voelin-ui-vm/src//logic.rs`, keep the writes in `voelin-ui/src//bind.rs`. @@ -140,10 +146,20 @@ about four fifths of each. Each one is a slice of the same shape as | `popout.rs` | 8 | the viewer's own window | | `members.rs`, `links.rs`, `inbox.rs`, `home.rs`, `events.rs` | 6, 5, 5, 5, 4 | small; split with their neighbours | -Before this round: `studio.rs` had 62 and `settings_pages.rs` 52 (the two -with the most). Their `bind.rs` files still show 58 and 51 `.set_` calls: the -Bridge and model writes stay where the toolkit is, and what each write says -now comes from `logic.rs`, which has tests of its own. +Before the work on `voelin-ui-vm` began, `studio.rs` had 64 `.set_` calls +and `settings_pages.rs` 52 (the two with the most, then `streams.rs` with 45; +62 was `studio.rs` once the view models had moved, two setters having +gone with them). Their `bind.rs` files still show 58 and 51: the Bridge and model writes +stay where the toolkit is, and what each write says now comes from +`logic.rs`, which has tests of its own. + +Why the studio went before `streams.rs`: it had the most calls, and it is +self-contained. It has its own state (`StudioState`), windows and bridge +(`studio-bridge.slint`), so its decisions moved without touching the event +dispatch of `app.rs`. `streams.rs`, `chat.rs` and the rest of the list are +driven by that dispatch (the watch, share and history events of `events.rs` +and `app.rs`), so they follow it: the state transition of every engine event +comes first, then the controllers that show the result. ## Theme tokens From 0672b217583da4d7c5374bf615e3d0bdb9340443 Mon Sep 17 00:00:00 2001 From: faumaray Date: Wed, 21 Oct 2026 05:55:24 +0300 Subject: [PATCH 04/24] Warn about undocumented public items of voelin-ui-vm #![warn(missing_docs)] on the crate, with the fields and variants that had no docs documented (BBCode styles and spans, settings, the tree's input) and a targeted allow on the two mirror modules, bridge and studio_bridge, whose fields are those of the Slint structs and are explained by the comments in bridge.slint and studio-bridge.slint. Co-Authored-By: Claude Sonnet 5.5 --- crates/voelin-ui-vm/src/bbcode.rs | 16 +++++++++++++++- crates/voelin-ui-vm/src/bridge.rs | 5 +++++ crates/voelin-ui-vm/src/chat.rs | 2 ++ crates/voelin-ui-vm/src/emoji.rs | 2 ++ crates/voelin-ui-vm/src/home.rs | 2 ++ crates/voelin-ui-vm/src/lib.rs | 7 +++++++ crates/voelin-ui-vm/src/servers.rs | 1 + crates/voelin-ui-vm/src/settings.rs | 15 +++++++++++++++ crates/voelin-ui-vm/src/studio/mod.rs | 3 +++ crates/voelin-ui-vm/src/studio_bridge.rs | 4 +++- crates/voelin-ui-vm/src/tree.rs | 6 ++++++ 11 files changed, 61 insertions(+), 2 deletions(-) diff --git a/crates/voelin-ui-vm/src/bbcode.rs b/crates/voelin-ui-vm/src/bbcode.rs index 1b8f238..24a67d3 100644 --- a/crates/voelin-ui-vm/src/bbcode.rs +++ b/crates/voelin-ui-vm/src/bbcode.rs @@ -36,9 +36,13 @@ pub const MAX_RUNS: usize = 1500; /// How a span of text looks. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Style { + /// Bold (`[b]`). pub bold: bool, + /// Italic (`[i]`). pub italic: bool, + /// Underlined (`[u]`). pub underline: bool, + /// Struck through (`[s]`). pub strike: bool, /// Code: on a background. pub code: bool, @@ -51,12 +55,16 @@ pub struct Style { /// A piece of a block. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Span { + /// Text with one style. Text { + /// The characters. text: String, + /// How they look. style: Style, }, /// A picture at an address (`[img]…[/img]`). Image { + /// Where the picture is. url: String, }, } @@ -68,7 +76,10 @@ pub enum BlockKind { Text, /// A line of a quote; the first names who said it (`[quote=Name]`), when /// the quote does. - Quote { author: String }, + Quote { + /// Who said it, empty when the quote does not say. + author: String, + }, /// Code: all its lines in one span. Code, /// An item of a list. @@ -80,13 +91,16 @@ pub enum BlockKind { /// A line, a quote's line, code, a list item or a rule. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Block { + /// What the block is. pub kind: BlockKind, + /// Its pieces, left to right. pub spans: Vec, } /// A message's text: its blocks, top to bottom. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Doc { + /// The lines, quotes, code and rules in order. pub blocks: Vec, } diff --git a/crates/voelin-ui-vm/src/bridge.rs b/crates/voelin-ui-vm/src/bridge.rs index 6dcdf21..1263f0f 100644 --- a/crates/voelin-ui-vm/src/bridge.rs +++ b/crates/voelin-ui-vm/src/bridge.rs @@ -5,6 +5,11 @@ //! (`bind/convert.rs`), the GPUI client will render them as they are. //! `MytsBadge` and `MytsForm` (account screens without a data source in this //! build) stay in Slint. +//! +//! The fields are not documented one by one: they are those of the Slint +//! structs, whose comments in `bridge.slint` explain them; the comments that +//! are here were carried over with them. +#![allow(missing_docs)] use std::sync::Arc; diff --git a/crates/voelin-ui-vm/src/chat.rs b/crates/voelin-ui-vm/src/chat.rs index e7c0b3c..0ff9905 100644 --- a/crates/voelin-ui-vm/src/chat.rs +++ b/crates/voelin-ui-vm/src/chat.rs @@ -24,7 +24,9 @@ const GROUP_MS: i64 = 5 * 60 * 1000; /// The author and time of the line before, for grouping. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Previous { + /// Who wrote it. pub author: String, + /// When, in milliseconds since the epoch. pub ts_ms: i64, } diff --git a/crates/voelin-ui-vm/src/emoji.rs b/crates/voelin-ui-vm/src/emoji.rs index 00af232..25e100d 100644 --- a/crates/voelin-ui-vm/src/emoji.rs +++ b/crates/voelin-ui-vm/src/emoji.rs @@ -298,7 +298,9 @@ pub fn first_key(text: &str) -> Option { /// A piece of text: plain, or one emoji (`emoji` is its key). #[derive(Clone, Debug, PartialEq, Eq)] pub struct Run { + /// The text: the word with its space, or the emoji's own characters. pub text: String, + /// The key of the Twemoji picture, none for plain text. pub emoji: Option, } diff --git a/crates/voelin-ui-vm/src/home.rs b/crates/voelin-ui-vm/src/home.rs index c0f2b3f..64563c2 100644 --- a/crates/voelin-ui-vm/src/home.rs +++ b/crates/voelin-ui-vm/src/home.rs @@ -18,9 +18,11 @@ pub enum ResumeAction { /// The card: the server, the channel and the button. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Resume { + /// The id of the server's bookmark. pub bookmark: i64, /// The channel's path, its names from the top as the server has them. pub path: Vec, + /// What the button does. pub action: ResumeAction, } diff --git a/crates/voelin-ui-vm/src/lib.rs b/crates/voelin-ui-vm/src/lib.rs index 66e5969..dbf6aff 100644 --- a/crates/voelin-ui-vm/src/lib.rs +++ b/crates/voelin-ui-vm/src/lib.rs @@ -3,6 +3,13 @@ //! Neither Slint nor GPUI is a dependency; each front end converts these //! types (docs/ui.md, "Two crates"). +// Every public item is documented, except the fields of the two mirror +// modules (`bridge`, `studio_bridge`): their 400 or so fields are those of +// the Slint structs and are explained by the comments in `bridge.slint` and +// `studio-bridge.slint`, which stay the one place to read them until the +// Slint front end goes. +#![warn(missing_docs)] + pub mod avatar; pub mod bbcode; pub mod bridge; diff --git a/crates/voelin-ui-vm/src/servers.rs b/crates/voelin-ui-vm/src/servers.rs index fe4e8cd..598cc5d 100644 --- a/crates/voelin-ui-vm/src/servers.rs +++ b/crates/voelin-ui-vm/src/servers.rs @@ -126,6 +126,7 @@ pub fn form( pub struct ConnectTo { /// A channel path, or `/`. pub channel: Option, + /// The channel's password, if the form has one. pub channel_password: Option, /// A privilege key. pub token: Option, diff --git a/crates/voelin-ui-vm/src/settings.rs b/crates/voelin-ui-vm/src/settings.rs index 715b70e..56c66dd 100644 --- a/crates/voelin-ui-vm/src/settings.rs +++ b/crates/voelin-ui-vm/src/settings.rs @@ -31,8 +31,10 @@ pub static CLIENT_PLAYBACK: Key = Key::new( #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ThemeChoice { + /// The dark palette. #[default] Dark, + /// The light palette. Light, /// The system's light or dark scheme. System, @@ -128,8 +130,11 @@ pub fn appearance_keys() -> [&'static dyn voelin_core::settings::Setting; 6] { #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum NotifyLevel { + /// Nothing. Off, + /// The bell in the app. App, + /// The bell and a desktop notification. #[default] Desktop, } @@ -294,6 +299,7 @@ pub struct UiSettings { pub openh264: bool, /// The ScreenCast portal's token for the last shared screen. pub portal_restore_token: Option, + /// The last choices in the share dialog. pub share: ShareDefaults, /// Write crash reports to disk (opt-in; never uploaded). pub crash_reports: bool, @@ -321,8 +327,11 @@ impl Default for UiSettings { /// path, its names from the top as the server has them. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct LastVoice { + /// The id of the server's bookmark. pub bookmark: i64, + /// The address the bookmark had then. pub address: String, + /// The channel's names from the top. pub channel: Vec, } @@ -333,9 +342,13 @@ pub struct LastVoice { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(default)] pub struct ShareDefaults { + /// The frame rate's position in the old list ([`LEGACY_FPS_CHOICES`]). pub fps_index: usize, + /// The bitrate's position in the old list ([`LEGACY_BITRATE_CHOICES`]). pub bitrate_index: usize, + /// Share the sound too. pub audio: bool, + /// Accept the viewers that ask to watch without asking us. pub auto_accept: bool, } @@ -350,6 +363,7 @@ impl Default for ShareDefaults { pub struct ClientPlayback { /// Linear, 1 = unchanged. pub volume: f32, + /// Not played at all. pub muted: bool, } @@ -372,6 +386,7 @@ pub type ClientPlaybackMap = BTreeMap; /// Audio devices as listed in the settings: the system default first. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct DeviceChoices { + /// What the list shows, by index. pub names: Vec, /// Device ids by index; `None` for the system default. pub ids: Vec>, diff --git a/crates/voelin-ui-vm/src/studio/mod.rs b/crates/voelin-ui-vm/src/studio/mod.rs index 2d7c1dd..0c501ef 100644 --- a/crates/voelin-ui-vm/src/studio/mod.rs +++ b/crates/voelin-ui-vm/src/studio/mod.rs @@ -117,6 +117,7 @@ pub fn audio_label(kind: &AudioSourceKindSetting) -> (String, String, &'static s pub struct AudioLive { /// Peak in dBFS. pub level: f32, + /// What went wrong with the source, if something did. pub error: Option, } @@ -502,7 +503,9 @@ pub fn placement(kind: &SourceKind, (w, h): (u32, u32)) -> Transform { /// (`None`: switched off, so it is removed). #[derive(Clone, Debug, PartialEq)] pub struct Overlay { + /// The source's name. pub name: &'static str, + /// What it shows, none to remove it. pub text: Option, } diff --git a/crates/voelin-ui-vm/src/studio_bridge.rs b/crates/voelin-ui-vm/src/studio_bridge.rs index 6daa15e..016bf5e 100644 --- a/crates/voelin-ui-vm/src/studio_bridge.rs +++ b/crates/voelin-ui-vm/src/studio_bridge.rs @@ -1,6 +1,8 @@ //! The Stream Studio's structs: the plain counterparts of //! `crates/voelin-ui/ui/studio-bridge.slint`, as [`crate::bridge`] has those of -//! `bridge.slint`. +//! `bridge.slint`. As there, the fields are not documented one by one: see the +//! comments in `studio-bridge.slint`. +#![allow(missing_docs)] use std::sync::Arc; diff --git a/crates/voelin-ui-vm/src/tree.rs b/crates/voelin-ui-vm/src/tree.rs index 146a569..031021a 100644 --- a/crates/voelin-ui-vm/src/tree.rs +++ b/crates/voelin-ui-vm/src/tree.rs @@ -56,11 +56,17 @@ pub fn badge_items(guids: &[String], pictures: &HashMap) -> Vec /// What the tree shows besides the presence. pub struct TreeInput<'a> { + /// The channels and clients of the server. pub presence: &'a Presence, + /// The channels folded shut. pub collapsed: &'a HashSet, + /// The clients that are talking. pub talking: &'a HashSet, + /// Local volume and mute of the clients we changed. pub playback: &'a ClientPlaybackMap, + /// The channel we are in. pub own_channel: Option, + /// Our own client. pub own_client: Option, /// Search text: only matching channels and clients (and the channels /// above them) are shown. Empty: everything. From 03d1c3bd0787f20f7af0e5b0d94c2c82d690f402 Mon Sep 17 00:00:00 2001 From: faumaray Date: Wed, 21 Oct 2026 06:30:39 +0300 Subject: [PATCH 05/24] 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::