iced_widget/
text_editor.rs

1//! Text editors display a multi-line text input for text editing.
2//!
3//! # Example
4//! ```no_run
5//! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
6//! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
7//! #
8//! use iced::widget::text_editor;
9//!
10//! struct State {
11//!    content: text_editor::Content,
12//! }
13//!
14//! #[derive(Debug, Clone)]
15//! enum Message {
16//!     Edit(text_editor::Action)
17//! }
18//!
19//! fn view(state: &State) -> Element<'_, Message> {
20//!     text_editor(&state.content)
21//!         .placeholder("Type something here...")
22//!         .on_action(Message::Edit)
23//!         .into()
24//! }
25//!
26//! fn update(state: &mut State, message: Message) {
27//!     match message {
28//!         Message::Edit(action) => {
29//!             state.content.perform(action);
30//!         }
31//!     }
32//! }
33//! ```
34use crate::core::alignment;
35use crate::core::clipboard::{self, Clipboard};
36use crate::core::input_method;
37use crate::core::keyboard;
38use crate::core::keyboard::key;
39use crate::core::layout::{self, Layout};
40use crate::core::mouse;
41use crate::core::renderer;
42use crate::core::text::editor::Editor as _;
43use crate::core::text::highlighter::{self, Highlighter};
44use crate::core::text::{self, LineHeight, Text, Wrapping};
45use crate::core::theme;
46use crate::core::time::{Duration, Instant};
47use crate::core::widget::operation;
48use crate::core::widget::{self, Widget};
49use crate::core::window;
50use crate::core::{
51    Background, Border, Color, Element, Event, InputMethod, Length, Padding, Pixels, Point,
52    Rectangle, Shell, Size, SmolStr, Theme, Vector,
53};
54
55use std::borrow::Cow;
56use std::cell::RefCell;
57use std::fmt;
58use std::ops;
59use std::ops::DerefMut;
60use std::sync::Arc;
61
62pub use text::editor::{Action, Cursor, Edit, Line, LineEnding, Motion, Position, Selection};
63
64/// A multi-line text input.
65///
66/// # Example
67/// ```no_run
68/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; }
69/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>;
70/// #
71/// use iced::widget::text_editor;
72///
73/// struct State {
74///    content: text_editor::Content,
75/// }
76///
77/// #[derive(Debug, Clone)]
78/// enum Message {
79///     Edit(text_editor::Action)
80/// }
81///
82/// fn view(state: &State) -> Element<'_, Message> {
83///     text_editor(&state.content)
84///         .placeholder("Type something here...")
85///         .on_action(Message::Edit)
86///         .into()
87/// }
88///
89/// fn update(state: &mut State, message: Message) {
90///     match message {
91///         Message::Edit(action) => {
92///             state.content.perform(action);
93///         }
94///     }
95/// }
96/// ```
97pub struct TextEditor<'a, Highlighter, Message, Theme = crate::Theme, Renderer = crate::Renderer>
98where
99    Highlighter: text::Highlighter,
100    Theme: Catalog,
101    Renderer: text::Renderer,
102{
103    id: Option<widget::Id>,
104    content: &'a Content<Renderer>,
105    placeholder: Option<text::Fragment<'a>>,
106    font: Option<Renderer::Font>,
107    text_size: Option<Pixels>,
108    line_height: LineHeight,
109    width: Length,
110    height: Length,
111    min_height: f32,
112    max_height: f32,
113    padding: Padding,
114    wrapping: Wrapping,
115    class: Theme::Class<'a>,
116    key_binding: Option<Box<dyn Fn(KeyPress) -> Option<Binding<Message>> + 'a>>,
117    on_edit: Option<Box<dyn Fn(Action) -> Message + 'a>>,
118    highlighter_settings: Highlighter::Settings,
119    highlighter_format: fn(&Highlighter::Highlight, &Theme) -> highlighter::Format<Renderer::Font>,
120    last_status: Option<Status>,
121}
122
123impl<'a, Message, Theme, Renderer> TextEditor<'a, highlighter::PlainText, Message, Theme, Renderer>
124where
125    Theme: Catalog,
126    Renderer: text::Renderer,
127{
128    /// Creates new [`TextEditor`] with the given [`Content`].
129    pub fn new(content: &'a Content<Renderer>) -> Self {
130        Self {
131            id: None,
132            content,
133            placeholder: None,
134            font: None,
135            text_size: None,
136            line_height: LineHeight::default(),
137            width: Length::Fill,
138            height: Length::Shrink,
139            min_height: 0.0,
140            max_height: f32::INFINITY,
141            padding: Padding::new(5.0),
142            wrapping: Wrapping::default(),
143            class: <Theme as Catalog>::default(),
144            key_binding: None,
145            on_edit: None,
146            highlighter_settings: (),
147            highlighter_format: |_highlight, _theme| highlighter::Format::default(),
148            last_status: None,
149        }
150    }
151
152    /// Sets the [`Id`](widget::Id) of the [`TextEditor`].
153    pub fn id(mut self, id: impl Into<widget::Id>) -> Self {
154        self.id = Some(id.into());
155        self
156    }
157}
158
159impl<'a, Highlighter, Message, Theme, Renderer>
160    TextEditor<'a, Highlighter, Message, Theme, Renderer>
161where
162    Highlighter: text::Highlighter,
163    Theme: Catalog,
164    Renderer: text::Renderer,
165{
166    /// Sets the placeholder of the [`TextEditor`].
167    pub fn placeholder(mut self, placeholder: impl text::IntoFragment<'a>) -> Self {
168        self.placeholder = Some(placeholder.into_fragment());
169        self
170    }
171
172    /// Sets the width of the [`TextEditor`].
173    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
174        self.width = Length::from(width.into());
175        self
176    }
177
178    /// Sets the height of the [`TextEditor`].
179    pub fn height(mut self, height: impl Into<Length>) -> Self {
180        self.height = height.into();
181        self
182    }
183
184    /// Sets the minimum height of the [`TextEditor`].
185    pub fn min_height(mut self, min_height: impl Into<Pixels>) -> Self {
186        self.min_height = min_height.into().0;
187        self
188    }
189
190    /// Sets the maximum height of the [`TextEditor`].
191    pub fn max_height(mut self, max_height: impl Into<Pixels>) -> Self {
192        self.max_height = max_height.into().0;
193        self
194    }
195
196    /// Sets the message that should be produced when some action is performed in
197    /// the [`TextEditor`].
198    ///
199    /// If this method is not called, the [`TextEditor`] will be disabled.
200    pub fn on_action(mut self, on_edit: impl Fn(Action) -> Message + 'a) -> Self {
201        self.on_edit = Some(Box::new(on_edit));
202        self
203    }
204
205    /// Sets the [`Font`] of the [`TextEditor`].
206    ///
207    /// [`Font`]: text::Renderer::Font
208    pub fn font(mut self, font: impl Into<Renderer::Font>) -> Self {
209        self.font = Some(font.into());
210        self
211    }
212
213    /// Sets the text size of the [`TextEditor`].
214    pub fn size(mut self, size: impl Into<Pixels>) -> Self {
215        self.text_size = Some(size.into());
216        self
217    }
218
219    /// Sets the [`text::LineHeight`] of the [`TextEditor`].
220    pub fn line_height(mut self, line_height: impl Into<text::LineHeight>) -> Self {
221        self.line_height = line_height.into();
222        self
223    }
224
225    /// Sets the [`Padding`] of the [`TextEditor`].
226    pub fn padding(mut self, padding: impl Into<Padding>) -> Self {
227        self.padding = padding.into();
228        self
229    }
230
231    /// Sets the [`Wrapping`] strategy of the [`TextEditor`].
232    pub fn wrapping(mut self, wrapping: Wrapping) -> Self {
233        self.wrapping = wrapping;
234        self
235    }
236
237    /// Highlights the [`TextEditor`] using the given syntax and theme.
238    #[cfg(feature = "highlighter")]
239    pub fn highlight(
240        self,
241        syntax: &str,
242        theme: iced_highlighter::Theme,
243    ) -> TextEditor<'a, iced_highlighter::Highlighter, Message, Theme, Renderer>
244    where
245        Renderer: text::Renderer<Font = crate::core::Font>,
246    {
247        self.highlight_with::<iced_highlighter::Highlighter>(
248            iced_highlighter::Settings {
249                theme,
250                token: syntax.to_owned(),
251            },
252            |highlight, _theme| highlight.to_format(),
253        )
254    }
255
256    /// Highlights the [`TextEditor`] with the given [`Highlighter`] and
257    /// a strategy to turn its highlights into some text format.
258    pub fn highlight_with<H: text::Highlighter>(
259        self,
260        settings: H::Settings,
261        to_format: fn(&H::Highlight, &Theme) -> highlighter::Format<Renderer::Font>,
262    ) -> TextEditor<'a, H, Message, Theme, Renderer> {
263        TextEditor {
264            id: self.id,
265            content: self.content,
266            placeholder: self.placeholder,
267            font: self.font,
268            text_size: self.text_size,
269            line_height: self.line_height,
270            width: self.width,
271            height: self.height,
272            min_height: self.min_height,
273            max_height: self.max_height,
274            padding: self.padding,
275            wrapping: self.wrapping,
276            class: self.class,
277            key_binding: self.key_binding,
278            on_edit: self.on_edit,
279            highlighter_settings: settings,
280            highlighter_format: to_format,
281            last_status: self.last_status,
282        }
283    }
284
285    /// Sets the closure to produce key bindings on key presses.
286    ///
287    /// See [`Binding`] for the list of available bindings.
288    pub fn key_binding(
289        mut self,
290        key_binding: impl Fn(KeyPress) -> Option<Binding<Message>> + 'a,
291    ) -> Self {
292        self.key_binding = Some(Box::new(key_binding));
293        self
294    }
295
296    /// Sets the style of the [`TextEditor`].
297    #[must_use]
298    pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self
299    where
300        Theme::Class<'a>: From<StyleFn<'a, Theme>>,
301    {
302        self.class = (Box::new(style) as StyleFn<'a, Theme>).into();
303        self
304    }
305
306    /// Sets the style class of the [`TextEditor`].
307    #[cfg(feature = "advanced")]
308    #[must_use]
309    pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self {
310        self.class = class.into();
311        self
312    }
313
314    fn input_method<'b>(
315        &self,
316        state: &'b State<Highlighter>,
317        renderer: &Renderer,
318        layout: Layout<'_>,
319    ) -> InputMethod<&'b str> {
320        let Some(Focus {
321            is_window_focused: true,
322            ..
323        }) = &state.focus
324        else {
325            return InputMethod::Disabled;
326        };
327
328        let bounds = layout.bounds();
329        let internal = self.content.0.borrow_mut();
330
331        let text_bounds = bounds.shrink(self.padding);
332        let translation = text_bounds.position() - Point::ORIGIN;
333
334        let cursor = match internal.editor.selection() {
335            Selection::Caret(position) => position,
336            Selection::Range(ranges) => ranges.first().cloned().unwrap_or_default().position(),
337        };
338
339        let line_height = self
340            .line_height
341            .to_absolute(self.text_size.unwrap_or_else(|| renderer.default_size()));
342
343        let position = cursor + translation;
344
345        InputMethod::Enabled {
346            cursor: Rectangle::new(position, Size::new(1.0, f32::from(line_height))),
347            purpose: input_method::Purpose::Normal,
348            preedit: state.preedit.as_ref().map(input_method::Preedit::as_ref),
349        }
350    }
351}
352
353/// The content of a [`TextEditor`].
354pub struct Content<R = crate::Renderer>(RefCell<Internal<R>>)
355where
356    R: text::Renderer;
357
358struct Internal<R>
359where
360    R: text::Renderer,
361{
362    editor: R::Editor,
363}
364
365impl<R> Content<R>
366where
367    R: text::Renderer,
368{
369    /// Creates an empty [`Content`].
370    pub fn new() -> Self {
371        Self::with_text("")
372    }
373
374    /// Creates a [`Content`] with the given text.
375    pub fn with_text(text: &str) -> Self {
376        Self(RefCell::new(Internal {
377            editor: R::Editor::with_text(text),
378        }))
379    }
380
381    /// Performs an [`Action`] on the [`Content`].
382    pub fn perform(&mut self, action: Action) {
383        let internal = self.0.get_mut();
384
385        internal.editor.perform(action);
386    }
387
388    /// Moves the current cursor to reflect the given one.
389    pub fn move_to(&mut self, cursor: Cursor) {
390        let internal = self.0.get_mut();
391
392        internal.editor.move_to(cursor);
393    }
394
395    /// Returns the current cursor position of the [`Content`].
396    pub fn cursor(&self) -> Cursor {
397        self.0.borrow().editor.cursor()
398    }
399
400    /// Returns the amount of lines of the [`Content`].
401    pub fn line_count(&self) -> usize {
402        self.0.borrow().editor.line_count()
403    }
404
405    /// Returns the text of the line at the given index, if it exists.
406    pub fn line(&self, index: usize) -> Option<Line<'_>> {
407        let internal = self.0.borrow();
408        let line = internal.editor.line(index)?;
409
410        Some(Line {
411            text: Cow::Owned(line.text.into_owned()),
412            ending: line.ending,
413        })
414    }
415
416    /// Returns an iterator of the text of the lines in the [`Content`].
417    pub fn lines(&self) -> impl Iterator<Item = Line<'_>> {
418        (0..)
419            .map(|i| self.line(i))
420            .take_while(Option::is_some)
421            .flatten()
422    }
423
424    /// Returns the text of the [`Content`].
425    pub fn text(&self) -> String {
426        let mut contents = String::new();
427        let mut lines = self.lines().peekable();
428
429        while let Some(line) = lines.next() {
430            contents.push_str(&line.text);
431
432            if lines.peek().is_some() {
433                contents.push_str(if line.ending == LineEnding::None {
434                    LineEnding::default().as_str()
435                } else {
436                    line.ending.as_str()
437                });
438            }
439        }
440
441        contents
442    }
443
444    /// Returns the selected text of the [`Content`].
445    pub fn selection(&self) -> Option<String> {
446        self.0.borrow().editor.copy()
447    }
448
449    /// Returns the kind of [`LineEnding`] used for separating lines in the [`Content`].
450    pub fn line_ending(&self) -> Option<LineEnding> {
451        Some(self.line(0)?.ending)
452    }
453
454    /// Returns whether or not the the [`Content`] is empty.
455    pub fn is_empty(&self) -> bool {
456        self.0.borrow().editor.is_empty()
457    }
458}
459
460impl<Renderer> Clone for Content<Renderer>
461where
462    Renderer: text::Renderer,
463{
464    fn clone(&self) -> Self {
465        Self::with_text(&self.text())
466    }
467}
468
469impl<Renderer> Default for Content<Renderer>
470where
471    Renderer: text::Renderer,
472{
473    fn default() -> Self {
474        Self::new()
475    }
476}
477
478impl<Renderer> fmt::Debug for Content<Renderer>
479where
480    Renderer: text::Renderer,
481    Renderer::Editor: fmt::Debug,
482{
483    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
484        let internal = self.0.borrow();
485
486        f.debug_struct("Content")
487            .field("editor", &internal.editor)
488            .finish()
489    }
490}
491
492/// The state of a [`TextEditor`].
493#[derive(Debug)]
494pub struct State<Highlighter: text::Highlighter> {
495    focus: Option<Focus>,
496    preedit: Option<input_method::Preedit>,
497    last_click: Option<mouse::Click>,
498    drag_click: Option<mouse::click::Kind>,
499    partial_scroll: f32,
500    last_theme: RefCell<Option<String>>,
501    highlighter: RefCell<Highlighter>,
502    highlighter_settings: Highlighter::Settings,
503    highlighter_format_address: usize,
504}
505
506#[derive(Debug, Clone)]
507struct Focus {
508    updated_at: Instant,
509    now: Instant,
510    is_window_focused: bool,
511}
512
513impl Focus {
514    const CURSOR_BLINK_INTERVAL_MILLIS: u128 = 500;
515
516    fn now() -> Self {
517        let now = Instant::now();
518
519        Self {
520            updated_at: now,
521            now,
522            is_window_focused: true,
523        }
524    }
525
526    fn is_cursor_visible(&self) -> bool {
527        self.is_window_focused
528            && ((self.now - self.updated_at).as_millis() / Self::CURSOR_BLINK_INTERVAL_MILLIS)
529                .is_multiple_of(2)
530    }
531}
532
533impl<Highlighter: text::Highlighter> State<Highlighter> {
534    /// Returns whether the [`TextEditor`] is currently focused or not.
535    pub fn is_focused(&self) -> bool {
536        self.focus.is_some()
537    }
538}
539
540impl<Highlighter: text::Highlighter> operation::Focusable for State<Highlighter> {
541    fn is_focused(&self) -> bool {
542        self.focus.is_some()
543    }
544
545    fn focus(&mut self) {
546        self.focus = Some(Focus::now());
547    }
548
549    fn unfocus(&mut self) {
550        self.focus = None;
551    }
552}
553
554impl<Highlighter, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
555    for TextEditor<'_, Highlighter, Message, Theme, Renderer>
556where
557    Highlighter: text::Highlighter,
558    Theme: Catalog,
559    Renderer: text::Renderer,
560{
561    fn tag(&self) -> widget::tree::Tag {
562        widget::tree::Tag::of::<State<Highlighter>>()
563    }
564
565    fn state(&self) -> widget::tree::State {
566        widget::tree::State::new(State {
567            focus: None,
568            preedit: None,
569            last_click: None,
570            drag_click: None,
571            partial_scroll: 0.0,
572            last_theme: RefCell::default(),
573            highlighter: RefCell::new(Highlighter::new(&self.highlighter_settings)),
574            highlighter_settings: self.highlighter_settings.clone(),
575            highlighter_format_address: self.highlighter_format as usize,
576        })
577    }
578
579    fn size(&self) -> Size<Length> {
580        Size {
581            width: self.width,
582            height: self.height,
583        }
584    }
585
586    fn layout(
587        &mut self,
588        tree: &mut widget::Tree,
589        renderer: &Renderer,
590        limits: &layout::Limits,
591    ) -> iced_renderer::core::layout::Node {
592        let mut internal = self.content.0.borrow_mut();
593        let state = tree.state.downcast_mut::<State<Highlighter>>();
594
595        if state.highlighter_format_address != self.highlighter_format as usize {
596            state.highlighter.borrow_mut().change_line(0);
597
598            state.highlighter_format_address = self.highlighter_format as usize;
599        }
600
601        if state.highlighter_settings != self.highlighter_settings {
602            state
603                .highlighter
604                .borrow_mut()
605                .update(&self.highlighter_settings);
606
607            state.highlighter_settings = self.highlighter_settings.clone();
608        }
609
610        let limits = limits
611            .width(self.width)
612            .height(self.height)
613            .min_height(self.min_height)
614            .max_height(self.max_height);
615
616        internal.editor.update(
617            limits.shrink(self.padding).max(),
618            self.font.unwrap_or_else(|| renderer.default_font()),
619            self.text_size.unwrap_or_else(|| renderer.default_size()),
620            self.line_height,
621            self.wrapping,
622            state.highlighter.borrow_mut().deref_mut(),
623        );
624
625        match self.height {
626            Length::Fill | Length::FillPortion(_) | Length::Fixed(_) => {
627                layout::Node::new(limits.max())
628            }
629            Length::Shrink => {
630                let min_bounds = internal.editor.min_bounds();
631
632                layout::Node::new(
633                    limits
634                        .height(min_bounds.height)
635                        .max()
636                        .expand(Size::new(0.0, self.padding.y())),
637                )
638            }
639        }
640    }
641
642    fn update(
643        &mut self,
644        tree: &mut widget::Tree,
645        event: &Event,
646        layout: Layout<'_>,
647        cursor: mouse::Cursor,
648        renderer: &Renderer,
649        clipboard: &mut dyn Clipboard,
650        shell: &mut Shell<'_, Message>,
651        _viewport: &Rectangle,
652    ) {
653        let Some(on_edit) = self.on_edit.as_ref() else {
654            return;
655        };
656
657        let state = tree.state.downcast_mut::<State<Highlighter>>();
658        let is_redraw = matches!(event, Event::Window(window::Event::RedrawRequested(_now)),);
659
660        match event {
661            Event::Window(window::Event::Unfocused) => {
662                if let Some(focus) = &mut state.focus {
663                    focus.is_window_focused = false;
664                }
665            }
666            Event::Window(window::Event::Focused) => {
667                if let Some(focus) = &mut state.focus {
668                    focus.is_window_focused = true;
669                    focus.updated_at = Instant::now();
670
671                    shell.request_redraw();
672                }
673            }
674            Event::Window(window::Event::RedrawRequested(now)) => {
675                if let Some(focus) = &mut state.focus
676                    && focus.is_window_focused
677                {
678                    focus.now = *now;
679
680                    let millis_until_redraw = Focus::CURSOR_BLINK_INTERVAL_MILLIS
681                        - (focus.now - focus.updated_at).as_millis()
682                            % Focus::CURSOR_BLINK_INTERVAL_MILLIS;
683
684                    shell.request_redraw_at(
685                        focus.now + Duration::from_millis(millis_until_redraw as u64),
686                    );
687                }
688            }
689            _ => {}
690        }
691
692        if let Some(update) = Update::from_event(
693            event,
694            state,
695            layout.bounds(),
696            self.padding,
697            cursor,
698            self.key_binding.as_deref(),
699        ) {
700            match update {
701                Update::Click(click) => {
702                    let action = match click.kind() {
703                        mouse::click::Kind::Single => Action::Click(click.position()),
704                        mouse::click::Kind::Double => Action::SelectWord,
705                        mouse::click::Kind::Triple => Action::SelectLine,
706                    };
707
708                    state.focus = Some(Focus::now());
709                    state.last_click = Some(click);
710                    state.drag_click = Some(click.kind());
711
712                    shell.publish(on_edit(action));
713                    shell.capture_event();
714                }
715                Update::Drag(position) => {
716                    shell.publish(on_edit(Action::Drag(position)));
717                }
718                Update::Release => {
719                    state.drag_click = None;
720                }
721                Update::Scroll(lines) => {
722                    let bounds = self.content.0.borrow().editor.bounds();
723
724                    if bounds.height >= i32::MAX as f32 {
725                        return;
726                    }
727
728                    let lines = lines + state.partial_scroll;
729                    state.partial_scroll = lines.fract();
730
731                    shell.publish(on_edit(Action::Scroll {
732                        lines: lines as i32,
733                    }));
734                    shell.capture_event();
735                }
736                Update::InputMethod(update) => match update {
737                    Ime::Toggle(is_open) => {
738                        state.preedit = is_open.then(input_method::Preedit::new);
739
740                        shell.request_redraw();
741                    }
742                    Ime::Preedit { content, selection } => {
743                        state.preedit = Some(input_method::Preedit {
744                            content,
745                            selection,
746                            text_size: self.text_size,
747                        });
748
749                        shell.request_redraw();
750                    }
751                    Ime::Commit(text) => {
752                        shell.publish(on_edit(Action::Edit(Edit::Paste(Arc::new(text)))));
753                    }
754                },
755                Update::Binding(binding) => {
756                    fn apply_binding<H: text::Highlighter, R: text::Renderer, Message>(
757                        binding: Binding<Message>,
758                        content: &Content<R>,
759                        state: &mut State<H>,
760                        on_edit: &dyn Fn(Action) -> Message,
761                        clipboard: &mut dyn Clipboard,
762                        shell: &mut Shell<'_, Message>,
763                    ) {
764                        let mut publish = |action| shell.publish(on_edit(action));
765
766                        match binding {
767                            Binding::Unfocus => {
768                                state.focus = None;
769                                state.drag_click = None;
770                            }
771                            Binding::Copy => {
772                                if let Some(selection) = content.selection() {
773                                    clipboard.write(clipboard::Kind::Standard, selection);
774                                }
775                            }
776                            Binding::Cut => {
777                                if let Some(selection) = content.selection() {
778                                    clipboard.write(clipboard::Kind::Standard, selection);
779
780                                    publish(Action::Edit(Edit::Delete));
781                                }
782                            }
783                            Binding::Paste => {
784                                if let Some(contents) = clipboard.read(clipboard::Kind::Standard) {
785                                    publish(Action::Edit(Edit::Paste(Arc::new(contents))));
786                                }
787                            }
788                            Binding::Move(motion) => {
789                                publish(Action::Move(motion));
790                            }
791                            Binding::Select(motion) => {
792                                publish(Action::Select(motion));
793                            }
794                            Binding::SelectWord => {
795                                publish(Action::SelectWord);
796                            }
797                            Binding::SelectLine => {
798                                publish(Action::SelectLine);
799                            }
800                            Binding::SelectAll => {
801                                publish(Action::SelectAll);
802                            }
803                            Binding::Insert(c) => {
804                                publish(Action::Edit(Edit::Insert(c)));
805                            }
806                            Binding::Enter => {
807                                publish(Action::Edit(Edit::Enter));
808                            }
809                            Binding::Backspace => {
810                                publish(Action::Edit(Edit::Backspace));
811                            }
812                            Binding::Delete => {
813                                publish(Action::Edit(Edit::Delete));
814                            }
815                            Binding::Sequence(sequence) => {
816                                for binding in sequence {
817                                    apply_binding(
818                                        binding, content, state, on_edit, clipboard, shell,
819                                    );
820                                }
821                            }
822                            Binding::Custom(message) => {
823                                shell.publish(message);
824                            }
825                        }
826                    }
827
828                    if !matches!(binding, Binding::Unfocus) {
829                        shell.capture_event();
830                    }
831
832                    apply_binding(binding, self.content, state, on_edit, clipboard, shell);
833
834                    if let Some(focus) = &mut state.focus {
835                        focus.updated_at = Instant::now();
836                    }
837                }
838            }
839        }
840
841        let status = {
842            let is_disabled = self.on_edit.is_none();
843            let is_hovered = cursor.is_over(layout.bounds());
844
845            if is_disabled {
846                Status::Disabled
847            } else if state.focus.is_some() {
848                Status::Focused { is_hovered }
849            } else if is_hovered {
850                Status::Hovered
851            } else {
852                Status::Active
853            }
854        };
855
856        if is_redraw {
857            self.last_status = Some(status);
858
859            shell.request_input_method(&self.input_method(state, renderer, layout));
860        } else if self
861            .last_status
862            .is_some_and(|last_status| status != last_status)
863        {
864            shell.request_redraw();
865        }
866    }
867
868    fn draw(
869        &self,
870        tree: &widget::Tree,
871        renderer: &mut Renderer,
872        theme: &Theme,
873        _defaults: &renderer::Style,
874        layout: Layout<'_>,
875        _cursor: mouse::Cursor,
876        _viewport: &Rectangle,
877    ) {
878        let bounds = layout.bounds();
879
880        let mut internal = self.content.0.borrow_mut();
881        let state = tree.state.downcast_ref::<State<Highlighter>>();
882
883        let font = self.font.unwrap_or_else(|| renderer.default_font());
884
885        let theme_name = theme.name();
886
887        if state
888            .last_theme
889            .borrow()
890            .as_ref()
891            .is_none_or(|last_theme| last_theme != theme_name)
892        {
893            state.highlighter.borrow_mut().change_line(0);
894            let _ = state.last_theme.borrow_mut().replace(theme_name.to_owned());
895        }
896
897        internal.editor.highlight(
898            font,
899            state.highlighter.borrow_mut().deref_mut(),
900            |highlight| (self.highlighter_format)(highlight, theme),
901        );
902
903        let style = theme.style(&self.class, self.last_status.unwrap_or(Status::Active));
904
905        renderer.fill_quad(
906            renderer::Quad {
907                bounds,
908                border: style.border,
909                ..renderer::Quad::default()
910            },
911            style.background,
912        );
913
914        let text_bounds = bounds.shrink(self.padding);
915
916        if internal.editor.is_empty() {
917            if let Some(placeholder) = self.placeholder.clone() {
918                renderer.fill_text(
919                    Text {
920                        content: placeholder.into_owned(),
921                        bounds: text_bounds.size(),
922                        size: self.text_size.unwrap_or_else(|| renderer.default_size()),
923                        line_height: self.line_height,
924                        font,
925                        align_x: text::Alignment::Default,
926                        align_y: alignment::Vertical::Top,
927                        shaping: text::Shaping::Advanced,
928                        wrapping: self.wrapping,
929                    },
930                    text_bounds.position(),
931                    style.placeholder,
932                    text_bounds,
933                );
934            }
935        } else {
936            renderer.fill_editor(
937                &internal.editor,
938                text_bounds.position(),
939                style.value,
940                text_bounds,
941            );
942        }
943
944        let translation = text_bounds.position() - Point::ORIGIN;
945
946        if let Some(focus) = state.focus.as_ref() {
947            match internal.editor.selection() {
948                Selection::Caret(position) if focus.is_cursor_visible() => {
949                    let cursor = Rectangle::new(
950                        position + translation,
951                        Size::new(
952                            1.0,
953                            self.line_height
954                                .to_absolute(
955                                    self.text_size.unwrap_or_else(|| renderer.default_size()),
956                                )
957                                .into(),
958                        ),
959                    );
960
961                    if let Some(clipped_cursor) = text_bounds.intersection(&cursor) {
962                        renderer.fill_quad(
963                            renderer::Quad {
964                                bounds: clipped_cursor,
965                                ..renderer::Quad::default()
966                            },
967                            style.value,
968                        );
969                    }
970                }
971                Selection::Range(ranges) => {
972                    for range in ranges
973                        .into_iter()
974                        .filter_map(|range| text_bounds.intersection(&(range + translation)))
975                    {
976                        renderer.fill_quad(
977                            renderer::Quad {
978                                bounds: range,
979                                ..renderer::Quad::default()
980                            },
981                            style.selection,
982                        );
983                    }
984                }
985                Selection::Caret(_) => {}
986            }
987        }
988    }
989
990    fn mouse_interaction(
991        &self,
992        _tree: &widget::Tree,
993        layout: Layout<'_>,
994        cursor: mouse::Cursor,
995        _viewport: &Rectangle,
996        _renderer: &Renderer,
997    ) -> mouse::Interaction {
998        let is_disabled = self.on_edit.is_none();
999
1000        if cursor.is_over(layout.bounds()) {
1001            if is_disabled {
1002                mouse::Interaction::NotAllowed
1003            } else {
1004                mouse::Interaction::Text
1005            }
1006        } else {
1007            mouse::Interaction::default()
1008        }
1009    }
1010
1011    fn operate(
1012        &mut self,
1013        tree: &mut widget::Tree,
1014        layout: Layout<'_>,
1015        _renderer: &Renderer,
1016        operation: &mut dyn widget::Operation,
1017    ) {
1018        let state = tree.state.downcast_mut::<State<Highlighter>>();
1019
1020        operation.focusable(self.id.as_ref(), layout.bounds(), state);
1021    }
1022}
1023
1024impl<'a, Highlighter, Message, Theme, Renderer>
1025    From<TextEditor<'a, Highlighter, Message, Theme, Renderer>>
1026    for Element<'a, Message, Theme, Renderer>
1027where
1028    Highlighter: text::Highlighter,
1029    Message: 'a,
1030    Theme: Catalog + 'a,
1031    Renderer: text::Renderer,
1032{
1033    fn from(text_editor: TextEditor<'a, Highlighter, Message, Theme, Renderer>) -> Self {
1034        Self::new(text_editor)
1035    }
1036}
1037
1038/// A binding to an action in the [`TextEditor`].
1039#[derive(Debug, Clone, PartialEq)]
1040pub enum Binding<Message> {
1041    /// Unfocus the [`TextEditor`].
1042    Unfocus,
1043    /// Copy the selection of the [`TextEditor`].
1044    Copy,
1045    /// Cut the selection of the [`TextEditor`].
1046    Cut,
1047    /// Paste the clipboard contents in the [`TextEditor`].
1048    Paste,
1049    /// Apply a [`Motion`].
1050    Move(Motion),
1051    /// Select text with a given [`Motion`].
1052    Select(Motion),
1053    /// Select the word at the current cursor.
1054    SelectWord,
1055    /// Select the line at the current cursor.
1056    SelectLine,
1057    /// Select the entire buffer.
1058    SelectAll,
1059    /// Insert the given character.
1060    Insert(char),
1061    /// Break the current line.
1062    Enter,
1063    /// Delete the previous character.
1064    Backspace,
1065    /// Delete the next character.
1066    Delete,
1067    /// A sequence of bindings to execute.
1068    Sequence(Vec<Self>),
1069    /// Produce the given message.
1070    Custom(Message),
1071}
1072
1073/// A key press.
1074#[derive(Debug, Clone, PartialEq, Eq)]
1075pub struct KeyPress {
1076    /// The original key pressed without modifiers applied to it.
1077    ///
1078    /// You should use this key for combinations (e.g. Ctrl+C).
1079    pub key: keyboard::Key,
1080    /// The key pressed with modifiers applied to it.
1081    ///
1082    /// You should use this key for any single key bindings (e.g. motions).
1083    pub modified_key: keyboard::Key,
1084    /// The physical key pressed.
1085    ///
1086    /// You should use this key for layout-independent bindings.
1087    pub physical_key: keyboard::key::Physical,
1088    /// The state of the keyboard modifiers.
1089    pub modifiers: keyboard::Modifiers,
1090    /// The text produced by the key press.
1091    pub text: Option<SmolStr>,
1092    /// The current [`Status`] of the [`TextEditor`].
1093    pub status: Status,
1094}
1095
1096impl<Message> Binding<Message> {
1097    /// Returns the default [`Binding`] for the given key press.
1098    pub fn from_key_press(event: KeyPress) -> Option<Self> {
1099        let KeyPress {
1100            key,
1101            modified_key,
1102            physical_key,
1103            modifiers,
1104            text,
1105            status,
1106        } = event;
1107
1108        if !matches!(status, Status::Focused { .. }) {
1109            return None;
1110        }
1111
1112        let combination = match key.to_latin(physical_key) {
1113            Some('c') if modifiers.command() => Some(Self::Copy),
1114            Some('x') if modifiers.command() => Some(Self::Cut),
1115            Some('v') if modifiers.command() && !modifiers.alt() => Some(Self::Paste),
1116            Some('a') if modifiers.command() => Some(Self::SelectAll),
1117            _ => None,
1118        };
1119
1120        if let Some(binding) = combination {
1121            return Some(binding);
1122        }
1123
1124        #[cfg(target_os = "macos")]
1125        let modified_key = convert_macos_shortcut(&key, modifiers).unwrap_or(modified_key);
1126
1127        match modified_key.as_ref() {
1128            keyboard::Key::Named(key::Named::Enter) => Some(Self::Enter),
1129            keyboard::Key::Named(key::Named::Backspace) => Some(Self::Backspace),
1130            keyboard::Key::Named(key::Named::Delete)
1131                if text.is_none() || text.as_deref() == Some("\u{7f}") =>
1132            {
1133                Some(Self::Delete)
1134            }
1135            keyboard::Key::Named(key::Named::Escape) => Some(Self::Unfocus),
1136            _ => {
1137                if let Some(text) = text {
1138                    let c = text.chars().find(|c| !c.is_control())?;
1139
1140                    Some(Self::Insert(c))
1141                } else if let keyboard::Key::Named(named_key) = key.as_ref() {
1142                    let motion = motion(named_key)?;
1143
1144                    let motion = if modifiers.macos_command() {
1145                        match motion {
1146                            Motion::Left => Motion::Home,
1147                            Motion::Right => Motion::End,
1148                            _ => motion,
1149                        }
1150                    } else {
1151                        motion
1152                    };
1153
1154                    let motion = if modifiers.jump() {
1155                        motion.widen()
1156                    } else {
1157                        motion
1158                    };
1159
1160                    Some(if modifiers.shift() {
1161                        Self::Select(motion)
1162                    } else {
1163                        Self::Move(motion)
1164                    })
1165                } else {
1166                    None
1167                }
1168            }
1169        }
1170    }
1171}
1172
1173enum Update<Message> {
1174    Click(mouse::Click),
1175    Drag(Point),
1176    Release,
1177    Scroll(f32),
1178    InputMethod(Ime),
1179    Binding(Binding<Message>),
1180}
1181
1182enum Ime {
1183    Toggle(bool),
1184    Preedit {
1185        content: String,
1186        selection: Option<ops::Range<usize>>,
1187    },
1188    Commit(String),
1189}
1190
1191impl<Message> Update<Message> {
1192    fn from_event<H: Highlighter>(
1193        event: &Event,
1194        state: &State<H>,
1195        bounds: Rectangle,
1196        padding: Padding,
1197        cursor: mouse::Cursor,
1198        key_binding: Option<&dyn Fn(KeyPress) -> Option<Binding<Message>>>,
1199    ) -> Option<Self> {
1200        let binding = |binding| Some(Update::Binding(binding));
1201
1202        match event {
1203            Event::Mouse(event) => match event {
1204                mouse::Event::ButtonPressed(mouse::Button::Left) => {
1205                    if let Some(cursor_position) = cursor.position_in(bounds) {
1206                        let cursor_position =
1207                            cursor_position - Vector::new(padding.left, padding.top);
1208
1209                        let click = mouse::Click::new(
1210                            cursor_position,
1211                            mouse::Button::Left,
1212                            state.last_click,
1213                        );
1214
1215                        Some(Update::Click(click))
1216                    } else if state.focus.is_some() {
1217                        binding(Binding::Unfocus)
1218                    } else {
1219                        None
1220                    }
1221                }
1222                mouse::Event::ButtonReleased(mouse::Button::Left) => Some(Update::Release),
1223                mouse::Event::CursorMoved { .. } => match state.drag_click {
1224                    Some(mouse::click::Kind::Single) => {
1225                        let cursor_position =
1226                            cursor.position_in(bounds)? - Vector::new(padding.left, padding.top);
1227
1228                        Some(Update::Drag(cursor_position))
1229                    }
1230                    _ => None,
1231                },
1232                mouse::Event::WheelScrolled { delta } if cursor.is_over(bounds) => {
1233                    Some(Update::Scroll(match delta {
1234                        mouse::ScrollDelta::Lines { y, .. } => {
1235                            if y.abs() > 0.0 {
1236                                y.signum() * -(y.abs() * 4.0).max(1.0)
1237                            } else {
1238                                0.0
1239                            }
1240                        }
1241                        mouse::ScrollDelta::Pixels { y, .. } => -y / 4.0,
1242                    }))
1243                }
1244                _ => None,
1245            },
1246            Event::InputMethod(event) => match event {
1247                input_method::Event::Opened | input_method::Event::Closed => Some(
1248                    Update::InputMethod(Ime::Toggle(matches!(event, input_method::Event::Opened))),
1249                ),
1250                input_method::Event::Preedit(content, selection) if state.focus.is_some() => {
1251                    Some(Update::InputMethod(Ime::Preedit {
1252                        content: content.clone(),
1253                        selection: selection.clone(),
1254                    }))
1255                }
1256                input_method::Event::Commit(content) if state.focus.is_some() => {
1257                    Some(Update::InputMethod(Ime::Commit(content.clone())))
1258                }
1259                _ => None,
1260            },
1261            Event::Keyboard(keyboard::Event::KeyPressed {
1262                key,
1263                modified_key,
1264                physical_key,
1265                modifiers,
1266                text,
1267                ..
1268            }) => {
1269                let status = if state.focus.is_some() {
1270                    Status::Focused {
1271                        is_hovered: cursor.is_over(bounds),
1272                    }
1273                } else {
1274                    Status::Active
1275                };
1276
1277                let key_press = KeyPress {
1278                    key: key.clone(),
1279                    modified_key: modified_key.clone(),
1280                    physical_key: *physical_key,
1281                    modifiers: *modifiers,
1282                    text: text.clone(),
1283                    status,
1284                };
1285
1286                if let Some(key_binding) = key_binding {
1287                    key_binding(key_press)
1288                } else {
1289                    Binding::from_key_press(key_press)
1290                }
1291                .map(Self::Binding)
1292            }
1293            _ => None,
1294        }
1295    }
1296}
1297
1298fn motion(key: key::Named) -> Option<Motion> {
1299    match key {
1300        key::Named::ArrowLeft => Some(Motion::Left),
1301        key::Named::ArrowRight => Some(Motion::Right),
1302        key::Named::ArrowUp => Some(Motion::Up),
1303        key::Named::ArrowDown => Some(Motion::Down),
1304        key::Named::Home => Some(Motion::Home),
1305        key::Named::End => Some(Motion::End),
1306        key::Named::PageUp => Some(Motion::PageUp),
1307        key::Named::PageDown => Some(Motion::PageDown),
1308        _ => None,
1309    }
1310}
1311
1312/// The possible status of a [`TextEditor`].
1313#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1314pub enum Status {
1315    /// The [`TextEditor`] can be interacted with.
1316    Active,
1317    /// The [`TextEditor`] is being hovered.
1318    Hovered,
1319    /// The [`TextEditor`] is focused.
1320    Focused {
1321        /// Whether the [`TextEditor`] is hovered, while focused.
1322        is_hovered: bool,
1323    },
1324    /// The [`TextEditor`] cannot be interacted with.
1325    Disabled,
1326}
1327
1328/// The appearance of a text input.
1329#[derive(Debug, Clone, Copy, PartialEq)]
1330pub struct Style {
1331    /// The [`Background`] of the text input.
1332    pub background: Background,
1333    /// The [`Border`] of the text input.
1334    pub border: Border,
1335    /// The [`Color`] of the placeholder of the text input.
1336    pub placeholder: Color,
1337    /// The [`Color`] of the value of the text input.
1338    pub value: Color,
1339    /// The [`Color`] of the selection of the text input.
1340    pub selection: Color,
1341}
1342
1343/// The theme catalog of a [`TextEditor`].
1344pub trait Catalog: theme::Base {
1345    /// The item class of the [`Catalog`].
1346    type Class<'a>;
1347
1348    /// The default class produced by the [`Catalog`].
1349    fn default<'a>() -> Self::Class<'a>;
1350
1351    /// The [`Style`] of a class with the given status.
1352    fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
1353}
1354
1355/// A styling function for a [`TextEditor`].
1356pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme, Status) -> Style + 'a>;
1357
1358impl Catalog for Theme {
1359    type Class<'a> = StyleFn<'a, Self>;
1360
1361    fn default<'a>() -> Self::Class<'a> {
1362        Box::new(default)
1363    }
1364
1365    fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
1366        class(self, status)
1367    }
1368}
1369
1370/// The default style of a [`TextEditor`].
1371pub fn default(theme: &Theme, status: Status) -> Style {
1372    let palette = theme.extended_palette();
1373
1374    let active = Style {
1375        background: Background::Color(palette.background.base.color),
1376        border: Border {
1377            radius: 2.0.into(),
1378            width: 1.0,
1379            color: palette.background.strong.color,
1380        },
1381        placeholder: palette.secondary.base.color,
1382        value: palette.background.base.text,
1383        selection: palette.primary.weak.color,
1384    };
1385
1386    match status {
1387        Status::Active => active,
1388        Status::Hovered => Style {
1389            border: Border {
1390                color: palette.background.base.text,
1391                ..active.border
1392            },
1393            ..active
1394        },
1395        Status::Focused { .. } => Style {
1396            border: Border {
1397                color: palette.primary.strong.color,
1398                ..active.border
1399            },
1400            ..active
1401        },
1402        Status::Disabled => Style {
1403            background: Background::Color(palette.background.weak.color),
1404            value: active.placeholder,
1405            placeholder: palette.background.strongest.color,
1406            ..active
1407        },
1408    }
1409}
1410
1411#[cfg(target_os = "macos")]
1412pub(crate) fn convert_macos_shortcut(
1413    key: &keyboard::Key,
1414    modifiers: keyboard::Modifiers,
1415) -> Option<keyboard::Key> {
1416    if modifiers != keyboard::Modifiers::CTRL {
1417        return None;
1418    }
1419
1420    let key = match key.as_ref() {
1421        keyboard::Key::Character("b") => key::Named::ArrowLeft,
1422        keyboard::Key::Character("f") => key::Named::ArrowRight,
1423        keyboard::Key::Character("a") => key::Named::Home,
1424        keyboard::Key::Character("e") => key::Named::End,
1425        keyboard::Key::Character("h") => key::Named::Backspace,
1426        keyboard::Key::Character("d") => key::Named::Delete,
1427        _ => return None,
1428    };
1429
1430    Some(keyboard::Key::Named(key))
1431}