Skip to main content

crabshell_ui/
prop.rs

1//! Widget properties that take either a plain value or a closure.
2
3use std::cell::RefCell;
4use std::path::{Path, PathBuf};
5use std::rc::Rc;
6use std::time::Duration;
7
8use crate::animation::Transition;
9use crate::image::ImageTransition;
10use crate::input::CursorShape;
11use crate::menu::MenuEntry;
12use crate::popup::Adjust;
13use crate::region::Region;
14use crate::rich::Span;
15use crate::screencopy::CaptureSource;
16use crate::style::{Color, Style};
17use crate::widgets::{Align, Elide, Fit, IconSource, Justify};
18use crate::window::{Anchors, Edge, KeyboardFocus, Layer, Margins};
19
20/// A widget property: either a value set once, or a binding that reruns
21/// whenever a signal it read changes.
22///
23/// You never build one yourself. Widget methods take `impl IntoProp<T>`, so
24/// `.height(30)` sets a value and `.height(move || ...)` makes a binding.
25pub struct Prop<T>(pub(crate) PropKind<T>);
26
27impl<T: Clone + 'static> Prop<T> {
28  /// The property as a closure that can be called again and shared, as a
29  /// widget built from other widgets hands one property to many of them.
30  /// A binding stays one: whatever calls it subscribes to the signals it
31  /// reads.
32  pub fn shared(self) -> Rc<dyn Fn() -> T> {
33    match self.0 {
34      PropKind::Value(value) => Rc::new(move || value.clone()),
35      PropKind::Binding(compute) => {
36        let compute = RefCell::new(compute);
37        Rc::new(move || (compute.borrow_mut())())
38      }
39    }
40  }
41}
42
43impl<T: 'static> Prop<T> {
44  /// The property with `f` applied to each value it takes.
45  pub(crate) fn map<U>(self, f: impl Fn(T) -> U + 'static) -> Prop<U> {
46    Prop(match self.0 {
47      PropKind::Value(value) => PropKind::Value(f(value)),
48      PropKind::Binding(mut compute) => PropKind::Binding(Box::new(move || f(compute()))),
49    })
50  }
51}
52
53pub(crate) enum PropKind<T> {
54  Value(T),
55  Binding(Box<dyn FnMut() -> T>),
56}
57
58/// Anything a widget property accepts: a value of type `T`, or a closure
59/// that returns one.
60///
61/// Plain values work for the property types this crate uses, and a string
62/// slice works where a `String` is expected. Any `FnMut() -> T` closure
63/// works too: it runs in an effect, so it reruns when a signal it read
64/// changes.
65pub trait IntoProp<T> {
66  /// Wraps the value or closure.
67  fn into_prop(self) -> Prop<T>;
68}
69
70// A closure is a binding. This impl can sit next to the value impls below
71// because Rust knows that no plain type like `u32` implements `FnMut`.
72impl<T, F> IntoProp<T> for F
73where
74  F: FnMut() -> T + 'static,
75{
76  fn into_prop(self) -> Prop<T> {
77    Prop(PropKind::Binding(Box::new(self)))
78  }
79}
80
81/// A property taken from one widget can be handed to another, as a widget
82/// built from others passes its own on.
83impl<T> IntoProp<T> for Prop<T> {
84  fn into_prop(self) -> Prop<T> {
85    self
86  }
87}
88
89/// Any `Option` passes as a plain value, as `None` or `Some(value)`. It
90/// can sit beside the closure impl for the same reason the ones below do.
91impl<T> IntoProp<Option<T>> for Option<T> {
92  fn into_prop(self) -> Prop<Option<T>> {
93    Prop(PropKind::Value(self))
94  }
95}
96
97/// Lets each listed type be passed as a plain value.
98macro_rules! value_props {
99    ($($ty:ty),* $(,)?) => {
100        $(
101            impl IntoProp<$ty> for $ty {
102                fn into_prop(self) -> Prop<$ty> {
103                    Prop(PropKind::Value(self))
104                }
105            }
106        )*
107    };
108}
109
110value_props!(
111  bool,
112  u32,
113  i32,
114  f32,
115  String,
116  Style,
117  Align,
118  Elide,
119  Justify,
120  Anchors,
121  Layer,
122  Margins,
123  KeyboardFocus,
124  PathBuf,
125  Fit,
126  (u32, u32),
127  Adjust,
128  IconSource,
129  CaptureSource,
130  Vec<MenuEntry>,
131  Vec<Span>,
132  Duration,
133  CursorShape,
134  Transition,
135  ImageTransition,
136);
137
138impl IntoProp<String> for &str {
139  fn into_prop(self) -> Prop<String> {
140    Prop(PropKind::Value(self.to_owned()))
141  }
142}
143
144impl IntoProp<Option<Region>> for Region {
145  fn into_prop(self) -> Prop<Option<Region>> {
146    Prop(PropKind::Value(Some(self)))
147  }
148}
149
150impl IntoProp<Option<usize>> for usize {
151  fn into_prop(self) -> Prop<Option<usize>> {
152    Prop(PropKind::Value(Some(self)))
153  }
154}
155
156impl IntoProp<Option<Color>> for Color {
157  fn into_prop(self) -> Prop<Option<Color>> {
158    Prop(PropKind::Value(Some(self)))
159  }
160}
161
162impl IntoProp<Option<IconSource>> for IconSource {
163  fn into_prop(self) -> Prop<Option<IconSource>> {
164    Prop(PropKind::Value(Some(self)))
165  }
166}
167
168impl IntoProp<Option<Style>> for Style {
169  fn into_prop(self) -> Prop<Option<Style>> {
170    Prop(PropKind::Value(Some(self)))
171  }
172}
173
174/// A size where one is optional, such as an image's `decode_size((960, 540))`.
175impl IntoProp<Option<(u32, u32)>> for (u32, u32) {
176  fn into_prop(self) -> Prop<Option<(u32, u32)>> {
177    Prop(PropKind::Value(Some(self)))
178  }
179}
180
181/// A number where one is optional, such as a slider's `limit(50.0)`.
182impl IntoProp<Option<f32>> for f32 {
183  fn into_prop(self) -> Prop<Option<f32>> {
184    Prop(PropKind::Value(Some(self)))
185  }
186}
187
188impl IntoProp<Anchors> for Edge {
189  fn into_prop(self) -> Prop<Anchors> {
190    Prop(PropKind::Value(Anchors::from(self)))
191  }
192}
193
194/// An icon name, such as `"audio-volume-high"`.
195impl IntoProp<IconSource> for &str {
196  fn into_prop(self) -> Prop<IconSource> {
197    Prop(PropKind::Value(IconSource::Name(self.to_owned())))
198  }
199}
200
201/// An icon name, as tray items send them.
202impl IntoProp<IconSource> for String {
203  fn into_prop(self) -> Prop<IconSource> {
204    Prop(PropKind::Value(IconSource::Name(self)))
205  }
206}
207
208impl IntoProp<PathBuf> for &Path {
209  fn into_prop(self) -> Prop<PathBuf> {
210    Prop(PropKind::Value(self.to_owned()))
211  }
212}
213
214impl IntoProp<PathBuf> for &PathBuf {
215  fn into_prop(self) -> Prop<PathBuf> {
216    Prop(PropKind::Value(self.clone()))
217  }
218}
219
220impl IntoProp<PathBuf> for &str {
221  fn into_prop(self) -> Prop<PathBuf> {
222    Prop(PropKind::Value(PathBuf::from(self)))
223  }
224}
225
226impl IntoProp<PathBuf> for String {
227  fn into_prop(self) -> Prop<PathBuf> {
228    Prop(PropKind::Value(PathBuf::from(self)))
229  }
230}
231
232/// An SVG or PNG file.
233impl IntoProp<IconSource> for &Path {
234  fn into_prop(self) -> Prop<IconSource> {
235    Prop(PropKind::Value(IconSource::File(self.to_owned())))
236  }
237}
238
239/// An SVG or PNG file.
240impl IntoProp<IconSource> for PathBuf {
241  fn into_prop(self) -> Prop<IconSource> {
242    Prop(PropKind::Value(IconSource::File(self)))
243  }
244}
245
246#[cfg(test)]
247mod tests {
248  use std::path::PathBuf;
249
250  use super::{IntoProp, PropKind};
251
252  fn value(prop: impl IntoProp<PathBuf>) -> Option<PathBuf> {
253    match prop.into_prop().0 {
254      PropKind::Value(value) => Some(value),
255      PropKind::Binding(_) => None,
256    }
257  }
258
259  #[test]
260  fn a_path_buf_by_reference_is_a_plain_value() {
261    let path = PathBuf::from("/walls");
262    assert_eq!(value(&path), Some(path.clone()));
263    assert_eq!(value(path.as_path()), Some(path.clone()));
264    assert_eq!(value("/walls"), Some(path));
265  }
266}