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