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