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