use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use crabshell_ui::Affine;
use tiny_skia::Pixmap;
use super::patched::{Key, Patch};
pub(crate) const KEPT_LIMIT: u64 = 32 << 20;
#[derive(Default)]
pub(crate) struct Kept {
pub(super) frame: u64,
pub(super) budget: Arc<AtomicU64>,
theme: u64,
pub(super) seen: HashMap<String, Seen>,
pub(super) patches: HashMap<Key, (u64, Patch)>,
}
impl std::fmt::Debug for Kept {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let layers = self.seen.values().filter(|seen| seen.layer.is_some());
let patches = self.patches.len();
write!(
f,
"Kept {{ layers: {}, patches: {patches} }}",
layers.count()
)
}
}
impl Kept {
pub(super) fn start(&mut self, budget: &Arc<AtomicU64>, theme: u64) {
self.frame += 1;
self.budget = Arc::clone(budget);
if self.theme != theme {
self.theme = theme;
self.seen.clear();
}
}
pub(super) fn end(&mut self) {
let frame = self.frame;
self.seen.retain(|_, seen| seen.frame == frame);
self.patches.retain(|_, (used, _)| *used == frame);
}
pub(super) fn patch(&mut self, key: Key) -> Option<&Patch> {
#[cfg(test)]
if !PATCHES.get() {
return None;
}
let frame = self.frame;
if !self.patches.contains_key(&key) {
let held = self.hold(Patch::bytes(&key))?;
self.patches.insert(key, (frame, Patch::new(&key, held)));
}
let (used, patch) = self.patches.get_mut(&key)?;
*used = frame;
Some(patch)
}
pub(super) fn layer(&self, path: &str) -> Option<&Layer> {
self.seen.get(path)?.layer.as_ref()
}
pub(super) fn hold(&self, bytes: u64) -> Option<Held> {
let total = self.budget.fetch_add(bytes, Ordering::Relaxed) + bytes;
let held = Held {
bytes,
budget: Arc::clone(&self.budget),
};
(total <= KEPT_LIMIT).then_some(held)
}
}
#[cfg(test)]
thread_local! {
pub(crate) static PATCHES: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
}
pub(super) struct Seen {
pub(super) frame: u64,
pub(super) revision: u64,
pub(super) opacity: f32,
pub(super) transform: Option<Affine>,
pub(super) layer: Option<Layer>,
}
pub(super) struct Layer {
pub(super) pixmap: Pixmap,
pub(super) area: Area,
pub(super) at: (f32, f32),
pub(super) _held: Held,
}
pub(super) struct Want {
pub(super) needed: Area,
pub(super) whole: Area,
pub(super) at: (f32, f32),
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub(super) struct Area {
pub(super) x: i32,
pub(super) y: i32,
pub(super) width: u32,
pub(super) height: u32,
}
impl Area {
pub(super) fn holds(&self, inner: &Area) -> bool {
let right = |area: &Area| i64::from(area.x) + i64::from(area.width);
let bottom = |area: &Area| i64::from(area.y) + i64::from(area.height);
inner.x >= self.x
&& inner.y >= self.y
&& right(inner) <= right(self)
&& bottom(inner) <= bottom(self)
}
}
pub(super) struct Held {
bytes: u64,
budget: Arc<AtomicU64>,
}
impl Drop for Held {
fn drop(&mut self) {
self.budget.fetch_sub(self.bytes, Ordering::Relaxed);
}
}