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::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}
27
28/// The ids of images removed, or in windows dropped, since the last call,
29/// so a renderer can let go of what it kept for them, such as the picture
30/// a transition was leaving.
31pub fn dropped_images() -> Vec<u64> {
32  DROPPED.with(|dropped| std::mem::take(&mut *dropped.borrow_mut()))
33}
34
35impl Drop for ImageNode {
36  fn drop(&mut self) {
37    // At thread exit the list may be gone already; nobody is left to ask.
38    let _ = DROPPED.try_with(|dropped| {
39      let mut dropped = dropped.borrow_mut();
40      if dropped.len() < MAX_DROPPED {
41        dropped.push(self.id);
42      }
43    });
44  }
45}
46
47impl ImageNode {
48  pub(crate) fn new() -> ImageNode {
49    ImageNode {
50      id: NEXT_IMAGE.fetch_add(1, Ordering::Relaxed),
51      source: None,
52      width: crate::Image::DEFAULT_SIZE,
53      height: crate::Image::DEFAULT_SIZE,
54      fit: Fit::default(),
55      filters: ImageFilters::default(),
56      playing: true,
57      transition: ImageTransition::None,
58      leaving: None,
59      transitions: 0,
60    }
61  }
62}
63
64/// How an [`Image`](crate::Image) shows a new source: at once, or coming
65/// in over the old picture over a [`Transition`], which gives its time,
66/// curve and delay. Both pictures are drawn at the image's size, fit and
67/// filters.
68///
69/// ```
70/// use crabshell_ui::{Easing, ImageTransition, Transition};
71///
72/// const WALLPAPER: ImageTransition =
73///     ImageTransition::wipe(Transition::new(800).easing(Easing::InOutCubic), 90.0);
74/// ```
75#[derive(Clone, Copy, Debug, Default, PartialEq)]
76pub enum ImageTransition {
77  /// The new picture replaces the old at once. The default.
78  #[default]
79  None,
80  /// The new picture fades in as the old one fades out.
81  Crossfade(Transition),
82  /// An edge sweeps across the box in the direction of the angle, in
83  /// degrees as CSS's gradient angle: 0 toward the top, 90 toward the
84  /// right. The new picture is behind it. An angle that isn't finite
85  /// counts as 90.
86  Wipe(Transition, f32),
87  /// A circle grows from the middle until it covers the box, the new
88  /// picture inside it.
89  Circle(Transition),
90  /// The old picture breaks into growing blocks and the new one sharpens
91  /// out of them.
92  Pixelate(Transition),
93}
94
95impl ImageTransition {
96  /// No transition: a new source shows at once.
97  pub const fn none() -> ImageTransition {
98    ImageTransition::None
99  }
100
101  /// A crossfade over `transition`.
102  pub const fn crossfade(transition: Transition) -> ImageTransition {
103    ImageTransition::Crossfade(transition)
104  }
105
106  /// A wipe toward `angle` degrees over `transition`.
107  pub const fn wipe(transition: Transition, angle: f32) -> ImageTransition {
108    ImageTransition::Wipe(transition, angle)
109  }
110
111  /// A circle reveal over `transition`.
112  pub const fn circle(transition: Transition) -> ImageTransition {
113    ImageTransition::Circle(transition)
114  }
115
116  /// A pixelation over `transition`.
117  pub const fn pixelate(transition: Transition) -> ImageTransition {
118    ImageTransition::Pixelate(transition)
119  }
120
121  /// Its time and curve, `None` for none.
122  pub const fn transition(self) -> Option<Transition> {
123    match self {
124      ImageTransition::None => None,
125      ImageTransition::Crossfade(transition)
126      | ImageTransition::Wipe(transition, _)
127      | ImageTransition::Circle(transition)
128      | ImageTransition::Pixelate(transition) => Some(transition),
129    }
130  }
131}
132
133/// The picture a running transition leaves.
134pub(crate) struct Leaving {
135  pub(crate) source: PathBuf,
136  /// How far along the transition is, eased.
137  pub(crate) t: f32,
138  /// Which transition of the image it is, so one replaced stops.
139  generation: u64,
140}
141
142/// `value` if it is finite and above 0, 0 if it is finite and not, and
143/// `unset` otherwise. Never -0, so equal filters hash alike.
144fn filter_value(value: f32, unset: f32) -> f32 {
145  if !value.is_finite() {
146    unset
147  } else if value > 0.0 {
148    value
149  } else {
150    0.0
151  }
152}
153
154/// Sets `slot` to `value`: a change repaints, never lays out.
155fn repaint<T: PartialEq>(slot: &mut T, value: T) -> Change {
156  match replace(slot, value) {
157    Change::None => Change::None,
158    _ => Change::Paint,
159  }
160}
161
162impl Tree {
163  pub(crate) fn bind_image(&mut self, id: NodeId, props: ImageProps) {
164    self.images.push(id);
165    self.bind(id, props.source, "image", |tree, id, value| {
166      let mut started = None;
167      // A new picture of the same size only needs a repaint.
168      tree.update(id, |node| {
169        let drawn = node.rect.is_some();
170        let NodeKind::Image(image) = &mut node.kind else {
171          return Change::None;
172        };
173        if image.source.as_ref() == Some(&value) {
174          return Change::None;
175        }
176        let old = image.source.replace(value);
177        let transition = image
178          .transition
179          .transition()
180          .filter(|transition| !transition.is_instant());
181        // Mid-transition, it leaves the picture most of the box shows.
182        let old = match image.leaving.take() {
183          Some(leaving) if leaving.t < 0.5 => Some(leaving.source),
184          _ => old,
185        };
186        // One not drawn yet has nothing to leave, and one going back to
187        // what it shows needs no transition.
188        let old = old.filter(|old| image.source.as_ref() != Some(old));
189        if let (Some(old), Some(transition), true) = (old, transition, drawn) {
190          image.transitions += 1;
191          image.leaving = Some(Leaving {
192            source: old,
193            t: 0.0,
194            generation: image.transitions,
195          });
196          started = Some((image.transitions, transition));
197        }
198        Change::Paint
199      });
200      if let Some((generation, transition)) = started {
201        tree.start_image_transition(id, generation, transition);
202      }
203    });
204    self.bind_opt(id, props.width, "width", |tree, id, value| {
205      tree.update_image(id, |image| replace(&mut image.width, value));
206    });
207    self.bind_opt(id, props.height, "height", |tree, id, value| {
208      tree.update_image(id, |image| replace(&mut image.height, value));
209    });
210    self.bind_opt(id, props.fit, "fit", |tree, id, value| {
211      tree.update_image(id, |image| repaint(&mut image.fit, value));
212    });
213    self.bind_opt(id, props.tint, "tint", |tree, id, value| {
214      tree.update_image(id, |image| repaint(&mut image.filters.tint, value));
215    });
216    self.bind_opt(id, props.brightness, "brightness", |tree, id, value| {
217      let value = filter_value(value, 1.0);
218      tree.update_image(id, |image| repaint(&mut image.filters.brightness, value));
219    });
220    self.bind_opt(id, props.contrast, "contrast", |tree, id, value| {
221      let value = filter_value(value, 1.0);
222      tree.update_image(id, |image| repaint(&mut image.filters.contrast, value));
223    });
224    self.bind_opt(id, props.saturation, "saturation", |tree, id, value| {
225      let value = filter_value(value, 1.0);
226      tree.update_image(id, |image| repaint(&mut image.filters.saturation, value));
227    });
228    self.bind_opt(id, props.blur, "blur", |tree, id, value| {
229      let value = filter_value(value, 0.0);
230      tree.update_image(id, |image| repaint(&mut image.filters.blur, value));
231    });
232    self.bind_opt(id, props.playing, "playing", |tree, id, value| {
233      tree.update_image(id, |image| repaint(&mut image.playing, value));
234    });
235    self.bind_opt(id, props.transition, "transition", |tree, id, value| {
236      tree.update_image(id, |image| repaint(&mut image.transition, value));
237    });
238  }
239
240  /// Moves image `id`'s transition number `generation` with the animation
241  /// clock, repainting its box each tick, until it ends, when the old
242  /// picture is let go, or another replaces it.
243  fn start_image_transition(&self, id: NodeId, generation: u64, transition: Transition) {
244    let tree = self.this.clone();
245    let mut started = animation::start_time();
246    let label = self.node(id).map_or_else(
247      || Rc::from("an image transition"),
248      |node| format!("{}.transition", node.path).into(),
249    );
250    animation::start(
251      label,
252      Box::new(move |now| {
253        let Some(tree) = tree.upgrade() else {
254          return false;
255        };
256        let Ok(mut tree) = tree.try_borrow_mut() else {
257          return true;
258        };
259        let begun = *started.get_or_insert(now);
260        let waiting = transition.waiting(begun, now);
261        let (t, ended) = transition.progress(begun, now);
262        let mut mine = false;
263        tree.update_image(id, |image| {
264          let Some(leaving) = image
265            .leaving
266            .as_mut()
267            .filter(|leaving| leaving.generation == generation)
268          else {
269            return Change::None;
270          };
271          mine = true;
272          if ended {
273            image.leaving = None;
274          } else if waiting {
275            // Nothing on screen changes until the delay is over.
276            return Change::None;
277          } else {
278            leaving.t = t;
279          }
280          Change::Paint
281        });
282        mine && !ended
283      }),
284    );
285  }
286
287  pub(crate) fn bind_icon(&mut self, id: NodeId, props: IconProps) {
288    self.bind(id, props.source, "icon", |tree, id, value| {
289      // A new picture of the same size only needs a repaint.
290      tree.update_icon(id, |icon| repaint(&mut icon.source, Some(value)));
291    });
292    self.bind_opt(id, props.size, "size", |tree, id, value| {
293      tree.update_icon(id, |icon| replace(&mut icon.size, value));
294    });
295    self.bind_opt(id, props.tint, "tint", |tree, id, value| {
296      tree.update_icon(id, |icon| repaint(&mut icon.tint, value));
297    });
298  }
299}
300
301impl Window {
302  /// Repaints the box of image `id`, as when the renderer says a GIF's
303  /// next frame is due, and returns whether it did. An image in another
304  /// window, removed, hidden or not laid out yet repaints nothing.
305  pub fn repaint_image(&self, id: u64) -> bool {
306    let mut tree = borrow(&self.tree);
307    let found = tree.images.iter().copied().find(|&node| {
308      matches!(tree.node(node), Some(node) if node.rect.is_some()
309        && matches!(&node.kind, NodeKind::Image(image) if image.id == id))
310    });
311    let Some(node) = found else {
312      return false;
313    };
314    tree.invalidate(node, Change::Paint);
315    true
316  }
317}