Skip to main content

eternal_ui/
widgets.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! The built-in widgets.
6//!
7//! Each is a plain struct you can reach through
8//! [`Ui::widget`](crate::Ui::widget) and [`Ui::widget_mut`](crate::Ui::widget_mut)
9//! to read or change it imperatively. How they look comes entirely from the
10//! stylesheet; the widgets only know how to measure, react and paint their
11//! own content.
12
13use eternal_styler::{ComputedStyle, ElementState, TextAlign};
14
15use crate::event::{Event, Key, Modifiers};
16use crate::geometry::{Axis, Point, Rect, Size};
17use crate::layout::{Align, Justify};
18use crate::render::{FontSpec, Fonts, Renderer};
19use crate::widget::{EventCx, PaintCx, Widget};
20
21/// Implements the two `Any` accessors of [`Widget`] for a type.
22#[macro_export]
23macro_rules! impl_widget_any {
24    () => {
25        fn as_any(&self) -> &dyn ::std::any::Any {
26            self
27        }
28
29        fn as_any_mut(&mut self) -> &mut dyn ::std::any::Any {
30            self
31        }
32    };
33}
34
35/// Lays its children out in a row or a column. Also what `panel`,
36/// `separator`, `spacer` and `check` are made of; they differ only by tag,
37/// which is what the stylesheet sees.
38#[derive(Clone, Debug)]
39pub struct Container {
40    axis: Axis,
41    /// How children are placed across the axis unless they say otherwise.
42    /// The `align_items` attribute.
43    pub align: Align,
44    /// How children are spread along the axis when there is room left. The
45    /// `justify` attribute.
46    pub justify: Justify,
47}
48
49impl Container {
50    pub fn new(axis: Axis) -> Self {
51        Self {
52            axis,
53            align: Align::Stretch,
54            justify: Justify::Start,
55        }
56    }
57
58    pub fn column() -> Self {
59        Self::new(Axis::Vertical)
60    }
61
62    pub fn row() -> Self {
63        Self::new(Axis::Horizontal)
64    }
65}
66
67impl<M: 'static> Widget<M> for Container {
68    fn set_attribute(&mut self, name: &str, value: &str) -> bool {
69        match name {
70            "align_items" => match Align::parse(value) {
71                Some(align) => {
72                    self.align = align;
73                    true
74                }
75                None => false,
76            },
77            "justify" => match Justify::parse(value) {
78                Some(justify) => {
79                    self.justify = justify;
80                    true
81                }
82                None => false,
83            },
84            _ => false,
85        }
86    }
87
88    fn axis(&self) -> Option<Axis> {
89        Some(self.axis)
90    }
91
92    impl_widget_any!();
93}
94
95/// A single line of text.
96#[derive(Clone, Debug, Default)]
97pub struct Label {
98    text: String,
99}
100
101impl Label {
102    pub fn new(text: impl Into<String>) -> Self {
103        Self { text: text.into() }
104    }
105
106    pub fn text(&self) -> &str {
107        &self.text
108    }
109
110    pub fn set_text(&mut self, text: impl Into<String>) {
111        self.text = text.into();
112    }
113}
114
115impl<M: 'static> Widget<M> for Label {
116    fn set_attribute(&mut self, name: &str, value: &str) -> bool {
117        if name == "text" {
118            self.text = value.to_owned();
119            return true;
120        }
121        false
122    }
123
124    fn measure(&self, fonts: &dyn Fonts, style: &ComputedStyle) -> Size {
125        let metrics = fonts.measure(&self.text, &FontSpec::from_style(style));
126        Size::new(
127            metrics.width + style.letter_spacing * self.text.chars().count() as f32,
128            metrics.line_height,
129        )
130    }
131
132    fn paint(&self, renderer: &mut dyn Renderer, cx: &PaintCx<'_>, content: Rect) {
133        paint_line(renderer, cx.style, &self.text, content, cx.style.text_align);
134    }
135
136    impl_widget_any!();
137}
138
139/// Draws one line of text inside `content`, centred vertically and aligned
140/// horizontally per `align`. Needs the font metrics, so measures again.
141fn paint_line(
142    renderer: &mut dyn Renderer,
143    style: &ComputedStyle,
144    text: &str,
145    content: Rect,
146    align: TextAlign,
147) {
148    let font = FontSpec::from_style(style);
149    let line_height = font.line_height.unwrap_or(style.font_size * 1.25);
150    let x = match align {
151        TextAlign::Start | TextAlign::Left | TextAlign::Justify => content.x,
152        TextAlign::Center => content.x + (content.width - text_width(text, style)) / 2.0,
153        TextAlign::End | TextAlign::Right => content.right() - text_width(text, style),
154    };
155    let y = content.y + ((content.height - line_height) / 2.0).max(0.0);
156    renderer.text(text, &font, Point::new(x.round(), y.round()), style.color);
157}
158
159/// The width a label would have measured, without access to the font
160/// source: a label's content box is exactly its text unless it was
161/// stretched, so this is only used for alignment inside a stretched box.
162fn text_width(text: &str, style: &ComputedStyle) -> f32 {
163    // Without fonts at paint time, assume the content box was sized to the
164    // text unless the label was stretched; either way the best estimate is
165    // the monospace one. Backends that need exact alignment can measure in
166    // `Renderer::text` from the same font spec.
167    text.chars().count() as f32 * style.font_size * 0.6
168}
169
170/// A push button. Its children (usually a text label) are laid out in a
171/// row, so an icon element can sit next to the text.
172///
173/// Fires `click` on a pointer release over the button, on Enter or Space
174/// while focused, and when its `shortcut` is pressed.
175#[derive(Clone, Debug, Default)]
176pub struct Button;
177
178impl<M: 'static> Widget<M> for Button {
179    fn axis(&self) -> Option<Axis> {
180        Some(Axis::Horizontal)
181    }
182
183    fn focusable(&self) -> bool {
184        true
185    }
186
187    fn event(&mut self, cx: &mut EventCx<'_, M>, event: &Event) -> bool {
188        match event {
189            Event::PointerUp { position, .. }
190                if cx.state.contains(ElementState::ACTIVE) && cx.rect.contains(*position) =>
191            {
192                cx.click();
193                true
194            }
195            Event::KeyDown {
196                key: Key::Enter | Key::Space,
197                modifiers,
198            } if modifiers.is_empty() => {
199                cx.click();
200                true
201            }
202            _ => false,
203        }
204    }
205
206    impl_widget_any!();
207}
208
209/// A box that can be checked, followed by its children in a row.
210///
211/// The box itself is a child element with the tag `check`, so it is styled
212/// like anything else: `checkbox:checked > check { background-color: ... }`.
213/// Fires `toggle` with the new state on click or Space.
214#[derive(Clone, Debug, Default)]
215pub struct Checkbox {
216    checked: bool,
217}
218
219impl Checkbox {
220    pub fn new(checked: bool) -> Self {
221        Self { checked }
222    }
223
224    pub fn is_checked(&self) -> bool {
225        self.checked
226    }
227
228    pub fn set_checked(&mut self, checked: bool) {
229        self.checked = checked;
230    }
231}
232
233impl<M: 'static> Widget<M> for Checkbox {
234    fn set_attribute(&mut self, name: &str, value: &str) -> bool {
235        if name == "checked" {
236            self.checked = parse_bool(value);
237            return true;
238        }
239        false
240    }
241
242    fn axis(&self) -> Option<Axis> {
243        Some(Axis::Horizontal)
244    }
245
246    fn state(&self) -> ElementState {
247        if self.checked {
248            ElementState::CHECKED
249        } else {
250            ElementState::empty()
251        }
252    }
253
254    fn focusable(&self) -> bool {
255        true
256    }
257
258    fn event(&mut self, cx: &mut EventCx<'_, M>, event: &Event) -> bool {
259        let toggle = match event {
260            Event::PointerUp { position, .. } => {
261                cx.state.contains(ElementState::ACTIVE) && cx.rect.contains(*position)
262            }
263            Event::KeyDown {
264                key: Key::Space,
265                modifiers,
266            } => modifiers.is_empty(),
267            _ => false,
268        };
269        if toggle {
270            self.checked = !self.checked;
271            cx.toggle(self.checked);
272            cx.mark_changed();
273        }
274        toggle
275    }
276
277    impl_widget_any!();
278}
279
280/// `true`, `false`, or the attribute's bare presence (`checked=""`).
281pub(crate) fn parse_bool(value: &str) -> bool {
282    !matches!(value.trim(), "false" | "0" | "no" | "off")
283}
284
285/// A single-line text field.
286///
287/// Fires `change` on every edit and `submit` on Enter. Left, Right, Home,
288/// End, Backspace and Delete move and edit; a click places the caret.
289#[derive(Clone, Debug, Default)]
290pub struct TextInput {
291    text: String,
292    /// In characters from the start.
293    cursor: usize,
294    placeholder: String,
295}
296
297impl TextInput {
298    pub fn new(text: impl Into<String>) -> Self {
299        let text = text.into();
300        Self {
301            cursor: text.chars().count(),
302            text,
303            placeholder: String::new(),
304        }
305    }
306
307    pub fn text(&self) -> &str {
308        &self.text
309    }
310
311    /// Replaces the text and puts the caret at the end.
312    pub fn set_text(&mut self, text: impl Into<String>) {
313        self.text = text.into();
314        self.cursor = self.text.chars().count();
315    }
316
317    pub fn placeholder(&self) -> &str {
318        &self.placeholder
319    }
320
321    pub fn set_placeholder(&mut self, text: impl Into<String>) {
322        self.placeholder = text.into();
323    }
324
325    /// The caret position in characters from the start.
326    pub fn cursor(&self) -> usize {
327        self.cursor
328    }
329
330    fn byte_offset(&self, chars: usize) -> usize {
331        self.text
332            .char_indices()
333            .nth(chars)
334            .map_or(self.text.len(), |(offset, _)| offset)
335    }
336
337    fn insert(&mut self, inserted: &str) {
338        let offset = self.byte_offset(self.cursor);
339        self.text.insert_str(offset, inserted);
340        self.cursor += inserted.chars().count();
341    }
342
343    fn delete_before(&mut self) -> bool {
344        if self.cursor == 0 {
345            return false;
346        }
347        let start = self.byte_offset(self.cursor - 1);
348        let end = self.byte_offset(self.cursor);
349        self.text.replace_range(start..end, "");
350        self.cursor -= 1;
351        true
352    }
353
354    fn delete_after(&mut self) -> bool {
355        if self.cursor >= self.text.chars().count() {
356            return false;
357        }
358        let start = self.byte_offset(self.cursor);
359        let end = self.byte_offset(self.cursor + 1);
360        self.text.replace_range(start..end, "");
361        true
362    }
363
364    /// The caret position closest to `x` pixels into the text.
365    fn cursor_at(&self, x: f32, fonts: &dyn Fonts, font: &FontSpec) -> usize {
366        let mut best = 0;
367        let mut best_distance = f32::INFINITY;
368        for (index, offset) in self
369            .text
370            .char_indices()
371            .map(|(offset, _)| offset)
372            .chain(std::iter::once(self.text.len()))
373            .enumerate()
374        {
375            let width = fonts.measure(&self.text[..offset], font).width;
376            let distance = (width - x).abs();
377            if distance < best_distance {
378                best = index;
379                best_distance = distance;
380            }
381        }
382        best
383    }
384}
385
386impl<M: 'static> Widget<M> for TextInput {
387    fn set_attribute(&mut self, name: &str, value: &str) -> bool {
388        match name {
389            "value" => {
390                self.set_text(value);
391                true
392            }
393            "placeholder" => {
394                self.placeholder = value.to_owned();
395                true
396            }
397            _ => false,
398        }
399    }
400
401    fn measure(&self, fonts: &dyn Fonts, style: &ComputedStyle) -> Size {
402        let font = FontSpec::from_style(style);
403        let shown = if self.text.is_empty() {
404            &self.placeholder
405        } else {
406            &self.text
407        };
408        let metrics = fonts.measure(shown, &font);
409        Size::new(metrics.width, metrics.line_height)
410    }
411
412    fn state(&self) -> ElementState {
413        if self.text.is_empty() {
414            ElementState::PLACEHOLDER_SHOWN
415        } else {
416            ElementState::empty()
417        }
418    }
419
420    fn focusable(&self) -> bool {
421        true
422    }
423
424    fn event(&mut self, cx: &mut EventCx<'_, M>, event: &Event) -> bool {
425        match event {
426            Event::Text(text) => {
427                let clean: String = text.chars().filter(|c| !c.is_control()).collect();
428                if clean.is_empty() {
429                    return false;
430                }
431                self.insert(&clean);
432                cx.change(self.text.clone());
433                cx.mark_changed();
434                true
435            }
436            Event::KeyDown { key, modifiers }
437                if !modifiers.intersects(Modifiers::CTRL | Modifiers::ALT | Modifiers::META) =>
438            {
439                let edited = match key {
440                    Key::Backspace => self.delete_before(),
441                    Key::Delete => self.delete_after(),
442                    Key::ArrowLeft => {
443                        self.cursor = self.cursor.saturating_sub(1);
444                        cx.mark_changed();
445                        return true;
446                    }
447                    Key::ArrowRight => {
448                        self.cursor = (self.cursor + 1).min(self.text.chars().count());
449                        cx.mark_changed();
450                        return true;
451                    }
452                    Key::Home => {
453                        self.cursor = 0;
454                        cx.mark_changed();
455                        return true;
456                    }
457                    Key::End => {
458                        self.cursor = self.text.chars().count();
459                        cx.mark_changed();
460                        return true;
461                    }
462                    Key::Enter => {
463                        cx.submit(self.text.clone());
464                        return true;
465                    }
466                    _ => return false,
467                };
468                if edited {
469                    cx.change(self.text.clone());
470                    cx.mark_changed();
471                }
472                true
473            }
474            Event::PointerDown { position, .. } => {
475                let font = FontSpec::from_style(cx.style);
476                self.cursor = self.cursor_at(position.x - cx.content.x, cx.fonts(), &font);
477                cx.mark_changed();
478                true
479            }
480            _ => false,
481        }
482    }
483
484    fn paint(&self, renderer: &mut dyn Renderer, cx: &PaintCx<'_>, content: Rect) {
485        let font = FontSpec::from_style(cx.style);
486        let line_height = font.line_height.unwrap_or(cx.style.font_size * 1.25);
487        renderer.push_clip(content);
488        let shown = if self.text.is_empty() {
489            &self.placeholder
490        } else {
491            &self.text
492        };
493        let y = content.y + ((content.height - line_height) / 2.0).max(0.0);
494        renderer.text(
495            shown,
496            &font,
497            Point::new(content.x, y.round()),
498            cx.style.color,
499        );
500        if cx.state.contains(ElementState::FOCUS) {
501            // The caret sits after the character it follows. Its x position
502            // is measured by the renderer's own fonts in a real backend; the
503            // framework does not have them here, so it is estimated the same
504            // way `text_width` does and corrected by the backend if it can.
505            let prefix: String = self.text.chars().take(self.cursor).collect();
506            let x = content.x + text_width(&prefix, cx.style);
507            renderer.fill_rect(
508                Rect::new(x.round(), y.round(), 1.0, line_height),
509                Default::default(),
510                cx.style.color,
511            );
512        }
513        renderer.pop_clip();
514    }
515
516    impl_widget_any!();
517}
518
519/// A widget with nothing of its own: an empty box for the stylesheet to
520/// paint. Used for `check`, `separator` and `spacer`.
521#[derive(Clone, Debug, Default)]
522pub struct Blank;
523
524impl<M: 'static> Widget<M> for Blank {
525    impl_widget_any!();
526}
527
528#[cfg(test)]
529mod tests {
530    use super::*;
531
532    #[test]
533    fn text_input_editing() {
534        let mut input = TextInput::new("héllo");
535        assert_eq!(input.cursor(), 5);
536        assert!(input.delete_before());
537        assert_eq!(input.text(), "héll");
538        input.cursor = 1;
539        input.insert("XY");
540        assert_eq!(input.text(), "hXYéll");
541        assert_eq!(input.cursor(), 3);
542        assert!(input.delete_after());
543        assert_eq!(input.text(), "hXYll");
544        input.cursor = 0;
545        assert!(!input.delete_before());
546        input.cursor = 5;
547        assert!(!input.delete_after());
548    }
549
550    #[test]
551    fn caret_placement_from_x() {
552        let input = TextInput::new("abcd");
553        let fonts = crate::render::MonospaceFonts { advance: 0.5 };
554        let font = FontSpec {
555            family: Default::default(),
556            size: 10.0,
557            weight: Default::default(),
558            style: Default::default(),
559            line_height: None,
560        };
561        // Each glyph is 5px wide.
562        assert_eq!(input.cursor_at(0.0, &fonts, &font), 0);
563        assert_eq!(input.cursor_at(6.0, &fonts, &font), 1);
564        assert_eq!(input.cursor_at(13.0, &fonts, &font), 3);
565        assert_eq!(input.cursor_at(100.0, &fonts, &font), 4);
566    }
567
568    #[test]
569    fn bools() {
570        assert!(parse_bool("true"));
571        assert!(parse_bool(""));
572        assert!(!parse_bool("false"));
573        assert!(!parse_bool("0"));
574    }
575}