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