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
// Copyright 2018 the Xilem Authors and the Druid Authors
// SPDX-License-Identifier: Apache-2.0

use accesskit::Role;
use kurbo::{Affine, Point, Size, Stroke};
use parley::{
    layout::Alignment,
    style::{FontFamily, FontStack},
};
use smallvec::SmallVec;
use tracing::trace;
use vello::{
    peniko::{BlendMode, Color},
    Scene,
};

use crate::{
    text2::{TextBrush, TextEditor, TextStorage, TextWithSelection},
    AccessCtx, AccessEvent, BoxConstraints, EventCtx, LayoutCtx, LifeCycle, LifeCycleCtx, PaintCtx,
    PointerEvent, StatusChange, TextEvent, Widget,
};

use super::{LineBreaking, WidgetMut, WidgetRef};

const TEXTBOX_PADDING: f64 = 3.0;
/// HACK: A "margin" which is placed around the outside of all textboxes, ensuring that
/// they do not fill the entire width of the window.
///
/// This is added by making the width of the textbox be (twice) this amount less than
/// the space available, which is absolutely horrible.
///
/// In theory, this should be proper margin/padding in the parent widget, but that hasn't been
/// designed.
const TEXTBOX_MARGIN: f64 = 8.0;

/// The textbox widget is a widget which shows text which can be edited by the user
///
/// For immutable text [`Prose`](super::Prose) should be preferred
// TODO: RichTextBox 👀
pub struct Textbox {
    // We hardcode the underlying storage type as `String`.
    // We might change this to a rope based structure at some point.
    // If you need a text box which uses a different text type, you should
    // create a custom widget
    editor: TextEditor<String>,
    line_break_mode: LineBreaking,
    show_disabled: bool,
    brush: TextBrush,
}

impl Textbox {
    pub fn new(initial_text: impl Into<String>) -> Self {
        Textbox {
            editor: TextEditor::new(initial_text.into(), crate::theme::TEXT_SIZE_NORMAL as f32),
            line_break_mode: LineBreaking::WordWrap,
            show_disabled: true,
            brush: crate::theme::TEXT_COLOR.into(),
        }
    }

    // TODO: Can we reduce code duplication with `Label` widget somehow?
    pub fn text(&self) -> &str {
        self.editor.text()
    }

    #[doc(alias = "with_text_color")]
    pub fn with_text_brush(mut self, brush: impl Into<TextBrush>) -> Self {
        self.brush = brush.into();
        self.editor.set_brush(self.brush.clone());
        self
    }

    pub fn with_text_size(mut self, size: f32) -> Self {
        self.editor.set_text_size(size);
        self
    }

    pub fn with_text_alignment(mut self, alignment: Alignment) -> Self {
        self.editor.set_text_alignment(alignment);
        self
    }

    pub fn with_font(mut self, font: FontStack<'static>) -> Self {
        self.editor.set_font(font);
        self
    }
    pub fn with_font_family(self, font: FontFamily<'static>) -> Self {
        self.with_font(FontStack::Single(font))
    }

    pub fn with_line_break_mode(mut self, line_break_mode: LineBreaking) -> Self {
        self.line_break_mode = line_break_mode;
        self
    }
}

impl WidgetMut<'_, Textbox> {
    pub fn text(&self) -> &str {
        self.widget.editor.text()
    }

    pub fn set_text_properties<R>(
        &mut self,
        f: impl FnOnce(&mut TextWithSelection<String>) -> R,
    ) -> R {
        let ret = f(&mut self.widget.editor);
        if self.widget.editor.needs_rebuild() {
            self.ctx.request_layout();
        }
        ret
    }

    /// Reset the contents of the text box.
    ///
    /// This is likely to be disruptive if the user is focused on this widget,
    /// and so should be avoided if possible.
    // FIXME - it's not clear whether this is the right behaviour, or if there even
    // is one.
    // TODO: Create a method which sets the text and the cursor selection to be used if focused?
    pub fn reset_text(&mut self, new_text: String) {
        if self.ctx.is_focused() {
            tracing::warn!(
                "Called reset_text on a focused `Textbox`. This will lose the user's current selection and cursor"
            );
        }
        self.widget.editor.reset_preedit();
        self.set_text_properties(|layout| layout.set_text(new_text));
    }

    #[doc(alias = "set_text_color")]
    pub fn set_text_brush(&mut self, brush: impl Into<TextBrush>) {
        let brush = brush.into();
        self.widget.brush = brush;
        if !self.ctx.is_disabled() {
            let brush = self.widget.brush.clone();
            self.set_text_properties(|layout| layout.set_brush(brush));
        }
    }
    pub fn set_text_size(&mut self, size: f32) {
        self.set_text_properties(|layout| layout.set_text_size(size));
    }
    pub fn set_alignment(&mut self, alignment: Alignment) {
        self.set_text_properties(|layout| layout.set_text_alignment(alignment));
    }
    pub fn set_font(&mut self, font_stack: FontStack<'static>) {
        self.set_text_properties(|layout| layout.set_font(font_stack));
    }
    pub fn set_font_family(&mut self, family: FontFamily<'static>) {
        self.set_font(FontStack::Single(family));
    }
    pub fn set_line_break_mode(&mut self, line_break_mode: LineBreaking) {
        self.widget.line_break_mode = line_break_mode;
        self.ctx.request_paint();
    }
}

impl Widget for Textbox {
    fn on_pointer_event(&mut self, ctx: &mut EventCtx, event: &PointerEvent) {
        let window_origin = ctx.widget_state.window_origin();
        let inner_origin = Point::new(
            window_origin.x + TEXTBOX_PADDING,
            window_origin.y + TEXTBOX_PADDING,
        );
        match event {
            PointerEvent::PointerDown(button, state) => {
                if !ctx.is_disabled() {
                    // TODO: Start tracking currently pressed link?
                    let made_change = self.editor.pointer_down(inner_origin, state, *button);
                    if made_change {
                        ctx.request_layout();
                        ctx.request_paint();
                        ctx.request_focus();
                        ctx.set_active(true);
                    }
                }
            }
            PointerEvent::PointerMove(state) => {
                if !ctx.is_disabled() {
                    // TODO: Set cursor if over link
                    ctx.set_cursor(&winit::window::CursorIcon::Text);
                    if ctx.is_active() && self.editor.pointer_move(inner_origin, state) {
                        // We might have changed text colours, so we need to re-request a layout
                        ctx.request_layout();
                        ctx.request_paint();
                    }
                }
            }
            PointerEvent::PointerUp(button, state) => {
                // TODO: Follow link (if not now dragging ?)
                if !ctx.is_disabled() && ctx.is_active() {
                    self.editor.pointer_up(inner_origin, state, *button);
                }
                ctx.set_active(false);
            }
            PointerEvent::PointerLeave(_state) => {
                ctx.set_active(false);
            }
            _ => {}
        }
    }

    fn on_text_event(&mut self, ctx: &mut EventCtx, event: &TextEvent) {
        let result = self.editor.text_event(ctx, event);
        // If focused on a link and enter pressed, follow it?
        if result.is_handled() {
            ctx.set_handled();
            // TODO: only some handlers need this repaint
            ctx.request_layout();
            ctx.request_paint();
        }
    }

    fn on_access_event(&mut self, _ctx: &mut EventCtx, _event: &AccessEvent) {
        // TODO - Handle accesskit::Action::SetTextSelection
        // TODO - Handle accesskit::Action::ReplaceSelectedText
        // TODO - Handle accesskit::Action::SetValue
    }

    #[allow(missing_docs)]
    fn on_status_change(&mut self, ctx: &mut LifeCycleCtx, event: &StatusChange) {
        match event {
            StatusChange::FocusChanged(false) => {
                self.editor.focus_lost();
                ctx.request_layout();
                // TODO: Stop focusing on any links
            }
            StatusChange::FocusChanged(true) => {
                // TODO: Focus on first link
            }
            _ => {}
        }
    }

    fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle) {
        match event {
            LifeCycle::DisabledChanged(disabled) => {
                if self.show_disabled {
                    if *disabled {
                        self.editor.set_brush(crate::theme::DISABLED_TEXT_COLOR);
                    } else {
                        self.editor.set_brush(self.brush.clone());
                    }
                }
                // TODO: Parley seems to require a relayout when colours change
                ctx.request_layout();
            }
            LifeCycle::BuildFocusChain => {
                // TODO: This will always be empty
                if !self.editor.text().links().is_empty() {
                    tracing::warn!("Links present in text, but not yet integrated");
                }
            }
            _ => {}
        }
    }

    fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
        // Compute max_advance from box constraints
        let max_advance = if self.line_break_mode != LineBreaking::WordWrap {
            None
        } else if bc.max().width.is_finite() {
            Some((bc.max().width - 2. * TEXTBOX_PADDING - 2. * TEXTBOX_MARGIN) as f32)
        } else if bc.min().width.is_sign_negative() {
            Some(0.0)
        } else {
            None
        };
        self.editor.set_max_advance(max_advance);
        if self.editor.needs_rebuild() {
            self.editor.rebuild(ctx.font_ctx());
        }
        // We ignore trailing whitespace for a label
        let text_size = self.editor.size();
        let label_size = Size {
            height: text_size.height + 2. * TEXTBOX_PADDING,
            // TODO: Better heuristic here?
            width: bc.max().width - 2. * TEXTBOX_MARGIN,
        };
        let size = bc.constrain(label_size);
        trace!(
            "Computed layout: max={:?}. w={}, h={}",
            max_advance,
            size.width,
            size.height,
        );
        size
    }

    fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut Scene) {
        if self.editor.needs_rebuild() {
            debug_panic!("Called Label paint before layout");
        }
        if self.line_break_mode == LineBreaking::Clip {
            let clip_rect = ctx.size().to_rect();
            scene.push_layer(BlendMode::default(), 1., Affine::IDENTITY, &clip_rect);
        }

        self.editor
            .draw(scene, Point::new(TEXTBOX_PADDING, TEXTBOX_PADDING));

        let outline_rect = ctx.size().to_rect().inset(1.0);
        scene.stroke(
            &Stroke::new(1.0),
            Affine::IDENTITY,
            Color::WHITE,
            None,
            &outline_rect,
        );
        if self.line_break_mode == LineBreaking::Clip {
            scene.pop_layer();
        }
    }

    fn accessibility_role(&self) -> Role {
        Role::TextInput
    }

    fn accessibility(&mut self, _ctx: &mut AccessCtx) {
        // TODO
    }

    fn children(&self) -> SmallVec<[WidgetRef<'_, dyn Widget>; 16]> {
        SmallVec::new()
    }

    fn get_debug_text(&self) -> Option<String> {
        Some(self.editor.text().as_str().chars().take(100).collect())
    }
}