From ce7ec3afb74a743931e20922bde2b408969a8d44 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 20 Oct 2026 10:20:55 +0300 Subject: [PATCH] Move the view models into voelin-ui-vm; the Slint models take plain rows vm/{avatar,tree,servers,streams,home,chat,social,studio} and the UI settings (settings.rs: keys, UiSettings, LastVoice, ClientPlaybackMap, the audio form) move into voelin-ui-vm with their tests (102 there now; the 86 view-model tests of voelin-ui all survive, the old list::sync test became the list::diff tests). They produce the plain bridge structs, with Rgb for colours and ImageRef for pictures: - a file picture is ImageSource::File { path, stamp }: the engine writes a picture that arrives again into the same file, so the length and write time are part of the reference and a changed file redraws its row; size() reads the header once per stamp (no toolkit decoder); - pictures held in memory (chat previews) are ImageSource::Memory; - the line cache of the chat no longer keeps Slint models alive for pointer equality: plain lines compare by value, so an unchanged message makes the same line with or without the cache. voelin-ui keeps every model as bind::rows::Rows: the plain rows last shown plus the VecModel, synced with list::diff, converting only the rows that changed (bind/convert has the From impls). The controllers hand the view-model rows to Rows::sync and convert forms at the bridge (`.into()`); crate::vm is now `voelin_ui_vm as vm`, so paths stay. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 7 + crates/voelin-ui-vm/Cargo.toml | 9 +- .../src/vm => voelin-ui-vm/src}/avatar.rs | 23 +- .../src/vm => voelin-ui-vm/src}/chat.rs | 166 ++++---- .../src/vm => voelin-ui-vm/src}/home.rs | 0 crates/voelin-ui-vm/src/image.rs | 54 ++- crates/voelin-ui-vm/src/lib.rs | 9 + .../src/vm => voelin-ui-vm/src}/servers.rs | 63 +-- .../src/settings.rs | 2 +- .../src/vm => voelin-ui-vm/src}/social.rs | 27 +- .../src/vm => voelin-ui-vm/src}/streams.rs | 11 +- .../src/vm => voelin-ui-vm/src}/studio.rs | 24 +- .../src/vm => voelin-ui-vm/src}/tree.rs | 47 +-- crates/voelin-ui/src/app.rs | 119 +++--- crates/voelin-ui/src/appearance.rs | 18 +- crates/voelin-ui/src/bind/convert.rs | 2 +- crates/voelin-ui/src/bind/convert/items.rs | 366 ++++++++++++++++++ crates/voelin-ui/src/bind/pages.rs | 14 +- crates/voelin-ui/src/bind/rows.rs | 27 +- crates/voelin-ui/src/bind/servers.rs | 12 +- crates/voelin-ui/src/bind/settings.rs | 4 +- crates/voelin-ui/src/bind/social.rs | 8 +- crates/voelin-ui/src/bind/streams.rs | 4 +- crates/voelin-ui/src/bind/studio.rs | 13 +- crates/voelin-ui/src/chat.rs | 30 +- crates/voelin-ui/src/dev.rs | 20 +- crates/voelin-ui/src/events.rs | 36 +- crates/voelin-ui/src/home.rs | 15 +- crates/voelin-ui/src/lib.rs | 6 +- crates/voelin-ui/src/links.rs | 2 +- crates/voelin-ui/src/members.rs | 13 +- crates/voelin-ui/src/messages.rs | 150 ++++--- crates/voelin-ui/src/previews.rs | 11 +- crates/voelin-ui/src/servers.rs | 38 +- crates/voelin-ui/src/settings_page.rs | 22 +- crates/voelin-ui/src/settings_pages.rs | 201 +++++----- crates/voelin-ui/src/social.rs | 142 ++++--- crates/voelin-ui/src/streams.rs | 25 +- crates/voelin-ui/src/studio.rs | 102 ++--- crates/voelin-ui/src/vm/list.rs | 77 ---- crates/voelin-ui/src/vm/mod.rs | 15 - 41 files changed, 1154 insertions(+), 780 deletions(-) rename crates/{voelin-ui/src/vm => voelin-ui-vm/src}/avatar.rs (82%) rename crates/{voelin-ui/src/vm => voelin-ui-vm/src}/chat.rs (88%) rename crates/{voelin-ui/src/vm => voelin-ui-vm/src}/home.rs (100%) rename crates/{voelin-ui/src/vm => voelin-ui-vm/src}/servers.rs (93%) rename crates/{voelin-ui => voelin-ui-vm}/src/settings.rs (99%) rename crates/{voelin-ui/src/vm => voelin-ui-vm/src}/social.rs (93%) rename crates/{voelin-ui/src/vm => voelin-ui-vm/src}/streams.rs (90%) rename crates/{voelin-ui/src/vm => voelin-ui-vm/src}/studio.rs (97%) rename crates/{voelin-ui/src/vm => voelin-ui-vm/src}/tree.rs (96%) delete mode 100644 crates/voelin-ui/src/vm/list.rs delete mode 100644 crates/voelin-ui/src/vm/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 08f4313..9a00e04 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9759,11 +9759,18 @@ dependencies = [ name = "voelin-ui-vm" version = "0.0.1-alpha" dependencies = [ + "chrono", "image", "miniz_oxide 0.8.9", "png", + "serde", + "serde_json", "unicode-segmentation", + "voelin-audio", "voelin-core", + "voelin-gateway-proto", + "voelin-model", + "voelin-store", ] [[package]] diff --git a/crates/voelin-ui-vm/Cargo.toml b/crates/voelin-ui-vm/Cargo.toml index 0c92157..b452210 100644 --- a/crates/voelin-ui-vm/Cargo.toml +++ b/crates/voelin-ui-vm/Cargo.toml @@ -15,17 +15,24 @@ path = "src/lib.rs" # No UI toolkit here (no slint, no gpui): `cargo tree -p voelin-ui-vm -e normal` # 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. image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "ico"] } +serde = { version = "1", features = ["derive"] } # The Twemoji archive's blocks (raw deflate). miniz_oxide = "0.8" # Grapheme clusters for emoji in chat text. unicode-segmentation = "1.13" -voelin-core = { path = "../voelin-core", default-features = false } +voelin-audio = { path = "../voelin-audio", default-features = false } +voelin-core = { path = "../voelin-core", default-features = false, features = ["media"] } +voelin-gateway-proto = { path = "../voelin-gateway-proto" } +voelin-model = { path = "../voelin-model" } +voelin-store = { path = "../voelin-store" } [dev-dependencies] png = "0.18" +serde_json = "1" [lints] workspace = true diff --git a/crates/voelin-ui/src/vm/avatar.rs b/crates/voelin-ui-vm/src/avatar.rs similarity index 82% rename from crates/voelin-ui/src/vm/avatar.rs rename to crates/voelin-ui-vm/src/avatar.rs index 74af518..51347f0 100644 --- a/crates/voelin-ui/src/vm/avatar.rs +++ b/crates/voelin-ui-vm/src/avatar.rs @@ -1,8 +1,10 @@ //! Avatars without pictures: initials on a colour from the name. -use slint::Color; use unicode_segmentation::UnicodeSegmentation; +use crate::color::Rgb; +use crate::image::{ImageRef, ImageSource}; + /// Background colours for initials; white text reads on all of them. const TINTS: [u32; 10] = [ 0x2d6bff, 0x7c4dff, 0xc2379a, 0xe0572e, 0xd08a00, 0x1f9d6b, 0x0c93b8, 0x5865f2, 0xa0439e, @@ -31,10 +33,10 @@ pub fn first_letter(initials: &str) -> String { initials.graphemes(true).next().unwrap_or_default().to_owned() } -/// A picture from the engine's cache (an avatar, a group icon), decoded -/// once; an empty image when there is none. -pub fn image(path: Option<&std::path::PathBuf>) -> slint::Image { - path.map(|p| crate::images::file(p)).unwrap_or_default() +/// A picture from the engine's cache (an avatar, a group icon); none when +/// there is no path. +pub fn image(path: Option<&std::path::PathBuf>) -> ImageRef { + path.map(ImageSource::file).unwrap_or_default() } /// A stable number for a name, in any case (FNV-1a). @@ -48,12 +50,12 @@ pub fn name_hash(name: &str) -> u32 { } /// `0xrrggbb` as a colour. -pub fn rgb(rgb: u32) -> Color { - Color::from_rgb_u8((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8) +pub fn rgb(rgb: u32) -> Rgb { + Rgb::from(rgb) } /// A stable colour for a name. -pub fn tint(name: &str) -> Color { +pub fn tint(name: &str) -> Rgb { rgb(TINTS[(name_hash(name) % TINTS.len() as u32) as usize]) } @@ -86,10 +88,7 @@ mod tests { fn tints_are_stable() { assert_eq!(tint("Alice"), tint("alice")); let distinct: std::collections::HashSet<_> = - ["Alice", "Bob", "Carol", "Dave", "Eve", "Mallory"] - .iter() - .map(|n| tint(n).as_argb_encoded()) - .collect(); + ["Alice", "Bob", "Carol", "Dave", "Eve", "Mallory"].iter().map(|n| tint(n).0).collect(); assert!(distinct.len() > 2); } } diff --git a/crates/voelin-ui/src/vm/chat.rs b/crates/voelin-ui-vm/src/chat.rs similarity index 88% rename from crates/voelin-ui/src/vm/chat.rs rename to crates/voelin-ui-vm/src/chat.rs index af034ba..6fabdbc 100644 --- a/crates/voelin-ui/src/vm/chat.rs +++ b/crates/voelin-ui-vm/src/chat.rs @@ -6,17 +6,17 @@ use std::borrow::Cow; use std::cell::RefCell; use std::collections::HashMap; use std::path::PathBuf; -use std::rc::Rc; -use slint::{Color, Image, ModelRc, VecModel}; use unicode_segmentation::UnicodeSegmentation; use voelin_core::HistoryMessage; use voelin_model::{ChatMessage, ChatTarget, FileRef, Presence}; -use crate::app::{ChatLine, FileItem, ReactionItem, TextBlock, TextRun}; +use crate::avatar; +use crate::bbcode::{self, BlockKind, Doc, Span, Style}; +use crate::bridge::{ChatLine, FileItem, ReactionItem, TextBlock, TextRun}; +use crate::color::Rgb; use crate::emoji; -use crate::vm::avatar; -use crate::vm::bbcode::{self, BlockKind, Doc, Span, Style}; +use crate::image::ImageRef; /// Lines of the same author within this time are grouped (no header). const GROUP_MS: i64 = 5 * 60 * 1000; @@ -40,7 +40,7 @@ pub struct LineCtx<'a> { /// The message's handle in its chat. pub key: i32, /// The author's avatar picture. - pub avatar: Image, + pub avatar: ImageRef, /// The gateway takes reactions and pins for this chat. pub gateway: bool, /// Highlighted (jumped to from the pins). @@ -50,7 +50,7 @@ pub struct LineCtx<'a> { /// The state of the downloads started from this message, by link index. pub downloads: Vec<(usize, FileItem)>, /// Pictures of the links shown inline, by link index. - pub previews: Vec<(usize, Image)>, + pub previews: Vec<(usize, ImageRef)>, /// Pictures on the web in the engine's cache, by address: the `[img]` /// pictures here show as picture cards, the others as links (`None`: /// all as links). @@ -137,7 +137,7 @@ pub fn size_text(bytes: u64) -> String { #[derive(Clone, Default)] struct Body { text: String, - blocks: ModelRc, + blocks: Vec, rich: bool, jumbo: bool, link: String, @@ -152,10 +152,9 @@ struct Read { } /// What lines of a chat were built from, by message id, kept between -/// refreshes: a message whose text, reactions and cards did not change is -/// not read again and gets the same models (they compare by pointer), so -/// its line compares equal and `list::sync` leaves its row. (Not with an -/// empty picture: Slint's empty `Image` equals nothing, not even itself.) +/// refreshes: a message whose text did not change is not read again (its +/// BBCode parsed, its blocks and runs split), and builds the same line, so +/// the list diff leaves its row. #[derive(Default)] pub struct LineCache(RefCell>); @@ -166,8 +165,6 @@ struct Parts { read: Option, /// The body last built, and which pictures were cards then. body: Option<(Vec, Body)>, - reactions: (Vec, ModelRc), - files: (Vec, ModelRc), } impl LineCache { @@ -190,22 +187,6 @@ fn current<'a>(all: &'a mut HashMap, id: i64, rev: i64, text: &str) parts } -/// `rows` as a model: the one in `kept` when they are the same rows. -fn model_of( - rows: Vec, - kept: Option<&mut (Vec, ModelRc)>, -) -> ModelRc { - match kept { - Some((old, model)) if *old == rows => model.clone(), - Some(kept) => { - let model = ModelRc::from(Rc::new(VecModel::from(rows.clone()))); - *kept = (rows, model.clone()); - model - } - None => ModelRc::from(Rc::new(VecModel::from(rows))), - } -} - /// A link to a channel's file, which the chat shows as a card. fn is_file(address: &str) -> bool { FileRef::parse(address).is_some() @@ -236,11 +217,13 @@ pub fn web_pictures(text: &str) -> Vec { /// The colours of a span: the author's made readable on the dark and the /// light theme, or transparent for the text's own. -fn inks(color: Option<[u8; 3]>) -> (Color, Color) { - let rgb = |[r, g, b]: [u8; 3]| Color::from_rgb_u8(r, g, b); +fn inks(color: Option<[u8; 3]>) -> (Option, Option) { match color { - Some(c) => (rgb(bbcode::readable(c, true)), rgb(bbcode::readable(c, false))), - None => (Color::default(), Color::default()), + Some(c) => ( + Some(Rgb::from(bbcode::readable(c, true))), + Some(Rgb::from(bbcode::readable(c, false))), + ), + None => (None, None), } } @@ -251,7 +234,7 @@ fn run( emoji: Option, style: &Style, masked: bool, - inks: (Color, Color), + inks: (Option, Option), ) -> TextRun { TextRun { text: text.into(), @@ -356,11 +339,7 @@ fn blocks_of(doc: &Doc) -> Option<(Vec, bool)> { if count > bbcode::MAX_RUNS { return None; } - blocks.push(TextBlock { - runs: ModelRc::from(Rc::new(VecModel::from(runs))), - kind, - caption: caption.into(), - }); + blocks.push(TextBlock { runs, kind, caption: caption.into() }); } } Some((blocks, any_emoji)) @@ -388,19 +367,13 @@ fn body_of(doc: &Doc, cards: &[bool]) -> Body { let rich = !doc.is_plain() || words.iter().any(|w| w.emoji.is_some()); // Past the runs a line can have: its plain text. match rich.then(|| blocks_of(&doc)).flatten() { - Some((blocks, _)) => Body { - text, - blocks: ModelRc::from(Rc::new(VecModel::from(blocks))), - rich: true, - jumbo, - link, - }, - None => Body { text, blocks: ModelRc::default(), rich: false, jumbo, link }, + Some((blocks, _)) => Body { text, blocks, rich: true, jumbo, link }, + None => Body { text, blocks: Vec::new(), rich: false, jumbo, link }, } } /// The picture at `url`, if the engine has it and it can be shown. -fn picture(pictures: Option<&HashMap>, url: &str) -> Option { +fn picture(pictures: Option<&HashMap>, url: &str) -> Option { let image = avatar::image(pictures?.get(url)); (image.size().width > 0).then_some(image) } @@ -417,7 +390,7 @@ pub fn tab_title(presence: &Presence, target: &ChatTarget, peer: &str) -> String match target { ChatTarget::Channel(cid) => presence.channels.get(cid).map_or_else( || format!("Channel {cid}"), - |c| crate::vm::tree::channel_title(c).0.to_owned(), + |c| crate::tree::channel_title(c).0.to_owned(), ), ChatTarget::Private(_) => format!("@{peer}"), ChatTarget::Server => "Server".into(), @@ -469,7 +442,7 @@ pub fn preview(message: &ChatMessage) -> (String, String) { std::iter::once(read.doc.one_line()).chain(names).collect::>().join(" ") }; // A one-line text cannot show emoji (they are pictures): left out. - let mut text = crate::vm::social::without_emoji(&text); + let mut text = crate::social::without_emoji(&text); if text.is_empty() { text = "sent an emoji".into(); } @@ -560,12 +533,11 @@ fn line_of( && previous.is_some_and(|p| { p.author == message.author_name && (0..GROUP_MS).contains(&(message.ts_ms - p.ts_ms)) }); - let cached = parts.is_some(); let mut own = Parts::default(); let parts = parts.unwrap_or(&mut own); let read = parts.read.get_or_insert_with(|| read(message)); // Pictures on the web that are here are cards, after the files'. - let pictures: Vec> = + let pictures: Vec> = read.images.iter().map(|url| picture(ctx.pictures, url)).collect(); let shown: Vec = pictures.iter().map(Option::is_some).collect(); let body = match &parts.body { @@ -612,8 +584,6 @@ fn line_of( }); } } - let files = model_of(cards, cached.then_some(&mut parts.files)); - let reactions = model_of(reactions, cached.then_some(&mut parts.reactions)); ChatLine { key: ctx.key, author: message.author_name.clone().into(), @@ -629,7 +599,7 @@ fn line_of( blocked: message.blocked, pinned: false, reactions, - files, + files: cards, remote: false, topic: ctx.topic.clone().into(), marked: ctx.marked, @@ -652,7 +622,7 @@ pub fn is_picture(name: &str) -> bool { #[cfg(test)] mod tests { - use slint::Model; + use crate::image::ImageSource; use voelin_core::HistoryMessage; use voelin_gateway_proto::ReactionCount; use voelin_store::MessageSource; @@ -690,7 +660,7 @@ mod tests { let first = message("Alice", "hi", 1_000_000); let a = line(&first, None); assert!(!a.continued); - assert_eq!(a.initials, "AL"); + assert_eq!(&*a.initials, "AL"); let prev = Previous::of(&first); assert!(line(&message("Alice", "again", 1_060_000), Some(&prev)).continued); assert!(!line(&message("Bob", "me", 1_060_000), Some(&prev)).continued); @@ -744,27 +714,27 @@ mod tests { /// The runs of block `i` of a line, as (text, emoji). fn runs(line: &ChatLine, i: usize) -> Vec { - line.blocks.row_data(i).unwrap().runs.iter().collect() + line.blocks[i].runs.clone() } #[test] fn emoji_runs() { let plain = line(&message("A", "no emoji here\nnor here", 0), None); - assert!(!plain.rich && plain.blocks.row_count() == 0); - assert_eq!(plain.text, "no emoji here\nnor here"); + assert!(!plain.rich && plain.blocks.is_empty()); + assert_eq!(&*plain.text, "no emoji here\nnor here"); let rich = line(&message("A", "gg πŸŽ‰", 0), None); assert!(rich.rich && !rich.jumbo); - assert_eq!(rich.blocks.row_count(), 1); + assert_eq!(rich.blocks.len(), 1); let r = runs(&rich, 0); - assert_eq!((r.len(), r[0].text.as_str(), r[1].emoji.as_str()), (2, "gg ", "1f389")); + assert_eq!((r.len(), r[0].text.as_ref(), r[1].emoji.as_ref()), (2, "gg ", "1f389")); assert!(line(&message("A", "πŸŽ‰", 0), None).jumbo); // Formatting around it: still large. let jumbo = line(&message("A", "[b]πŸŽ‰[/b]", 0), None); assert!(jumbo.rich && jumbo.jumbo); // Lines stay lines with emoji (they were run together). let lines = line(&message("A", "first πŸŽ‰\nsecond", 0), None); - assert_eq!(lines.blocks.row_count(), 2); - assert_eq!(lines.text, "first πŸŽ‰\nsecond"); + assert_eq!(lines.blocks.len(), 2); + assert_eq!(&*lines.text, "first πŸŽ‰\nsecond"); } #[test] @@ -775,10 +745,10 @@ mod tests { let line = line(&message("A", text, 0), None); assert!(line.rich && !line.jumbo); assert_eq!( - line.text, + &*line.text, "Raid at 8, see https://x.org/raid\n> Nova: bring elixirs\nβ€’ one\nβ€’ two\n---\na\n\nb" ); - assert_eq!(line.link, "https://x.org/raid"); + assert_eq!(&*line.link, "https://x.org/raid"); let kinds: Vec<(i32, String)> = line.blocks.iter().map(|b| (b.kind, b.caption.to_string())).collect(); let kind = |k: i32| (k, String::new()); @@ -787,15 +757,15 @@ mod tests { [kind(0), (1, "Nova".into()), kind(3), kind(3), kind(4), kind(2), kind(2), kind(2)] ); let first = runs(&line, 0); - assert!(first[0].bold && first[0].text == "Raid"); + assert!(first[0].bold && &*first[0].text == "Raid"); let eight = first.iter().find(|r| r.text.starts_with('8')).unwrap(); // The author's red, readable on both themes. - assert!(eight.ink_dark.alpha() == 255 && eight.ink_light.alpha() == 255); - assert!(eight.ink_dark.red() > eight.ink_dark.green()); - assert_eq!(first[0].ink_dark.alpha(), 0, "the text's own colour"); + let (dark, light) = (eight.ink_dark.unwrap(), eight.ink_light.unwrap()); + assert!(dark.r() > dark.g() && light.r() > light.g()); + assert_eq!(first[0].ink_dark, None, "the text's own colour"); let address = first.iter().find(|r| !r.link.is_empty()).unwrap(); assert_eq!( - (address.text.as_str(), address.link.as_str()), + (address.text.as_ref(), address.link.as_ref()), ("https://x.org/raid", "https://x.org/raid") ); assert!(!address.masked, "its own address"); @@ -807,10 +777,10 @@ mod tests { // Inline code: one run. let inline = super::line(&message("A", "run [code]/pull 10[/code]", 0), None); let r = runs(&inline, 0); - assert!(r[1].code && r[1].text == "/pull 10"); + assert!(r[1].code && &*r[1].text == "/pull 10"); // Not formatting: plain. let relayed = super::line(&message("A", "[Nova] hi [1]", 0), None); - assert!(!relayed.rich && relayed.text == "[Nova] hi [1]" && relayed.link.is_empty()); + assert!(!relayed.rich && &*relayed.text == "[Nova] hi [1]" && relayed.link.is_empty()); } /// A link whose text is not its address asks before it opens: each of @@ -916,15 +886,15 @@ mod tests { let url = format!("https://x.org/{}", "a".repeat(40)); let line = line(&message("A", &format!("see {url}"), 0), None); let r = runs(&line, 0); - let pieces: Vec<&str> = r[1..].iter().map(|r| r.text.as_str()).collect(); + let pieces: Vec<&str> = r[1..].iter().map(|r| r.text.as_ref()).collect(); assert_eq!(pieces.concat(), url); assert!(pieces.len() == 3 && pieces.iter().all(|p| p.chars().count() <= LONG_WORD)); - assert!(r[1..].iter().all(|r| r.link == url.as_str())); + assert!(r[1..].iter().all(|r| &*r.link == url.as_str())); let code = "cargo build --release --locked -j 1"; let line = super::line(&message("A", &format!("[code]{code}[/code]"), 0), None); let r = runs(&line, 0); assert!(r.len() > 1 && r.iter().all(|r| r.code)); - assert_eq!(r.iter().map(|r| r.text.as_str()).collect::(), code); + assert_eq!(r.iter().map(|r| r.text.as_ref()).collect::(), code); } #[test] @@ -933,9 +903,9 @@ mod tests { let text = format!("loot [img]{url}[/img]"); // Not here (or not fetched): the address, as a link. let link = line(&message("A", &text, 0), None); - assert_eq!(link.files.row_count(), 0); + assert_eq!(link.files.len(), 0); let r = runs(&link, 0); - assert_eq!((r[1].text.as_str(), r[1].link.as_str()), (url, url)); + assert_eq!((r[1].text.as_ref(), r[1].link.as_ref()), (url, url)); // Here: a picture card after the files, and no address. let dir = std::env::temp_dir().join(format!("voelin-chat-picture-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); @@ -951,10 +921,10 @@ mod tests { let stored = stored(message("A", &format!("{text} [URL={file}]plan.pdf[/URL]"), 0)); let ctx = LineCtx { pictures: Some(&pictures), ..Default::default() }; let shown = history_line(&stored, None, &ctx); - assert_eq!(shown.text, "loot"); - assert_eq!(shown.files.row_count(), 2); - let card = shown.files.row_data(1).unwrap(); - assert_eq!((card.name.as_str(), card.index, card.preview.size().width), ("loot.png", 1, 4)); + assert_eq!(&*shown.text, "loot"); + assert_eq!(shown.files.len(), 2); + let card = shown.files[1].clone(); + assert_eq!((card.name.as_ref(), card.index, card.preview.size().width), ("loot.png", 1, 4)); assert_eq!(picture_link(&stored.message, 1).as_deref(), Some(url)); assert_eq!(picture_link(&stored.message, 0), None); assert_eq!(web_pictures(&text), [url]); @@ -962,20 +932,18 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } - /// A line built again from an unchanged message is equal (its models - /// are the same), so `list::sync` leaves its row; a change builds anew. + /// A line built again from an unchanged message is equal (so the list diff + /// leaves its row), with the cache or without; a change builds anew. #[test] fn unchanged_lines_compare_equal() { let cache = LineCache::default(); - // An avatar: an empty picture is never equal. - let avatar = Image::from_rgba8(slint::SharedPixelBuffer::new(1, 1)); + let avatar = ImageSource::rgba(1, 1, vec![0u8; 4]); let ctx = LineCtx { key: 3, avatar, cache: Some(&cache), ..Default::default() }; let mut stored = stored(message("A", "[b]hi[/b] πŸŽ‰", 0)); let first = history_line(&stored, None, &ctx); assert!(first == history_line(&stored, None, &ctx)); - // Without the cache, models are new each time. let plain = LineCtx { key: 3, avatar: ctx.avatar.clone(), ..Default::default() }; - assert!(history_line(&stored, None, &plain) != history_line(&stored, None, &plain)); + assert!(history_line(&stored, None, &plain) == first); stored.reactions[0].count = 3; let reacted = history_line(&stored, None, &ctx); assert!(reacted != first && reacted.blocks == first.blocks); @@ -983,7 +951,7 @@ mod tests { stored.rev = 2; let edited = history_line(&stored, None, &ctx); assert!(edited.blocks != first.blocks); - assert_eq!(edited.text, "edited"); + assert_eq!(&*edited.text, "edited"); cache.keep([], 0); assert_eq!(cache.0.borrow().len(), 1, "few: kept"); } @@ -994,9 +962,9 @@ mod tests { let ctx = LineCtx { key: -1, cache: Some(&cache), ..Default::default() }; let welcome = server_line("Nightfall", "Welcome to [b]Nightfall[/b]!", i64::MIN, false, &ctx); - assert_eq!((welcome.author.as_str(), welcome.time.as_str()), ("Nightfall", "")); + assert_eq!((welcome.author.as_ref(), welcome.time.as_ref()), ("Nightfall", "")); assert!(welcome.rich && !welcome.continued && !welcome.remote && welcome.key == -1); - assert_eq!(welcome.text, "Welcome to Nightfall!"); + assert_eq!(&*welcome.text, "Welcome to Nightfall!"); assert!(server_line("Nightfall", "News", i64::MIN + 1, true, &ctx).continued); } @@ -1005,9 +973,9 @@ mod tests { let ctx = LineCtx { key: 4, gateway: true, ..Default::default() }; let line = history_line(&stored(message("A", "hi", 0)), None, &ctx); assert!(line.pinned && line.remote && line.key == 4); - assert_eq!(line.reactions.row_count(), 1); - let r = line.reactions.row_data(0).unwrap(); - assert_eq!((r.key.as_str(), r.count, r.me), ("1f389", 2, true)); + assert_eq!(line.reactions.len(), 1); + let r = line.reactions[0].clone(); + assert_eq!((r.key.as_ref(), r.count, r.me), ("1f389", 2, true)); // Without a gateway nothing can be pinned or reacted to. let plain = history_line(&stored(message("A", "hi", 0)), None, &LineCtx::default()); assert!(!plain.remote); @@ -1022,10 +990,10 @@ mod tests { format!("here you go {url} πŸŽ‰"), ] { let line = line(&message("A", &text, 0), None); - assert_eq!(line.files.row_count(), 1); - let file = line.files.row_data(0).unwrap(); - assert_eq!((file.name.as_str(), file.detail.as_str()), ("plan.pdf", "2.0 kB")); - assert_eq!(line.text, "here you go πŸŽ‰"); + assert_eq!(line.files.len(), 1); + let file = line.files[0].clone(); + assert_eq!((file.name.as_ref(), file.detail.as_ref()), ("plan.pdf", "2.0 kB")); + assert_eq!(&*line.text, "here you go πŸŽ‰"); assert!(line.rich); } // Only the link: no text. diff --git a/crates/voelin-ui/src/vm/home.rs b/crates/voelin-ui-vm/src/home.rs similarity index 100% rename from crates/voelin-ui/src/vm/home.rs rename to crates/voelin-ui-vm/src/home.rs diff --git a/crates/voelin-ui-vm/src/image.rs b/crates/voelin-ui-vm/src/image.rs index c82067d..e92f464 100644 --- a/crates/voelin-ui-vm/src/image.rs +++ b/crates/voelin-ui-vm/src/image.rs @@ -19,8 +19,15 @@ pub enum ImageSource { None, /// A file of the engine's picture cache (`avatars/`, `icons/`, /// banners): PNG, JPEG, GIF, WebP, BMP, ICO or SVG, told by content, not - /// by name. - File(PathBuf), + /// by name. The engine writes a picture that arrives again into the same + /// file, so the reference carries the file's [`Stamp`]: a changed file is + /// another picture, and a list that shows it redraws the row. + File { + /// Where the file is. + path: PathBuf, + /// 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. @@ -47,7 +54,7 @@ impl fmt::Debug for ImageSource { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::None => f.write_str("None"), - Self::File(path) => f.debug_tuple("File").field(path).finish(), + Self::File { path, .. } => f.debug_tuple("File").field(path).finish(), Self::Rgba { w, h, .. } => write!(f, "Rgba({w}x{h})"), Self::Svg(bytes) => write!(f, "Svg({} bytes)", bytes.len()), Self::Memory { key, bytes } => write!(f, "Memory({key}, {} bytes)", bytes.len()), @@ -55,6 +62,23 @@ impl fmt::Debug for ImageSource { } } +/// What identifies a file's content without reading it: its length and the +/// time it was last written. Both zero for a file that is missing. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Stamp { + len: u64, + modified: Option, +} + +impl Stamp { + /// The stamp of the file at `path`. + pub fn of(path: &Path) -> Self { + std::fs::metadata(path) + .map(|meta| Self { len: meta.len(), modified: meta.modified().ok() }) + .unwrap_or_default() + } +} + /// A picture's size in pixels. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Size { @@ -70,9 +94,11 @@ impl ImageSource { ImageRef::default() } - /// A reference to a file of the picture cache. + /// A reference to a file of the picture cache, as the file is now. pub fn file(path: impl Into) -> ImageRef { - Arc::new(Self::File(path.into())) + let path = path.into(); + let stamp = Stamp::of(&path); + Arc::new(Self::File { path, stamp }) } /// A reference to decoded pixels (`bytes`: `w * h * 4`, red, green, blue, @@ -95,7 +121,7 @@ impl ImageSource { pub fn size(&self) -> Size { match self { Self::None => Size::default(), - Self::File(path) => file_size(path), + Self::File { path, stamp } => file_size(path, *stamp), Self::Rgba { w, h, .. } => Size { width: *w, height: *h }, Self::Svg(bytes) => svg_size(bytes), Self::Memory { bytes, .. } => bytes_size(bytes), @@ -174,7 +200,7 @@ fn svg_size(bytes: &[u8]) -> Size { } /// What a probe of a file found, and what the file was then. -type Probe = ((u64, Option), Size); +type Probe = (Stamp, Size); /// Probed files, so a picture shown in many rows is read once; entries are /// checked against the file's length and time before use. @@ -183,9 +209,10 @@ static PROBES: Mutex>> = Mutex::new(None); /// Probes kept at most; the picture cache is far smaller than this. const MAX_PROBES: usize = 4096; -fn file_size(path: &Path) -> Size { - let Ok(meta) = std::fs::metadata(path) else { return Size::default() }; - let stamp = (meta.len(), meta.modified().ok()); +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) @@ -242,9 +269,14 @@ mod tests { let path = dir.join("1234"); std::fs::write(&path, png(4, 2)).unwrap(); assert_eq!(ImageSource::file(&path).size(), Size { width: 4, height: 2 }); + let before = ImageSource::file(&path); // A changed file is read again. std::fs::write(&path, png(5, 3)).unwrap(); - assert_eq!(ImageSource::file(&path).size(), Size { width: 5, height: 3 }); + let after = ImageSource::file(&path); + assert_eq!(after.size(), Size { width: 5, height: 3 }); + // The same file, another picture: a list redraws the row. + assert_ne!(before, after); + assert_eq!(after, ImageSource::file(&path)); let junk = dir.join("junk"); std::fs::write(&junk, b"not a picture").unwrap(); assert!(ImageSource::file(&junk).is_empty()); diff --git a/crates/voelin-ui-vm/src/lib.rs b/crates/voelin-ui-vm/src/lib.rs index 65297b6..65ba192 100644 --- a/crates/voelin-ui-vm/src/lib.rs +++ b/crates/voelin-ui-vm/src/lib.rs @@ -3,13 +3,22 @@ //! Neither Slint nor GPUI is a dependency; each front end converts these //! types (docs/ui.md, "Two crates"). +pub mod avatar; pub mod bbcode; pub mod bridge; +pub mod chat; pub mod color; pub mod emoji; +pub mod home; pub mod image; pub mod list; +pub mod servers; +pub mod settings; +pub mod social; +pub mod streams; +pub mod studio; pub mod studio_bridge; +pub mod tree; pub use color::Rgb; pub use image::{ImageRef, ImageSource, Size}; diff --git a/crates/voelin-ui/src/vm/servers.rs b/crates/voelin-ui-vm/src/servers.rs similarity index 93% rename from crates/voelin-ui/src/vm/servers.rs rename to crates/voelin-ui-vm/src/servers.rs index c737f31..fe4e8cd 100644 --- a/crates/voelin-ui/src/vm/servers.rs +++ b/crates/voelin-ui-vm/src/servers.rs @@ -1,16 +1,19 @@ //! The server rail, the server dialog, and joining a channel. -use slint::{Color, SharedString}; +use std::sync::Arc; + use voelin_core::{ObserveState, SessionState, VoiceState}; use voelin_model::{ChannelId, ChannelInfo, Presence, ServerLink}; use voelin_store::Bookmark; -use crate::app::{BookmarkForm, ServerItem}; -use crate::vm::avatar; +use crate::avatar; +use crate::bridge::{BookmarkForm, ServerItem}; +use crate::color::Rgb; +use crate::image::ImageRef; /// Restore a known server icon before any session exists. A missing/evicted /// cache file falls back to initials; the bookmark stores no filesystem path. -pub fn cached_icon(bookmark: &Bookmark, cache: &voelin_core::Cache) -> slint::Image { +pub fn cached_icon(bookmark: &Bookmark, cache: &voelin_core::Cache) -> ImageRef { avatar::image(bookmark.server_icon_id().and_then(|id| cache.icon(id)).as_ref()) } @@ -33,7 +36,7 @@ const SERVER_TINTS: [u32; 10] = [ /// when an earlier server has it, it takes the next free one. So no two /// share a colour until there are more servers than colours (then they /// start over), and adding a server leaves the others' colours. -pub fn tints(bookmarks: &[Bookmark]) -> Vec { +pub fn tints(bookmarks: &[Bookmark]) -> Vec { let n = SERVER_TINTS.len(); let mut taken = [false; SERVER_TINTS.len()]; bookmarks @@ -76,8 +79,8 @@ pub fn item( live: bool, detail: String, product: String, - icon: slint::Image, - tint: Color, + icon: ImageRef, + tint: Rgb, ) -> ServerItem { ServerItem { id: bookmark.id as i32, @@ -106,7 +109,7 @@ pub fn form( BookmarkForm { id: bookmark.id as i32, name: if bookmark.name == bookmark.address { - SharedString::new() + "".into() } else { bookmark.name.clone().into() }, @@ -134,7 +137,7 @@ pub struct ConnectTo { /// channel; and the link's privilege key. pub fn connect_to(form: &BookmarkForm, saved: Option<&Bookmark>) -> Option { let saved = saved?; - let given = |text: &SharedString| Some(text.to_string()).filter(|t| !t.is_empty()); + let given = |text: &Arc| Some(text.to_string()).filter(|t| !t.is_empty()); let channel = given(&form.channel); Some(ConnectTo { channel_password: channel.as_ref().and_then(|_| given(&form.channel_password)), @@ -215,7 +218,7 @@ pub fn link_form( mut form: BookmarkForm, default_nickname: &str, ) -> BookmarkForm { - let text = |value: &Option| SharedString::from(value.as_deref().unwrap_or_default()); + let text = |value: &Option| Arc::::from(value.as_deref().unwrap_or_default()); if form.id < 0 { form.address = link.address().into(); } @@ -223,7 +226,7 @@ pub fn link_form( form.nickname = link.nickname.as_deref().unwrap_or(default_nickname).into(); } if let Some(password) = &link.password { - form.server_password = password.into(); + form.server_password = password.as_str().into(); } form.channel = text(&link.channel); form.channel_password = text(&link.channel_password); @@ -302,9 +305,9 @@ mod tests { String::new(), String::new(), cached_icon(&bookmark, &cache), - Color::default(), + Rgb::default(), ); - assert_eq!(server.status.as_str(), "offline"); + assert_eq!(server.status.as_ref(), "offline"); assert_eq!(server.icon.size().width, 4); bookmark.address = "different.test".into(); assert_eq!(cached_icon(&bookmark, &cache).size().width, 0); @@ -328,12 +331,12 @@ mod tests { String::new(), product.into(), Default::default(), - Color::default(), + Rgb::default(), ) }; - assert_eq!(on("TeamSpeak 6").product.as_str(), "TeamSpeak 6"); + assert_eq!(on("TeamSpeak 6").product.as_ref(), "TeamSpeak 6"); // Before the server answered, and for software nobody recognised: none. - assert_eq!(on("").product.as_str(), ""); + assert_eq!(on("").product.as_ref(), ""); } fn named(names: &[&str]) -> Vec { @@ -341,7 +344,7 @@ mod tests { } /// The colour a name picks. - fn own_tint(name: &str, step: usize) -> Color { + fn own_tint(name: &str, step: usize) -> Rgb { let n = SERVER_TINTS.len(); avatar::rgb(SERVER_TINTS[(avatar::name_hash(name) as usize + step) % n]) } @@ -351,7 +354,7 @@ mod tests { let names: Vec = (0..SERVER_TINTS.len()).map(|i| format!("Server {i}")).collect(); let mut bookmarks = named(&names.iter().map(String::as_str).collect::>()); let distinct: std::collections::HashSet<_> = - tints(&bookmarks).iter().map(|t| t.as_argb_encoded()).collect(); + tints(&bookmarks).iter().map(|t| t.0).collect(); assert_eq!(distinct.len(), SERVER_TINTS.len()); // One more starts over with its name's colour. bookmarks.extend(named(&["One more"])); @@ -385,8 +388,8 @@ mod tests { }; let mut state = SessionState::default(); let f = form(&b, None, "pw"); - assert_eq!((f.id, f.name.as_str(), f.address.as_str()), (3, "", "ts.example.test")); - assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Nova", "pw")); + assert_eq!((f.id, f.name.as_ref(), f.address.as_ref()), (3, "", "ts.example.test")); + assert_eq!((f.nickname.as_ref(), f.server_password.as_ref()), ("Nova", "pw")); assert!(!f.connected); for (voice, connected) in [ (VoiceState::Disconnected, false), @@ -402,7 +405,7 @@ mod tests { state.observe = ObserveState::Observing; assert!(!form(&b, Some(&state), "").connected); let named = Bookmark { name: "Nightfall".into(), ..b }; - assert_eq!(form(&named, None, "").name.as_str(), "Nightfall"); + assert_eq!(form(&named, None, "").name.as_ref(), "Nightfall"); } #[test] @@ -568,16 +571,16 @@ mod tests { // A new server: the link's address, nickname and password. let new = BookmarkForm { id: -1, nickname: "Me".into(), ..Default::default() }; let f = link_form(&link, new.clone(), "Me"); - assert_eq!((f.id, f.name.as_str(), f.address.as_str()), (-1, "", "ts.example.org:9988")); - assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Link", "pw")); + assert_eq!((f.id, f.name.as_ref(), f.address.as_ref()), (-1, "", "ts.example.org:9988")); + assert_eq!((f.nickname.as_ref(), f.server_password.as_ref()), ("Link", "pw")); assert_eq!( - (f.channel.as_str(), f.channel_password.as_str(), f.token.as_str()), + (f.channel.as_ref(), f.channel_password.as_ref(), f.token.as_ref()), ("Gaming/Raid Night", "raid", "key") ); let f = link_form(&bare, new, "Me"); - assert_eq!((f.address.as_str(), f.nickname.as_str()), ("ts.example.org", "Me")); + assert_eq!((f.address.as_ref(), f.nickname.as_ref()), ("ts.example.org", "Me")); assert_eq!( - (f.server_password.as_str(), f.channel.as_str(), f.token.as_str()), + (f.server_password.as_ref(), f.channel.as_ref(), f.token.as_ref()), ("", "", "") ); // A saved server keeps its address, name, nickname and password... @@ -591,14 +594,14 @@ mod tests { }; let f = link_form(&bare, saved.clone(), "Me"); assert_eq!( - (f.id, f.name.as_str(), f.address.as_str()), + (f.id, f.name.as_ref(), f.address.as_ref()), (3, "Nightfall", "TS.example.org:9988") ); - assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Nova", "stored")); + assert_eq!((f.nickname.as_ref(), f.server_password.as_ref()), ("Nova", "stored")); // ...the link's password in place of the stored one. let f = link_form(&link, saved, "Me"); - assert_eq!((f.nickname.as_str(), f.server_password.as_str()), ("Nova", "pw")); - assert_eq!((f.channel.as_str(), f.token.as_str()), ("Gaming/Raid Night", "key")); + assert_eq!((f.nickname.as_ref(), f.server_password.as_ref()), ("Nova", "pw")); + assert_eq!((f.channel.as_ref(), f.token.as_ref()), ("Gaming/Raid Night", "key")); } #[test] diff --git a/crates/voelin-ui/src/settings.rs b/crates/voelin-ui-vm/src/settings.rs similarity index 99% rename from crates/voelin-ui/src/settings.rs rename to crates/voelin-ui-vm/src/settings.rs index 8d1c2f0..d271933 100644 --- a/crates/voelin-ui/src/settings.rs +++ b/crates/voelin-ui-vm/src/settings.rs @@ -9,7 +9,7 @@ use voelin_audio::process::NoiseLevel; use voelin_core::settings::{Key, Kind}; use voelin_core::{AudioSettings, TransmitMode}; -use crate::app::AudioForm; +use crate::bridge::AudioForm; /// The window's settings, one value (the `ui` blob of earlier versions). pub static UI: Key = Key::new( diff --git a/crates/voelin-ui/src/vm/social.rs b/crates/voelin-ui-vm/src/social.rs similarity index 93% rename from crates/voelin-ui/src/vm/social.rs rename to crates/voelin-ui-vm/src/social.rs index 9bb6f91..4e4f6f8 100644 --- a/crates/voelin-ui/src/vm/social.rs +++ b/crates/voelin-ui-vm/src/social.rs @@ -4,6 +4,23 @@ //! chats of the home sidebar; pure, so they are tested here. use chrono::{DateTime, Local, NaiveDateTime, TimeZone}; +use voelin_core::HistoryMessage; +use voelin_model::ChatTarget; + +/// A chat of any server. +#[derive(Clone, Debug, PartialEq)] +pub struct ChatRef { + /// The bookmark (session) it belongs to, when known. + pub session: Option, + /// The server's unique id. + pub server_uid: Option, + /// Which chat of the server. + pub target: ChatTarget, + /// Its newest message. + pub last: Option, + /// Messages not read. + pub unread: i32, +} fn local(ts_ms: i64) -> Option { DateTime::from_timestamp_millis(ts_ms).map(|t| t.with_timezone(&Local).naive_local()) @@ -53,7 +70,7 @@ pub fn list_time_at(then: NaiveDateTime, now: NaiveDateTime) -> String { /// Chat text without BBCode (`[b]`, `[URL=…]`, `[/URL]`), on one line. pub fn plain(text: &str) -> String { - without_emoji(&crate::vm::bbcode::parse(text).one_line()) + without_emoji(&crate::bbcode::parse(text).one_line()) } /// Text without emoji, runs of spaces as one: one line of text draws no @@ -76,7 +93,7 @@ fn is_emoji(c: char) -> bool { pub fn preview(text: &str, mine: bool, files: &[voelin_model::FileRef]) -> String { let body = if files.is_empty() { plain(text) } else { String::new() }; let body = if body.is_empty() && !files.is_empty() { - if files.iter().any(|f| crate::vm::chat::is_picture(&f.name)) { + if files.iter().any(|f| crate::chat::is_picture(&f.name)) { "Sent a picture".to_owned() } else { "Sent a file".to_owned() @@ -116,7 +133,7 @@ pub fn poke_message(text: &str) -> String { /// The private chats of the home sidebar, by their index in `chats` /// (newest first): at most `n`, those with unread messages first. -pub fn sidebar_dms(chats: &[crate::messages::ChatRef], n: usize) -> Vec { +pub fn sidebar_dms(chats: &[ChatRef], n: usize) -> Vec { let mut private: Vec = (0..chats.len()) .filter(|&i| matches!(chats[i].target, voelin_model::ChatTarget::Private(_))) .collect(); @@ -133,7 +150,7 @@ pub fn found_channels<'a>( ) -> Vec<(u64, &'a str)> { channels .into_iter() - .filter_map(|c| Some((c.id, crate::vm::tree::listed_title(c)?))) + .filter_map(|c| Some((c.id, crate::tree::listed_title(c)?))) .filter(|(_, title)| matches(query, &[*title])) .collect() } @@ -287,7 +304,7 @@ mod tests { #[test] fn sidebar_chats() { use voelin_model::ChatTarget; - let chat = |target: ChatTarget, unread| crate::messages::ChatRef { + let chat = |target: ChatTarget, unread| ChatRef { session: Some(1), server_uid: None, target, diff --git a/crates/voelin-ui/src/vm/streams.rs b/crates/voelin-ui-vm/src/streams.rs similarity index 90% rename from crates/voelin-ui/src/vm/streams.rs rename to crates/voelin-ui-vm/src/streams.rs index f922a4b..af50de7 100644 --- a/crates/voelin-ui/src/vm/streams.rs +++ b/crates/voelin-ui-vm/src/streams.rs @@ -5,8 +5,8 @@ use std::path::PathBuf; use voelin_core::stream::StreamKind; -use crate::app::StreamItem; -use crate::vm::avatar; +use crate::avatar; +use crate::bridge::StreamItem; /// "Screen", "Window", "Camera"; "" for a kind we do not know. pub fn kind_label(kind: &StreamKind) -> &'static str { @@ -40,6 +40,7 @@ pub fn streamer(name: &str, picture: Option<&PathBuf>) -> StreamItem { #[cfg(test)] mod tests { use super::*; + use crate::Size; #[test] fn kinds_have_labels() { @@ -60,10 +61,10 @@ mod tests { #[test] fn streamers_look_as_in_the_members() { let item = streamer("Nova Star", None); - assert_eq!(item.streamer, "Nova Star"); - assert_eq!(item.initials, "NS"); + assert_eq!(&*item.streamer, "Nova Star"); + assert_eq!(&*item.initials, "NS"); assert_eq!(item.tint, avatar::tint("Nova Star")); - assert_eq!(item.avatar.size(), slint::Image::default().size()); + assert_eq!(item.avatar.size(), Size::default()); assert!(item.id.is_empty() && !item.own && !item.studio); } } diff --git a/crates/voelin-ui/src/vm/studio.rs b/crates/voelin-ui-vm/src/studio.rs similarity index 97% rename from crates/voelin-ui/src/vm/studio.rs rename to crates/voelin-ui-vm/src/studio.rs index 1530bf0..ef07b4a 100644 --- a/crates/voelin-ui/src/vm/studio.rs +++ b/crates/voelin-ui-vm/src/studio.rs @@ -11,7 +11,7 @@ use voelin_core::studio::scene::{ Align, Background, Colour, Crop, Fit, Scene, Scenes, Source, SourceKind, Transform, }; -use crate::app::{StudioAudio, StudioLayer, StudioScene, StudioSource, StudioSourceForm}; +use crate::studio_bridge::{StudioAudio, StudioLayer, StudioScene, StudioSource, StudioSourceForm}; /// The scenes; the live one marked, each with what it shows. pub fn scenes(scenes: &Scenes) -> Vec { @@ -356,7 +356,7 @@ fn transform(form: &StudioSourceForm) -> Result { width: parse_size(&form.width, "width")?, height: parse_size(&form.height, "height")?, scale, - fit: match form.fit.as_str() { + fit: match form.fit.as_ref() { "cover" => Fit::Cover, "stretch" => Fit::Stretch, _ => Fit::Contain, @@ -365,7 +365,7 @@ fn transform(form: &StudioSourceForm) -> Result { } fn background(form: &StudioSourceForm) -> Result { - Ok(match form.background.as_str() { + Ok(match form.background.as_ref() { "blur" => Background::Blur { strength: parse_f32(&form.blur, "blur")?.max(0.0) / 100.0 }, "image" if !form.background_path.trim().is_empty() => { Background::Image { path: form.background_path.trim().into() } @@ -392,7 +392,7 @@ pub fn change(form: &StudioSourceForm, old: &Source) -> Result Result) -> Result { - Ok(match (form.kind.as_str(), old) { + Ok(match (form.kind.as_ref(), old) { ("text", old) => { let (font, backdrop, align, padding) = match old { Some(SourceKind::Text { font, backdrop, align, padding, .. }) => { @@ -454,7 +454,7 @@ pub fn new_source(form: &StudioSourceForm, output: (u32, u32)) -> Result>(), + sources.iter().map(|s| s.name.as_ref()).collect::>(), ["Camera", "Screen"] ); assert!(sources[0].front && !sources[0].back && sources[1].back); @@ -652,7 +652,7 @@ mod tests { assert!(parse_layer(&row("big", "", "800"), &old).is_err()); assert!(parse_layer(&row("1", "", "fast"), &old).is_err()); let rows = layers(&[l]); - assert_eq!((rows[0].scale.as_str(), rows[0].bitrate.as_str()), ("0.5", "800")); + assert_eq!((rows[0].scale.as_ref(), rows[0].bitrate.as_ref()), ("0.5", "800")); let below = next_layer(&[LayerSetting { bitrate: 8_000_000, ..old.clone() }], 8000); assert_eq!((below.scale, below.bitrate), (0.5, 2_000_000)); } @@ -673,8 +673,8 @@ mod tests { ); source.transform = Transform::box_at(10.0, 20.0, 300.0, 100.0); let mut f = form(&source); - assert_eq!(f.text, "Hello\\nthere"); - assert_eq!((f.x.as_str(), f.width.as_str()), ("10", "300")); + assert_eq!(&*f.text, "Hello\\nthere"); + assert_eq!((f.x.as_ref(), f.width.as_ref()), ("10", "300")); assert_eq!(change(&f, &source).unwrap(), SourceChange::default()); f.x = "40".into(); f.opacity = 50.0; diff --git a/crates/voelin-ui/src/vm/tree.rs b/crates/voelin-ui-vm/src/tree.rs similarity index 96% rename from crates/voelin-ui/src/vm/tree.rs rename to crates/voelin-ui-vm/src/tree.rs index 06f23e0..146a569 100644 --- a/crates/voelin-ui/src/vm/tree.rs +++ b/crates/voelin-ui-vm/src/tree.rs @@ -10,9 +10,10 @@ use voelin_model::{ tree_rows, }; -use crate::app::{BadgeItem, MemberItem, TreeItem}; +use crate::avatar; +use crate::bridge::{BadgeItem, MemberItem, TreeItem}; +use crate::image::ImageRef; use crate::settings::ClientPlaybackMap; -use crate::vm::avatar; /// A banner mode as the UI takes it (`TreeItem.banner-mode`). pub fn banner_mode(mode: BannerMode) -> i32 { @@ -24,12 +25,12 @@ pub fn banner_mode(mode: BannerMode) -> i32 { } /// The picture of a banner address, if the engine fetched it. -pub fn banner(pictures: &HashMap, url: Option<&str>) -> slint::Image { +pub fn banner(pictures: &HashMap, url: Option<&str>) -> ImageRef { avatar::image(url.and_then(|u| pictures.get(u))) } /// A badge's picture, if the engine fetched it. -fn badge_icon(pictures: &HashMap, guid: &str) -> slint::Image { +fn badge_icon(pictures: &HashMap, guid: &str) -> ImageRef { avatar::image(badges::icon_url(guid).and_then(|url| pictures.get(&url))) } @@ -79,19 +80,19 @@ pub struct TreeInput<'a> { } impl TreeInput<'_> { - fn avatar(&self, client: &ClientInfo) -> slint::Image { + fn avatar(&self, client: &ClientInfo) -> ImageRef { avatar::image(client.uid.as_ref().and_then(|uid| self.avatars.get(uid))) } /// An icon by id, if the engine fetched it (0: none). - fn icon(&self, id: u32) -> Option { + fn icon(&self, id: u32) -> Option { let path = self.icons.get(&id).filter(|_| id != 0)?; Some(avatar::image(Some(path))).filter(|i| i.size().width > 0) } /// The icons beside a client, as TeamSpeak shows them: its server /// groups' in display order, its channel group's, its own. - fn client_icons(&self, client: &ClientInfo) -> Vec { + fn client_icons(&self, client: &ClientInfo) -> Vec { let groups = self.groups.iter().filter(|g| client.server_groups.contains(&g.id)); let channel_group = self.channel_groups.iter().filter(|g| client.channel_group == Some(g.id)); @@ -105,7 +106,7 @@ impl TreeInput<'_> { /// The pictures of the badges a client shows that arrived, in its /// order; empty slots last. - fn badges(&self, client: &ClientInfo) -> [slint::Image; badges::SHOWN] { + fn badges(&self, client: &ClientInfo) -> [ImageRef; badges::SHOWN] { let mut icons = client .badges .iter() @@ -384,7 +385,7 @@ impl TreeInput<'_> { #[derive(Clone, Default)] struct Section { title: String, - icon: slint::Image, + icon: ImageRef, } /// Rows in sections: each section's first row carries the heading and how @@ -456,7 +457,7 @@ pub fn matching(rows: Vec, filter: &str) -> Vec { pub fn server_members(input: &TreeInput, voice_first: bool) -> Vec { let first = Section { title: if voice_first { "In Voice" } else { "Streaming" }.into(), - icon: slint::Image::default(), + icon: ImageRef::default(), }; let clients = input .presence @@ -596,7 +597,7 @@ mod tests { }; let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new()); let rows = rows(&input(&p, &t, &c, &pb, "", &e)); - let width = |i: &slint::Image| i.size().width; + let width = |i: &ImageRef| i.size().width; let lobby = &rows[0]; assert_eq!((width(&lobby.icon), width(&lobby.banner), lobby.banner_mode), (7, 9, 2)); let alice = &rows[1]; @@ -631,11 +632,11 @@ mod tests { pictures: HashMap::from([picture(0, 3), picture(2, 5), picture(3, 7)]), ..Default::default() }; - let width = |i: &slint::Image| i.size().width; + let width = |i: &ImageRef| i.size().width; let card = badge_items(&guids, &e.pictures); - let names: Vec<_> = card.iter().map(|b| b.name.as_str()).collect(); + let names: Vec<_> = card.iter().map(|b| b.name.as_ref()).collect(); assert_eq!(names, ["20th Anniversary", "Badge", "April Fools!"]); - assert_eq!(card[1].description.as_str(), guids[1]); + assert_eq!(card[1].description.as_ref(), guids[1]); assert_eq!(card.iter().map(|b| width(&b.icon)).collect::>(), [3, 0, 5]); let mut p = presence(); @@ -697,7 +698,7 @@ mod tests { let c = HashSet::new(); let rows = super::rows(&input(&p, &t, &c, &pb, "", &e)); let chess = rows.iter().find(|r| r.is_channel && r.id == 3).unwrap(); - assert_eq!((chess.name.as_str(), chess.spacer), ("[cspacer1]Chess", 0)); + assert_eq!((chess.name.as_ref(), chess.spacer), ("[cspacer1]Chess", 0)); assert_eq!(channel_title(&p.channels[&2]), ("ГамСсы", Some(Spacer::Center))); assert_eq!(channel_title(&p.channels[&3]), ("[cspacer1]Chess", None)); // Lists and pickers leave out what only separates. @@ -737,12 +738,12 @@ mod tests { let (t, c, pb) = (HashSet::from([11]), HashSet::new(), ClientPlaybackMap::new()); let e = Extras::default(); let rows = rows(&input(&p, &t, &c, &pb, "", &e)); - let names: Vec<_> = rows.iter().map(|r| r.name.as_str()).collect(); + let names: Vec<_> = rows.iter().map(|r| r.name.as_ref()).collect(); assert_eq!(names, ["Lobby", "Alice", "Games", "bob", "Chess", "Carol"]); assert_eq!((rows[0].members, rows[0].max_members), (1, -1)); assert_eq!((rows[2].members, rows[2].max_members, rows[2].own), (1, 5, true)); assert!(rows[3].talking && rows[3].myself); - assert_eq!(rows[3].initials, "BO"); + assert_eq!(&*rows[3].initials, "BO"); assert_eq!(stats(&p), "3 online Β· 3 channels"); } @@ -752,7 +753,7 @@ mod tests { let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new()); let e = Extras::default(); let rows = rows(&input(&p, &t, &c, &pb, "car", &e)); - let names: Vec<_> = rows.iter().map(|r| r.name.as_str()).collect(); + let names: Vec<_> = rows.iter().map(|r| r.name.as_ref()).collect(); assert_eq!(names, ["Games", "Chess", "Carol"]); let rows = super::rows(&input(&p, &t, &c, &pb, "LOBBY", &e)); assert_eq!(rows.len(), 1); @@ -766,7 +767,7 @@ mod tests { let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new()); let e = Extras::default(); let members = members(&input(&p, &t, &c, &pb, "", &e)); - let names: Vec<_> = members.iter().map(|m| (m.name.as_str(), m.status.as_str())).collect(); + let names: Vec<_> = members.iter().map(|m| (m.name.as_ref(), m.status.as_ref())).collect(); assert_eq!(names, [("bob", "Listening"), ("Carol", "Away")]); } @@ -790,7 +791,7 @@ mod tests { let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new()); let members = members(&input(&p, &t, &c, &pb, "", &e)); let rows: Vec<_> = - members.iter().map(|m| (m.name.as_str(), m.group.as_str(), m.first_in_group)).collect(); + members.iter().map(|m| (m.name.as_ref(), m.group.as_ref(), m.first_in_group)).collect(); assert_eq!(rows, [("Carol", "Server Admin", true), ("bob", "Guest", true)]); assert!(members[0].admin && !members[1].admin); } @@ -884,12 +885,14 @@ mod tests { ] ); let all = server_members(&input(&p, &t, &c, &pb, "", &e), false); - assert_eq!(all[1].role, "Moderator"); + assert_eq!(&*all[1].role, "Moderator"); assert!(!all[1].admin); // The search keeps the sections of what it finds. let found = matching(all, "al"); assert_eq!(found.len(), 1); - assert!(found[0].first_in_group && found[0].group == "Guest" && found[0].group_count == 1); + assert!( + found[0].first_in_group && &*found[0].group == "Guest" && found[0].group_count == 1 + ); } #[test] diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 8007559..60aa8b0 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -38,6 +38,7 @@ use crate::settings::{ }; use crate::streams::{Share, Watch}; use crate::video::Video; +use crate::vm; use crate::vm::chat::Previous; slint::include_modules!(); @@ -131,7 +132,7 @@ pub(crate) struct Msg { pub(crate) struct Tab { pub target: ChatTarget, pub title: String, - pub lines: Rc>, + pub lines: Rows, /// The messages, oldest first, by `(ts_ms, id)`. pub messages: Vec, /// Live messages of a session that keeps no history (no server unique @@ -175,7 +176,7 @@ impl Tab { Self { target, title, - lines: Rc::new(VecModel::default()), + lines: Rows::default(), messages: Vec::new(), last: None, unread: 0, @@ -462,77 +463,75 @@ impl SessionView { } /// The server's icon, if it has one and the engine fetched it. - pub fn server_icon(&self) -> slint::Image { - crate::vm::avatar::image( - self.icons.get(&self.server_icon).filter(|_| self.server_icon != 0), - ) + pub fn server_icon(&self) -> vm::ImageRef { + vm::avatar::image(self.icons.get(&self.server_icon).filter(|_| self.server_icon != 0)) } /// Icons stay associated with the address that supplied them, including /// while a reconnect to an edited bookmark is pending or has failed. - pub fn server_icon_for(&self, address: &str) -> slint::Image { + pub fn server_icon_for(&self, address: &str) -> vm::ImageRef { if self.icon_address.as_deref() == Some(address) { self.server_icon() } else { - slint::Image::default() + vm::ImageRef::default() } } } /// The models the Bridge shows, created once and updated row by row -/// (`vm::list::sync`). +/// ([`Rows::sync`]). pub(crate) struct Models { - pub servers: Rc>, - pub tree: Rc>, - pub members: Rc>, - pub server_members: Rc>, + pub servers: Rows, + pub tree: Rows, + pub members: Rows, + pub server_members: Rows, /// The chat strip: the current session's tabs without its private chats. - pub tabs: Rc>, + pub tabs: Rows, /// Which of the session's tabs each of `tabs` is ([`crate::vm::chat::strip`]). pub strip: RefCell>, - pub streams: Rc>, - pub viewers: Rc>, - pub pins: Rc>, - pub topics: Rc>, - pub topic_messages: Rc>, + pub streams: Rows, + pub viewers: Rows, + pub pins: Rows, + pub topics: Rows, + pub topic_messages: Rows, /// The quality choices of the watched stream. pub qualities: Rows>, /// Shown when there is no chat. - pub no_chat: Rc>, + pub no_chat: Rows, /// Home, friends, messages, the bell, the search, events. pub social: crate::social::SocialModels, /// Settings pages. - pub layers: Rc>, - pub audio_sources: Rc>, - pub identities: Rc>, - pub gateway_config: Rc>, - pub gateway_perms: Rc>, - pub all_settings: Rc>, + pub layers: Rows, + pub audio_sources: Rows, + pub identities: Rows, + pub gateway_config: Rows, + pub gateway_perms: Rows, + pub all_settings: Rows, } impl Models { fn new(bridge: &Bridge) -> Self { let models = Self { - servers: Rc::default(), - tree: Rc::default(), - members: Rc::default(), - server_members: Rc::default(), - tabs: Rc::default(), + servers: Rows::default(), + tree: Rows::default(), + members: Rows::default(), + server_members: Rows::default(), + tabs: Rows::default(), strip: RefCell::new(vec![0]), - streams: Rc::default(), - viewers: Rc::default(), - pins: Rc::default(), - topics: Rc::default(), - topic_messages: Rc::default(), + streams: Rows::default(), + viewers: Rows::default(), + pins: Rows::default(), + topics: Rows::default(), + topic_messages: Rows::default(), qualities: Rows::default(), - no_chat: Rc::default(), + no_chat: Rows::default(), social: crate::social::SocialModels::new(bridge), - layers: Rc::default(), - audio_sources: Rc::default(), - identities: Rc::default(), - gateway_config: Rc::default(), - gateway_perms: Rc::default(), - all_settings: Rc::default(), + layers: Rows::default(), + audio_sources: Rows::default(), + identities: Rows::default(), + gateway_config: Rows::default(), + gateway_perms: Rows::default(), + all_settings: Rows::default(), }; models.attach(bridge); models @@ -541,24 +540,24 @@ impl Models { /// Show the models in `bridge`: the main window's, and the viewer's own /// window's (its player reads the stream's qualities). pub(crate) fn attach(&self, bridge: &Bridge) { - bridge.set_servers(ModelRc::from(self.servers.clone())); - bridge.set_tree(ModelRc::from(self.tree.clone())); - bridge.set_members(ModelRc::from(self.members.clone())); - bridge.set_server_members(ModelRc::from(self.server_members.clone())); - bridge.set_tabs(ModelRc::from(self.tabs.clone())); - bridge.set_streams(ModelRc::from(self.streams.clone())); - bridge.set_share_viewers(ModelRc::from(self.viewers.clone())); - bridge.set_pins(ModelRc::from(self.pins.clone())); - bridge.set_topics(ModelRc::from(self.topics.clone())); - bridge.set_topic_messages(ModelRc::from(self.topic_messages.clone())); + bridge.set_servers(self.servers.model()); + bridge.set_tree(self.tree.model()); + bridge.set_members(self.members.model()); + bridge.set_server_members(self.server_members.model()); + bridge.set_tabs(self.tabs.model()); + bridge.set_streams(self.streams.model()); + bridge.set_share_viewers(self.viewers.model()); + bridge.set_pins(self.pins.model()); + bridge.set_topics(self.topics.model()); + bridge.set_topic_messages(self.topic_messages.model()); bridge.set_viewer_qualities(self.qualities.model()); - bridge.set_messages(ModelRc::from(self.no_chat.clone())); - bridge.set_layers(ModelRc::from(self.layers.clone())); - bridge.set_audio_sources(ModelRc::from(self.audio_sources.clone())); - bridge.set_identities(ModelRc::from(self.identities.clone())); - bridge.set_gateway_config(ModelRc::from(self.gateway_config.clone())); - bridge.set_gateway_perms(ModelRc::from(self.gateway_perms.clone())); - bridge.set_all_settings(ModelRc::from(self.all_settings.clone())); + bridge.set_messages(self.no_chat.model()); + bridge.set_layers(self.layers.model()); + bridge.set_audio_sources(self.audio_sources.model()); + bridge.set_identities(self.identities.model()); + bridge.set_gateway_config(self.gateway_config.model()); + bridge.set_gateway_perms(self.gateway_perms.model()); + bridge.set_all_settings(self.all_settings.model()); } } diff --git a/crates/voelin-ui/src/appearance.rs b/crates/voelin-ui/src/appearance.rs index 310e4aa..478d7c5 100644 --- a/crates/voelin-ui/src/appearance.rs +++ b/crates/voelin-ui/src/appearance.rs @@ -6,12 +6,13 @@ use slint::ComponentHandle; use tracing::warn; -use crate::app::{App, AppearanceForm, Bridge, Nav, Theme}; +use crate::app::{App, Bridge, Nav, Theme}; use crate::images; use crate::settings::{ ThemeChoice, UI_FONT_SCALE, UI_IMAGE_CACHE_MB, UI_MEMBERS_WIDTH, UI_NARROW_BREAKPOINT, UI_THEME, UI_VOICE_COMPACT, }; +use crate::vm::bridge::AppearanceForm; impl App { /// Show the current values of the appearance keys. @@ -33,12 +34,15 @@ impl App { } nav.set_voice_compact(self.prefs.get(&UI_VOICE_COMPACT)); let bridge = ui.global::(); - bridge.set_appearance(AppearanceForm { - theme: theme.as_str().into(), - font_scale: scale, - narrow_breakpoint: breakpoint as f32, - image_cache_mb: cache_mb as f32, - }); + bridge.set_appearance( + AppearanceForm { + theme: theme.as_str().into(), + font_scale: scale, + narrow_breakpoint: breakpoint as f32, + image_cache_mb: cache_mb as f32, + } + .into(), + ); bridge.set_image_cache_usage(images::usage_text().into()); self.theme_windows(); } diff --git a/crates/voelin-ui/src/bind/convert.rs b/crates/voelin-ui/src/bind/convert.rs index 1392655..3cddcbb 100644 --- a/crates/voelin-ui/src/bind/convert.rs +++ b/crates/voelin-ui/src/bind/convert.rs @@ -36,7 +36,7 @@ pub(crate) fn unink(c: Color) -> Option { pub(crate) fn image(picture: &ImageRef) -> Image { match &**picture { ImageSource::None => Image::default(), - ImageSource::File(path) => crate::images::file(path), + ImageSource::File { path, .. } => crate::images::file(path), ImageSource::Rgba { w, h, bytes } => { Image::from_rgba8(SharedPixelBuffer::::clone_from_slice(bytes, *w, *h)) } diff --git a/crates/voelin-ui/src/bind/convert/items.rs b/crates/voelin-ui/src/bind/convert/items.rs index 569bf99..f0dc0c2 100644 --- a/crates/voelin-ui/src/bind/convert/items.rs +++ b/crates/voelin-ui/src/bind/convert/items.rs @@ -32,6 +32,12 @@ impl From<&vm::ServerItem> for ServerItem { } } +impl From for ServerItem { + fn from(v: vm::ServerItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::ServerItem { type Shown = ServerItem; @@ -76,6 +82,12 @@ impl From<&vm::TreeItem> for TreeItem { } } +impl From for TreeItem { + fn from(v: vm::TreeItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::TreeItem { type Shown = TreeItem; @@ -117,6 +129,12 @@ impl From<&vm::MemberItem> for MemberItem { } } +impl From for MemberItem { + fn from(v: vm::MemberItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::MemberItem { type Shown = MemberItem; @@ -135,6 +153,12 @@ impl From<&vm::BadgeItem> for BadgeItem { } } +impl From for BadgeItem { + fn from(v: vm::BadgeItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::BadgeItem { type Shown = BadgeItem; @@ -168,6 +192,12 @@ impl From<&vm::MemberCard> for MemberCard { } } +impl From for MemberCard { + fn from(v: vm::MemberCard) -> Self { + Self::from(&v) + } +} + impl Row for vm::MemberCard { type Shown = MemberCard; @@ -193,6 +223,12 @@ impl From<&vm::ChatTab> for ChatTab { } } +impl From for ChatTab { + fn from(v: vm::ChatTab) -> Self { + Self::from(&v) + } +} + impl Row for vm::ChatTab { type Shown = ChatTab; @@ -219,6 +255,12 @@ impl From<&vm::TextRun> for TextRun { } } +impl From for TextRun { + fn from(v: vm::TextRun) -> Self { + Self::from(&v) + } +} + impl Row for vm::TextRun { type Shown = TextRun; @@ -251,6 +293,12 @@ impl From<&vm::TextBlock> for TextBlock { } } +impl From for TextBlock { + fn from(v: vm::TextBlock) -> Self { + Self::from(&v) + } +} + impl Row for vm::TextBlock { type Shown = TextBlock; @@ -276,6 +324,12 @@ impl From<&vm::ReactionItem> for ReactionItem { } } +impl From for ReactionItem { + fn from(v: vm::ReactionItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::ReactionItem { type Shown = ReactionItem; @@ -309,6 +363,12 @@ impl From<&vm::FileItem> for FileItem { } } +impl From for FileItem { + fn from(v: vm::FileItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::FileItem { type Shown = FileItem; @@ -344,6 +404,12 @@ impl From<&vm::ChatLine> for ChatLine { } } +impl From for ChatLine { + fn from(v: vm::ChatLine) -> Self { + Self::from(&v) + } +} + impl Row for vm::ChatLine { type Shown = ChatLine; @@ -358,6 +424,12 @@ impl From<&vm::PinItem> for PinItem { } } +impl From for PinItem { + fn from(v: vm::PinItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::PinItem { type Shown = PinItem; @@ -380,6 +452,12 @@ impl From<&vm::TopicItem> for TopicItem { } } +impl From for TopicItem { + fn from(v: vm::TopicItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::TopicItem { type Shown = TopicItem; @@ -418,6 +496,12 @@ impl From<&vm::BookmarkForm> for BookmarkForm { } } +impl From for BookmarkForm { + fn from(v: vm::BookmarkForm) -> Self { + Self::from(&v) + } +} + impl Row for vm::BookmarkForm { type Shown = BookmarkForm; @@ -464,6 +548,12 @@ impl From<&vm::StreamItem> for StreamItem { } } +impl From for StreamItem { + fn from(v: vm::StreamItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::StreamItem { type Shown = StreamItem; @@ -484,6 +574,12 @@ impl From<&vm::ViewerItem> for ViewerItem { } } +impl From for ViewerItem { + fn from(v: vm::ViewerItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::ViewerItem { type Shown = ViewerItem; @@ -498,6 +594,12 @@ impl From<&vm::SourceItem> for SourceItem { } } +impl From for SourceItem { + fn from(v: vm::SourceItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::SourceItem { type Shown = SourceItem; @@ -527,6 +629,12 @@ impl From<&vm::ShareForm> for ShareForm { } } +impl From for ShareForm { + fn from(v: vm::ShareForm) -> Self { + Self::from(&v) + } +} + impl Row for vm::ShareForm { type Shown = ShareForm; @@ -568,6 +676,12 @@ impl From<&vm::AudioForm> for AudioForm { } } +impl From for AudioForm { + fn from(v: vm::AudioForm) -> Self { + Self::from(&v) + } +} + impl Row for vm::AudioForm { type Shown = AudioForm; @@ -606,6 +720,12 @@ impl From<&vm::ClientAudio> for ClientAudio { } } +impl From for ClientAudio { + fn from(v: vm::ClientAudio) -> Self { + Self::from(&v) + } +} + impl Row for vm::ClientAudio { type Shown = ClientAudio; @@ -637,6 +757,12 @@ impl From<&vm::AppearanceForm> for AppearanceForm { } } +impl From for AppearanceForm { + fn from(v: vm::AppearanceForm) -> Self { + Self::from(&v) + } +} + impl Row for vm::AppearanceForm { type Shown = AppearanceForm; @@ -682,6 +808,12 @@ impl From<&vm::ContactItem> for ContactItem { } } +impl From for ContactItem { + fn from(v: vm::ContactItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::ContactItem { type Shown = ContactItem; @@ -710,6 +842,12 @@ impl From<&vm::LiveItem> for LiveItem { } } +impl From for LiveItem { + fn from(v: vm::LiveItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::LiveItem { type Shown = LiveItem; @@ -738,6 +876,12 @@ impl From<&vm::ConversationItem> for ConversationItem { } } +impl From for ConversationItem { + fn from(v: vm::ConversationItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::ConversationItem { type Shown = ConversationItem; @@ -762,6 +906,12 @@ impl From<&vm::NoticeItem> for NoticeItem { } } +impl From for NoticeItem { + fn from(v: vm::NoticeItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::NoticeItem { type Shown = NoticeItem; @@ -784,6 +934,12 @@ impl From<&vm::SearchItem> for SearchItem { } } +impl From for SearchItem { + fn from(v: vm::SearchItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::SearchItem { type Shown = SearchItem; @@ -806,6 +962,12 @@ impl From<&vm::HappeningItem> for HappeningItem { } } +impl From for HappeningItem { + fn from(v: vm::HappeningItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::HappeningItem { type Shown = HappeningItem; @@ -844,6 +1006,12 @@ impl From<&vm::ResumeItem> for ResumeItem { } } +impl From for ResumeItem { + fn from(v: vm::ResumeItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::ResumeItem { type Shown = ResumeItem; @@ -878,6 +1046,12 @@ impl From<&vm::EventItem> for EventItem { } } +impl From for EventItem { + fn from(v: vm::EventItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::EventItem { type Shown = EventItem; @@ -928,6 +1102,12 @@ impl From<&vm::EventForm> for EventForm { } } +impl From for EventForm { + fn from(v: vm::EventForm) -> Self { + Self::from(&v) + } +} + impl Row for vm::EventForm { type Shown = EventForm; @@ -963,6 +1143,12 @@ impl From<&vm::OfflineForm> for OfflineForm { } } +impl From for OfflineForm { + fn from(v: vm::OfflineForm) -> Self { + Self::from(&v) + } +} + impl Row for vm::OfflineForm { type Shown = OfflineForm; @@ -1018,6 +1204,12 @@ impl From<&vm::DmPeer> for DmPeer { } } +impl From for DmPeer { + fn from(v: vm::DmPeer) -> Self { + Self::from(&v) + } +} + impl Row for vm::DmPeer { type Shown = DmPeer; @@ -1043,6 +1235,12 @@ impl From<&vm::IdentityItem> for IdentityItem { } } +impl From for IdentityItem { + fn from(v: vm::IdentityItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::IdentityItem { type Shown = IdentityItem; @@ -1081,6 +1279,12 @@ impl From<&vm::FoundIdentity> for FoundIdentity { } } +impl From for FoundIdentity { + fn from(v: vm::FoundIdentity) -> Self { + Self::from(&v) + } +} + impl Row for vm::FoundIdentity { type Shown = FoundIdentity; @@ -1108,6 +1312,12 @@ impl From<&vm::BookmarkIdentity> for BookmarkIdentity { } } +impl From for BookmarkIdentity { + fn from(v: vm::BookmarkIdentity) -> Self { + Self::from(&v) + } +} + impl Row for vm::BookmarkIdentity { type Shown = BookmarkIdentity; @@ -1140,6 +1350,12 @@ impl From<&vm::VideoForm> for VideoForm { } } +impl From for VideoForm { + fn from(v: vm::VideoForm) -> Self { + Self::from(&v) + } +} + impl Row for vm::VideoForm { type Shown = VideoForm; @@ -1178,6 +1394,12 @@ impl From<&vm::LayerItem> for LayerItem { } } +impl From for LayerItem { + fn from(v: vm::LayerItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::LayerItem { type Shown = LayerItem; @@ -1210,6 +1432,12 @@ impl From<&vm::AudioSourceItem> for AudioSourceItem { } } +impl From for AudioSourceItem { + fn from(v: vm::AudioSourceItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::AudioSourceItem { type Shown = AudioSourceItem; @@ -1244,6 +1472,12 @@ impl From<&vm::StreamingForm> for StreamingForm { } } +impl From for StreamingForm { + fn from(v: vm::StreamingForm) -> Self { + Self::from(&v) + } +} + impl Row for vm::StreamingForm { type Shown = StreamingForm; @@ -1278,6 +1512,12 @@ impl From<&vm::NotifyForm> for NotifyForm { } } +impl From for NotifyForm { + fn from(v: vm::NotifyForm) -> Self { + Self::from(&v) + } +} + impl Row for vm::NotifyForm { type Shown = NotifyForm; @@ -1304,6 +1544,12 @@ impl From<&vm::PrivacyForm> for PrivacyForm { } } +impl From for PrivacyForm { + fn from(v: vm::PrivacyForm) -> Self { + Self::from(&v) + } +} + impl Row for vm::PrivacyForm { type Shown = PrivacyForm; @@ -1331,6 +1577,12 @@ impl From<&vm::GatewayItem> for GatewayItem { } } +impl From for GatewayItem { + fn from(v: vm::GatewayItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::GatewayItem { type Shown = GatewayItem; @@ -1365,6 +1617,12 @@ impl From<&vm::ConfigItem> for ConfigItem { } } +impl From for ConfigItem { + fn from(v: vm::ConfigItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::ConfigItem { type Shown = ConfigItem; @@ -1399,6 +1657,12 @@ impl From<&vm::PermItem> for PermItem { } } +impl From for PermItem { + fn from(v: vm::PermItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::PermItem { type Shown = PermItem; @@ -1433,6 +1697,12 @@ impl From<&vm::EncoderItem> for EncoderItem { } } +impl From for EncoderItem { + fn from(v: vm::EncoderItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::EncoderItem { type Shown = EncoderItem; @@ -1465,6 +1735,12 @@ impl From<&vm::SettingItem> for SettingItem { } } +impl From for SettingItem { + fn from(v: vm::SettingItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::SettingItem { type Shown = SettingItem; @@ -1495,6 +1771,12 @@ impl From<&vm::RecordingItem> for RecordingItem { } } +impl From for RecordingItem { + fn from(v: vm::RecordingItem) -> Self { + Self::from(&v) + } +} + impl Row for vm::RecordingItem { type Shown = RecordingItem; @@ -1535,6 +1817,12 @@ impl From<&vm::AdvancedForm> for AdvancedForm { } } +impl From for AdvancedForm { + fn from(v: vm::AdvancedForm) -> Self { + Self::from(&v) + } +} + impl Row for vm::AdvancedForm { type Shown = AdvancedForm; @@ -1577,6 +1865,12 @@ impl From<&vm::AccountForm> for AccountForm { } } +impl From for AccountForm { + fn from(v: vm::AccountForm) -> Self { + Self::from(&v) + } +} + impl Row for vm::AccountForm { type Shown = AccountForm; @@ -1608,6 +1902,12 @@ impl From<&vm::EmojiCell> for EmojiCell { } } +impl From for EmojiCell { + fn from(v: vm::EmojiCell) -> Self { + Self::from(&v) + } +} + impl Row for vm::EmojiCell { type Shown = EmojiCell; @@ -1632,6 +1932,12 @@ impl From<&vm::EmojiRow> for EmojiRow { } } +impl From for EmojiRow { + fn from(v: vm::EmojiRow) -> Self { + Self::from(&v) + } +} + impl Row for vm::EmojiRow { type Shown = EmojiRow; @@ -1658,6 +1964,12 @@ impl From<&studio::StudioScene> for StudioScene { } } +impl From for StudioScene { + fn from(v: studio::StudioScene) -> Self { + Self::from(&v) + } +} + impl Row for studio::StudioScene { type Shown = StudioScene; @@ -1695,6 +2007,12 @@ impl From<&studio::StudioSource> for StudioSource { } } +impl From for StudioSource { + fn from(v: studio::StudioSource) -> Self { + Self::from(&v) + } +} + impl Row for studio::StudioSource { type Shown = StudioSource; @@ -1734,6 +2052,12 @@ impl From<&studio::StudioAudio> for StudioAudio { } } +impl From for StudioAudio { + fn from(v: studio::StudioAudio) -> Self { + Self::from(&v) + } +} + impl Row for studio::StudioAudio { type Shown = StudioAudio; @@ -1768,6 +2092,12 @@ impl From<&studio::StudioLayer> for StudioLayer { } } +impl From for StudioLayer { + fn from(v: studio::StudioLayer) -> Self { + Self::from(&v) + } +} + impl Row for studio::StudioLayer { type Shown = StudioLayer; @@ -1798,6 +2128,12 @@ impl From<&studio::StudioViewer> for StudioViewer { } } +impl From for StudioViewer { + fn from(v: studio::StudioViewer) -> Self { + Self::from(&v) + } +} + impl Row for studio::StudioViewer { type Shown = StudioViewer; @@ -1828,6 +2164,12 @@ impl From<&studio::StudioPick> for StudioPick { } } +impl From for StudioPick { + fn from(v: studio::StudioPick) -> Self { + Self::from(&v) + } +} + impl Row for studio::StudioPick { type Shown = StudioPick; @@ -1868,6 +2210,12 @@ impl From<&studio::StudioStatus> for StudioStatus { } } +impl From for StudioStatus { + fn from(v: studio::StudioStatus) -> Self { + Self::from(&v) + } +} + impl Row for studio::StudioStatus { type Shown = StudioStatus; @@ -1924,6 +2272,12 @@ impl From<&studio::StudioForm> for StudioForm { } } +impl From for StudioForm { + fn from(v: studio::StudioForm) -> Self { + Self::from(&v) + } +} + impl Row for studio::StudioForm { type Shown = StudioForm; @@ -1980,6 +2334,12 @@ impl From<&studio::StudioSourceForm> for StudioSourceForm { } } +impl From for StudioSourceForm { + fn from(v: studio::StudioSourceForm) -> Self { + Self::from(&v) + } +} + impl Row for studio::StudioSourceForm { type Shown = StudioSourceForm; @@ -2032,6 +2392,12 @@ impl From<&studio::StudioSettingsForm> for StudioSettingsForm { } } +impl From for StudioSettingsForm { + fn from(v: studio::StudioSettingsForm) -> Self { + Self::from(&v) + } +} + impl Row for studio::StudioSettingsForm { type Shown = StudioSettingsForm; diff --git a/crates/voelin-ui/src/bind/pages.rs b/crates/voelin-ui/src/bind/pages.rs index db8783f..7459314 100644 --- a/crates/voelin-ui/src/bind/pages.rs +++ b/crates/voelin-ui/src/bind/pages.rs @@ -33,7 +33,7 @@ pub(super) fn wire(ui: &MainWindow) { }); // Voice & Video. bridge.on_video_changed(|form| { - with_app(|app| app.video_changed(&form)); + with_app(|app| app.video_changed(&form.into())); }); bridge.on_toggle_camera_preview(|| { with_app(|app| app.toggle_camera_preview()); @@ -43,10 +43,10 @@ pub(super) fn wire(ui: &MainWindow) { }); // Streaming. bridge.on_streaming_changed(|form| { - with_app(|app| app.streaming_changed(&form)); + with_app(|app| app.streaming_changed(&form.into())); }); bridge.on_layer_changed(|index, item| { - with_app(|app| app.layer_changed(index, &item)); + with_app(|app| app.layer_changed(index, &item.into())); }); bridge.on_add_layer(|| { with_app(|app| app.add_layer()); @@ -55,7 +55,7 @@ pub(super) fn wire(ui: &MainWindow) { with_app(|app| app.remove_layer(index)); }); bridge.on_audio_source_changed(|index, item| { - with_app(|app| app.audio_source_changed(index, &item)); + with_app(|app| app.audio_source_changed(index, &item.into())); }); bridge.on_add_audio_source(|kind, name| { with_app(|app| app.add_audio_source(&kind, &name)); @@ -65,13 +65,13 @@ pub(super) fn wire(ui: &MainWindow) { }); // Notifications, privacy. bridge.on_notify_changed(|form| { - with_app(|app| app.notify_changed(&form)); + with_app(|app| app.notify_changed(&form.into())); }); bridge.on_test_notification(|| { with_app(|app| app.test_notification()); }); bridge.on_privacy_changed(|form| { - with_app(|app| app.privacy_changed(&form)); + with_app(|app| app.privacy_changed(&form.into())); }); // Integrations. bridge.on_gateway_admin(|session| { @@ -97,7 +97,7 @@ pub(super) fn wire(ui: &MainWindow) { }); // Advanced. bridge.on_advanced_changed(|form| { - with_app(|app| app.advanced_changed(&form)); + with_app(|app| app.advanced_changed(&form.into())); }); bridge.on_srtp_move(|index, by| { with_app(|app| app.srtp_move(index, by)); diff --git a/crates/voelin-ui/src/bind/rows.rs b/crates/voelin-ui/src/bind/rows.rs index 96a9a63..2f5540b 100644 --- a/crates/voelin-ui/src/bind/rows.rs +++ b/crates/voelin-ui/src/bind/rows.rs @@ -4,7 +4,7 @@ //! `VecModel` (views redraw only the rows that changed: a client that //! starts talking is one `set_row_data`). -use std::cell::RefCell; +use std::cell::{Ref, RefCell}; use std::rc::Rc; use std::sync::Arc; @@ -48,6 +48,31 @@ impl Rows { ModelRc::from(self.model.clone()) } + /// The rows now. + pub fn rows(&self) -> Ref<'_, [T]> { + Ref::map(self.rows.borrow(), Vec::as_slice) + } + + /// Row `i` now. + pub fn get(&self, i: usize) -> Option { + self.rows.borrow().get(i).cloned() + } + + /// Change row `i` to `row` if it differs. + pub fn set(&self, i: usize, row: T) { + let mut rows = self.rows.borrow_mut(); + if rows.get(i).is_some_and(|old| *old != row) { + self.model.set_row_data(i, row.show()); + rows[i] = row; + } + } + + /// Append a row. + pub fn push(&self, row: T) { + self.model.push(row.show()); + self.rows.borrow_mut().push(row); + } + /// Make the list `new`, with the fewest row operations. pub fn sync(&self, new: &[T]) -> Changes { let mut rows = self.rows.borrow_mut(); diff --git a/crates/voelin-ui/src/bind/servers.rs b/crates/voelin-ui/src/bind/servers.rs index 54e9558..f237fcf 100644 --- a/crates/voelin-ui/src/bind/servers.rs +++ b/crates/voelin-ui/src/bind/servers.rs @@ -45,17 +45,21 @@ pub(super) fn wire(ui: &MainWindow) { bridge.on_push_to_talk(|on| { with_app(|app| app.command(|session| Command::SetTransmitting { session, on })); }); - bridge.on_edit_bookmark(|id| with_app(|app| app.bookmark_form(id as i64)).unwrap_or_default()); + bridge.on_edit_bookmark(|id| { + with_app(|app| app.bookmark_form(id as i64)).unwrap_or_default().into() + }); bridge.on_save_bookmark(|form| { - with_app(|app| app.save_bookmark(&form)); + with_app(|app| app.save_bookmark(&form.into())); + }); + bridge.on_save_and_connect(|form| { + with_app(|app| app.save_and_connect(&form.into())).unwrap_or(false) }); - bridge.on_save_and_connect(|form| with_app(|app| app.save_and_connect(&form)).unwrap_or(false)); bridge.on_delete_bookmark(|id| { with_app(|app| app.delete_bookmark(id as i64)); }); bridge.on_open_client(|id| with_app(|app| app.open_client(id as u16)).unwrap_or(false)); bridge.on_client_audio_changed(|form| { - with_app(|app| app.client_playback_changed(&form)); + with_app(|app| app.client_playback_changed(&form.into())); }); bridge.on_invite(|| with_app(|app| app.invite_link()).unwrap_or_default().into()); // Nav.copy, from any screen. diff --git a/crates/voelin-ui/src/bind/settings.rs b/crates/voelin-ui/src/bind/settings.rs index 7654074..5b05978 100644 --- a/crates/voelin-ui/src/bind/settings.rs +++ b/crates/voelin-ui/src/bind/settings.rs @@ -13,7 +13,7 @@ pub(super) fn wire(ui: &MainWindow) { with_app(|app| app.close_settings()); }); bridge.on_audio_changed(|form| { - with_app(|app| app.audio_changed(&form)); + with_app(|app| app.audio_changed(&form.into())); }); bridge.on_toggle_mic_test(|| { with_app(|app| app.set_mic_test(!app.mic_test)); @@ -34,7 +34,7 @@ pub(super) fn wire(ui: &MainWindow) { with_app(|app| app.voice_compact_changed(compact)); }); bridge.on_appearance_changed(|form| { - with_app(|app| app.appearance_changed(&form)); + with_app(|app| app.appearance_changed(&form.into())); }); bridge.on_set_crash_reports(|enabled| { with_app(|app| app.set_crash_reports(enabled)); diff --git a/crates/voelin-ui/src/bind/social.rs b/crates/voelin-ui/src/bind/social.rs index 5971719..cb04078 100644 --- a/crates/voelin-ui/src/bind/social.rs +++ b/crates/voelin-ui/src/bind/social.rs @@ -64,7 +64,7 @@ pub(super) fn wire(ui: &MainWindow) { with_app(|app| app.dm_volume(percent)); }); bridge.on_send_offline(|form| { - with_app(|app| app.send_offline(form)); + with_app(|app| app.send_offline(form.into())); }); // The bell. @@ -97,8 +97,10 @@ pub(super) fn wire(ui: &MainWindow) { bridge.on_toggle_event(|id| { with_app(|app| app.toggle_event(id)); }); - bridge.on_edit_event(|id| with_app(|app| app.edit_event(id)).unwrap_or_default()); - bridge.on_save_event(|form| with_app(|app| app.save_event(&form)).unwrap_or_default().into()); + bridge.on_edit_event(|id| with_app(|app| app.edit_event(id)).unwrap_or_default().into()); + bridge.on_save_event(|form| { + with_app(|app| app.save_event(&form.into())).unwrap_or_default().into() + }); bridge.on_delete_event(|id| { with_app(|app| app.delete_event(id)); }); diff --git a/crates/voelin-ui/src/bind/streams.rs b/crates/voelin-ui/src/bind/streams.rs index 93b02b9..ed30b87 100644 --- a/crates/voelin-ui/src/bind/streams.rs +++ b/crates/voelin-ui/src/bind/streams.rs @@ -4,9 +4,9 @@ use crate::app::{Bridge, with_app}; pub(crate) fn wire(bridge: &Bridge) { - bridge.on_open_share(|| with_app(|app| app.open_share()).unwrap_or_default()); + bridge.on_open_share(|| with_app(|app| app.open_share()).unwrap_or_default().into()); bridge.on_start_share(|form| { - with_app(|app| app.start_share(form)); + with_app(|app| app.start_share(form.into())); }); bridge.on_stop_share(|| { with_app(|app| app.stop_share()); diff --git a/crates/voelin-ui/src/bind/studio.rs b/crates/voelin-ui/src/bind/studio.rs index 4ed0b1c..7ffd743 100644 --- a/crates/voelin-ui/src/bind/studio.rs +++ b/crates/voelin-ui/src/bind/studio.rs @@ -52,13 +52,13 @@ pub(crate) fn wire(bridge: &StudioBridge) { with_app(|app| app.studio_add_picked(index(i))); }); bridge.on_add_source(|form| { - with_app(|app| app.studio_add_source(&form)); + with_app(|app| app.studio_add_source(&form.into())); }); bridge.on_source_form(|source| { - with_app(|app| app.studio_source_form(id(source))).unwrap_or_default() + with_app(|app| app.studio_source_form(id(source))).unwrap_or_default().into() }); bridge.on_apply_source(|form| { - with_app(|app| app.studio_apply_source(&form)); + with_app(|app| app.studio_apply_source(&form.into())); }); bridge.on_toggle_source(|source| { with_app(|app| app.studio_toggle_source(id(source))); @@ -93,7 +93,7 @@ pub(crate) fn wire(bridge: &StudioBridge) { with_app(|app| app.studio_set_output(&w, &h, &fps)); }); bridge.on_set_layer(|i, layer| { - with_app(|app| app.studio_set_layer(index(i), &layer)); + with_app(|app| app.studio_set_layer(index(i), &layer.into())); }); bridge.on_add_layer(|| { with_app(|app| app.studio_add_layer()); @@ -120,9 +120,10 @@ pub(crate) fn wire(bridge: &StudioBridge) { bridge.on_end_stream(|| { with_app(|app| app.studio_end()); }); - bridge.on_settings_form(|| with_app(|app| app.studio_settings_form()).unwrap_or_default()); + bridge + .on_settings_form(|| with_app(|app| app.studio_settings_form()).unwrap_or_default().into()); bridge.on_apply_settings(|form| { - with_app(|app| app.studio_apply_settings(&form)); + with_app(|app| app.studio_apply_settings(&form.into())); }); bridge.on_respond_viewer(|client, accept| { diff --git a/crates/voelin-ui/src/chat.rs b/crates/voelin-ui/src/chat.rs index 6444c64..35f6aaa 100644 --- a/crates/voelin-ui/src/chat.rs +++ b/crates/voelin-ui/src/chat.rs @@ -6,7 +6,7 @@ //! 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)`, and the lines of -//! the selected tab are rebuilt from them with [`vm::list::sync`], which +//! the selected tab are rebuilt from them and synced ([`Rows::sync`]), which //! touches only the rows that changed. Sessions the engine keeps no history //! for (it does not know the server yet) fall back to [`Event::Chat`]. //! @@ -19,7 +19,7 @@ use std::collections::HashMap; use std::path::PathBuf; -use slint::{ComponentHandle, ModelRc}; +use slint::ComponentHandle; use voelin_core::gateway::Pin; use voelin_core::settings::CACHE_FETCH_IMAGES; use voelin_core::{ @@ -30,10 +30,11 @@ use voelin_gateway_proto::{ErrorCode, TopicInfo, feature}; use voelin_model::{ChatMessage, ChatTarget, HostMessageMode, ServerDetails}; use voelin_store::ChatRead; -use crate::app::{App, Bridge, ChatLine, ChatTab, FileItem, Msg, Nav, PinItem, SessionView, Tab}; +use crate::app::{App, Bridge, Msg, Nav, SessionView, Tab}; use crate::settings::UI_IMAGE_PREVIEW_KB; use crate::vm; use crate::vm::bbcode::LinkKind; +use crate::vm::bridge::{ChatLine, ChatTab, FileItem, PinItem}; use crate::vm::chat::{LineCache, LineCtx, Previous}; /// Where the server's welcome and host message keep what their lines were @@ -466,14 +467,11 @@ impl App { let Some(ui) = self.ui.upgrade() else { return }; let bridge = ui.global::(); let Some(view) = self.view() else { - vm::list::sync( - &self.models.tabs, - &[ChatTab { title: "Server".into(), ..Default::default() }], - ); + self.models.tabs.sync(&[ChatTab { title: "Server".into(), ..Default::default() }]); *self.models.strip.borrow_mut() = vec![0]; bridge.set_current_tab(0); bridge.set_current_chat(0); - let empty = ModelRc::from(self.models.no_chat.clone()); + let empty = self.models.no_chat.model(); if bridge.get_messages() != empty { bridge.set_messages(empty); } @@ -523,7 +521,7 @@ impl App { } }) .collect(); - vm::list::sync(&self.models.tabs, &tabs); + self.models.tabs.sync(&tabs); *self.models.strip.borrow_mut() = strip; if bridge.get_current_tab() != current { bridge.set_current_tab(current); @@ -535,9 +533,9 @@ impl App { if view.has_history() { let lines = self.lines_of(view, tab, true); divider = lines.iter().position(|l| l.unread_start); - vm::list::sync(&tab.lines, &lines); + tab.lines.sync(&lines); } - let lines = ModelRc::from(tab.lines.clone()); + let lines = tab.lines.model(); if bridge.get_messages() != lines { bridge.set_messages(lines); } @@ -586,14 +584,14 @@ impl App { } }) .collect(); - vm::list::sync(&self.models.pins, &pins); + self.models.pins.sync(&pins); let filter = self.topic_filter.trim().to_lowercase(); let now = chrono::Utc::now().timestamp_millis(); - let topics: Vec = tab + let topics: Vec = tab .topics .iter() .filter(|t| filter.is_empty() || t.title.to_lowercase().contains(&filter)) - .map(|t| crate::app::TopicItem { + .map(|t| vm::bridge::TopicItem { id: t.id as i32, title: t.title.clone().into(), creator: t.creator.name.clone().into(), @@ -609,7 +607,7 @@ impl App { archived: t.archived, }) .collect(); - vm::list::sync(&self.models.topics, &topics); + self.models.topics.sync(&topics); bridge.set_current_topic(tab.topic.map_or(-1, |t| t as i32)); bridge.set_topic_title( tab.topic @@ -618,7 +616,7 @@ impl App { .unwrap_or_default() .into(), ); - vm::list::sync(&self.models.topic_messages, &self.lines_of(view, tab, false)); + self.models.topic_messages.sync(&self.lines_of(view, tab, false)); } /// A link in a message was clicked (`masked`: its text shows something diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index 9973194..1a2fd1a 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -83,10 +83,9 @@ use voelin_model::{ }; use voelin_store::{Bookmark, MessageSource}; -use crate::app::{ - App, Bridge, MainWindow, MobileTab, Nav, Page, RecordingItem, SettingsSection, with_app, -}; +use crate::app::{App, Bridge, MainWindow, MobileTab, Nav, Page, SettingsSection, with_app}; use crate::settings::LastVoice; +use crate::vm::bridge::RecordingItem; /// The switches read at start. #[derive(Clone, Debug, Default)] @@ -1195,15 +1194,12 @@ fn demo_social(app: &mut App) { clip: name.contains("clip"), path: format!("/tmp/{name}").into(), }; - crate::vm::list::sync( - &app.models.social.recordings, - &[ - recording("raid-night-2026-10-02.webm", "1.2 GB Β· 2 Oct 22:41"), - recording("clip-boss-down.mkv", "38.4 MB Β· 2 Oct 21:57"), - recording("lands-between-stream.mkv", "2.8 GB Β· 28 Sep 20:12"), - recording("clip-lucky-parry.mkv", "12.1 MB Β· 28 Sep 19:40"), - ], - ); + app.models.social.recordings.sync(&[ + recording("raid-night-2026-10-02.webm", "1.2 GB Β· 2 Oct 22:41"), + recording("clip-boss-down.mkv", "38.4 MB Β· 2 Oct 21:57"), + recording("lands-between-stream.mkv", "2.8 GB Β· 28 Sep 20:12"), + recording("clip-lucky-parry.mkv", "12.1 MB Β· 28 Sep 19:40"), + ]); app.refresh_chats(); app.refresh_people(); app.refresh_home(); diff --git a/crates/voelin-ui/src/events.rs b/crates/voelin-ui/src/events.rs index 4758555..b0232b2 100644 --- a/crates/voelin-ui/src/events.rs +++ b/crates/voelin-ui/src/events.rs @@ -3,13 +3,16 @@ //! home page), our permissions there, its configuration (gateway //! administration). The pins, reactions and topics are in `chat.rs`. +use std::sync::Arc; + use slint::{ComponentHandle, SharedString}; use voelin_core::{Command, GatewayRequest, GatewayUpdate}; use voelin_gateway_proto::{Action, EventKind, EventQuery, EventSpec, RsvpStatus, feature}; -use crate::app::{App, Bridge, EventForm, EventItem}; +use crate::app::{App, Bridge}; use crate::social::{NoticeKind, NoticeTarget, now_ms}; use crate::vm; +use crate::vm::bridge::{EventForm, EventItem}; use crate::vm::social::{date_block, event_when, format_local, parse_local, soon}; impl App { @@ -205,27 +208,26 @@ impl App { editable: moderate || extra.gateway_uid.as_deref() == Some(e.creator.uid.as_str()), soon: soon(e.spec.start_ms, e.spec.end_ms, now).into(), - attendees: crate::app::model( - e.attendees - .iter() - .map(|a| { - let status = match a.status { - RsvpStatus::Going => "going", - RsvpStatus::Maybe => "maybe", - RsvpStatus::NotGoing => "not going", - RsvpStatus::Unknown => "?", - }; - SharedString::from(format!("{} ({status})", a.user.name)) - }) - .collect(), - ), + attendees: e + .attendees + .iter() + .map(|a| { + let status = match a.status { + RsvpStatus::Going => "going", + RsvpStatus::Maybe => "maybe", + RsvpStatus::NotGoing => "not going", + RsvpStatus::Unknown => "?", + }; + Arc::::from(format!("{} ({status})", a.user.name)) + }) + .collect(), expanded: extra.expanded.contains(&e.id), } }) .collect() }) .unwrap_or_default(); - vm::list::sync(&self.models.social.events, &items); + self.models.social.events.sync(&items); } /// Answer an event ("" withdraws the answer). @@ -289,7 +291,7 @@ impl App { } }; let channels = self.event_channels(); - let text = |s: &slint::SharedString| Some(s.to_string()).filter(|s| !s.trim().is_empty()); + let text = |s: &Arc| Some(s.to_string()).filter(|s| !s.trim().is_empty()); let spec = EventSpec { title: form.title.trim().to_owned(), description: form.description.to_string(), diff --git a/crates/voelin-ui/src/home.rs b/crates/voelin-ui/src/home.rs index eeedd70..edf1d4c 100644 --- a/crates/voelin-ui/src/home.rs +++ b/crates/voelin-ui/src/home.rs @@ -9,11 +9,10 @@ use std::path::{Path, PathBuf}; use slint::ComponentHandle; use voelin_core::VoiceState; -use crate::app::{ - App, Bridge, HappeningItem, LiveItem, Page, RecordingItem, ResumeItem, ServerItem, -}; +use crate::app::{App, Bridge, Page}; use crate::settings::LastVoice; use crate::vm; +use crate::vm::bridge::{HappeningItem, LiveItem, RecordingItem, ResumeItem, ServerItem}; use crate::vm::home::ResumeAction; use crate::vm::social::{event_when, plain}; @@ -45,7 +44,7 @@ impl App { let avatar = match (client, uid) { (Some(c), _) if view.avatar(c).is_some() => vm::avatar::image(view.avatar(c)), (_, Some(uid)) => self.avatar_of(uid), - _ => slint::Image::default(), + _ => vm::ImageRef::default(), }; LiveItem { session: b.id as i32, @@ -184,9 +183,9 @@ impl App { /// `refresh_chats`). pub(crate) fn refresh_home(&self) { let m = &self.models.social; - vm::list::sync(&m.live, &self.live_rooms()); + m.live.sync(&self.live_rooms()); let items: Vec = self.happenings().into_iter().map(|(i, _)| i).collect(); - vm::list::sync(&m.happenings, &items); + m.happenings.sync(&items); } /// A live room's card: watch it at once in our channel, else go to its @@ -253,7 +252,7 @@ impl App { icon: server.icon.clone(), channel: resume.title().into(), open: resume.action == ResumeAction::Open, - connecting: server.status == "connecting", + connecting: &*server.status == "connecting", } } @@ -304,7 +303,7 @@ impl App { } let dir = self.recordings_dir(); let items = recordings_in(&dir); - vm::list::sync(&self.models.social.recordings, &items); + self.models.social.recordings.sync(&items); if let Some(ui) = self.ui.upgrade() { ui.global::().set_recordings_dir(dir.display().to_string().into()); } diff --git a/crates/voelin-ui/src/lib.rs b/crates/voelin-ui/src/lib.rs index 53065d3..6bcc099 100644 --- a/crates/voelin-ui/src/lib.rs +++ b/crates/voelin-ui/src/lib.rs @@ -18,17 +18,15 @@ mod messages; mod popout; mod previews; mod servers; -mod settings; mod settings_page; mod settings_pages; mod social; mod streams; mod studio; mod video; -mod vm; -// The Twemoji archive and text splitting live with the view models. -use voelin_ui_vm::emoji; +// The view models live in their own crate; the modules keep their old paths. +use voelin_ui_vm::{self as vm, emoji, settings}; pub use app::{HostedEngine, RunOptions, run}; pub use inbox::{Request, request}; diff --git a/crates/voelin-ui/src/links.rs b/crates/voelin-ui/src/links.rs index 2445e78..82570c3 100644 --- a/crates/voelin-ui/src/links.rs +++ b/crates/voelin-ui/src/links.rs @@ -64,7 +64,7 @@ impl App { let form = vm::servers::link_form(link, form, &self.default_nickname()); let Some(ui) = self.ui.upgrade() else { return }; let nav = ui.global::