densa-widgets 0.2.2

Standard widgets for densa: labels, buttons, text inputs, scroll views, splitters, docking
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
use densa_core::{Color, Point, Rect, Size};
use densa_draw::Canvas;
use densa_paragraph::{
    Motion, ParagraphError, ParagraphStyle, TextEditor, TextSelection, TextSystem,
};
use densa_ui::{
    AccessAction, AccessNode, AccessRequest, ActionKind, Constraints, Cursor, Event, EventCx,
    Handled, Ime, Key, KeyEvent, LayoutCx, NamedKey, PaintCx, PointerButton, PointerKind, Role,
    Widget,
};

use crate::paint::outline;
use crate::text::Text;

/// Space between the frame and the text, in logical pixels.
const PADDING_X: f32 = 6.0;
const PADDING_Y: f32 = 5.0;
/// The width a text input asks for, in logical pixels.
const WIDTH: f32 = 180.0;

/// A single line of editable text. Reports [`ActionKind::Changed`] after every edit and
/// [`ActionKind::Submitted`] on Enter.
///
/// Clicks place the caret (two select a word, three everything), dragging selects, the arrow
/// keys and Home/End move (with Shift: select; with Ctrl, or Cmd on macOS: by word),
/// Backspace and Delete remove characters or words, and input methods compose in place.
///
/// Ctrl (Cmd on macOS) with X, C and V cuts, copies and pastes through the
/// [`Ui`](densa_ui::Ui)'s clipboard, as do Shift+Delete, Ctrl+Insert and Shift+Insert; pasted
/// line breaks become spaces. Ctrl+Z undoes, Ctrl+Y or Ctrl+Shift+Z redoes (see
/// [`TextEditor`] for what one step is). An application's Edit menu calls the same
/// [`cut`](Self::cut), [`copy`](Self::copy), [`paste`](Self::paste), [`undo`](Self::undo) and
/// [`redo`](Self::redo) from an [`Ui::update`](densa_ui::Ui::update) on the input.
#[derive(Debug)]
pub struct TextInput {
    /// The text until the editor exists (it is created at the first layout).
    initial: String,
    placeholder: Text,
    editor: Option<TextEditor>,
    /// The size and color the editor's text was shaped with.
    shaped: Option<(f32, Color)>,
    /// How far the text is scrolled left to keep the caret in view.
    scroll: f32,
}

impl TextInput {
    /// An input holding `text`.
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            initial: text.into(),
            placeholder: Text::new(""),
            editor: None,
            shaped: None,
            scroll: 0.0,
        }
    }

    /// The input showing `placeholder`, dimmed, while it is empty.
    #[must_use]
    pub fn with_placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = Text::new(placeholder);
        self
    }

    /// The text.
    pub fn text(&self) -> &str {
        self.editor
            .as_ref()
            .map_or(self.initial.as_str(), TextEditor::text)
    }

    /// Replaces the text, the caret at its end.
    ///
    /// # Errors
    /// [`ParagraphError::UnreadableFont`] if a font for `text` cannot be read; nothing
    /// changes.
    pub fn set_text(
        &mut self,
        cx: &mut EventCx<'_>,
        text: impl Into<String>,
    ) -> Result<(), ParagraphError> {
        let text = text.into();
        match &mut self.editor {
            Some(editor) => editor.set_text(cx.text_system(), &text)?,
            None => self.initial = text,
        }
        self.follow_caret(cx);
        Ok(())
    }

    /// Whether text is selected, to cut or copy.
    pub fn has_selection(&self) -> bool {
        self.editor
            .as_ref()
            .is_some_and(|e| !e.selection().is_caret())
    }

    /// Whether there is an edit to [`undo`](Self::undo).
    pub fn can_undo(&self) -> bool {
        self.editor.as_ref().is_some_and(TextEditor::can_undo)
    }

    /// Whether there is an edit to [`redo`](Self::redo).
    pub fn can_redo(&self) -> bool {
        self.editor.as_ref().is_some_and(TextEditor::can_redo)
    }

    /// Puts the selected text on the clipboard; `false` if none is selected, an input
    /// method is composing, or the clipboard would not take it.
    pub fn copy(&mut self, cx: &mut EventCx<'_>) -> bool {
        let Some(editor) = self.editor.as_ref().filter(|e| e.composition().is_none()) else {
            return false;
        };
        let selected = editor.selected_text();
        !selected.is_empty() && cx.clipboard().set_text(selected).is_ok()
    }

    /// Copies the selected text and deletes it; nothing is deleted unless it was copied.
    /// The edit methods return `false` when the text did not change, including when it could
    /// not be laid out again (a font that cannot be read).
    pub fn cut(&mut self, cx: &mut EventCx<'_>) -> bool {
        self.copy(cx) && self.edit(cx, |e, s| e.delete(s, Motion::Previous).map(|()| true))
    }

    /// Replaces the selection with the clipboard's text, its line breaks made spaces; `false`
    /// if the clipboard holds no text.
    pub fn paste(&mut self, cx: &mut EventCx<'_>) -> bool {
        let Ok(text) = cx.clipboard().text() else {
            return false;
        };
        let line = one_line(&text);
        !line.is_empty() && self.edit(cx, |e, s| e.paste(s, &line).map(|()| true))
    }

    /// Takes back the last edit; `false` if there is none.
    pub fn undo(&mut self, cx: &mut EventCx<'_>) -> bool {
        self.edit(cx, TextEditor::undo)
    }

    /// Makes the last undone edit again; `false` if there is none.
    pub fn redo(&mut self, cx: &mut EventCx<'_>) -> bool {
        self.edit(cx, TextEditor::redo)
    }

    /// Runs `edit` on the editor, reporting [`ActionKind::Changed`] if it changed the text.
    fn edit(
        &mut self,
        cx: &mut EventCx<'_>,
        edit: impl FnOnce(&mut TextEditor, &mut TextSystem) -> Result<bool, ParagraphError>,
    ) -> bool {
        let Some(editor) = &mut self.editor else {
            return false;
        };
        let changed = edit(editor, cx.text_system()).unwrap_or(false);
        if changed {
            cx.emit(ActionKind::Changed);
        }
        self.follow_caret(cx);
        changed
    }

    /// Runs the clipboard or undo command `key` asks for, if any.
    fn command(&mut self, cx: &mut EventCx<'_>, key: &KeyEvent<'_>) -> Option<()> {
        let m = key.modifiers;
        let command = match key.key {
            Key::Character(c) if m.command() && !m.alt() => {
                let letters = [
                    ("x", Command::Cut),
                    ("c", Command::Copy),
                    ("v", Command::Paste),
                    ("z", Command::Undo),
                    ("y", Command::Redo),
                ];
                match letters
                    .into_iter()
                    .find(|(l, _)| c.eq_ignore_ascii_case(l))?
                {
                    (_, Command::Undo) if m.shift() => Command::Redo,
                    (_, command) => command,
                }
            }
            // Without a selection, Shift+Delete deletes as Delete does.
            Key::Named(NamedKey::Delete) if m.shift() && !m.control() && self.has_selection() => {
                Command::Cut
            }
            Key::Named(NamedKey::Insert) if m.control() && !m.shift() => Command::Copy,
            Key::Named(NamedKey::Insert) if m.shift() && !m.control() => Command::Paste,
            _ => return None,
        };
        let _ = match command {
            Command::Cut => self.cut(cx),
            Command::Copy => self.copy(cx),
            Command::Paste => self.paste(cx),
            Command::Undo => self.undo(cx),
            Command::Redo => self.redo(cx),
        };
        Some(())
    }

    /// The editor, created or restyled for the theme's text size and color.
    fn prepare(&mut self, cx: &mut LayoutCx<'_>) {
        let px = cx.px(cx.theme().font_size);
        let color = cx.theme().text;
        if self.shaped == Some((px, color)) && self.editor.is_some() {
            return;
        }
        let style = ParagraphStyle::new(px).with_color(color);
        match &mut self.editor {
            Some(editor) => {
                if editor.set_style(cx.text_system(), style).is_err() {
                    return;
                }
            }
            None => {
                let text = std::mem::take(&mut self.initial);
                match TextEditor::new(cx.text_system(), text.clone(), style) {
                    Ok(editor) => self.editor = Some(editor),
                    Err(_) => {
                        self.initial = text;
                        return;
                    }
                }
            }
        }
        self.shaped = Some((px, color));
    }

    /// The rectangle the text is shown in: inside the frame's padding.
    fn inner(content: Rect, scale: f32) -> Rect {
        let pad = PADDING_X * scale;
        Rect::from_edges(
            content.left() + pad,
            content.top(),
            content.right() - pad,
            content.bottom(),
        )
    }

    /// Where the paragraph's top-left corner is drawn.
    fn origin(&self, inner: Rect) -> Point {
        let height = self.editor.as_ref().map_or(0.0, |e| e.paragraph().height());
        Point::new(
            inner.left() - self.scroll,
            (inner.top() + (inner.height() - height) / 2.0).round(),
        )
    }

    /// Scrolls so the caret is in view, and tells the input method where it is.
    fn follow_caret(&mut self, cx: &mut EventCx<'_>) {
        let Some(editor) = &self.editor else {
            return;
        };
        let inner = Self::inner(cx.content_rect(), cx.scale());
        let paragraph = editor.paragraph();
        let caret = editor.selection().caret_rect(paragraph, cx.px(1.0));
        let room = inner.width().max(0.0);
        if caret.left() < self.scroll {
            self.scroll = caret.left();
        } else if caret.right() > self.scroll + room {
            self.scroll = caret.right() - room;
        }
        let longest = (paragraph.width() + caret.width() - room).max(0.0);
        self.scroll = self.scroll.clamp(0.0, longest);
        let origin = self.origin(inner);
        cx.set_ime_area(Some(editor.ime_area().translate(origin)));
        cx.request_paint();
    }

    fn pointer(
        &mut self,
        cx: &mut EventCx<'_>,
        kind: PointerKind,
        at: Point,
        clicks: u8,
        shift: bool,
    ) -> Handled {
        let inner = Self::inner(cx.content_rect(), cx.scale());
        let origin = self.origin(inner);
        let Some(editor) = &mut self.editor else {
            return Handled::No;
        };
        let local = Point::new(at.x - origin.x, at.y - origin.y);
        let paragraph = editor.paragraph();
        let selection = match kind {
            PointerKind::Down(PointerButton::Primary) => match clicks {
                1 if shift => editor.selection().shift_click(paragraph, local),
                1 => TextSelection::at_point(paragraph, local),
                2 => TextSelection::word_at_point(paragraph, local),
                _ => TextSelection::select_all(paragraph),
            },
            PointerKind::Move if cx.is_pressed() => {
                editor.selection().extend_to_point(paragraph, local)
            }
            _ => return Handled::No,
        };
        editor.set_selection(selection);
        self.follow_caret(cx);
        Handled::Yes
    }

    fn key(&mut self, cx: &mut EventCx<'_>, key: &KeyEvent<'_>) -> Handled {
        if self.editor.is_none() {
            return Handled::No;
        }
        // Handled even when there is nothing to do: the keys are the input's while it has
        // focus, not shortcuts for the application.
        if self.command(cx, key).is_some() {
            return Handled::Yes;
        }
        let Some(editor) = &mut self.editor else {
            return Handled::No;
        };
        let (command, shift) = (key.modifiers.command(), key.modifiers.shift());
        let by_word = |word: Motion, single: Motion| if command { word } else { single };
        // Ctrl+Alt is AltGr on Windows: it types (@, €) rather than commands.
        let types = !command || key.modifiers.alt();
        let edited = match key.key {
            Key::Named(NamedKey::Backspace) => editor.delete(
                cx.text_system(),
                by_word(Motion::PreviousWord, Motion::Previous),
            ),
            Key::Named(NamedKey::Delete) => {
                editor.delete(cx.text_system(), by_word(Motion::NextWord, Motion::Next))
            }
            Key::Named(named) => {
                let motion = match named {
                    NamedKey::ArrowLeft => by_word(Motion::WordLeft, Motion::Left),
                    NamedKey::ArrowRight => by_word(Motion::WordRight, Motion::Right),
                    NamedKey::Home => Motion::LineStart,
                    NamedKey::End => Motion::LineEnd,
                    NamedKey::Enter => {
                        cx.emit(ActionKind::Submitted);
                        return Handled::Yes;
                    }
                    // Space and other named keys that type something.
                    _ => match key.text.filter(|_| types) {
                        Some(text) => {
                            let edited = editor.insert(cx.text_system(), text);
                            if edited.is_ok() {
                                cx.emit(ActionKind::Changed);
                            }
                            self.follow_caret(cx);
                            return Handled::Yes;
                        }
                        None => return Handled::No,
                    },
                };
                editor.move_caret(motion, shift);
                self.follow_caret(cx);
                return Handled::Yes;
            }
            Key::Character(c) if command && c.eq_ignore_ascii_case("a") => {
                let all = TextSelection::select_all(editor.paragraph());
                editor.set_selection(all);
                self.follow_caret(cx);
                return Handled::Yes;
            }
            _ => match key.text.filter(|_| types) {
                Some(text) => editor.insert(cx.text_system(), text),
                None => return Handled::No,
            },
        };
        if edited.is_ok() {
            cx.emit(ActionKind::Changed);
        }
        self.follow_caret(cx);
        Handled::Yes
    }

    fn ime(&mut self, cx: &mut EventCx<'_>, ime: &Ime<'_>) -> Handled {
        let Some(editor) = &mut self.editor else {
            return Handled::No;
        };
        // A composition is not part of the text yet: only a commit changes it. A composition
        // the editor refuses (a cursor inside a character) leaves it as it was.
        let changed = match *ime {
            Ime::Preedit { text, cursor } => {
                let cursor = cursor.map(|(start, end)| start..end);
                let _ = editor.set_composition(cx.text_system(), text, cursor);
                false
            }
            Ime::Commit(text) => editor.insert(cx.text_system(), text).is_ok(),
            Ime::Disabled => {
                let _ = editor.set_composition(cx.text_system(), "", None);
                false
            }
            _ => false,
        };
        if changed {
            cx.emit(ActionKind::Changed);
        }
        self.follow_caret(cx);
        Handled::Yes
    }
}

/// What a clipboard or undo key asks for.
#[derive(Debug, Clone, Copy)]
enum Command {
    Cut,
    Copy,
    Paste,
    Undo,
    Redo,
}

/// `text` on one line: trailing line breaks dropped, the others (CR LF counting as one)
/// made spaces.
fn one_line(text: &str) -> String {
    let text = text.trim_end_matches(['\r', '\n']);
    text.replace("\r\n", " ").replace(['\r', '\n'], " ")
}

impl Widget for TextInput {
    fn accessibility(&self, _: &PaintCx<'_>, node: &mut AccessNode) {
        node.set_role(Role::TextInput);
        node.set_value(self.text());
        if !self.placeholder.as_str().is_empty() {
            node.set_placeholder(self.placeholder.as_str());
        }
        node.add_action(AccessAction::SetValue);
    }

    fn access_action(&mut self, cx: &mut EventCx<'_>, request: &AccessRequest<'_>) -> Handled {
        let (AccessAction::SetValue, Some(value)) = (request.action, request.value) else {
            return Handled::No;
        };
        if self.set_text(cx, value).is_err() {
            return Handled::No;
        }
        cx.emit(ActionKind::Changed);
        Handled::Yes
    }

    fn measure(&mut self, cx: &mut LayoutCx<'_>, _: Constraints) -> Size {
        self.prepare(cx);
        let line = self
            .editor
            .as_ref()
            .map_or(0.0, |e| e.paragraph().height())
            .max(cx.px(cx.theme().font_size) * 1.2);
        Size::new(cx.px(WIDTH), (line + 2.0 * cx.px(PADDING_Y)).ceil())
    }

    fn layout(&mut self, cx: &mut LayoutCx<'_>, size: Size) {
        self.prepare(cx);
        // A wider input, or shorter text, leaves less to scroll.
        if let Some(editor) = &self.editor {
            let room = (size.width - 2.0 * cx.px(PADDING_X)).max(0.0);
            let longest = (editor.paragraph().width() + cx.px(1.0) - room).max(0.0);
            self.scroll = self.scroll.clamp(0.0, longest);
        }
        let dim = cx.theme().text_dim;
        self.placeholder.fit(cx, f32::INFINITY, dim);
    }

    fn paint(&mut self, cx: &PaintCx<'_>, canvas: &mut Canvas<'_>) {
        let theme = cx.theme();
        let rect = cx.rect();
        canvas.fill_rect(rect, theme.raised);
        let border = if cx.is_focused() {
            theme.focus
        } else {
            theme.border
        };
        outline(canvas, rect, cx.px(1.0).round(), border);
        let inner = Self::inner(cx.content_rect(), cx.scale());
        let origin = self.origin(inner);
        let Some(editor) = &self.editor else {
            return;
        };
        let saved = canvas.state();
        canvas.clip(inner);
        if editor.text().is_empty() && editor.composition().is_none() {
            let size = self.placeholder.size();
            let y = (inner.top() + (inner.height() - size.height) / 2.0).round();
            self.placeholder.paint(canvas, Point::new(inner.left(), y));
        }
        let paragraph = editor.paragraph();
        let selection = editor.selection();
        if cx.is_focused() && !selection.is_caret() {
            selection.for_each_rect(paragraph, |r| {
                canvas.fill_rect(r.translate(origin), theme.selection);
            });
        }
        let underline = cx.px(1.0).round();
        editor.for_each_composition_rect(|r| {
            let r = r.translate(origin);
            canvas.fill_rect(
                Rect::from_edges(r.left(), r.bottom() - underline, r.right(), r.bottom()),
                theme.text,
            );
        });
        for run in paragraph.runs() {
            canvas.draw_run(run, origin);
        }
        if cx.is_focused() && editor.shows_caret() {
            let caret = selection.caret_rect(paragraph, cx.px(1.0).round());
            canvas.fill_rect(caret.translate(origin), theme.text);
        }
        canvas.restore(saved);
    }

    fn event(&mut self, cx: &mut EventCx<'_>, event: &Event<'_>) -> Handled {
        match event {
            Event::Pointer(pointer) => match pointer.kind {
                PointerKind::Enter => {
                    cx.set_cursor(Some(Cursor::Text));
                    Handled::Yes
                }
                PointerKind::Up(PointerButton::Primary) => Handled::Yes,
                kind => {
                    let shift = pointer.modifiers.shift();
                    self.pointer(cx, kind, pointer.position, pointer.clicks, shift)
                }
            },
            Event::Key(key) if key.pressed => self.key(cx, key),
            Event::Ime(ime) => self.ime(cx, ime),
            Event::FocusGained | Event::FocusLost => {
                self.follow_caret(cx);
                Handled::Yes
            }
            _ => Handled::No,
        }
    }

    fn accepts_focus(&self) -> bool {
        true
    }
}