Skip to main content

crabshell_ui/
capture.rs

1//! [`Capture`], one frame of an output or a window that any number of
2//! screencopy views show, and what the platform reads and writes of it.
3
4use std::cell::RefCell;
5use std::panic::Location;
6
7use crabshell_reactive::{ReadSignal, Signal, untrack};
8
9use crate::cx::Cx;
10use crate::prop::{IntoProp, PropKind};
11use crate::screencopy::{CaptureFrame, CaptureSource, next_id};
12
13thread_local! {
14  /// Every capture made, for the platform to find those waiting for a
15  /// frame. Per thread, like the reactive runtime.
16  static CAPTURES: RefCell<Vec<Capture>> = const { RefCell::new(Vec::new()) };
17}
18
19/// One captured frame of an output or a window, made by
20/// [`Cx::capture`], for [`ScreencopyView::of`](crate::ScreencopyView::of)
21/// views to show. It is a `Copy` handle, like a signal, and goes with the
22/// context that made it. Calls on a capture whose context is gone do
23/// nothing.
24///
25/// Every view of it shows the same frame, and none of them captures
26/// anything itself, so a frame shown whole and cut into pieces is taken
27/// once. A capture takes its frame at once, whether or not a view shows
28/// it, and then wakes nothing until [`refresh`](Self::refresh). It holds
29/// the source's whole frame, at the source's own resolution.
30///
31/// A capture of an output holds the shell's own windows on it too, so
32/// hide a view of the output that covers it before you refresh.
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub struct Capture {
35  /// `None` until the source's binding first runs.
36  source: Signal<Option<CaptureSource>>,
37  frame: Signal<Option<CaptureFrame>>,
38  ready: Signal<bool>,
39  /// The number the frame waited for is asked under, never reused, so a
40  /// frame asked for before a refresh or another source is turned away.
41  /// `None` while no frame is waited for.
42  asked: Signal<Option<u64>>,
43}
44
45impl Cx {
46  /// A capture of `source`: a [`CaptureSource`], or a closure that
47  /// returns one. It takes one frame as soon as the source is there,
48  /// waiting while it isn't, as for an output not plugged in yet. A new
49  /// source drops the frame and takes one of the new source. The capture
50  /// belongs to this context and goes with it.
51  ///
52  /// The frame, about 8 MB for a 1920 by 1080 output, stays in memory
53  /// until the capture's context goes, even once no view shows it. So
54  /// make a capture for a passing effect in a child context, from
55  /// [`Cx::child`], and dispose that context's owner after use.
56  ///
57  /// ```
58  /// use crabshell_reactive::Runtime;
59  /// use crabshell_ui::{CaptureSource, Cx, Rect, ScreencopyView, Style};
60  ///
61  /// let cx = Cx::new(Runtime::current().new_owner());
62  /// let screen = cx.capture(CaptureSource::Output(String::from("DP-1")));
63  /// let whole = ScreencopyView::of(screen).style(Style::new().width(1920.0).height(1080.0));
64  /// let corner = ScreencopyView::of(screen)
65  ///     .crop(Some(Rect::new(0.0, 0.0, 480.0, 270.0)))
66  ///     .style(Style::new().width(480.0).height(270.0));
67  /// # let _ = (whole, corner);
68  /// ```
69  #[track_caller]
70  pub fn capture(&self, source: impl IntoProp<CaptureSource>) -> Capture {
71    let capture = Capture {
72      source: self.signal(None),
73      frame: self.signal(None),
74      ready: self.signal(false),
75      asked: self.signal(None),
76    };
77    match source.into_prop().0 {
78      PropKind::Value(source) => capture.retarget(source),
79      PropKind::Binding(mut compute) => {
80        let place = self
81          .owner()
82          .name()
83          .map(|name| format!(" in {name}"))
84          .unwrap_or_default();
85        let label = format!("cx.capture source at {}{place}", Location::caller());
86        self
87          .effect(move || {
88            let source = compute();
89            untrack(|| capture.retarget(source));
90          })
91          .named(label);
92      }
93    }
94    CAPTURES.with(|captures| captures.borrow_mut().push(capture));
95    capture
96  }
97}
98
99impl Capture {
100  /// Whether it holds a frame of its source taken since the last
101  /// [`refresh`](Self::refresh): `false` from a refresh until the new
102  /// frame lands, while its views keep showing the old one.
103  pub fn ready(&self) -> ReadSignal<bool> {
104    self.ready.read_only()
105  }
106
107  /// Takes a new frame. [`ready`](Self::ready) reads `false` from now
108  /// until the new frame lands, so wait for it to turn `true` before you
109  /// rely on the new picture; the views keep showing the old one
110  /// meanwhile. A refresh while a frame is on its way asks again, and
111  /// the earlier frame is turned away.
112  pub fn refresh(&self) {
113    if untrack(|| self.source.try_with(Option::is_some)) == Some(true) {
114      self.ready.try_set(false);
115      self.asked.try_set(Some(next_id()));
116    }
117  }
118
119  /// Takes `source`, dropping the frame of another.
120  fn retarget(&self, source: CaptureSource) {
121    if self.source.try_with(|now| now.as_ref() == Some(&source)) != Some(false) {
122      return;
123    }
124    self.source.try_set(Some(source));
125    if self.frame.try_with(Option::is_some) == Some(true) {
126      self.frame.try_set(None);
127    }
128    if self.ready.try_get() == Some(true) {
129      self.ready.try_set(false);
130    }
131    self.asked.try_set(Some(next_id()));
132  }
133
134  /// The frame its views show, for their bindings.
135  pub(crate) fn frame(&self) -> Option<CaptureFrame> {
136    self.frame.try_get().flatten()
137  }
138}
139
140/// The captures waiting for a frame, for the platform: the number each
141/// frame is asked under, for [`deliver_capture`], and the source. Captures
142/// whose context is gone are freed first.
143pub fn wanted_captures() -> Vec<(u64, CaptureSource)> {
144  untrack(|| {
145    CAPTURES.with(|captures| {
146      let mut captures = captures.borrow_mut();
147      captures.retain(|capture| capture.asked.try_get().is_some());
148      captures
149        .iter()
150        .filter_map(|capture| {
151          let asked = capture.asked.try_get().flatten()?;
152          Some((asked, capture.source.try_get().flatten()?))
153        })
154        .collect()
155    })
156  })
157}
158
159/// Gives the capture that asked for a frame under `asked` its frame, and
160/// returns whether one did: a frame asked for before a refresh or a new
161/// source is turned away.
162pub fn deliver_capture(asked: u64, frame: CaptureFrame) -> bool {
163  let found = CAPTURES.with(|captures| {
164    let captures = captures.borrow();
165    let mut all = captures.iter();
166    all
167      .find(|capture| untrack(|| capture.asked.try_get()) == Some(Some(asked)))
168      .copied()
169  });
170  let Some(capture) = found else {
171    return false;
172  };
173  // Written with the table released: a write drops the old frame.
174  capture.asked.try_set(None);
175  capture.frame.try_set(Some(frame));
176  capture.ready.try_set(true);
177  true
178}