1use std::cell::RefCell;
6use std::path::{Path, PathBuf};
7use std::rc::Rc;
8use std::sync::atomic::{AtomicU64, Ordering};
9
10use crate::animation::{self, Transition};
11use crate::tree::{Change, ImageNode, NodeId, NodeKind, Tree, borrow, replace};
12use crate::widgets::{Fit, IconProps, ImageFilters, ImageProps};
13use crate::window::Window;
14
15static NEXT_IMAGE: AtomicU64 = AtomicU64::new(0);
18
19const MAX_DROPPED: usize = 4096;
22
23thread_local! {
24 static DROPPED: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
26 static FAILED: RefCell<Vec<(u64, PathBuf)>> = const { RefCell::new(Vec::new()) };
29 static DECODING: RefCell<Vec<(u64, PathBuf)>> = const { RefCell::new(Vec::new()) };
32}
33
34pub fn dropped_images() -> Vec<u64> {
38 DROPPED.with(|dropped| std::mem::take(&mut *dropped.borrow_mut()))
39}
40
41pub fn image_source_failed(id: u64, source: &Path) {
47 FAILED.with(|failed| {
48 let mut failed = failed.borrow_mut();
49 if failed.len() < MAX_DROPPED && !failed.iter().any(|(at, path)| *at == id && path == source) {
50 failed.push((id, source.to_owned()));
51 }
52 });
53}
54
55pub fn image_source_decoding(id: u64, source: &Path) {
60 DECODING.with(|decoding| {
61 let mut decoding = decoding.borrow_mut();
62 if decoding.len() < MAX_DROPPED
63 && !decoding
64 .iter()
65 .any(|(at, path)| *at == id && path == source)
66 {
67 decoding.push((id, source.to_owned()));
68 }
69 });
70}
71
72fn source_decoding(id: u64, source: Option<&PathBuf>) -> bool {
74 DECODING.with(|decoding| {
75 decoding
76 .borrow()
77 .iter()
78 .any(|(at, path)| *at == id && Some(path) == source)
79 })
80}
81
82fn decoded(id: u64) {
84 let _ = DECODING.try_with(|decoding| decoding.borrow_mut().retain(|(at, _)| *at != id));
85}
86
87#[cfg(test)]
89pub(crate) fn decoding_reports() -> usize {
90 DECODING.with(|decoding| decoding.borrow().len())
91}
92
93#[cfg(test)]
95pub(crate) fn failed_reports() -> usize {
96 FAILED.with(|failed| failed.borrow().len())
97}
98
99fn source_failed(id: u64, source: Option<&PathBuf>) -> bool {
102 FAILED.with(|failed| {
103 let mut found = false;
104 failed.borrow_mut().retain(|(at, path)| {
105 let mine = *at == id;
106 found |= mine && Some(path) == source;
107 !mine
108 });
109 found
110 })
111}
112
113impl Drop for ImageNode {
114 fn drop(&mut self) {
115 let _ = DROPPED.try_with(|dropped| {
117 let mut dropped = dropped.borrow_mut();
118 if dropped.len() < MAX_DROPPED {
119 dropped.push(self.id);
120 }
121 });
122 let _ = FAILED.try_with(|failed| failed.borrow_mut().retain(|(id, _)| *id != self.id));
124 decoded(self.id);
125 }
126}
127
128impl ImageNode {
129 pub(crate) fn new() -> ImageNode {
130 ImageNode {
131 id: NEXT_IMAGE.fetch_add(1, Ordering::Relaxed),
132 source: None,
133 width: crate::Image::DEFAULT_SIZE,
134 height: crate::Image::DEFAULT_SIZE,
135 fit: Fit::default(),
136 filters: ImageFilters::default(),
137 playing: true,
138 transition: ImageTransition::None,
139 leaving: None,
140 transitions: 0,
141 }
142 }
143}
144
145#[derive(Clone, Copy, Debug, Default, PartialEq)]
157pub enum ImageTransition {
158 #[default]
160 None,
161 Crossfade(Transition),
163 Wipe(Transition, f32),
168 Circle(Transition),
171 Pixelate(Transition),
174}
175
176impl ImageTransition {
177 pub const fn none() -> ImageTransition {
179 ImageTransition::None
180 }
181
182 pub const fn crossfade(transition: Transition) -> ImageTransition {
184 ImageTransition::Crossfade(transition)
185 }
186
187 pub const fn wipe(transition: Transition, angle: f32) -> ImageTransition {
189 ImageTransition::Wipe(transition, angle)
190 }
191
192 pub const fn circle(transition: Transition) -> ImageTransition {
194 ImageTransition::Circle(transition)
195 }
196
197 pub const fn pixelate(transition: Transition) -> ImageTransition {
199 ImageTransition::Pixelate(transition)
200 }
201
202 pub const fn transition(self) -> Option<Transition> {
204 match self {
205 ImageTransition::None => None,
206 ImageTransition::Crossfade(transition)
207 | ImageTransition::Wipe(transition, _)
208 | ImageTransition::Circle(transition)
209 | ImageTransition::Pixelate(transition) => Some(transition),
210 }
211 }
212}
213
214pub(crate) struct Leaving {
216 pub(crate) source: PathBuf,
217 pub(crate) t: f32,
219 generation: u64,
221}
222
223fn filter_value(value: f32, unset: f32) -> f32 {
226 if !value.is_finite() {
227 unset
228 } else if value > 0.0 {
229 value
230 } else {
231 0.0
232 }
233}
234
235fn repaint<T: PartialEq>(slot: &mut T, value: T) -> Change {
237 match replace(slot, value) {
238 Change::None => Change::None,
239 _ => Change::Paint,
240 }
241}
242
243impl Tree {
244 pub(crate) fn bind_image(&mut self, id: NodeId, props: ImageProps) {
245 self.images.push(id);
246 self.bind(id, props.source, "image", |tree, id, value| {
247 let mut started = None;
248 tree.update(id, |node| {
250 let drawn = node.rect.is_some();
251 let NodeKind::Image(image) = &mut node.kind else {
252 return Change::None;
253 };
254 if image.source.as_ref() == Some(&value) {
255 return Change::None;
256 }
257 let old = image.source.replace(value);
258 let transition = image
259 .transition
260 .transition()
261 .filter(|transition| !transition.is_instant());
262 let old = match image.leaving.take() {
264 Some(leaving) if leaving.t < 0.5 => Some(leaving.source),
265 _ => old,
266 };
267 let old = old.filter(|old| image.source.as_ref() != Some(old));
270 if let (Some(old), Some(transition), true) = (old, transition, drawn) {
271 image.transitions += 1;
272 image.leaving = Some(Leaving {
273 source: old,
274 t: 0.0,
275 generation: image.transitions,
276 });
277 started = Some((image.transitions, transition));
278 }
279 Change::Paint
280 });
281 if let Some((generation, transition)) = started {
282 tree.start_image_transition(id, generation, transition);
283 }
284 });
285 self.bind_opt(id, props.width, "width", |tree, id, value| {
286 tree.update_image(id, |image| replace(&mut image.width, value));
287 });
288 self.bind_opt(id, props.height, "height", |tree, id, value| {
289 tree.update_image(id, |image| replace(&mut image.height, value));
290 });
291 self.bind_opt(id, props.fit, "fit", |tree, id, value| {
292 tree.update_image(id, |image| repaint(&mut image.fit, value));
293 });
294 self.bind_opt(id, props.tint, "tint", |tree, id, value| {
295 tree.update_image(id, |image| repaint(&mut image.filters.tint, value));
296 });
297 self.bind_opt(id, props.brightness, "brightness", |tree, id, value| {
298 let value = filter_value(value, 1.0);
299 tree.update_image(id, |image| repaint(&mut image.filters.brightness, value));
300 });
301 self.bind_opt(id, props.contrast, "contrast", |tree, id, value| {
302 let value = filter_value(value, 1.0);
303 tree.update_image(id, |image| repaint(&mut image.filters.contrast, value));
304 });
305 self.bind_opt(id, props.saturation, "saturation", |tree, id, value| {
306 let value = filter_value(value, 1.0);
307 tree.update_image(id, |image| repaint(&mut image.filters.saturation, value));
308 });
309 self.bind_opt(id, props.blur, "blur", |tree, id, value| {
310 let value = filter_value(value, 0.0);
311 tree.update_image(id, |image| repaint(&mut image.filters.blur, value));
312 });
313 self.bind_opt(id, props.playing, "playing", |tree, id, value| {
314 tree.update_image(id, |image| repaint(&mut image.playing, value));
315 });
316 self.bind_opt(id, props.transition, "transition", |tree, id, value| {
317 tree.update_image(id, |image| repaint(&mut image.transition, value));
318 });
319 }
320
321 fn start_image_transition(&self, id: NodeId, generation: u64, transition: Transition) {
325 let tree = self.this.clone();
326 let mut started = animation::start_time();
327 let label = self.node(id).map_or_else(
328 || Rc::from("an image transition"),
329 |node| format!("{}.transition", node.path).into(),
330 );
331 let busy = self.node(id).and_then(|node| node.cx.busy());
332 animation::start(
333 label,
334 busy,
335 Box::new(move |now| {
336 let Some(tree) = tree.upgrade() else {
337 return false;
338 };
339 let Ok(mut tree) = tree.try_borrow_mut() else {
340 return true;
341 };
342 let held = tree.node(id).is_some_and(|node| {
344 matches!(&node.kind, NodeKind::Image(image)
345 if image.leaving.as_ref().is_some_and(|leaving| leaving.generation == generation)
346 && source_decoding(image.id, image.source.as_ref()))
347 });
348 if held {
349 started = None;
350 return true;
351 }
352 let begun = *started.get_or_insert(now);
353 let waiting = transition.waiting(begun, now);
354 let (t, mut ended) = transition.progress(begun, now);
355 let mut mine = false;
356 tree.update_image(id, |image| {
357 let failed = source_failed(image.id, image.source.as_ref());
358 let Some(leaving) = image
359 .leaving
360 .as_mut()
361 .filter(|leaving| leaving.generation == generation)
362 else {
363 return Change::None;
364 };
365 mine = true;
366 ended |= failed;
367 if ended {
368 image.leaving = None;
369 } else if waiting {
370 return Change::None;
372 } else {
373 leaving.t = t;
374 }
375 Change::Paint
376 });
377 mine && !ended
378 }),
379 );
380 }
381
382 pub(crate) fn bind_icon(&mut self, id: NodeId, props: IconProps) {
383 self.bind(id, props.source, "icon", |tree, id, value| {
384 tree.update_icon(id, |icon| repaint(&mut icon.source, Some(value)));
386 });
387 self.bind_opt(id, props.fallback, "fallback", |tree, id, value| {
388 tree.update_icon(id, |icon| repaint(&mut icon.fallback, Some(value)));
389 });
390 self.bind_opt(id, props.size, "size", |tree, id, value| {
391 tree.update_icon(id, |icon| replace(&mut icon.size, value));
392 });
393 self.bind_opt(id, props.tint, "tint", |tree, id, value| {
394 tree.update_icon(id, |icon| repaint(&mut icon.tint, value));
395 });
396 }
397}
398
399impl Window {
400 pub fn repaint_image(&self, id: u64) -> bool {
405 let mut tree = borrow(&self.tree);
406 let found = tree.images.iter().copied().find(|&node| {
407 matches!(tree.node(node), Some(node) if node.rect.is_some()
408 && matches!(&node.kind, NodeKind::Image(image) if image.id == id))
409 });
410 decoded(id);
412 let Some(node) = found else {
413 return false;
414 };
415 tree.invalidate(node, Change::Paint);
416 true
417 }
418}