Skip to main content

crabshell_ui/
widgets.rs

1//! The widgets, and the [`Widget`] trait they share.
2//!
3//! A widget value is only a description. Nothing happens until its window is
4//! created: then each description becomes a node in the window's tree, and
5//! each closure property becomes an effect that updates that node.
6
7use std::hash::Hash;
8use std::path::PathBuf;
9use std::rc::Rc;
10use std::time::Duration;
11
12use crabshell_reactive::{Memo, Signal};
13
14use crate::cx::Cx;
15use crate::geometry::{Point, Rect, Size};
16use crate::image::ImageTransition;
17use crate::input::{
18  CursorShape, Drag, DragValue, DropTarget, Handler, Handlers, LinkHandler, Wheel,
19};
20use crate::keyboard::KeyEvent;
21use crate::keyed::{self, KeyedList, KeyedMount};
22use crate::prop::{IntoProp, Prop};
23use crate::rich::Span;
24use crate::screencopy::ScreencopyProps;
25use crate::scroll::ScrollProps;
26use crate::style::{Color, Style};
27use crate::text_input::InputProps;
28
29/// Something that can be placed in a window: one of this crate's widgets, or
30/// a type of your own that is made of them.
31///
32/// To make your own, return another widget's element. Calling
33/// `into_element` on a container describes everything inside it too, so the
34/// result is plain data:
35///
36/// ```
37/// use crabshell_ui::{Element, Row, Text, Widget};
38///
39/// struct Greeting;
40///
41/// impl Widget for Greeting {
42///     fn into_element(self: Box<Self>) -> Element {
43///         Box::new(Row::new().gap(4).child(Text::new("hello")).child(Text::new("world")))
44///             .into_element()
45///     }
46/// }
47/// ```
48pub trait Widget: 'static {
49  /// Turns the description, and everything inside it, into the element
50  /// the window builds nodes from. It runs when the window is created or a
51  /// list item first appears, before the window's tree is touched and
52  /// without recording what it reads, so it only describes.
53  fn into_element(self: Box<Self>) -> Element;
54}
55
56/// What a [`Widget`] turns into: plain data, with every child already turned
57/// into its element. Only this crate's widgets create one.
58pub struct Element {
59  pub(crate) name: &'static str,
60  pub(crate) common: Common,
61  pub(crate) kind: ElementKind,
62  pub(crate) children: Vec<ElementChild>,
63}
64
65pub(crate) enum ElementKind {
66  Flex(FlexProps),
67  Grid(GridProps),
68  Stack,
69  Spacer,
70  Text(TextProps),
71  Icon(IconProps),
72  Image(ImageProps),
73  Capture(ScreencopyProps),
74  Canvas(Box<dyn FnMut(&mut crate::canvas::Pen)>),
75  // Boxed: a button's handlers make it the largest by far.
76  Button(Box<ButtonProps>),
77  // Boxed: its scroll bar's style makes it large.
78  Scroll(Box<ScrollProps>),
79  Input(Box<InputProps>),
80}
81
82/// What every widget takes besides its own properties.
83#[derive(Default)]
84pub(crate) struct Common {
85  pub(crate) style: Option<Prop<Style>>,
86  pub(crate) visible: Option<Prop<bool>>,
87  pub(crate) geometry: Option<Signal<Rect>>,
88  pub(crate) mapped_geometry: Option<Signal<Rect>>,
89  /// Told the widget's size after each layout that changes it, with the
90  /// tree released. Lists measure their rows with it; configs have
91  /// `geometry`.
92  pub(crate) measure: Option<Measure>,
93}
94
95/// What a list runs with a row's size after a layout changes it.
96pub(crate) type Measure = Rc<dyn Fn(Size)>;
97
98/// One entry of a container's child list: a single widget, or a keyed list
99/// that grows and shrinks.
100pub(crate) enum Child {
101  One(Box<dyn Widget>),
102  Keyed(KeyedList),
103}
104
105/// A [`Child`] with its widget turned into an element.
106pub(crate) enum ElementChild {
107  One(Box<Element>),
108  Keyed(KeyedMount),
109}
110
111/// Turns every child widget into its element, which does the same for its
112/// own children.
113fn describe(children: Vec<Child>) -> Vec<ElementChild> {
114  children
115    .into_iter()
116    .map(|child| match child {
117      Child::One(widget) => ElementChild::One(Box::new(widget.into_element())),
118      Child::Keyed(list) => ElementChild::Keyed(list.into_mount()),
119    })
120    .collect()
121}
122
123pub(crate) struct FlexProps {
124  pub(crate) column: bool,
125  /// Takes the room left in its parent, like a spacer. Only `Menu` sets
126  /// it, so an entry's row fills its button.
127  pub(crate) grow: bool,
128  pub(crate) gap: Option<Prop<u32>>,
129  pub(crate) padding_vertical: Option<Prop<u32>>,
130  pub(crate) padding_horizontal: Option<Prop<u32>>,
131  pub(crate) align: Option<Prop<Align>>,
132  pub(crate) justify: Option<Prop<Justify>>,
133  pub(crate) wrap: Option<Prop<bool>>,
134  pub(crate) reverse: Option<Prop<bool>>,
135  /// Overrides `column` with a binding, for a list that turns.
136  pub(crate) column_binding: Option<Prop<bool>>,
137}
138
139pub(crate) struct GridProps {
140  pub(crate) columns: Option<Prop<u32>>,
141  pub(crate) gap: Option<Prop<u32>>,
142  pub(crate) row_gap: Option<Prop<u32>>,
143  pub(crate) column_gap: Option<Prop<u32>>,
144  pub(crate) padding_vertical: Option<Prop<u32>>,
145  pub(crate) padding_horizontal: Option<Prop<u32>>,
146}
147
148pub(crate) struct TextProps {
149  /// The plain text, or for a rich text `None` and its spans.
150  pub(crate) text: Option<Prop<String>>,
151  pub(crate) spans: Option<Prop<Vec<Span>>>,
152  pub(crate) elide: Option<Prop<Elide>>,
153  pub(crate) max_lines: Option<Prop<u32>>,
154  pub(crate) selectable: Option<Prop<bool>>,
155  pub(crate) on_link: Option<LinkHandler>,
156  pub(crate) link_hover_color: Option<Prop<Option<Color>>>,
157}
158
159pub(crate) struct IconProps {
160  pub(crate) source: Prop<IconSource>,
161  pub(crate) size: Option<Prop<u32>>,
162  pub(crate) tint: Option<Prop<Option<Color>>>,
163}
164
165pub(crate) struct ImageProps {
166  pub(crate) source: Prop<PathBuf>,
167  pub(crate) width: Option<Prop<u32>>,
168  pub(crate) height: Option<Prop<u32>>,
169  pub(crate) fit: Option<Prop<Fit>>,
170  pub(crate) tint: Option<Prop<Option<Color>>>,
171  pub(crate) brightness: Option<Prop<f32>>,
172  pub(crate) contrast: Option<Prop<f32>>,
173  pub(crate) saturation: Option<Prop<f32>>,
174  pub(crate) blur: Option<Prop<f32>>,
175  pub(crate) playing: Option<Prop<bool>>,
176  pub(crate) transition: Option<Prop<ImageTransition>>,
177}
178
179/// The filters an [`Image`] is drawn through, for the renderer. Each
180/// number is finite and at least 0, and the default changes nothing.
181#[derive(Clone, Copy, Debug, PartialEq)]
182pub struct ImageFilters {
183  /// The color every pixel is painted in, keeping its alpha.
184  pub tint: Option<Color>,
185  /// Scales each color channel, as CSS's `brightness()`.
186  pub brightness: f32,
187  /// Moves each channel from or toward the middle gray, as CSS's
188  /// `contrast()`.
189  pub contrast: f32,
190  /// Moves each color from or toward its gray, as CSS's `saturate()`.
191  pub saturation: f32,
192  /// A Gaussian blur's standard deviation in logical pixels, as CSS's
193  /// `blur()`.
194  pub blur: f32,
195}
196
197impl Default for ImageFilters {
198  fn default() -> ImageFilters {
199    ImageFilters {
200      tint: None,
201      brightness: 1.0,
202      contrast: 1.0,
203      saturation: 1.0,
204      blur: 0.0,
205    }
206  }
207}
208
209/// How an [`Image`] fills its box when their shapes differ, as CSS's
210/// `object-fit`.
211#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
212pub enum Fit {
213  /// Stretched to the box. The default.
214  #[default]
215  Fill,
216  /// As large as fits whole, centered, keeping its shape.
217  Contain,
218  /// Covering the whole box, centered, keeping its shape; what sticks out
219  /// is cut off.
220  Cover,
221}
222
223pub(crate) struct ButtonProps {
224  pub(crate) hover_style: Option<Prop<Style>>,
225  pub(crate) pressed_style: Option<Prop<Style>>,
226  pub(crate) focus_style: Option<Prop<Style>>,
227  pub(crate) hovered: Option<Signal<bool>>,
228  pub(crate) position: Option<Signal<Option<Point>>>,
229  pub(crate) enabled: Option<Prop<bool>>,
230  pub(crate) focus: Option<Prop<bool>>,
231  pub(crate) cursor: Option<Prop<CursorShape>>,
232  pub(crate) drag_data: Option<Prop<Option<DragValue>>>,
233  pub(crate) drop_hovered: Option<Signal<bool>>,
234  pub(crate) handlers: Handlers,
235}
236
237/// How a [`Row`] or [`Column`] places children across its direction: up and
238/// down in a row, left and right in a column. As a child's own
239/// [`Style::align_self`] and [`Style::justify_self`], it also places the
240/// child in a [`Stack`]'s or grid's cell: start is the top or the left.
241#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
242pub enum Align {
243  /// At the start: the top of a row, the left of a column.
244  Start,
245  /// In the middle.
246  Center,
247  /// At the end: the bottom of a row, the right of a column.
248  End,
249  /// Stretched to fill. The default, as in CSS.
250  #[default]
251  Stretch,
252}
253
254/// How a [`Row`] or [`Column`] places children along its direction when
255/// they don't fill it.
256#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
257pub enum Justify {
258  /// Packed at the start. The default.
259  #[default]
260  Start,
261  /// Packed in the middle.
262  Center,
263  /// Packed at the end.
264  End,
265  /// The first child at the start, the last at the end, equal space between.
266  SpaceBetween,
267  /// Equal space around each child.
268  SpaceAround,
269  /// Equal space between children and at both ends.
270  SpaceEvenly,
271}
272
273/// What an [`Icon`] shows.
274#[derive(Clone, Debug, PartialEq)]
275pub enum IconSource {
276  /// A freedesktop icon name such as `"audio-volume-high"`, looked up in
277  /// the icon theme.
278  Name(String),
279  /// An SVG or PNG file.
280  File(PathBuf),
281  /// Raw pixels, as a tray item sends them.
282  Pixels(IconPixels),
283}
284
285/// Raw icon pixels: ARGB32 in network byte order (A, R, G, B bytes), row
286/// by row, as the StatusNotifierItem spec sends them.
287#[derive(Clone, Debug, PartialEq)]
288pub struct IconPixels {
289  /// Width in pixels.
290  pub width: u32,
291  /// Height in pixels.
292  pub height: u32,
293  /// `width * height * 4` bytes. Shared, so the same icon isn't copied.
294  pub data: Rc<[u8]>,
295}
296
297/// The methods every container has: `child`, `children_keyed`, `exit`
298/// and `displaced`.
299macro_rules! container_methods {
300  () => {
301    /// Adds `child` after the children added so far.
302    pub fn child(mut self, child: impl Widget) -> Self {
303      self.children.push(Child::One(Box::new(child)));
304      self
305    }
306
307    /// Adds one child per item, after the children added so far.
308    ///
309    /// `items` runs in an effect, so the list updates when a signal it
310    /// read changes. `key` names each item. `view` builds the child for
311    /// a key the first time it appears, and that child is kept while
312    /// its key stays in the list, even if it moves. `view` receives the
313    /// item's [`Cx`] and a [`Memo`] that updates when that item's value
314    /// changes. When a key leaves the list, its child and everything
315    /// created in `view` are freed, at once or after an
316    /// [`exit`](Self::exit). If two items share a key, only the first is
317    /// shown and the duplicate is logged.
318    pub fn children_keyed<T, K, W>(
319      mut self,
320      items: impl FnMut() -> Vec<T> + 'static,
321      key: impl FnMut(&T) -> K + 'static,
322      view: impl FnMut(&Cx, Memo<T>) -> W + 'static,
323    ) -> Self
324    where
325      T: Clone + PartialEq + 'static,
326      K: Eq + Hash + 'static,
327      W: Widget,
328    {
329      self
330        .children
331        .push(Child::Keyed(keyed::mount(items, key, view)));
332      self
333    }
334
335    /// Lets the children of the last [`children_keyed`](Self::children_keyed)
336    /// list added leave over `exit` instead of at once. A child whose key
337    /// leaves stays mounted and painted right after the child that was
338    /// before it, and its context's [`leaving`](Cx::leaving) turns `true`,
339    /// so its own `cx.animate` can fade or shrink it out. It is freed at
340    /// the first tick of the animation clock that finds nothing moving in
341    /// it, or after `exit` at the latest; motion the clock doesn't run in
342    /// the item, such as one stepped by `cx.interval`, doesn't hold it.
343    /// If its key comes back first, the same child, with its
344    /// state, takes the key's new place. A closure is read as each key
345    /// leaves, and an exit of 0 removes at once. Leaving children still
346    /// take pointer and keyboard input; a handler can check
347    /// [`cx.leaving()`](Cx::leaving) to ignore clicks during the exit.
348    pub fn exit(mut self, exit: impl IntoProp<Duration>) -> Self {
349      let last = self
350        .children
351        .iter_mut()
352        .rev()
353        .find_map(|child| match child {
354          Child::Keyed(list) => Some(list),
355          Child::One(_) => None,
356        });
357      match last {
358        Some(list) => list.exit = Some(exit.into_prop()),
359        None => tracing::warn!("`exit` was called before any `children_keyed`; it does nothing"),
360      }
361      self
362    }
363
364    /// Slides the children that a change of the last
365    /// [`children_keyed`](Self::children_keyed) list moves, instead of
366    /// jumping: when its keys are added, leave (once their
367    /// [`exit`](Self::exit) ends) or move, each child of this container
368    /// whose place changes goes from where it was drawn to its new place
369    /// over `transition`. It moves where it is drawn and hit, as
370    /// [`Style::translate`](crate::Style::translate) does, so a slide never
371    /// lays the window out again. A child moved again mid-slide starts from
372    /// where it is drawn. Other layout changes, such as a resize or text
373    /// growing, still move children at once, and a new child shows in its
374    /// place. A closure is read at each change of the list, and a
375    /// transition of 0 jumps.
376    pub fn displaced(mut self, transition: impl IntoProp<crate::Transition>) -> Self {
377      let last = self
378        .children
379        .iter_mut()
380        .rev()
381        .find_map(|child| match child {
382          Child::Keyed(list) => Some(list),
383          Child::One(_) => None,
384        });
385      match last {
386        Some(list) => list.displaced = Some(transition.into_prop()),
387        None => {
388          tracing::warn!("`displaced` was called before any `children_keyed`; it does nothing")
389        }
390      }
391      self
392    }
393  };
394}
395
396/// The `visible`, `geometry` and `mapped_geometry` methods every widget
397/// has.
398macro_rules! visibility_methods {
399  () => {
400    /// Shows or hides the widget. Hidden, it is taken out of the layout,
401    /// so its space goes to the others, and it isn't drawn, hit or
402    /// reached by Tab; it drops the keyboard focus and the pointer. Its
403    /// bindings and state stay, so it shows again as it was. Shown by
404    /// default.
405    pub fn visible(mut self, visible: impl $crate::IntoProp<bool>) -> Self {
406      self.common.visible = Some(visible.into_prop());
407      self
408    }
409
410    /// Shares where the widget is: after each layout that moves or
411    /// resizes it, its laid-out rectangle in the window's logical
412    /// pixels, scrolled with any scroll view around it but not moved by
413    /// a style's translate, scale or rotate, is written to `geometry`. A
414    /// hidden widget writes nothing. An effect that reads it may change
415    /// the layout: the window is laid out again at once, until nothing
416    /// moves.
417    pub fn geometry(mut self, geometry: ::crabshell_reactive::Signal<$crate::Rect>) -> Self {
418      self.common.geometry = Some(geometry);
419      self
420    }
421
422    /// Shares where the widget is drawn: the box around it once its own
423    /// and its ancestors' translate, scale and rotate have moved it, in
424    /// the window's logical pixels, scrolled with any scroll view around
425    /// it. It is written after each layout that moves it and after each
426    /// change of a transform or an offset that does, every frame of an
427    /// animated one. A hidden widget writes nothing. Where the window
428    /// itself is on its output is unknown: Wayland doesn't tell a client.
429    pub fn mapped_geometry(mut self, geometry: ::crabshell_reactive::Signal<$crate::Rect>) -> Self {
430      self.common.mapped_geometry = Some(geometry);
431      self
432    }
433  };
434}
435
436/// The `style` method every widget has, with `visible` and `geometry`.
437macro_rules! style_method {
438  () => {
439    /// Sets the widget's [`Style`](crate::Style).
440    pub fn style(mut self, style: impl $crate::IntoProp<$crate::Style>) -> Self {
441      self.common.style = Some(style.into_prop());
442      self
443    }
444
445    $crate::widgets::visibility_methods!();
446  };
447}
448
449pub(crate) use visibility_methods;
450
451/// Defines `Row` and `Column`, which differ only in direction.
452macro_rules! flex_widget {
453  ($name:ident, $column:literal, $doc:literal) => {
454    #[doc = $doc]
455    ///
456    /// `gap`, `padding`, `align`, `justify`, `wrap` and `reverse` change
457    /// the layout. Each takes a value or a closure.
458    pub struct $name {
459      flex: FlexProps,
460      common: Common,
461      children: Vec<Child>,
462    }
463
464    impl $name {
465      /// An empty container.
466      pub fn new() -> Self {
467        $name {
468          flex: FlexProps {
469            column: $column,
470            grow: false,
471            gap: None,
472            padding_vertical: None,
473            padding_horizontal: None,
474            align: None,
475            justify: None,
476            wrap: None,
477            reverse: None,
478            column_binding: None,
479          },
480          common: Common::default(),
481          children: Vec::new(),
482        }
483      }
484
485      /// Sets the space between children in logical pixels.
486      pub fn gap(mut self, gap: impl IntoProp<u32>) -> Self {
487        self.flex.gap = Some(gap.into_prop());
488        self
489      }
490
491      /// Sets the padding: `vertical` above and below, `horizontal`
492      /// left and right, in logical pixels. It wins over the padding
493      /// of the container's [`Style`].
494      pub fn padding(
495        mut self,
496        vertical: impl IntoProp<u32>,
497        horizontal: impl IntoProp<u32>,
498      ) -> Self {
499        self.flex.padding_vertical = Some(vertical.into_prop());
500        self.flex.padding_horizontal = Some(horizontal.into_prop());
501        self
502      }
503
504      /// Sets how children are placed across the direction.
505      pub fn align(mut self, align: impl IntoProp<Align>) -> Self {
506        self.flex.align = Some(align.into_prop());
507        self
508      }
509
510      /// Sets how children are placed along the direction.
511      pub fn justify(mut self, justify: impl IntoProp<Justify>) -> Self {
512        self.flex.justify = Some(justify.into_prop());
513        self
514      }
515
516      /// When on, children that don't fit start a new line, `gap` apart
517      /// like the children, and the lines pack at the start. Off by
518      /// default.
519      pub fn wrap(mut self, wrap: impl IntoProp<bool>) -> Self {
520        self.flex.wrap = Some(wrap.into_prop());
521        self
522      }
523
524      /// When on, a row runs right to left and a column bottom to top, so
525      /// [`Justify::Start`] packs children at the right or the bottom.
526      /// Tab still moves through them in child order. Off by default.
527      pub fn reverse(mut self, reverse: impl IntoProp<bool>) -> Self {
528        self.flex.reverse = Some(reverse.into_prop());
529        self
530      }
531
532      container_methods!();
533      style_method!();
534    }
535
536    impl Default for $name {
537      fn default() -> Self {
538        Self::new()
539      }
540    }
541
542    impl Widget for $name {
543      fn into_element(self: Box<Self>) -> Element {
544        Element {
545          name: stringify!($name),
546          common: self.common,
547          kind: ElementKind::Flex(self.flex),
548          children: describe(self.children),
549        }
550      }
551    }
552  };
553}
554
555flex_widget!(
556  Row,
557  false,
558  "Lays its children out left to right, like a CSS flexbox row."
559);
560flex_widget!(
561  Column,
562  true,
563  "Lays its children out top to bottom, like a CSS flexbox column."
564);
565
566/// Places its children row by row into equal-width columns, each row as
567/// tall as its tallest child. A child takes several cells with
568/// [`Style::span`], and places itself in its cell with
569/// [`Style::align_self`] and [`Style::justify_self`]; it fills the cell by
570/// default.
571///
572/// `columns`, `gap`, `row_gap`, `column_gap` and `padding` change the
573/// layout. Each takes a value or a closure.
574///
575/// ```
576/// use crabshell_ui::{Grid, Style, Text};
577///
578/// let days = (1..=31).fold(Grid::new().columns(7).gap(4), |grid, day| {
579///     grid.child(Text::new(day.to_string()))
580/// });
581/// let wide = Grid::new()
582///     .columns(2)
583///     .child(Text::new("title").style(Style::new().span(2, 1)));
584/// ```
585pub struct Grid {
586  grid: GridProps,
587  common: Common,
588  children: Vec<Child>,
589}
590
591impl Grid {
592  /// An empty grid of one column.
593  pub fn new() -> Grid {
594    Grid {
595      grid: GridProps {
596        columns: None,
597        gap: None,
598        row_gap: None,
599        column_gap: None,
600        padding_vertical: None,
601        padding_horizontal: None,
602      },
603      common: Common::default(),
604      children: Vec::new(),
605    }
606  }
607
608  /// Sets the number of columns, all as wide. 1 by default, and 0
609  /// counts as 1.
610  pub fn columns(mut self, columns: impl IntoProp<u32>) -> Grid {
611    self.grid.columns = Some(columns.into_prop());
612    self
613  }
614
615  /// Sets the space between rows and between columns in logical pixels.
616  /// `row_gap` and `column_gap` win over it.
617  pub fn gap(mut self, gap: impl IntoProp<u32>) -> Grid {
618    self.grid.gap = Some(gap.into_prop());
619    self
620  }
621
622  /// Sets the space between rows in logical pixels.
623  pub fn row_gap(mut self, gap: impl IntoProp<u32>) -> Grid {
624    self.grid.row_gap = Some(gap.into_prop());
625    self
626  }
627
628  /// Sets the space between columns in logical pixels.
629  pub fn column_gap(mut self, gap: impl IntoProp<u32>) -> Grid {
630    self.grid.column_gap = Some(gap.into_prop());
631    self
632  }
633
634  /// Sets the padding: `vertical` above and below, `horizontal` left and
635  /// right, in logical pixels. It wins over the padding of the grid's
636  /// [`Style`], as a [`Row`]'s does.
637  pub fn padding(mut self, vertical: impl IntoProp<u32>, horizontal: impl IntoProp<u32>) -> Grid {
638    self.grid.padding_vertical = Some(vertical.into_prop());
639    self.grid.padding_horizontal = Some(horizontal.into_prop());
640    self
641  }
642
643  container_methods!();
644  style_method!();
645}
646
647impl Default for Grid {
648  fn default() -> Self {
649    Self::new()
650  }
651}
652
653impl Widget for Grid {
654  fn into_element(self: Box<Self>) -> Element {
655    Element {
656      name: "Grid",
657      common: self.common,
658      kind: ElementKind::Grid(self.grid),
659      children: describe(self.children),
660    }
661  }
662}
663
664/// Draws its children on top of each other in one cell, each stretched to
665/// the size of the largest. Later children are on top.
666pub struct Stack {
667  common: Common,
668  children: Vec<Child>,
669}
670
671impl Stack {
672  /// An empty stack.
673  pub fn new() -> Stack {
674    Stack {
675      common: Common::default(),
676      children: Vec::new(),
677    }
678  }
679
680  container_methods!();
681  style_method!();
682}
683
684impl Default for Stack {
685  fn default() -> Self {
686    Self::new()
687  }
688}
689
690impl Widget for Stack {
691  fn into_element(self: Box<Self>) -> Element {
692    Element {
693      name: "Stack",
694      common: self.common,
695      kind: ElementKind::Stack,
696      children: describe(self.children),
697    }
698  }
699}
700
701/// Takes the space left over in a [`Row`] or [`Column`]. Several spacers
702/// share it equally, or by their styles' [`grow`](Style::grow).
703pub struct Spacer {
704  common: Common,
705}
706
707impl Spacer {
708  /// A spacer.
709  pub fn new() -> Spacer {
710    Spacer {
711      common: Common::default(),
712    }
713  }
714
715  style_method!();
716}
717
718impl Default for Spacer {
719  fn default() -> Self {
720    Self::new()
721  }
722}
723
724impl Widget for Spacer {
725  fn into_element(self: Box<Self>) -> Element {
726    Element {
727      name: "Spacer",
728      common: self.common,
729      kind: ElementKind::Spacer,
730      children: Vec::new(),
731    }
732  }
733}
734
735/// Where text that doesn't fit is cut, with "…" in its place.
736#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
737pub enum Elide {
738  /// Not cut: the text keeps its width and overflows. The default.
739  #[default]
740  None,
741  /// The start of the last line shown.
742  Start,
743  /// The middle of the last line shown.
744  Middle,
745  /// The end of the last line shown.
746  End,
747}
748
749/// A line of text.
750///
751/// The text, `elide` and `max_lines` change the layout. Color, font,
752/// alignment, line height and decorations come from the nearest widget
753/// whose [`Style`] sets each, starting with the text's own.
754pub struct Text {
755  text: TextProps,
756  common: Common,
757}
758
759impl Text {
760  /// Text showing `text`: a string, or a closure that returns a `String`.
761  pub fn new(text: impl IntoProp<String>) -> Text {
762    Text {
763      text: TextProps {
764        text: Some(text.into_prop()),
765        spans: None,
766        elide: None,
767        max_lines: None,
768        selectable: None,
769        on_link: None,
770        link_hover_color: None,
771      },
772      common: Common::default(),
773    }
774  }
775
776  /// Text made of styled spans: a `Vec<Span>`, or a closure that returns
777  /// one. Each span takes what it doesn't set from the text, and
778  /// everything else a `Text` takes works the same.
779  pub fn rich(spans: impl IntoProp<Vec<Span>>) -> Text {
780    Text {
781      text: TextProps {
782        text: None,
783        spans: Some(spans.into_prop()),
784        elide: None,
785        max_lines: None,
786        selectable: None,
787        on_link: None,
788        link_hover_color: None,
789      },
790      common: Common::default(),
791    }
792  }
793
794  /// Runs `handler` with a link span's URL when a left click lands on
795  /// the span's glyphs. Over a link the cursor is the pointing hand and
796  /// the click goes to nothing else, not even a button around the text;
797  /// elsewhere the text lets the pointer through as before. In a
798  /// [`selectable`](Self::selectable) text, a press and release on one
799  /// link that selected nothing opens it, and a drag selects. Tab stops
800  /// on each link shown, in text order, and Enter or Space opens the one
801  /// focused. A link under the pointer or the focus draws underlined, in
802  /// [`link_hover_color`](Self::link_hover_color) if set. A handler that
803  /// panics is logged and disabled, and its links are plain text.
804  pub fn on_link(mut self, handler: impl Fn(&Cx, &str) + 'static) -> Text {
805    self.text.on_link = Some(Rc::new(Handler::new(handler)));
806    self
807  }
808
809  /// The color a link is drawn in while the pointer is over it or the
810  /// keyboard focus is on it: a color, `None`, or a closure returning
811  /// either. Either way the link is underlined; with `None`, the default,
812  /// it keeps its own color.
813  pub fn link_hover_color(mut self, color: impl IntoProp<Option<Color>>) -> Text {
814    self.text.link_hover_color = Some(color.into_prop());
815    self
816  }
817
818  /// When on, the text takes the pointer with an I-beam: a press, a drag,
819  /// a double click on a word, a triple click on a line and Shift+click
820  /// select it, as in a text field, and a
821  /// press takes the keyboard focus, so Ctrl+C copies the selection.
822  /// Inside a [`Button`], it takes the press, so the button doesn't
823  /// click. Tab doesn't stop on it. Off by default.
824  pub fn selectable(mut self, selectable: impl IntoProp<bool>) -> Text {
825    self.text.selectable = Some(selectable.into_prop());
826    self
827  }
828
829  /// When on, text that doesn't fit ends in "…" instead of being cut off.
830  /// Off by default. The same as [`elide`](Self::elide) with
831  /// [`Elide::End`] or [`Elide::None`]; whichever is called last wins.
832  pub fn ellipsis(mut self, ellipsis: impl IntoProp<bool>) -> Text {
833    let elide = ellipsis
834      .into_prop()
835      .map(|on| if on { Elide::End } else { Elide::None });
836    self.text.elide = Some(elide);
837    self
838  }
839
840  /// Where text that doesn't fit is cut, with "…" in its place:
841  /// [`Elide::None`] by default. With `max_lines` above 1, the last line
842  /// shown is cut.
843  pub fn elide(mut self, elide: impl IntoProp<Elide>) -> Text {
844    self.text.elide = Some(elide.into_prop());
845    self
846  }
847
848  /// Lets the text wrap onto at most this many lines, at word boundaries,
849  /// or inside a word too long for a line. The default is 1, which never
850  /// wraps. 0 counts as 1.
851  pub fn max_lines(mut self, max_lines: impl IntoProp<u32>) -> Text {
852    self.text.max_lines = Some(max_lines.into_prop());
853    self
854  }
855
856  style_method!();
857}
858
859impl Widget for Text {
860  fn into_element(self: Box<Self>) -> Element {
861    Element {
862      name: "Text",
863      common: self.common,
864      kind: ElementKind::Text(self.text),
865      children: Vec::new(),
866    }
867  }
868}
869
870/// An icon, drawn as a square.
871pub struct Icon {
872  icon: IconProps,
873  common: Common,
874}
875
876impl Icon {
877  /// The default size in logical pixels.
878  pub const DEFAULT_SIZE: u32 = 16;
879
880  /// An icon showing `source`: an icon name (`&str`), a file (`&Path` or
881  /// `PathBuf`), an [`IconSource`], or a closure that returns one.
882  pub fn new(source: impl IntoProp<IconSource>) -> Icon {
883    Icon {
884      icon: IconProps {
885        source: source.into_prop(),
886        size: None,
887        tint: None,
888      },
889      common: Common::default(),
890    }
891  }
892
893  /// Sets the width and height in logical pixels.
894  pub fn size(mut self, size: impl IntoProp<u32>) -> Icon {
895    self.icon.size = Some(size.into_prop());
896    self
897  }
898
899  /// Paints the icon's pixels in `tint`, keeping their alpha, as a
900  /// symbolic icon's color follows the theme. `None`, the default, draws
901  /// it as it is.
902  pub fn tint(mut self, tint: impl IntoProp<Option<Color>>) -> Icon {
903    self.icon.tint = Some(tint.into_prop());
904    self
905  }
906
907  style_method!();
908}
909
910/// A picture from a PNG, JPEG, GIF, WebP or SVG file, drawn at a fixed
911/// size.
912///
913/// A GIF of more than one frame plays while it is drawn, at its own
914/// delays, looping as the file says. The filters run once on the picture
915/// at the size drawn, and the result is cached, so a filtered image costs
916/// what a plain one does to draw.
917pub struct Image {
918  image: ImageProps,
919  common: Common,
920}
921
922impl Image {
923  /// The default width and height in logical pixels.
924  pub const DEFAULT_SIZE: u32 = 64;
925
926  /// An image of the file at `source`: a path (`&str`, `String`, `&Path`
927  /// or `PathBuf`) or a closure that returns one.
928  pub fn new(source: impl IntoProp<PathBuf>) -> Image {
929    Image {
930      image: ImageProps {
931        source: source.into_prop(),
932        width: None,
933        height: None,
934        fit: None,
935        tint: None,
936        brightness: None,
937        contrast: None,
938        saturation: None,
939        blur: None,
940        playing: None,
941        transition: None,
942      },
943      common: Common::default(),
944    }
945  }
946
947  /// Sets the width in logical pixels.
948  pub fn width(mut self, width: impl IntoProp<u32>) -> Image {
949    self.image.width = Some(width.into_prop());
950    self
951  }
952
953  /// Sets the height in logical pixels.
954  pub fn height(mut self, height: impl IntoProp<u32>) -> Image {
955    self.image.height = Some(height.into_prop());
956    self
957  }
958
959  /// Sets how the picture fills the image's box when their shapes differ.
960  pub fn fit(mut self, fit: impl IntoProp<Fit>) -> Image {
961    self.image.fit = Some(fit.into_prop());
962    self
963  }
964
965  /// Paints the picture's pixels in `tint`, keeping their alpha, as
966  /// [`Icon::tint`] does. `None`, the default, draws it as it is.
967  pub fn tint(mut self, tint: impl IntoProp<Option<Color>>) -> Image {
968    self.image.tint = Some(tint.into_prop());
969    self
970  }
971
972  /// Scales the colors, as CSS's `brightness()`: 1, the default, leaves
973  /// them, 0 is black and 2 twice as bright. A number that isn't finite
974  /// counts as 1, and one below 0 as 0.
975  pub fn brightness(mut self, brightness: impl IntoProp<f32>) -> Image {
976    self.image.brightness = Some(brightness.into_prop());
977    self
978  }
979
980  /// Sets the contrast, as CSS's `contrast()`: 1, the default, leaves the
981  /// colors, 0 is middle gray and more than 1 is stronger. A number that
982  /// isn't finite counts as 1, and one below 0 as 0.
983  pub fn contrast(mut self, contrast: impl IntoProp<f32>) -> Image {
984    self.image.contrast = Some(contrast.into_prop());
985    self
986  }
987
988  /// Sets the saturation, as CSS's `saturate()`: 1, the default, leaves
989  /// the colors, 0 is gray and more than 1 is more vivid. A number that
990  /// isn't finite counts as 1, and one below 0 as 0.
991  pub fn saturation(mut self, saturation: impl IntoProp<f32>) -> Image {
992    self.image.saturation = Some(saturation.into_prop());
993    self
994  }
995
996  /// Blurs the picture, as CSS's `blur()`: the Gaussian's standard
997  /// deviation in logical pixels, 0 by default. Pixels past the picture's
998  /// edge count as its edge pixels, so a blurred picture keeps its edges
999  /// opaque. A number that isn't finite or is below 0 counts as 0. The
1000  /// blur is for still pictures, such as album art and wallpapers: a
1001  /// blurred GIF shows its first frame, still.
1002  pub fn blur(mut self, blur: impl IntoProp<f32>) -> Image {
1003    self.image.blur = Some(blur.into_prop());
1004    self
1005  }
1006
1007  /// Whether an animated GIF plays, true by default. False pauses it on
1008  /// the frame it shows.
1009  pub fn playing(mut self, playing: impl IntoProp<bool>) -> Image {
1010    self.image.playing = Some(playing.into_prop());
1011    self
1012  }
1013
1014  /// How a new source comes in: [`ImageTransition::None`], the default,
1015  /// shows it at once; the others bring it in over the old picture on the
1016  /// animation clock, repainting only the image's box. A new source
1017  /// mid-transition starts again from the picture most of the box shows:
1018  /// the one leaving before halfway, the one coming in from halfway on.
1019  /// A new source that can't be loaded keeps the old picture; the clock
1020  /// still runs and repaints the box for the transition's length, since
1021  /// only the renderer learns the file is bad.
1022  pub fn transition(mut self, transition: impl IntoProp<ImageTransition>) -> Image {
1023    self.image.transition = Some(transition.into_prop());
1024    self
1025  }
1026
1027  style_method!();
1028}
1029
1030impl Widget for Image {
1031  fn into_element(self: Box<Self>) -> Element {
1032    Element {
1033      name: "Image",
1034      common: self.common,
1035      kind: ElementKind::Image(self.image),
1036      children: Vec::new(),
1037    }
1038  }
1039}
1040
1041impl Widget for Icon {
1042  fn into_element(self: Box<Self>) -> Element {
1043    Element {
1044      name: "Icon",
1045      common: self.common,
1046      kind: ElementKind::Icon(self.icon),
1047      children: Vec::new(),
1048    }
1049  }
1050}
1051
1052/// A clickable box around one child, which it centers.
1053///
1054/// While the pointer is over it, `hover_style` is laid over its style, and
1055/// while it is also held down, `pressed_style` on top of that. Handlers run
1056/// on the main thread and receive the button's [`Cx`]. A handler that panics
1057/// is logged and never called again.
1058pub struct Button {
1059  button: ButtonProps,
1060  common: Common,
1061  child: Box<dyn Widget>,
1062}
1063
1064impl Button {
1065  /// A button around `child`.
1066  pub fn new(child: impl Widget) -> Button {
1067    Button {
1068      child: Box::new(child),
1069      button: ButtonProps {
1070        hover_style: None,
1071        pressed_style: None,
1072        focus_style: None,
1073        hovered: None,
1074        position: None,
1075        enabled: None,
1076        focus: None,
1077        cursor: None,
1078        drag_data: None,
1079        drop_hovered: None,
1080        handlers: Handlers::default(),
1081      },
1082      common: Common::default(),
1083    }
1084  }
1085
1086  /// Sets the style laid over the normal one while the pointer is over the
1087  /// button.
1088  pub fn hover_style(mut self, style: impl IntoProp<Style>) -> Button {
1089    self.button.hover_style = Some(style.into_prop());
1090    self
1091  }
1092
1093  /// Shares whether the pointer is over the button: the button sets
1094  /// `hovered` to `true` while the pointer is over it or anything inside
1095  /// it, buttons too, and back to `false` when it leaves, the window loses
1096  /// it, or the button goes. Unlike `hover_style`, which only the deepest
1097  /// button under the pointer shows, an outer button stays hovered while
1098  /// the pointer is over one inside it, so it can show controls on hover.
1099  /// A drag of this button or one inside it keeps it hovered until the
1100  /// release.
1101  pub fn hovered(mut self, hovered: Signal<bool>) -> Button {
1102    self.button.hovered = Some(hovered);
1103    self
1104  }
1105
1106  /// Sets the style laid over the hover style while the button is held
1107  /// down.
1108  pub fn pressed_style(mut self, style: impl IntoProp<Style>) -> Button {
1109    self.button.pressed_style = Some(style.into_prop());
1110    self
1111  }
1112
1113  /// Sets the style laid over the normal one while the button has the
1114  /// keyboard focus, which Tab moves between buttons.
1115  pub fn focus_style(mut self, style: impl IntoProp<Style>) -> Button {
1116    self.button.focus_style = Some(style.into_prop());
1117    self
1118  }
1119
1120  /// Runs `handler` for each key pressed while the button has the
1121  /// keyboard focus. It returns `true` when it used the key; otherwise the
1122  /// window's `on_key` gets it, and then Tab, Enter and Space do what
1123  /// they do by default.
1124  pub fn on_key(mut self, handler: impl Fn(&Cx, &KeyEvent) -> bool + 'static) -> Button {
1125    self.button.handlers.key = Some(Rc::new(Handler::new(handler)));
1126    self
1127  }
1128
1129  /// Runs `handler` as soon as the left button goes down over this
1130  /// button, while it is held: the time to call
1131  /// [`Cx::start_move`](crate::Cx::start_move), as a title bar does.
1132  pub fn on_press(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1133    self.button.handlers.press = Some(Rc::new(Handler::new(handler)));
1134    self
1135  }
1136
1137  /// Runs `handler` when the left button comes up after going down on
1138  /// this button, wherever the pointer is by then, before `on_click`.
1139  pub fn on_release(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1140    self.button.handlers.release = Some(Rc::new(Handler::new(handler)));
1141    self
1142  }
1143
1144  /// Runs `handler` when the left button is pressed and released over this
1145  /// button, unless that ended a drag or a long press, or made a double
1146  /// click.
1147  pub fn on_click(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1148    self.button.handlers.click = Some(Rc::new(Handler::new(handler)));
1149    self
1150  }
1151
1152  /// Runs `handler` instead of a second `on_click` when a click comes
1153  /// within 400 ms and 5 logical pixels of the one before, as Qt's
1154  /// defaults say. A third click starts over. Without it, every click
1155  /// runs `on_click`.
1156  pub fn on_double_click(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1157    self.button.handlers.double_click = Some(Rc::new(Handler::new(handler)));
1158    self
1159  }
1160
1161  /// Runs `handler` once the left button has been held on this button for
1162  /// 800 ms without moving 10 logical pixels, as Qt's press and hold. The
1163  /// release after it doesn't click, though moving on can still drag.
1164  pub fn on_long_press(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1165    self.button.handlers.long_press = Some(Rc::new(Handler::new(handler)));
1166    self
1167  }
1168
1169  /// Runs `handler` as the left button drags this button: a
1170  /// [`DragPhase::Start`](crate::DragPhase::Start) once it moves 10
1171  /// logical pixels from where it went down, a `Move` for each motion
1172  /// after, and an `End` when it comes up, the pointer leaves the window,
1173  /// or the button is disabled. A button with no `on_click`,
1174  /// `on_double_click` or `on_long_press` starts at the press instead, so
1175  /// a slider moves from the first touch.
1176  ///
1177  /// While it drags, the button gets every motion, even outside itself or
1178  /// the window, stays hovered, and doesn't click.
1179  pub fn on_drag(mut self, handler: impl Fn(&Cx, Drag) + 'static) -> Button {
1180    self.button.handlers.drag = Some(Rc::new(Handler::new(handler)));
1181    self
1182  }
1183
1184  /// Runs `handler` when the right button is pressed and released over this
1185  /// button.
1186  pub fn on_right_click(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1187    self.button.handlers.right_click = Some(Rc::new(Handler::new(handler)));
1188    self
1189  }
1190
1191  /// Runs `handler` when the middle button is pressed and released over
1192  /// this button.
1193  pub fn on_middle_click(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1194    self.button.handlers.middle_click = Some(Rc::new(Handler::new(handler)));
1195    self
1196  }
1197
1198  /// Runs `handler` when the mouse's back side button is pressed and
1199  /// released over this button.
1200  pub fn on_back(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1201    self.button.handlers.back = Some(Rc::new(Handler::new(handler)));
1202    self
1203  }
1204
1205  /// Runs `handler` when the mouse's forward side button is pressed and
1206  /// released over this button.
1207  pub fn on_forward(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1208    self.button.handlers.forward = Some(Rc::new(Handler::new(handler)));
1209    self
1210  }
1211
1212  /// Runs `handler` with whole scroll steps while the pointer is over this
1213  /// button: positive for up, negative for down. A mouse wheel gives one
1214  /// step per notch; touchpad scrolling gives one step per 15 logical
1215  /// pixels. Sideways scrolling gives none.
1216  pub fn on_scroll(mut self, handler: impl Fn(&Cx, i32) + 'static) -> Button {
1217    self.button.handlers.scroll = Some(Rc::new(Handler::new(handler)));
1218    self
1219  }
1220
1221  /// Runs `handler` with every scroll event while the pointer is over
1222  /// this button, on both axes: a wheel's notches, a touchpad's pixels,
1223  /// where it came from, and the `stop` when the fingers lift. Positive
1224  /// is down and right. With `on_scroll` too, both run.
1225  pub fn on_wheel(mut self, handler: impl Fn(&Cx, Wheel) + 'static) -> Button {
1226    self.button.handlers.wheel = Some(Rc::new(Handler::new(handler)));
1227    self
1228  }
1229
1230  /// Shares where the pointer is: the button writes `position`, in its
1231  /// own coordinates with (0, 0) at its top-left, while the pointer is
1232  /// over it or anything inside it, and `None` when it leaves. While a
1233  /// button inside it, or this one, is dragged, it follows the pointer
1234  /// wherever it goes, even outside the button. It is written only on a
1235  /// change.
1236  pub fn pointer_position(mut self, position: Signal<Option<Point>>) -> Button {
1237    self.button.position = Some(position);
1238    self
1239  }
1240
1241  /// Turns the button on or off; it is on by default. Off, none of its
1242  /// handlers run, it shows no hover, pressed or focus style and the
1243  /// default cursor, and Tab skips it. The pointer passes through it to
1244  /// the button around it, as through a disabled Qt `MouseArea`. Turning
1245  /// it off while it is held lets go, ending a drag with its `End`, and
1246  /// drops its focus.
1247  pub fn enabled(mut self, enabled: impl IntoProp<bool>) -> Button {
1248    self.button.enabled = Some(enabled.into_prop());
1249    self
1250  }
1251
1252  /// Takes the keyboard focus whenever this turns true, as
1253  /// [`TextInput::focus`](crate::TextInput::focus) does. Tab and a field
1254  /// may take it away again.
1255  pub fn focus(mut self, focus: impl IntoProp<bool>) -> Button {
1256    self.button.focus = Some(focus.into_prop());
1257    self
1258  }
1259
1260  /// Makes a drag of this button carry `data`, which a button whose
1261  /// [`on_drop`](Self::on_drop) takes a `T` is given when the drag is
1262  /// released over it. A closure is read as it changes, and a drop gets
1263  /// the value it holds at the release. While it holds a value, the button
1264  /// drags as one with [`on_drag`](Self::on_drag) does, and its `on_drag`
1265  /// still runs, so it can follow the pointer with a translate; its `End`
1266  /// says whether it was dropped. While it holds `None`, the button acts as
1267  /// if it had no data: it clicks, and drags only with its own `on_drag`,
1268  /// so `editing.get().then_some(id)` drags only in an edit mode. A drag
1269  /// carries data only within its window.
1270  pub fn drag_data<T: Clone + 'static>(mut self, data: impl IntoProp<Option<T>>) -> Button {
1271    let data = data
1272      .into_prop()
1273      .map(|data| data.map(|value| Rc::new(value) as DragValue));
1274    self.button.drag_data = Some(data);
1275    self
1276  }
1277
1278  /// Runs `handler` with a copy of the [`drag_data`](Self::drag_data) of a
1279  /// drag released over this button, or over anything inside it, when
1280  /// that data is a `T`. Data of any other type passes over it, as if it
1281  /// weren't there. The deepest button under the pointer that takes it is
1282  /// the one dropped on, and the dragged button never takes its own.
1283  pub fn on_drop<T: Clone + 'static>(mut self, handler: impl Fn(&Cx, T) + 'static) -> Button {
1284    let take = move |cx: &Cx, value: &dyn std::any::Any| {
1285      if let Some(value) = value.downcast_ref::<T>() {
1286        handler(cx, value.clone());
1287      }
1288    };
1289    self.button.handlers.drop = Some(DropTarget {
1290      accepts: std::any::TypeId::of::<T>(),
1291      handler: Rc::new(Handler::new(take)),
1292    });
1293    self
1294  }
1295
1296  /// Shares whether a drop is waiting: the button writes `hovered` true
1297  /// while a drag whose data its [`on_drop`](Self::on_drop) would take is
1298  /// over it, as Qt's `DropArea.containsDrag`, and false when the drag
1299  /// leaves, ends, or either button goes, is hidden or is turned off.
1300  pub fn drop_hovered(mut self, hovered: Signal<bool>) -> Button {
1301    self.button.drop_hovered = Some(hovered);
1302    self
1303  }
1304
1305  /// Sets the cursor shown over the button, instead of the pointing hand.
1306  /// While the button drags, the pointing hand and the open hand show as
1307  /// the grabbing hand until the release; any other shape stays.
1308  pub fn cursor(mut self, cursor: impl IntoProp<CursorShape>) -> Button {
1309    self.button.cursor = Some(cursor.into_prop());
1310    self
1311  }
1312
1313  style_method!();
1314}
1315
1316impl Widget for Button {
1317  fn into_element(self: Box<Self>) -> Element {
1318    Element {
1319      name: "Button",
1320      common: self.common,
1321      kind: ElementKind::Button(Box::new(self.button)),
1322      children: vec![ElementChild::One(Box::new(self.child.into_element()))],
1323    }
1324  }
1325}