1use std::cell::{Cell, RefCell};
6use std::path::PathBuf;
7use std::rc::Rc;
8use std::sync::atomic::{AtomicU64, Ordering};
9
10use crabshell_reactive::{Signal, untrack};
11
12use crate::animation::{self, Transition};
13use crate::tree::{Change, ImageNode, NodeId, NodeKind, Tree, borrow, replace};
14use crate::widgets::{Fit, IconProps, IconSource, ImageFilters, ImageProps};
15use crate::window::Window;
16
17static NEXT_IMAGE: AtomicU64 = AtomicU64::new(0);
20
21const MAX_DROPPED: usize = 4096;
24
25thread_local! {
26 static DROPPED: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
28 static FAILED: RefCell<Vec<(u64, IconSource)>> = const { RefCell::new(Vec::new()) };
31 static DECODING: RefCell<Vec<(u64, IconSource)>> = const { RefCell::new(Vec::new()) };
34 static WATCHED: RefCell<Vec<(u64, Signal<ImageStatus>, IconSource)>> =
37 const { RefCell::new(Vec::new()) };
38 static STATUS_CHANGED: Cell<bool> = const { Cell::new(false) };
41 static SOURCES_CHANGED: Cell<bool> = const { Cell::new(false) };
44}
45
46#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
49pub enum ImageStatus {
50 #[default]
53 Empty,
54 Loading,
57 Ready,
59 Failed,
61}
62
63pub fn image_status(id: u64, source: &IconSource, status: ImageStatus) {
72 if is_empty(source) {
73 return;
74 }
75 let _ = WATCHED.try_with(|watched| {
76 for (_, signal, _) in watched
77 .borrow()
78 .iter()
79 .filter(|(at, _, shown)| *at == id && shown == source)
80 {
81 if write_status(*signal, status) {
82 STATUS_CHANGED.with(|changed| changed.set(true));
83 }
84 }
85 });
86}
87
88pub fn image_status_changed() -> bool {
91 STATUS_CHANGED.with(|changed| changed.replace(false))
92}
93
94pub fn image_sources_changed() -> bool {
100 SOURCES_CHANGED.with(|changed| changed.replace(false))
101}
102
103fn write_status(signal: Signal<ImageStatus>, status: ImageStatus) -> bool {
106 untrack(|| signal.try_get()) != Some(status) && signal.try_set(status)
107}
108
109fn watch(id: u64, signal: Signal<ImageStatus>) {
111 WATCHED.with(|watched| watched.borrow_mut().push((id, signal, empty_source())));
112}
113
114fn watch_source(id: u64, source: &IconSource) {
117 WATCHED.with(|watched| {
118 for (_, signal, shown) in watched.borrow_mut().iter_mut().filter(|(at, ..)| *at == id) {
119 source.clone_into(shown);
120 let status = match is_empty(source) {
121 true => ImageStatus::Empty,
122 false => ImageStatus::Loading,
123 };
124 write_status(*signal, status);
125 if status == ImageStatus::Loading {
126 SOURCES_CHANGED.with(|changed| changed.set(true));
127 }
128 }
129 });
130}
131
132pub(crate) fn empty_source() -> IconSource {
134 IconSource::File(PathBuf::new())
135}
136
137fn is_empty(source: &IconSource) -> bool {
139 match source {
140 IconSource::File(path) => path.as_os_str().is_empty(),
141 IconSource::Name(name) => name.is_empty(),
142 IconSource::Pixels(_) => false,
143 }
144}
145
146pub(crate) fn awaits_status(id: u64) -> bool {
148 WATCHED
149 .try_with(|watched| {
150 watched.borrow().iter().any(|(at, signal, _)| {
151 *at == id && untrack(|| signal.try_get()) == Some(ImageStatus::Loading)
152 })
153 })
154 .unwrap_or(false)
155}
156
157#[cfg(test)]
159pub(crate) fn watched_images() -> usize {
160 WATCHED.with(|watched| watched.borrow().len())
161}
162
163pub fn dropped_images() -> Vec<u64> {
167 DROPPED.with(|dropped| std::mem::take(&mut *dropped.borrow_mut()))
168}
169
170pub fn image_source_failed(id: u64, source: &IconSource) {
176 FAILED.with(|failed| {
177 let mut failed = failed.borrow_mut();
178 if failed.len() < MAX_DROPPED && !failed.iter().any(|(at, path)| *at == id && path == source) {
179 failed.push((id, source.clone()));
180 }
181 });
182}
183
184pub fn image_source_decoding(id: u64, source: &IconSource) {
189 DECODING.with(|decoding| {
190 let mut decoding = decoding.borrow_mut();
191 if decoding.len() < MAX_DROPPED
192 && !decoding
193 .iter()
194 .any(|(at, path)| *at == id && path == source)
195 {
196 decoding.push((id, source.clone()));
197 }
198 });
199}
200
201fn source_decoding(id: u64, source: Option<&IconSource>) -> bool {
203 DECODING.with(|decoding| {
204 decoding
205 .borrow()
206 .iter()
207 .any(|(at, path)| *at == id && Some(path) == source)
208 })
209}
210
211fn decoded(id: u64) {
213 let _ = DECODING.try_with(|decoding| decoding.borrow_mut().retain(|(at, _)| *at != id));
214}
215
216#[cfg(test)]
218pub(crate) fn decoding_reports() -> usize {
219 DECODING.with(|decoding| decoding.borrow().len())
220}
221
222#[cfg(test)]
224pub(crate) fn failed_reports() -> usize {
225 FAILED.with(|failed| failed.borrow().len())
226}
227
228fn source_failed(id: u64, source: Option<&IconSource>) -> bool {
231 FAILED.with(|failed| {
232 let mut found = false;
233 failed.borrow_mut().retain(|(at, path)| {
234 let mine = *at == id;
235 found |= mine && Some(path) == source;
236 !mine
237 });
238 found
239 })
240}
241
242impl Drop for ImageNode {
243 fn drop(&mut self) {
244 let _ = DROPPED.try_with(|dropped| {
246 let mut dropped = dropped.borrow_mut();
247 if dropped.len() < MAX_DROPPED {
248 dropped.push(self.id);
249 }
250 });
251 let _ = FAILED.try_with(|failed| failed.borrow_mut().retain(|(id, _)| *id != self.id));
253 decoded(self.id);
254 let _ = WATCHED.try_with(|watched| watched.borrow_mut().retain(|(id, ..)| *id != self.id));
255 }
256}
257
258impl ImageNode {
259 pub(crate) fn new() -> ImageNode {
260 ImageNode {
261 id: NEXT_IMAGE.fetch_add(1, Ordering::Relaxed),
262 source: None,
263 width: crate::Image::DEFAULT_SIZE,
264 height: crate::Image::DEFAULT_SIZE,
265 fit: Fit::default(),
266 filters: ImageFilters::default(),
267 playing: true,
268 transition: ImageTransition::None,
269 leaving: None,
270 transitions: 0,
271 }
272 }
273}
274
275#[derive(Clone, Copy, Debug, Default, PartialEq)]
287pub enum ImageTransition {
288 #[default]
290 None,
291 Crossfade(Transition),
293 Wipe(Transition, f32),
298 Circle(Transition),
301 Pixelate(Transition),
304}
305
306impl ImageTransition {
307 pub const fn none() -> ImageTransition {
309 ImageTransition::None
310 }
311
312 pub const fn crossfade(transition: Transition) -> ImageTransition {
314 ImageTransition::Crossfade(transition)
315 }
316
317 pub const fn wipe(transition: Transition, angle: f32) -> ImageTransition {
319 ImageTransition::Wipe(transition, angle)
320 }
321
322 pub const fn circle(transition: Transition) -> ImageTransition {
324 ImageTransition::Circle(transition)
325 }
326
327 pub const fn pixelate(transition: Transition) -> ImageTransition {
329 ImageTransition::Pixelate(transition)
330 }
331
332 pub const fn transition(self) -> Option<Transition> {
334 match self {
335 ImageTransition::None => None,
336 ImageTransition::Crossfade(transition)
337 | ImageTransition::Wipe(transition, _)
338 | ImageTransition::Circle(transition)
339 | ImageTransition::Pixelate(transition) => Some(transition),
340 }
341 }
342}
343
344pub(crate) struct Leaving {
346 pub(crate) source: IconSource,
347 pub(crate) t: f32,
349 generation: u64,
351}
352
353fn filter_value(value: f32, unset: f32) -> f32 {
356 if !value.is_finite() {
357 unset
358 } else if value > 0.0 {
359 value
360 } else {
361 0.0
362 }
363}
364
365fn repaint<T: PartialEq>(slot: &mut T, value: T) -> Change {
367 match replace(slot, value) {
368 Change::None => Change::None,
369 _ => Change::Paint,
370 }
371}
372
373impl Tree {
374 pub(crate) fn bind_image(&mut self, id: NodeId, props: ImageProps) {
375 self.images.push(id);
376 if let (Some(signal), Some(NodeKind::Image(image))) =
377 (props.status, self.node(id).map(|node| &node.kind))
378 {
379 watch(image.id, signal);
380 }
381 self.bind(id, props.source, "image", |tree, id, value| {
382 let mut started = None;
383 tree.update(id, |node| {
385 let drawn = node.rect.is_some();
386 let NodeKind::Image(image) = &mut node.kind else {
387 return Change::None;
388 };
389 if image.source.as_ref() == Some(&value) {
390 return Change::None;
391 }
392 watch_source(image.id, &value);
393 let old = image.source.replace(value);
394 let transition = image
395 .transition
396 .transition()
397 .filter(|transition| !transition.is_instant());
398 let old = match image.leaving.take() {
400 Some(leaving) if leaving.t < 0.5 => Some(leaving.source),
401 _ => old,
402 };
403 let old = old.filter(|old| image.source.as_ref() != Some(old));
406 if let (Some(old), Some(transition), true) = (old, transition, drawn) {
407 image.transitions += 1;
408 image.leaving = Some(Leaving {
409 source: old,
410 t: 0.0,
411 generation: image.transitions,
412 });
413 started = Some((image.transitions, transition));
414 }
415 Change::Paint
416 });
417 if let Some((generation, transition)) = started {
418 tree.start_image_transition(id, generation, transition);
419 }
420 });
421 self.bind_opt(id, props.width, "width", |tree, id, value| {
422 tree.update_image(id, |image| replace(&mut image.width, value));
423 });
424 self.bind_opt(id, props.height, "height", |tree, id, value| {
425 tree.update_image(id, |image| replace(&mut image.height, value));
426 });
427 self.bind_opt(id, props.fit, "fit", |tree, id, value| {
428 tree.update_image(id, |image| repaint(&mut image.fit, value));
429 });
430 self.bind_opt(id, props.tint, "tint", |tree, id, value| {
431 tree.update_image(id, |image| repaint(&mut image.filters.tint, value));
432 });
433 self.bind_opt(id, props.brightness, "brightness", |tree, id, value| {
434 let value = filter_value(value, 1.0);
435 tree.update_image(id, |image| repaint(&mut image.filters.brightness, value));
436 });
437 self.bind_opt(id, props.contrast, "contrast", |tree, id, value| {
438 let value = filter_value(value, 1.0);
439 tree.update_image(id, |image| repaint(&mut image.filters.contrast, value));
440 });
441 self.bind_opt(id, props.saturation, "saturation", |tree, id, value| {
442 let value = filter_value(value, 1.0);
443 tree.update_image(id, |image| repaint(&mut image.filters.saturation, value));
444 });
445 self.bind_opt(id, props.blur, "blur", |tree, id, value| {
446 let value = filter_value(value, 0.0);
447 tree.update_image(id, |image| repaint(&mut image.filters.blur, value));
448 });
449 self.bind_opt(id, props.playing, "playing", |tree, id, value| {
450 tree.update_image(id, |image| repaint(&mut image.playing, value));
451 });
452 self.bind_opt(id, props.transition, "transition", |tree, id, value| {
453 tree.update_image(id, |image| repaint(&mut image.transition, value));
454 });
455 }
456
457 fn start_image_transition(&self, id: NodeId, generation: u64, transition: Transition) {
461 let tree = self.this.clone();
462 let mut started = animation::start_time();
463 let label = self.node(id).map_or_else(
464 || Rc::from("an image transition"),
465 |node| format!("{}.transition", node.path).into(),
466 );
467 let busy = self.node(id).and_then(|node| node.cx.busy());
468 animation::start(
469 label,
470 busy,
471 Box::new(move |now| {
472 let Some(tree) = tree.upgrade() else {
473 return false;
474 };
475 let Ok(mut tree) = tree.try_borrow_mut() else {
476 return true;
477 };
478 let held = tree.node(id).is_some_and(|node| {
480 matches!(&node.kind, NodeKind::Image(image)
481 if image.leaving.as_ref().is_some_and(|leaving| leaving.generation == generation)
482 && source_decoding(image.id, image.source.as_ref()))
483 });
484 if held {
485 started = None;
486 return true;
487 }
488 let begun = *started.get_or_insert(now);
489 let waiting = transition.waiting(begun, now);
490 let (t, mut ended) = transition.progress(begun, now);
491 let mut mine = false;
492 tree.update_image(id, |image| {
493 let failed = source_failed(image.id, image.source.as_ref());
494 let Some(leaving) = image
495 .leaving
496 .as_mut()
497 .filter(|leaving| leaving.generation == generation)
498 else {
499 return Change::None;
500 };
501 mine = true;
502 ended |= failed;
503 if ended {
504 image.leaving = None;
505 } else if waiting {
506 return Change::None;
508 } else {
509 leaving.t = t;
510 }
511 Change::Paint
512 });
513 mine && !ended
514 }),
515 );
516 }
517
518 pub(crate) fn bind_icon(&mut self, id: NodeId, props: IconProps) {
519 self.bind(id, props.source, "icon", |tree, id, value| {
520 tree.update_icon(id, |icon| repaint(&mut icon.source, Some(value)));
522 });
523 self.bind_opt(id, props.fallback, "fallback", |tree, id, value| {
524 tree.update_icon(id, |icon| repaint(&mut icon.fallback, Some(value)));
525 });
526 self.bind_opt(id, props.size, "size", |tree, id, value| {
527 tree.update_icon(id, |icon| replace(&mut icon.size, value));
528 });
529 self.bind_opt(id, props.tint, "tint", |tree, id, value| {
530 tree.update_icon(id, |icon| repaint(&mut icon.tint, value));
531 });
532 }
533}
534
535impl Window {
536 pub fn repaint_image(&self, id: u64) -> bool {
542 let mut tree = borrow(&self.tree);
543 let found = tree.images.iter().copied().find(|&node| {
544 matches!(tree.node(node), Some(node) if node.rect.is_some()
545 && matches!(&node.kind, NodeKind::Image(image) if image.id == id))
546 });
547 decoded(id);
549 let Some(node) = found.filter(|&node| !tree.transparent(node)) else {
550 return false;
551 };
552 tree.invalidate(node, Change::Paint);
553 true
554 }
555}