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.
966///
967/// An image the renderer skips, at opacity 0, under an ancestor at
968/// opacity 0, or cut out by its mask region, still loads its picture at
969/// the size it would be drawn at whenever its area is repainted, with or
970/// without a [`status`](Image::status), and the cache keeps it as it
971/// keeps a drawn one, so revealing or moving it draws it on its first
972/// frame. That is the way to keep pictures warm. A GIF doesn't play
973/// there. A hidden image, with `visible` false, loads nothing unless it
974/// has a status.
975pub struct Image {
976 image: ImageProps,
977 common: Common,
978}
979
980impl Image {
981 /// The default width and height in logical pixels.
982 pub const DEFAULT_SIZE: u32 = 64;
983
984 /// An image of the file at `source`: a path (`&str`, `String`, `&Path`
985 /// or `PathBuf`) or a closure that returns one.
986 pub fn new(source: impl IntoProp<PathBuf>) -> Image {
987 Image {
988 image: ImageProps {
989 source: source.into_prop().map(IconSource::File),
990 width: None,
991 height: None,
992 fit: None,
993 tint: None,
994 brightness: None,
995 contrast: None,
996 saturation: None,
997 blur: None,
998 playing: None,
999 transition: None,
1000 status: None,
1001 },
1002 common: Common::default(),
1003 }
1004 }
1005
1006 /// An image of an [`IconSource`], or a closure that returns an
1007 /// `Option` of one, such as crabshell-services' `Notification::image`:
1008 /// raw pixels, a file as [`new`](Image::new) reads it, or an icon name
1009 /// looked up in the icon theme at the box's larger side and the
1010 /// window's scale rounded up, then read as that file. `None` shows
1011 /// nothing and is [`ImageStatus::Empty`], as an empty path is. `fit`,
1012 /// the filters, `transition` and `status` work as for a file.
1013 ///
1014 /// Pixels keep an [`Icon`]'s limits: at most 512 a side and exactly
1015 /// `width * height * 4` bytes, or the image is [`ImageStatus::Failed`]
1016 /// and the bad buffer is logged once. They are scaled on the loop's
1017 /// thread, once for each size, fit and filters, and cached by their
1018 /// shared allocation, so images showing the same [`IconPixels`] share
1019 /// one picture. A new source with the same bytes keeps the one shown. A
1020 /// name that no theme has fails as a missing file does.
1021 ///
1022 /// [`ImageStatus::Empty`]: crate::ImageStatus::Empty
1023 /// [`ImageStatus::Failed`]: crate::ImageStatus::Failed
1024 pub fn from_source(source: impl IntoProp<Option<IconSource>>) -> Image {
1025 let mut image = Image::new(PathBuf::new());
1026 image.image.source = source
1027 .into_prop()
1028 .map(|source| source.unwrap_or_else(crate::image::empty_source));
1029 image
1030 }
1031
1032 /// Sets the width in logical pixels.
1033 pub fn width(mut self, width: impl IntoProp<u32>) -> Image {
1034 self.image.width = Some(width.into_prop());
1035 self
1036 }
1037
1038 /// Sets the height in logical pixels.
1039 pub fn height(mut self, height: impl IntoProp<u32>) -> Image {
1040 self.image.height = Some(height.into_prop());
1041 self
1042 }
1043
1044 /// Sets how the picture fills the image's box when their shapes differ.
1045 pub fn fit(mut self, fit: impl IntoProp<Fit>) -> Image {
1046 self.image.fit = Some(fit.into_prop());
1047 self
1048 }
1049
1050 /// Paints the picture's pixels in `tint`, keeping their alpha, as
1051 /// [`Icon::tint`] does. `None`, the default, draws it as it is.
1052 pub fn tint(mut self, tint: impl IntoProp<Option<Color>>) -> Image {
1053 self.image.tint = Some(tint.into_prop());
1054 self
1055 }
1056
1057 /// Scales the colors, as CSS's `brightness()`: 1, the default, leaves
1058 /// them, 0 is black and 2 twice as bright. A number that isn't finite
1059 /// counts as 1, and one below 0 as 0.
1060 pub fn brightness(mut self, brightness: impl IntoProp<f32>) -> Image {
1061 self.image.brightness = Some(brightness.into_prop());
1062 self
1063 }
1064
1065 /// Sets the contrast, as CSS's `contrast()`: 1, the default, leaves the
1066 /// colors, 0 is middle gray and more than 1 is stronger. A number that
1067 /// isn't finite counts as 1, and one below 0 as 0.
1068 pub fn contrast(mut self, contrast: impl IntoProp<f32>) -> Image {
1069 self.image.contrast = Some(contrast.into_prop());
1070 self
1071 }
1072
1073 /// Sets the saturation, as CSS's `saturate()`: 1, the default, leaves
1074 /// the colors, 0 is gray and more than 1 is more vivid. A number that
1075 /// isn't finite counts as 1, and one below 0 as 0.
1076 pub fn saturation(mut self, saturation: impl IntoProp<f32>) -> Image {
1077 self.image.saturation = Some(saturation.into_prop());
1078 self
1079 }
1080
1081 /// Blurs the picture, as CSS's `blur()`: the Gaussian's standard
1082 /// deviation in logical pixels, 0 by default. Pixels past the picture's
1083 /// edge count as its edge pixels, so a blurred picture keeps its edges
1084 /// opaque. A number that isn't finite or is below 0 counts as 0. The
1085 /// blur is for still pictures, such as album art and wallpapers: a
1086 /// blurred GIF shows its first frame, still.
1087 pub fn blur(mut self, blur: impl IntoProp<f32>) -> Image {
1088 self.image.blur = Some(blur.into_prop());
1089 self
1090 }
1091
1092 /// Whether an animated GIF plays, true by default. False pauses it on
1093 /// the frame it shows.
1094 pub fn playing(mut self, playing: impl IntoProp<bool>) -> Image {
1095 self.image.playing = Some(playing.into_prop());
1096 self
1097 }
1098
1099 /// How a new source comes in: [`ImageTransition::None`], the default,
1100 /// shows it at once; the others bring it in over the old picture on the
1101 /// animation clock, repainting only the image's box. A new source
1102 /// mid-transition starts again from the picture most of the box shows:
1103 /// the one leaving before halfway, the one coming in from halfway on.
1104 /// A new source that can't be loaded keeps the old picture; the clock
1105 /// still runs and repaints the box for the transition's length, since
1106 /// only the renderer learns the file is bad.
1107 pub fn transition(mut self, transition: impl IntoProp<ImageTransition>) -> Image {
1108 self.image.transition = Some(transition.into_prop());
1109 self
1110 }
1111
1112 /// Shares where the picture is, as Qt's `Image.status`, so a config can
1113 /// fade album art in once it has loaded or show a glyph when a picture
1114 /// can't be read: [`ImageStatus::Empty`] for an empty path,
1115 /// [`ImageStatus::Loading`] from each new source until its picture is
1116 /// loaded, [`ImageStatus::Ready`] once it is, and
1117 /// [`ImageStatus::Failed`] when the file can't be read or decoded, the
1118 /// pixels or name of [`from_source`](Image::from_source) are bad or
1119 /// missing, or it is past the size limits. Each new source is loaded in
1120 /// the loop turn that set it, whether the image is drawn or not, so its
1121 /// own status can show it: one at opacity 0 or cut out by its mask
1122 /// region loads at its size, as it does without a status, and one
1123 /// hidden or of no size at the box it was last laid out in, or one
1124 /// pixel if it has none. A hidden image is decoded again at its size
1125 /// once shown, so binding its opacity to Ready is the cheap
1126 /// way to fade it in. A picture decoded again at another size stays
1127 /// Ready. Written only on a change; the signal belongs to the config,
1128 /// and the image repaints nothing for it.
1129 ///
1130 /// [`ImageStatus::Empty`]: crate::ImageStatus::Empty
1131 /// [`ImageStatus::Loading`]: crate::ImageStatus::Loading
1132 /// [`ImageStatus::Ready`]: crate::ImageStatus::Ready
1133 /// [`ImageStatus::Failed`]: crate::ImageStatus::Failed
1134 pub fn status(mut self, status: Signal<crate::ImageStatus>) -> Image {
1135 self.image.status = Some(status);
1136 self
1137 }
1138
1139 style_method!();
1140}
1141
1142impl Widget for Image {
1143 fn into_element(self: Box<Self>) -> Element {
1144 Element {
1145 name: "Image",
1146 common: self.common,
1147 kind: ElementKind::Image(self.image),
1148 children: Vec::new(),
1149 }
1150 }
1151}
1152
1153impl Widget for Icon {
1154 fn into_element(self: Box<Self>) -> Element {
1155 Element {
1156 name: "Icon",
1157 common: self.common,
1158 kind: ElementKind::Icon(self.icon),
1159 children: Vec::new(),
1160 }
1161 }
1162}
1163
1164/// A clickable box around one child, which it centers.
1165///
1166/// While the pointer is over it, `hover_style` is laid over its style, and
1167/// while it is also held down, `pressed_style` on top of that. Handlers run
1168/// on the main thread and receive the button's [`Cx`]. A handler that panics
1169/// is logged and never called again.
1170pub struct Button {
1171 pub(crate) button: ButtonProps,
1172 common: Common,
1173 child: Box<dyn Widget>,
1174}
1175
1176impl Button {
1177 /// A button around `child`.
1178 pub fn new(child: impl Widget) -> Button {
1179 Button {
1180 child: Box::new(child),
1181 button: ButtonProps {
1182 hover_style: None,
1183 pressed_style: None,
1184 focus_style: None,
1185 hovered: None,
1186 pressed: None,
1187 position: None,
1188 enabled: None,
1189 focus: None,
1190 cursor: None,
1191 drag_data: None,
1192 drop_hovered: None,
1193 handlers: Handlers::default(),
1194 value: None,
1195 },
1196 common: Common::default(),
1197 }
1198 }
1199
1200 /// Sets the style laid over the normal one while the pointer is over the
1201 /// button.
1202 pub fn hover_style(mut self, style: impl IntoProp<Style>) -> Button {
1203 self.button.hover_style = Some(style.into_prop());
1204 self
1205 }
1206
1207 /// Shares whether the pointer is over the button: the button sets
1208 /// `hovered` to `true` while the pointer is over it or anything inside
1209 /// it, buttons too, and back to `false` when it leaves, the window loses
1210 /// it, or the button goes. Unlike `hover_style`, which only the deepest
1211 /// button under the pointer shows, an outer button stays hovered while
1212 /// the pointer is over one inside it, so it can show controls on hover.
1213 /// A drag of this button or one inside it keeps it hovered until the
1214 /// release.
1215 pub fn hovered(mut self, hovered: Signal<bool>) -> Button {
1216 self.button.hovered = Some(hovered);
1217 self
1218 }
1219
1220 /// Shares whether the button is held: the button sets `pressed` to
1221 /// `true` at a left press or touch on it and back to `false` at the
1222 /// release, wherever the pointer is then, as Qt's `MouseArea.pressed`,
1223 /// so a config can scale what is inside it while it is held. A press
1224 /// that is cancelled lets go too: the pointer leaves the window, a
1225 /// scroll view takes the drag, or the button is turned off, hidden or
1226 /// removed. The button's own drag keeps it held. A press on a button
1227 /// inside it holds that one instead. Written only on a change; the
1228 /// signal belongs to the config, and the button repaints nothing for
1229 /// it.
1230 pub fn pressed(mut self, pressed: Signal<bool>) -> Button {
1231 self.button.pressed = Some(pressed);
1232 self
1233 }
1234
1235 /// Sets the style laid over the hover style while the button is held
1236 /// down.
1237 pub fn pressed_style(mut self, style: impl IntoProp<Style>) -> Button {
1238 self.button.pressed_style = Some(style.into_prop());
1239 self
1240 }
1241
1242 /// Sets the style laid over the normal one while the button has the
1243 /// keyboard focus, which Tab moves between buttons.
1244 pub fn focus_style(mut self, style: impl IntoProp<Style>) -> Button {
1245 self.button.focus_style = Some(style.into_prop());
1246 self
1247 }
1248
1249 /// Runs `handler` for each key pressed while the button has the
1250 /// keyboard focus. It returns `true` when it used the key; otherwise the
1251 /// window's `on_key` gets it, and then Tab, Enter and Space do what
1252 /// they do by default.
1253 pub fn on_key(mut self, handler: impl Fn(&Cx, &KeyEvent) -> bool + 'static) -> Button {
1254 self.button.handlers.key = Some(Rc::new(Handler::new(handler)));
1255 self
1256 }
1257
1258 /// Runs `handler` as soon as the left button goes down over this
1259 /// button, while it is held: the time to call
1260 /// [`Cx::start_move`](crate::Cx::start_move), as a title bar does.
1261 pub fn on_press(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1262 self.button.handlers.press = Some(Rc::new(Handler::new(handler)));
1263 self
1264 }
1265
1266 /// Runs `handler` with the button as soon as any pointer button goes
1267 /// down over this button, as a `MouseArea` taking every button: a click
1268 /// catcher that closes a panel at the first press. A left press or a
1269 /// touch runs it after `on_press`. It runs only for the press that
1270 /// starts a hold, not for a second button pressed while one is held, and
1271 /// not for a left press or a touch on a scroll bar, which the bar takes;
1272 /// the other buttons reach the button under it. Only the innermost
1273 /// enabled button under the pointer gets it, and a disabled one lets it
1274 /// through to the button around it.
1275 pub fn on_any_press(mut self, handler: impl Fn(&Cx, PointerButton) + 'static) -> Button {
1276 self.button.handlers.any_press = Some(Rc::new(Handler::new(handler)));
1277 self
1278 }
1279
1280 /// Runs `handler` when the left button comes up after going down on
1281 /// this button, wherever the pointer is by then, before `on_click`.
1282 pub fn on_release(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1283 self.button.handlers.release = Some(Rc::new(Handler::new(handler)));
1284 self
1285 }
1286
1287 /// Runs `handler` when the left button is pressed and released over this
1288 /// button, unless that ended a drag or a long press, or made a double
1289 /// click.
1290 pub fn on_click(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1291 self.button.handlers.click = Some(Rc::new(Handler::new(handler)));
1292 self
1293 }
1294
1295 /// Runs `handler` instead of a second `on_click` when a click comes
1296 /// within 400 ms and 5 logical pixels of the one before, as Qt's
1297 /// defaults say. A third click starts over. Without it, every click
1298 /// runs `on_click`.
1299 pub fn on_double_click(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1300 self.button.handlers.double_click = Some(Rc::new(Handler::new(handler)));
1301 self
1302 }
1303
1304 /// Runs `handler` once the left button has been held on this button for
1305 /// 800 ms without moving 10 logical pixels, as Qt's press and hold. The
1306 /// release after it doesn't click, though moving on can still drag.
1307 pub fn on_long_press(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1308 self.button.handlers.long_press = Some(Rc::new(Handler::new(handler)));
1309 self
1310 }
1311
1312 /// Runs `handler` as the left button drags this button: a
1313 /// [`DragPhase::Start`](crate::DragPhase::Start) once it moves 10
1314 /// logical pixels from where it went down, a `Move` for each motion
1315 /// after, and an `End` when it comes up, the pointer leaves the window,
1316 /// or the button is disabled. A button with no `on_click`,
1317 /// `on_double_click` or `on_long_press` starts at the press instead, so
1318 /// a slider moves from the first touch.
1319 ///
1320 /// While it drags, the button gets every motion, even outside itself or
1321 /// the window, stays hovered, and doesn't click.
1322 pub fn on_drag(mut self, handler: impl Fn(&Cx, Drag) + 'static) -> Button {
1323 self.button.handlers.drag = Some(Rc::new(Handler::new(handler)));
1324 self
1325 }
1326
1327 /// Runs `handler` when the right button is pressed and released over this
1328 /// button.
1329 pub fn on_right_click(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1330 self.button.handlers.right_click = Some(Rc::new(Handler::new(handler)));
1331 self
1332 }
1333
1334 /// Runs `handler` when the middle button is pressed and released over
1335 /// this button.
1336 pub fn on_middle_click(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1337 self.button.handlers.middle_click = Some(Rc::new(Handler::new(handler)));
1338 self
1339 }
1340
1341 /// Runs `handler` when the mouse's back side button is pressed and
1342 /// released over this button.
1343 pub fn on_back(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1344 self.button.handlers.back = Some(Rc::new(Handler::new(handler)));
1345 self
1346 }
1347
1348 /// Runs `handler` when the mouse's forward side button is pressed and
1349 /// released over this button.
1350 pub fn on_forward(mut self, handler: impl Fn(&Cx) + 'static) -> Button {
1351 self.button.handlers.forward = Some(Rc::new(Handler::new(handler)));
1352 self
1353 }
1354
1355 /// Runs `handler` with whole scroll steps while the pointer is over this
1356 /// button: positive for up, negative for down. A mouse wheel gives one
1357 /// step per notch; touchpad scrolling gives one step per 15 logical
1358 /// pixels. Sideways scrolling gives none.
1359 pub fn on_scroll(mut self, handler: impl Fn(&Cx, i32) + 'static) -> Button {
1360 self.button.handlers.scroll = Some(Rc::new(Handler::new(handler)));
1361 self
1362 }
1363
1364 /// Runs `handler` with every scroll event while the pointer is over
1365 /// this button, on both axes: a wheel's notches, a touchpad's pixels,
1366 /// where it came from, and the `stop` when the fingers lift. Positive
1367 /// is down and right. With `on_scroll` too, both run.
1368 pub fn on_wheel(mut self, handler: impl Fn(&Cx, Wheel) + 'static) -> Button {
1369 self.button.handlers.wheel = Some(Rc::new(Handler::new(handler)));
1370 self
1371 }
1372
1373 /// Shares where the pointer is: the button writes `position`, in its
1374 /// own coordinates with (0, 0) at its top-left, while the pointer is
1375 /// over it or anything inside it, and `None` when it leaves. While a
1376 /// button inside it, or this one, is dragged, it follows the pointer
1377 /// wherever it goes, even outside the button. It is written only on a
1378 /// change.
1379 pub fn pointer_position(mut self, position: Signal<Option<Point>>) -> Button {
1380 self.button.position = Some(position);
1381 self
1382 }
1383
1384 /// Turns the button on or off; it is on by default. Off, none of its
1385 /// handlers run, it shows no hover, pressed or focus style and the
1386 /// default cursor, and Tab skips it. The pointer passes through it to
1387 /// the button around it, as through a disabled Qt `MouseArea`. Turning
1388 /// it off while it is held lets go, ending a drag with its `End`, and
1389 /// drops its focus.
1390 pub fn enabled(mut self, enabled: impl IntoProp<bool>) -> Button {
1391 self.button.enabled = Some(enabled.into_prop());
1392 self
1393 }
1394
1395 /// Takes the keyboard focus whenever this turns true, as
1396 /// [`TextInput::focus`](crate::TextInput::focus) does. Tab and a field
1397 /// may take it away again.
1398 pub fn focus(mut self, focus: impl IntoProp<bool>) -> Button {
1399 self.button.focus = Some(focus.into_prop());
1400 self
1401 }
1402
1403 /// Makes a drag of this button carry `data`, which a button whose
1404 /// [`on_drop`](Self::on_drop) takes a `T` is given when the drag is
1405 /// released over it. A closure is read as it changes, and a drop gets
1406 /// the value it holds at the release. While it holds a value, the button
1407 /// drags as one with [`on_drag`](Self::on_drag) does, and its `on_drag`
1408 /// still runs, so it can follow the pointer with a translate; its `End`
1409 /// says whether it was dropped. While it holds `None`, the button acts as
1410 /// if it had no data: it clicks, and drags only with its own `on_drag`,
1411 /// so `editing.get().then_some(id)` drags only in an edit mode. Once
1412 /// the pointer leaves the window, the drag reaches buttons in the
1413 /// shell's other windows too, and other programs see one they can't
1414 /// take.
1415 pub fn drag_data<T: Clone + 'static>(mut self, data: impl IntoProp<Option<T>>) -> Button {
1416 let data = data
1417 .into_prop()
1418 .map(|data| data.map(|value| Rc::new(value) as DragValue));
1419 self.button.drag_data = Some(data);
1420 self
1421 }
1422
1423 /// Runs `handler` with a copy of the [`drag_data`](Self::drag_data) of a
1424 /// drag released over this button, or over anything inside it, when
1425 /// that data is a `T`. Data of any other type passes over it, as if it
1426 /// weren't there. The deepest button under the pointer that takes it is
1427 /// the one dropped on, and the dragged button never takes its own.
1428 pub fn on_drop<T: Clone + 'static>(mut self, handler: impl Fn(&Cx, T) + 'static) -> Button {
1429 let take = move |cx: &Cx, value: &dyn std::any::Any| {
1430 if let Some(value) = value.downcast_ref::<T>() {
1431 handler(cx, value.clone());
1432 }
1433 };
1434 self.button.handlers.drop = Some(DropTarget {
1435 accepts: std::any::TypeId::of::<T>(),
1436 handler: Rc::new(Handler::new(take)),
1437 name: "on_drop",
1438 });
1439 self
1440 }
1441
1442 /// Makes a drag of this button carry `content`, as
1443 /// [`drag_data`](Self::drag_data) does, to buttons in any of the
1444 /// shell's windows and, once the pointer leaves the window, to other
1445 /// programs, as text or a URI list. It replaces any `drag_data`.
1446 pub fn drag_content(self, content: impl IntoProp<Option<DragContent>>) -> Button {
1447 self.drag_data(content)
1448 }
1449
1450 /// Runs `handler` with what a drag from another program, or a
1451 /// [`drag_content`](Self::drag_content) of the shell's, carries when it
1452 /// is released over this button: URIs when the program offers them,
1453 /// else text. It replaces any [`on_drop`](Self::on_drop).
1454 pub fn on_drop_content(mut self, handler: impl Fn(&Cx, DragContent) + 'static) -> Button {
1455 self = self.on_drop(handler);
1456 if let Some(target) = &mut self.button.handlers.drop {
1457 target.name = "on_drop_content";
1458 }
1459 self
1460 }
1461
1462 /// Shares whether a drop is waiting: the button writes `hovered` true
1463 /// while a drag whose data its [`on_drop`](Self::on_drop) would take is
1464 /// over it, as Qt's `DropArea.containsDrag`, and false when the drag
1465 /// leaves, ends, or either button goes, is hidden or is turned off.
1466 pub fn drop_hovered(mut self, hovered: Signal<bool>) -> Button {
1467 self.button.drop_hovered = Some(hovered);
1468 self
1469 }
1470
1471 /// Sets the cursor shown over the button, instead of the pointing hand.
1472 /// While the button drags, the pointing hand and the open hand show as
1473 /// the grabbing hand until the release; any other shape stays.
1474 pub fn cursor(mut self, cursor: impl IntoProp<CursorShape>) -> Button {
1475 self.button.cursor = Some(cursor.into_prop());
1476 self
1477 }
1478
1479 style_method!();
1480}
1481
1482impl Widget for Button {
1483 fn into_element(self: Box<Self>) -> Element {
1484 Element {
1485 name: "Button",
1486 common: self.common,
1487 kind: ElementKind::Button(Box::new(self.button)),
1488 children: vec![ElementChild::One(Box::new(self.child.into_element()))],
1489 }
1490 }
1491}