Skip to main content

crabshell_ui/
image.rs

1//! The bindings of [`Image`](crate::Image) and [`Icon`](crate::Icon), an
2//! image's transition to a new source, and what the platform asks of an
3//! image: a repaint of one GIF's box when its next frame is due.
4
5use 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
15/// Numbers every image mounted, in every window, so the renderer's
16/// playback of one GIF and the platform's repaint of it can't mix two up.
17static NEXT_IMAGE: AtomicU64 = AtomicU64::new(0);
18
19/// The most dropped images kept for the renderer to hear of; a shell
20/// without one stops counting there.
21const MAX_DROPPED: usize = 4096;
22
23thread_local! {
24  /// The ids of images dropped since [`dropped_images`] last ran.
25  static DROPPED: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
26  /// Images whose transition's new source the renderer couldn't load,
27  /// with that source, until the transition's next tick.
28  static FAILED: RefCell<Vec<(u64, PathBuf)>> = const { RefCell::new(Vec::new()) };
29  /// Images whose transition's new source the renderer is decoding, with
30  /// that source, until the picture comes in.
31  static DECODING: RefCell<Vec<(u64, PathBuf)>> = const { RefCell::new(Vec::new()) };
32}
33
34/// The ids of images removed, or in windows dropped, since the last call,
35/// so a renderer can let go of what it kept for them, such as the picture
36/// a transition was leaving.
37pub fn dropped_images() -> Vec<u64> {
38  DROPPED.with(|dropped| std::mem::take(&mut *dropped.borrow_mut()))
39}
40
41/// Tells image `id`'s transition that the renderer can't load its new
42/// `source`, so at its next tick it ends at once, leaving the old picture
43/// shown and its box still. The reverse of [`dropped_images`]: a renderer
44/// calls it while drawing. A report for an image with no transition
45/// running, or one to another source, changes nothing.
46pub 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
55/// Tells image `id`'s transition that the renderer is still decoding its
56/// new `source`, so its clock waits at the start, the old picture shown,
57/// until [`Window::repaint_image`] says the picture came in. A renderer
58/// calls it while drawing. A report for another source holds nothing.
59pub 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
72/// Whether the renderer said it is decoding `source` for image `id`.
73fn 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
82/// Forgets what the renderer said it decodes for image `id`.
83fn decoded(id: u64) {
84  let _ = DECODING.try_with(|decoding| decoding.borrow_mut().retain(|(at, _)| *at != id));
85}
86
87/// How many decoding reports are held, for tests.
88#[cfg(test)]
89pub(crate) fn decoding_reports() -> usize {
90  DECODING.with(|decoding| decoding.borrow().len())
91}
92
93/// How many reports wait for a transition's tick, for tests.
94#[cfg(test)]
95pub(crate) fn failed_reports() -> usize {
96  FAILED.with(|failed| failed.borrow().len())
97}
98
99/// Whether the renderer said image `id` can't load `source`, using up
100/// every report about `id`.
101fn 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    // At thread exit the list may be gone already; nobody is left to ask.
116    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    // A report about it would wait for a tick that never comes.
123    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/// How an [`Image`](crate::Image) shows a new source: at once, or coming
146/// in over the old picture over a [`Transition`], which gives its time,
147/// curve and delay. Both pictures are drawn at the image's size, fit and
148/// filters.
149///
150/// ```
151/// use crabshell_ui::{Easing, ImageTransition, Transition};
152///
153/// const WALLPAPER: ImageTransition =
154///     ImageTransition::wipe(Transition::new(800).easing(Easing::InOutCubic), 90.0);
155/// ```
156#[derive(Clone, Copy, Debug, Default, PartialEq)]
157pub enum ImageTransition {
158  /// The new picture replaces the old at once. The default.
159  #[default]
160  None,
161  /// The new picture fades in as the old one fades out.
162  Crossfade(Transition),
163  /// An edge sweeps across the box in the direction of the angle, in
164  /// degrees as CSS's gradient angle: 0 toward the top, 90 toward the
165  /// right. The new picture is behind it. An angle that isn't finite
166  /// counts as 90.
167  Wipe(Transition, f32),
168  /// A circle grows from the middle until it covers the box, the new
169  /// picture inside it.
170  Circle(Transition),
171  /// The old picture breaks into growing blocks and the new one sharpens
172  /// out of them.
173  Pixelate(Transition),
174}
175
176impl ImageTransition {
177  /// No transition: a new source shows at once.
178  pub const fn none() -> ImageTransition {
179    ImageTransition::None
180  }
181
182  /// A crossfade over `transition`.
183  pub const fn crossfade(transition: Transition) -> ImageTransition {
184    ImageTransition::Crossfade(transition)
185  }
186
187  /// A wipe toward `angle` degrees over `transition`.
188  pub const fn wipe(transition: Transition, angle: f32) -> ImageTransition {
189    ImageTransition::Wipe(transition, angle)
190  }
191
192  /// A circle reveal over `transition`.
193  pub const fn circle(transition: Transition) -> ImageTransition {
194    ImageTransition::Circle(transition)
195  }
196
197  /// A pixelation over `transition`.
198  pub const fn pixelate(transition: Transition) -> ImageTransition {
199    ImageTransition::Pixelate(transition)
200  }
201
202  /// Its time and curve, `None` for none.
203  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
214/// The picture a running transition leaves.
215pub(crate) struct Leaving {
216  pub(crate) source: PathBuf,
217  /// How far along the transition is, eased.
218  pub(crate) t: f32,
219  /// Which transition of the image it is, so one replaced stops.
220  generation: u64,
221}
222
223/// `value` if it is finite and above 0, 0 if it is finite and not, and
224/// `unset` otherwise. Never -0, so equal filters hash alike.
225fn 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
235/// Sets `slot` to `value`: a change repaints, never lays out.
236fn 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      // A new picture of the same size only needs a repaint.
249      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        // Mid-transition, it leaves the picture most of the box shows.
263        let old = match image.leaving.take() {
264          Some(leaving) if leaving.t < 0.5 => Some(leaving.source),
265          _ => old,
266        };
267        // One not drawn yet has nothing to leave, and one going back to
268        // what it shows needs no transition.
269        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  /// Moves image `id`'s transition number `generation` with the animation
322  /// clock, repainting its box each tick, until it ends, when the old
323  /// picture is let go, or another replaces it.
324  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        // While its new picture is decoded, the clock waits at the start.
343        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            // Nothing on screen changes until the delay is over.
371            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      // A new picture of the same size only needs a repaint.
385      tree.update_icon(id, |icon| repaint(&mut icon.source, Some(value)));
386    });
387    self.bind_opt(id, props.size, "size", |tree, id, value| {
388      tree.update_icon(id, |icon| replace(&mut icon.size, value));
389    });
390    self.bind_opt(id, props.tint, "tint", |tree, id, value| {
391      tree.update_icon(id, |icon| repaint(&mut icon.tint, value));
392    });
393  }
394}
395
396impl Window {
397  /// Repaints the box of image `id`, as when the renderer says a GIF's
398  /// next frame is due or a picture it decoded came in, which also ends
399  /// its transition's wait for it, and returns whether it did. An image in another
400  /// window, removed, hidden or not laid out yet repaints nothing.
401  pub fn repaint_image(&self, id: u64) -> bool {
402    let mut tree = borrow(&self.tree);
403    let found = tree.images.iter().copied().find(|&node| {
404      matches!(tree.node(node), Some(node) if node.rect.is_some()
405        && matches!(&node.kind, NodeKind::Image(image) if image.id == id))
406    });
407    // A picture that came in ends any wait for it.
408    decoded(id);
409    let Some(node) = found else {
410      return false;
411    };
412    tree.invalidate(node, Change::Paint);
413    true
414  }
415}