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::{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
17/// Numbers every image mounted, in every window, so the renderer's
18/// playback of one GIF and the platform's repaint of it can't mix two up.
19static NEXT_IMAGE: AtomicU64 = AtomicU64::new(0);
20
21/// The most dropped images kept for the renderer to hear of; a shell
22/// without one stops counting there.
23const MAX_DROPPED: usize = 4096;
24
25thread_local! {
26  /// The ids of images dropped since [`dropped_images`] last ran.
27  static DROPPED: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
28  /// Images whose transition's new source the renderer couldn't load,
29  /// with that source, until the transition's next tick.
30  static FAILED: RefCell<Vec<(u64, IconSource)>> = const { RefCell::new(Vec::new()) };
31  /// Images whose transition's new source the renderer is decoding, with
32  /// that source, until the picture comes in.
33  static DECODING: RefCell<Vec<(u64, IconSource)>> = const { RefCell::new(Vec::new()) };
34  /// The images with a `status` signal: their id, the signal and the
35  /// source they show.
36  static WATCHED: RefCell<Vec<(u64, Signal<ImageStatus>, IconSource)>> =
37    const { RefCell::new(Vec::new()) };
38  /// A report changed a status signal since [`image_status_changed`]
39  /// last ran.
40  static STATUS_CHANGED: Cell<bool> = const { Cell::new(false) };
41  /// A watched image went back to Loading since
42  /// [`image_sources_changed`] last ran.
43  static SOURCES_CHANGED: Cell<bool> = const { Cell::new(false) };
44}
45
46/// Where an [`Image`](crate::Image)'s picture is, as Qt's `Image.status`,
47/// written to the signal [`Image::status`](crate::Image::status) takes.
48#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
49pub enum ImageStatus {
50  /// The source is an empty path or icon name, or none, so nothing is
51  /// shown. The default.
52  #[default]
53  Empty,
54  /// The source is new and its picture hasn't loaded yet: it is read in
55  /// the loop turn that set it, or decoded off the loop's thread.
56  Loading,
57  /// The source's picture loaded, whether it was drawn or not.
58  Ready,
59  /// The source can't be read or decoded, or is past the size limits.
60  Failed,
61}
62
63/// Writes `status` to image `id`'s status signal while it shows
64/// `source`, if that changes it. A renderer calls it as it loads a
65/// picture, with [`ImageStatus::Ready`] when the image's source loaded and
66/// [`ImageStatus::Failed`] when it can't be, whether the image is drawn or
67/// not (see [`WindowView::loading_images`](crate::WindowView::loading_images)). A report
68/// about another source, an empty one, or an image without a `status`
69/// signal changes nothing. The platform then asks
70/// [`image_status_changed`] and runs the reactive flush.
71pub 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
88/// Whether a report since the last call changed an image's status
89/// signal, so the platform runs the reactive flush for what reads it.
90pub fn image_status_changed() -> bool {
91  STATUS_CHANGED.with(|changed| changed.replace(false))
92}
93
94/// Whether an image with a `status` signal got a new source since the
95/// last call, so its picture waits to load. The platform then has the
96/// renderer load each window's waiting images, drawn or not, as
97/// `Renderer::load_images` does, since a hidden image may be shown only
98/// once it is Ready.
99pub fn image_sources_changed() -> bool {
100  SOURCES_CHANGED.with(|changed| changed.replace(false))
101}
102
103/// Writes `status` to `signal` if that changes it, and says whether it
104/// did.
105fn write_status(signal: Signal<ImageStatus>, status: ImageStatus) -> bool {
106  untrack(|| signal.try_get()) != Some(status) && signal.try_set(status)
107}
108
109/// Watches image `id`'s status with `signal`, from its source's binding.
110fn watch(id: u64, signal: Signal<ImageStatus>) {
111  WATCHED.with(|watched| watched.borrow_mut().push((id, signal, empty_source())));
112}
113
114/// Image `id` shows `source` now: its status goes back to Loading, or to
115/// Empty for an empty path or name.
116fn 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
132/// The source an image shows nothing for: an empty path.
133pub(crate) fn empty_source() -> IconSource {
134  IconSource::File(PathBuf::new())
135}
136
137/// Whether `source` is an empty path or icon name, which shows nothing.
138fn 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
146/// Whether image `id` has a `status` signal that still says Loading.
147pub(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/// How many images have a status watched, for tests.
158#[cfg(test)]
159pub(crate) fn watched_images() -> usize {
160  WATCHED.with(|watched| watched.borrow().len())
161}
162
163/// The ids of images removed, or in windows dropped, since the last call,
164/// so a renderer can let go of what it kept for them, such as the picture
165/// a transition was leaving.
166pub fn dropped_images() -> Vec<u64> {
167  DROPPED.with(|dropped| std::mem::take(&mut *dropped.borrow_mut()))
168}
169
170/// Tells image `id`'s transition that the renderer can't load its new
171/// `source`, so at its next tick it ends at once, leaving the old picture
172/// shown and its box still. The reverse of [`dropped_images`]: a renderer
173/// calls it while drawing. A report for an image with no transition
174/// running, or one to another source, changes nothing.
175pub 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
184/// Tells image `id`'s transition that the renderer is still decoding its
185/// new `source`, so its clock waits at the start, the old picture shown,
186/// until [`Window::repaint_image`] says the picture came in. A renderer
187/// calls it while drawing. A report for another source holds nothing.
188pub 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
201/// Whether the renderer said it is decoding `source` for image `id`.
202fn 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
211/// Forgets what the renderer said it decodes for image `id`.
212fn decoded(id: u64) {
213  let _ = DECODING.try_with(|decoding| decoding.borrow_mut().retain(|(at, _)| *at != id));
214}
215
216/// How many decoding reports are held, for tests.
217#[cfg(test)]
218pub(crate) fn decoding_reports() -> usize {
219  DECODING.with(|decoding| decoding.borrow().len())
220}
221
222/// How many reports wait for a transition's tick, for tests.
223#[cfg(test)]
224pub(crate) fn failed_reports() -> usize {
225  FAILED.with(|failed| failed.borrow().len())
226}
227
228/// Whether the renderer said image `id` can't load `source`, using up
229/// every report about `id`.
230fn 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    // At thread exit the list may be gone already; nobody is left to ask.
245    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    // A report about it would wait for a tick that never comes.
252    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/// How an [`Image`](crate::Image) shows a new source: at once, or coming
276/// in over the old picture over a [`Transition`], which gives its time,
277/// curve and delay. Both pictures are drawn at the image's size, fit and
278/// filters.
279///
280/// ```
281/// use crabshell_ui::{Easing, ImageTransition, Transition};
282///
283/// const WALLPAPER: ImageTransition =
284///     ImageTransition::wipe(Transition::new(800).easing(Easing::InOutCubic), 90.0);
285/// ```
286#[derive(Clone, Copy, Debug, Default, PartialEq)]
287pub enum ImageTransition {
288  /// The new picture replaces the old at once. The default.
289  #[default]
290  None,
291  /// The new picture fades in as the old one fades out.
292  Crossfade(Transition),
293  /// An edge sweeps across the box in the direction of the angle, in
294  /// degrees as CSS's gradient angle: 0 toward the top, 90 toward the
295  /// right. The new picture is behind it. An angle that isn't finite
296  /// counts as 90.
297  Wipe(Transition, f32),
298  /// A circle grows from the middle until it covers the box, the new
299  /// picture inside it.
300  Circle(Transition),
301  /// The old picture breaks into growing blocks and the new one sharpens
302  /// out of them.
303  Pixelate(Transition),
304}
305
306impl ImageTransition {
307  /// No transition: a new source shows at once.
308  pub const fn none() -> ImageTransition {
309    ImageTransition::None
310  }
311
312  /// A crossfade over `transition`.
313  pub const fn crossfade(transition: Transition) -> ImageTransition {
314    ImageTransition::Crossfade(transition)
315  }
316
317  /// A wipe toward `angle` degrees over `transition`.
318  pub const fn wipe(transition: Transition, angle: f32) -> ImageTransition {
319    ImageTransition::Wipe(transition, angle)
320  }
321
322  /// A circle reveal over `transition`.
323  pub const fn circle(transition: Transition) -> ImageTransition {
324    ImageTransition::Circle(transition)
325  }
326
327  /// A pixelation over `transition`.
328  pub const fn pixelate(transition: Transition) -> ImageTransition {
329    ImageTransition::Pixelate(transition)
330  }
331
332  /// Its time and curve, `None` for none.
333  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
344/// The picture a running transition leaves.
345pub(crate) struct Leaving {
346  pub(crate) source: IconSource,
347  /// How far along the transition is, eased.
348  pub(crate) t: f32,
349  /// Which transition of the image it is, so one replaced stops.
350  generation: u64,
351}
352
353/// `value` if it is finite and above 0, 0 if it is finite and not, and
354/// `unset` otherwise. Never -0, so equal filters hash alike.
355fn 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
365/// Sets `slot` to `value`: a change repaints, never lays out.
366fn 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      // A new picture of the same size only needs a repaint.
384      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        // Mid-transition, it leaves the picture most of the box shows.
399        let old = match image.leaving.take() {
400          Some(leaving) if leaving.t < 0.5 => Some(leaving.source),
401          _ => old,
402        };
403        // One not drawn yet has nothing to leave, and one going back to
404        // what it shows needs no transition.
405        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  /// Moves image `id`'s transition number `generation` with the animation
458  /// clock, repainting its box each tick, until it ends, when the old
459  /// picture is let go, or another replaces it.
460  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        // While its new picture is decoded, the clock waits at the start.
479        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            // Nothing on screen changes until the delay is over.
507            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      // A new picture of the same size only needs a repaint.
521      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  /// Repaints the box of image `id`, as when the renderer says a GIF's
537  /// next frame is due or a picture it decoded came in, which also ends
538  /// its transition's wait for it, and returns whether it did. An image in
539  /// another window, removed, hidden, not laid out yet, or at opacity 0 or
540  /// under a widget at opacity 0 repaints nothing: the renderer skips it.
541  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    // A picture that came in ends any wait for it.
548    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}