Files
VoelinClient/crates/voelin-ui-vm/src/previews.rs
T
faumarayandClaude Sonnet 5.5 03d1c3bd07 Move the state transition of every engine event that the AppState holds into voelin-ui-vm
events::apply(state, host, event) changes the AppState for an engine Event and
returns an Update: the parts to draw again (Refresh, each once), the status
line, the engine commands, what to keep (Persist), pictures to decode again,
the password dialog, notices for the bell, the chats that changed, a stream to
watch. Host is what a transition asks while it runs (is the chat on screen,
the store's read markers, the preview limit); the Slint client answers it in
host.rs and carries the update out there, so App::handle_event is
social_event, apply_event and social_refresh. The chat transitions (tabs,
messages, what is read, pins and topics, files), the pictures linked in
chats, the server's name, icon and gateway, joining again and the password
prompt, the last place of voice and the stored volumes moved with it; Spot,
the notice types, own_uids and peer_name moved to the view model crate.

Update::rest hands back the events whose state is not in the AppState yet
(the streams we share and watch, the studio's stream, a setting that
changed); the friends, pokes and offline messages are still looked at by
social.rs before and after. The vm tests replay tapes of events against a
fake Host.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:30:39 +03:00

173 lines
5.2 KiB
Rust

//! Pictures linked in chat, shown inline: a link to a PNG, JPEG, GIF or
//! WebP file (by name) up to `ui.image_preview_kb` is downloaded into
//! memory once (`Command::DownloadChatFile` with `DownloadTo::Memory`,
//! voice connections only) and the chat shows it as a picture card, and a
//! click opens it larger. A picture on the web a message shows (`[img]`)
//! comes the way banners do, into the engine's cache (`Command::FetchPicture`,
//! up to the same size, only with `cache.fetch_images`), and until it is
//! there the message shows its address.
use std::sync::Arc;
use voelin_core::{Command, DownloadTo, TransferState, VoiceState};
use voelin_model::{ChatTarget, FileRef};
use crate::host::Cx;
use crate::image::{ImageRef, ImageSource};
use crate::state::{AppState, Preview, SessionView};
/// Whether a file name is a picture the chat shows inline.
pub fn is_previewable(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
[".png", ".jpg", ".jpeg", ".gif", ".webp"].iter().any(|e| lower.ends_with(e))
}
/// The key of a link: where the file is.
pub fn link_key(file: &FileRef) -> String {
format!(
"{}/{}{}{}",
file.server_uid.as_deref().unwrap_or(""),
file.channel,
file.path,
file.name
)
}
/// The picture of a link, if it is there and shows.
pub fn image_of<L>(view: &SessionView<L>, file: &FileRef) -> Option<ImageRef> {
let key = link_key(file);
match view.extra.previews.get(&key)? {
Preview::Ready(bytes) => {
let image = Arc::new(ImageSource::Memory { key: key.into(), bytes: bytes.0.clone() });
(!image.is_empty()).then_some(image)
}
_ => None,
}
}
/// Download the pictures linked in the current chat of `session` that are
/// not there yet.
pub fn fetch_previews<L>(state: &mut AppState<L>, cx: &mut Cx<'_>, session: i64) {
if cx.host.demo_ui() {
return;
}
let limit = cx.host.preview_limit();
if limit == 0 {
return;
}
fetch_web_pictures(state, cx, session, limit);
let Some(view) = state.sessions.get_mut(&session) else { return };
if view.state.voice != VoiceState::Connected || !view.capabilities.file_transfer {
return;
}
let Some(tab) = view.tabs.get(view.current_tab) else { return };
// Channel chats only: a link names its channel's file browser.
if matches!(tab.target, ChatTarget::Private(_)) && tab.messages.is_empty() {
return;
}
let wanted: Vec<FileRef> = tab
.messages
.iter()
.rev()
.take(200)
.flat_map(|m| m.message.message.file_refs())
.filter(|f| is_previewable(&f.name) && f.size.is_some_and(|s| s <= limit))
.filter(|f| !view.extra.previews.contains_key(&link_key(f)))
.collect();
for file in wanted {
let transfer = view.next_transfer;
view.next_transfer += 1;
view.extra.previews.insert(link_key(&file), Preview::Loading(transfer));
cx.send(Command::DownloadChatFile {
session: session as u64,
transfer,
file,
password: None,
to: DownloadTo::Memory,
});
}
}
/// Ask the engine for the pictures on the web (`[img]`) of the current chat
/// of `session` that it has not reported; it fetches each once.
fn fetch_web_pictures<L>(state: &AppState<L>, cx: &mut Cx<'_>, session: i64, limit: u64) {
if !cx.host.fetch_images() {
return;
}
let Some(view) = state.sessions.get(&session) else { return };
let Some(tab) = view.tabs.get(view.current_tab) else { return };
// The server chat starts with the server's messages.
let server = match tab.target {
ChatTarget::Server => crate::chat::server_texts(&view.presence.server),
_ => Vec::new(),
};
let wanted: Vec<String> = tab
.messages
.iter()
.rev()
.take(200)
.map(|m| m.message.message.text.as_str())
.chain(server.into_iter().map(|(text, _)| text))
.flat_map(crate::chat::web_pictures)
.filter(|url| !view.pictures.contains_key(url))
.collect();
for url in wanted {
cx.send(Command::FetchPicture { session: session as u64, url, max_bytes: limit });
}
}
/// A transfer of a picture: `true` if it was one.
pub fn preview_progress<L>(
state: &mut AppState<L>,
cx: &mut Cx<'_>,
session: i64,
transfer: u64,
progress: &TransferState,
) -> bool {
let limit = cx.host.preview_limit();
let current = state.current == Some(session);
let Some(view) = state.sessions.get_mut(&session) else { return false };
let Some(key) = view
.extra
.previews
.iter()
.find(|(_, p)| matches!(p, Preview::Loading(t) if *t == transfer))
.map(|(k, _)| k.clone())
else {
return false;
};
match progress {
TransferState::Started { size, .. } if *size > limit => {
view.extra.previews.insert(key, Preview::Failed);
cx.send_real(Command::CancelTransfer { session: session as u64, transfer });
}
TransferState::Done { data: Some(data), .. } => {
view.extra.previews.insert(key, Preview::Ready(data.clone()));
if current {
cx.update.refresh.chat = true;
}
}
TransferState::Done { .. } | TransferState::Failed(_) | TransferState::Cancelled => {
view.extra.previews.insert(key, Preview::Failed);
}
_ => {}
}
true
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn previewable_names() {
assert!(is_previewable("Banner.PNG"));
assert!(is_previewable("a.webp"));
assert!(!is_previewable("notes.svg"));
assert!(!is_previewable("route.pdf"));
let file =
FileRef { channel: 2, path: "/".into(), name: "a.png".into(), ..Default::default() };
assert_eq!(link_key(&file), "/2/a.png");
}
}