//! Shared description frame storage and projection; no window or network effects.
use crate::{DescriptionBlock, DescriptionImage, DescriptionImages, ModsWindow};
use fmm_core::description_images::{APP_MEMORY_CAP, Decoded, layout};
use slint::{ComponentHandle, Image, Model, ModelRc, Rgba8Pixel, SharedPixelBuffer, VecModel};
use std::{collections::HashMap, rc::Rc};
struct Entry {
frames: Rc<VecModel<Image>>,
delays: Rc<VecModel<i32>>,
playhead: Rc<VecModel<i32>>,
frame_bytes: usize,
shown: u64,
}
#[derive(Default)]
pub struct Images {
entries: HashMap<String, Entry>,
pub failed: std::collections::HashSet<String>,
tick: u64,
}
impl Images {
pub fn clear(&mut self) {
for entry in self.entries.values() {
entry.frames.set_vec(Vec::new());
entry.delays.set_vec(Vec::new());
}
self.entries.clear();
self.failed.clear();
}
pub fn contains(&self, url: &str) -> bool {
self.entries.contains_key(url) || self.failed.contains(url)
}
pub fn memory(&self) -> usize {
self.entries
.values()
.map(|e| e.frame_bytes * e.frames.row_count())
.sum()
}
pub fn insert(&mut self, url: String, decoded: Decoded) {
self.insert_with_budget(url, decoded, APP_MEMORY_CAP);
}
pub(crate) fn insert_with_budget(&mut self, url: String, mut decoded: Decoded, budget: usize) {
self.entries.remove(&url);
let Some(first) = decoded.frames.first() else {
self.failed.insert(url);
return;
};
let frame_bytes = first.as_raw().len();
let mut needed = decoded.bytes();
// The shared VecModels make eviction visible even to an already projected document.
let mut oldest: Vec<_> = self.entries.keys().cloned().collect();
oldest.sort_by_key(|k| self.entries[k].shown);
for key in &oldest {
if self.memory() + needed <= budget {
break;
}
let e = &self.entries[key];
while e.frames.row_count() > 1 {
e.frames.remove(e.frames.row_count() - 1);
e.delays.remove(e.delays.row_count() - 1);
}
e.playhead.set_row_data(0, 0);
}
if self.memory() + needed > budget {
decoded.frames.truncate(1);
decoded.delays.truncate(1);
needed = frame_bytes;
}
if self.memory() + needed > budget {
// First frames themselves still count against the shared cap.
self.failed.insert(url);
return;
}
let frames = decoded
.frames
.into_iter()
.map(|f| {
Image::from_rgba8(SharedPixelBuffer::<Rgba8Pixel>::clone_from_slice(
f.as_raw(),
f.width(),
f.height(),
))
})
.collect::<Vec<_>>();
self.entries.insert(
url.clone(),
Entry {
frames: Rc::new(VecModel::from(frames)),
delays: Rc::new(VecModel::from(decoded.delays)),
playhead: Rc::new(VecModel::from(vec![0])),
frame_bytes,
shown: 0,
},
);
self.failed.remove(&url);
}
pub fn shown(&mut self, url: &str) {
self.tick += 1;
if let Some(entry) = self.entries.get_mut(url) {
entry.shown = self.tick;
}
}
pub fn project(&mut self, blocks: &ModelRc<DescriptionBlock>) {
for block in blocks.iter().filter(|b| b.kind == 5) {
let Some(items) = block
.images
.as_any()
.downcast_ref::<VecModel<DescriptionImage>>()
else {
continue;
};
for i in 0..items.row_count() {
let mut item = items.row_data(i).unwrap();
let old = (item.state, item.frames.clone());
if let Some(entry) = self.entries.get_mut(item.url.as_str()) {
item.frames = ModelRc::from(entry.frames.clone());
item.delays = ModelRc::from(entry.delays.clone());
item.playhead = ModelRc::from(entry.playhead.clone());
item.state = 1;
} else {
item.state = if self.failed.contains(item.url.as_str())
|| fmm_core::description_images::validate_url(item.url.as_str()).is_err()
{
2
} else {
0
};
item.frames = ModelRc::default();
}
if old != (item.state, item.frames.clone()) {
items.set_row_data(i, item);
}
}
}
}
}
pub fn reflow(blocks: &ModelRc<DescriptionBlock>, width: f32) {
let Some(model) = blocks.as_any().downcast_ref::<VecModel<DescriptionBlock>>() else {
return;
};
for i in 0..model.row_count() {
let mut block = model.row_data(i).unwrap();
if block.kind != 5 {
continue;
}
let Some(items) = block
.images
.as_any()
.downcast_ref::<VecModel<DescriptionImage>>()
else {
continue;
};
let sizes: Vec<_> = items
.iter()
.map(|item| {
if item.state == 1 {
let size = item.frames.row_data(0).unwrap_or_default().size();
(size.width as f32, size.height as f32)
} else {
(
(item.alt.chars().count().max(5) as f32 * 8.0 + 8.0).min(width.max(1.0)),
28.0,
)
}
})
.collect();
let (positions, height) = layout(&sizes, width);
for (j, position) in positions.into_iter().enumerate() {
let mut item = items.row_data(j).unwrap();
if (item.x, item.y, item.width, item.height)
!= (position.x, position.y, position.width, position.height)
{
item.x = position.x;
item.y = position.y;
item.width = position.width;
item.height = position.height;
items.set_row_data(j, item);
}
}
if block.row_height != height {
block.row_height = height;
model.set_row_data(i, block);
}
}
}
pub fn bind_layout(app: &ModsWindow) {
app.global::<DescriptionImages>()
.on_layout(|blocks, width| reflow(&blocks, width));
}
/// Rebuilt from the shown document, so unstarted work for an old selection is discarded.
pub fn pending(blocks: &ModelRc<DescriptionBlock>) -> Vec<String> {
blocks
.iter()
.flat_map(|b| {
b.images
.iter()
.filter(|i| i.state == 0)
.map(|i| i.url.to_string())
.collect::<Vec<_>>()
})
.collect()
}
pub struct FixtureTransport(pub HashMap<String, std::path::PathBuf>);
impl fmm_core::description_images::Transport for FixtureTransport {
fn get(
&self,
url: &str,
_: std::time::Duration,
) -> fmm_core::Result<fmm_core::description_images::Response> {
let bytes = std::fs::read(self.0.get(url).ok_or("No offline image fixture")?)?;
Ok(fmm_core::description_images::Response {
status: 200,
length: Some(bytes.len() as u64),
location: None,
reader: Box::new(std::io::Cursor::new(bytes)),
})
}
}