Skip to main content

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            renderer.scale_factor(),
623            state.highlighter.borrow_mut().deref_mut(),
624        );
625
626        match self.height {
627            Length::Fill | Length::FillPortion(_) | Length::Fixed(_) => {
628                layout::Node::new(limits.max())
629            }
630            Length::Shrink => {
631                let min_bounds = internal.editor.min_bounds();
632
633                layout::Node::new(
634                    limits
635                        .height(min_bounds.height)
636                        .max()
637                        .expand(Size::new(0.0, self.padding.y())),
638                )
639            }
640        }
641    }
642
643    fn update(
644        &mut self,
645        tree: &mut widget::Tree,
646        event: &Event,
647        layout: Layout<'_>,
648        cursor: mouse::Cursor,
649        renderer: &Renderer,
650        clipboard: &mut dyn Clipboard,
651        shell: &mut Shell<'_, Message>,
652        _viewport: &Rectangle,
653    ) {
654        let Some(on_edit) = self.on_edit.as_ref() else {
655            return;
656        };
657
658        let state = tree.state.downcast_mut::<State<Highlighter>>();
659        let is_redraw = matches!(event, Event::Window(window::Event::RedrawRequested(_now)),);
660
661        match event {
662            Event::Window(window::Event::Unfocused) => {
663                if let Some(focus) = &mut state.focus {
664                    focus.is_window_focused = false;
665                }
666            }
667            Event::Window(window::Event::Focused) => {
668                if let Some(focus) = &mut state.focus {
669                    focus.is_window_focused = true;
670                    focus.updated_at = Instant::now();
671
672                    shell.request_redraw();
673                }
674            }
675            Event::Window(window::Event::RedrawRequested(now)) => {
676                if let Some(focus) = &mut state.focus
677                    && focus.is_window_focused
678                {
679                    focus.now = *now;
680
681                    let millis_until_redraw = Focus::CURSOR_BLINK_INTERVAL_MILLIS
682                        - (focus.now - focus.updated_at).as_millis()
683                            % Focus::CURSOR_BLINK_INTERVAL_MILLIS;
684
685                    shell.request_redraw_at(
686                        focus.now + Duration::from_millis(millis_until_redraw as u64),
687                    );
688                }
689            }
690            _ => {}
691        }
692
693        if let Some(update) = Update::from_event(
694            event,
695            state,
696            layout.bounds(),
697            self.padding,
698            cursor,
699            self.key_binding.as_deref(),
700        ) {
701            match update {
702                Update::Click(click) => {
703                    let action = match click.kind() {
704                        mouse::click::Kind::Single => Action::Click(click.position()),
705                        mouse::click::Kind::Double => Action::SelectWord,
706                        mouse::click::Kind::Triple => Action::SelectLine,
707                    };
708
709                    state.focus = Some(Focus::now());
710                    state.last_click = Some(click);
711                    state.drag_click = Some(click.kind());
712
713                    shell.publish(on_edit(action));
714                    shell.capture_event();
715                }
716                Update::Drag(position) => {
717                    shell.publish(on_edit(Action::Drag(position)));
718                }
719                Update::Release => {
720                    state.drag_click = None;
721                }
722                Update::Scroll(lines) => {
723                    let bounds = self.content.0.borrow().editor.bounds();
724
725                    if bounds.height >= i32::MAX as f32 {
726                        return;
727                    }
728
729                    let lines = lines + state.partial_scroll;
730                    state.partial_scroll = lines.fract();
731
732                    shell.publish(on_edit(Action::Scroll {
733                        lines: lines as i32,
734                    }));
735                    shell.capture_event();
736                }
737                Update::InputMethod(update) => match update {
738                    Ime::Toggle(is_open) => {
739                        state.preedit = is_open.then(input_method::Preedit::new);
740
741                        shell.request_redraw();
742                    }
743                    Ime::Preedit { content, selection } => {
744                        state.preedit = Some(input_method::Preedit {
745                            content,
746                            selection,
747                            text_size: self.text_size,
748                        });
749
750                        shell.request_redraw();
751                    }
752                    Ime::Commit(text) => {
753                        shell.publish(on_edit(Action::Edit(Edit::Paste(Arc::new(text)))));
754                    }
755                },
756                Update::Binding(binding) => {
757                    fn apply_binding<H: text::Highlighter, R: text::Renderer, Message>(
758                        binding: Binding<Message>,
759                        content: &Content<R>,
760                        state: &mut State<H>,
761                        on_edit: &dyn Fn(Action) -> Message,
762                        clipboard: &mut dyn Clipboard,
763                        shell: &mut Shell<'_, Message>,
764                    ) {
765                        let mut publish = |action| shell.publish(on_edit(action));
766
767                        match binding {
768                            Binding::Unfocus => {
769                                state.focus = None;
770                                state.drag_click = None;
771                            }
772                            Binding::Copy => {
773                                if let Some(selection) = content.selection() {
774                                    clipboard.write(clipboard::Kind::Standard, selection);
775                                }
776                            }
777                            Binding::Cut => {
778                                if let Some(selection) = content.selection() {
779                                    clipboard.write(clipboard::Kind::Standard, selection);
780
781                                    publish(Action::Edit(Edit::Delete));
782                                }
783                            }
784                            Binding::Paste => {
785                                if let Some(contents) = clipboard.read(clipboard::Kind::Standard) {
786                                    publish(Action::Edit(Edit::Paste(Arc::new(contents))));
787                                }
788                            }
789                            Binding::Move(motion) => {
790                                publish(Action::Move(motion));
791                            }
792                            Binding::Select(motion) => {
793                                publish(Action::Select(motion));
794                            }
795                            Binding::SelectWord => {
796                                publish(Action::SelectWord);
797                            }
798                            Binding::SelectLine => {
799                                publish(Action::SelectLine);
800                            }
801                            Binding::SelectAll => {
802                                publish(Action::SelectAll);
803                            }
804                            Binding::Insert(c) => {
805                                publish(Action::Edit(Edit::Insert(c)));
806                            }
807                            Binding::Enter => {
808                                publish(Action::Edit(Edit::Enter));
809                            }
810                            Binding::Backspace => {
811                                publish(Action::Edit(Edit::Backspace));
812                            }
813                            Binding::Delete => {
814                                publish(Action::Edit(Edit::Delete));
815                            }
816                            Binding::Sequence(sequence) => {
817                                for binding in sequence {
818                                    apply_binding(
819                                        binding, content, state, on_edit, clipboard, shell,
820                                    );
821                                }
822                            }
823                            Binding::Custom(message) => {
824                                shell.publish(message);
825                            }
826                        }
827                    }
828
829                    if !matches!(binding, Binding::Unfocus) {
830                        shell.capture_event();
831                    }
832
833                    apply_binding(binding, self.content, state, on_edit, clipboard, shell);
834
835                    if let Some(focus) = &mut state.focus {
836                        focus.updated_at = Instant::now();
837                    }
838                }
839            }
840        }
841
842        let status = {
843            let is_disabled = self.on_edit.is_none();
844            let is_hovered = cursor.is_over(layout.bounds());
845
846            if is_disabled {
847                Status::Disabled
848            } else if state.focus.is_some() {
849                Status::Focused { is_hovered }
850            } else if is_hovered {
851                Status::Hovered
852            } else {
853                Status::Active
854            }
855        };
856
857        if is_redraw {
858            self.last_status = Some(status);
859
860            shell.request_input_method(&self.input_method(state, renderer, layout));
861        } else if self
862            .last_status
863            .is_some_and(|last_status| status != last_status)
864        {
865            shell.request_redraw();
866        }
867    }
868
869    fn draw(
870        &self,
871        tree: &widget::Tree,
872        renderer: &mut Renderer,
873        theme: &Theme,
874        _defaults: &renderer::Style,
875        layout: Layout<'_>,
876        _cursor: mouse::Cursor,
877        _viewport: &Rectangle,
878    ) {
879        let bounds = layout.bounds();
880
881        let mut internal = self.content.0.borrow_mut();
882        let state = tree.state.downcast_ref::<State<Highlighter>>();
883
884        let font = self.font.unwrap_or_else(|| renderer.default_font());
885
886        let theme_name = theme.name();
887
888        if state
889            .last_theme
890            .borrow()
891            .as_ref()
892            .is_none_or(|last_theme| last_theme != theme_name)
893        {
894            state.highlighter.borrow_mut().change_line(0);
895            let _ = state.last_theme.borrow_mut().replace(theme_name.to_owned());
896        }
897
898        internal.editor.highlight(
899            font,
900            state.highlighter.borrow_mut().deref_mut(),
901            |highlight| (self.highlighter_format)(highlight, theme),
902        );
903
904        let style = theme.style(&self.class, self.last_status.unwrap_or(Status::Active));
905
906        renderer.fill_quad(
907            renderer::Quad {
908                bounds,
909                border: style.border,
910                ..renderer::Quad::default()
911            },
912            style.background,
913        );
914
915        let text_bounds = bounds.shrink(self.padding);
916
917        if internal.editor.is_empty() {
918            if let Some(placeholder) = self.placeholder.clone() {
919                renderer.fill_text(
920                    Text {
921                        content: placeholder.into_owned(),
922                        bounds: text_bounds.size(),
923                        size: self.text_size.unwrap_or_else(|| renderer.default_size()),
924                        line_height: self.line_height,
925                        font,
926                        align_x: text::Alignment::Default,
927                        align_y: alignment::Vertical::Top,
928                        shaping: text::Shaping::Advanced,
929                        wrapping: self.wrapping,
930                        hint_factor: renderer.scale_factor(),
931                    },
932                    text_bounds.position(),
933                    style.placeholder,
934                    text_bounds,
935                );
936            }
937        } else {
938            renderer.fill_editor(
939                &internal.editor,
940                text_bounds.position(),
941                style.value,
942                text_bounds,
943            );
944        }
945
946        let translation = text_bounds.position() - Point::ORIGIN;
947
948        if let Some(focus) = state.focus.as_ref() {
949            match internal.editor.selection() {
950                Selection::Caret(position) if focus.is_cursor_visible() => {
951                    let cursor = Rectangle::new(
952                        position + translation,
953                        Size::new(
954                            if renderer::CRISP {
955                                (1.0 / renderer.scale_factor().unwrap_or(1.0)).max(1.0)
956                            } else {
957                                1.0
958                            },
959                            self.line_height
960                                .to_absolute(
961                                    self.text_size.unwrap_or_else(|| renderer.default_size()),
962                                )
963                                .into(),
964                        ),
965                    );
966
967                    if let Some(clipped_cursor) = text_bounds.intersection(&cursor) {
968                        renderer.fill_quad(
969                            renderer::Quad {
970                                bounds: clipped_cursor,
971                                ..renderer::Quad::default()
972                            },
973                            style.value,
974                        );
975                    }
976                }
977                Selection::Range(ranges) => {
978                    for range in ranges
979                        .into_iter()
980                        .filter_map(|range| text_bounds.intersection(&(range + translation)))
981                    {
982                        renderer.fill_quad(
983                            renderer::Quad {
984                                bounds: range,
985                                ..renderer::Quad::default()
986                            },
987                            style.selection,
988                        );
989                    }
990                }
991                Selection::Caret(_) => {
992                    // Drawing an empty quad helps some renderers to track the damage of the blinking cursor
993                    renderer.fill_quad(renderer::Quad::default(), Color::TRANSPARENT);
994                }
995            }
996        }
997    }
998
999    fn mouse_interaction(
1000        &self,
1001        _tree: &widget::Tree,
1002        layout: Layout<'_>,
1003        cursor: mouse::Cursor,
1004        _viewport: &Rectangle,
1005        _renderer: &Renderer,
1006    ) -> mouse::Interaction {
1007        let is_disabled = self.on_edit.is_none();
1008
1009        if cursor.is_over(layout.bounds()) {
1010            if is_disabled {
1011                mouse::Interaction::NotAllowed
1012            } else {
1013                mouse::Interaction::Text
1014            }
1015        } else {
1016            mouse::Interaction::default()
1017        }
1018    }
1019
1020    fn operate(
1021        &mut self,
1022        tree: &mut widget::Tree,
1023        layout: Layout<'_>,
1024        _renderer: &Renderer,
1025        operation: &mut dyn widget::Operation,
1026    ) {
1027        let state = tree.state.downcast_mut::<State<Highlighter>>();
1028
1029        operation.focusable(self.id.as_ref(), layout.bounds(), state);
1030    }
1031}
1032
1033impl<'a, Highlighter, Message, Theme, Renderer>
1034    From<TextEditor<'a, Highlighter, Message, Theme, Renderer>>
1035    for Element<'a, Message, Theme, Renderer>
1036where
1037    Highlighter: text::Highlighter,
1038    Message: 'a,
1039    Theme: Catalog + 'a,
1040    Renderer: text::Renderer,
1041{
1042    fn from(text_editor: TextEditor<'a, Highlighter, Message, Theme, Renderer>) -> Self {
1043        Self::new(text_editor)
1044    }
1045}
1046
1047/// A binding to an action in the [`TextEditor`].
1048#[derive(Debug, Clone, PartialEq)]
1049pub enum Binding<Message> {
1050    /// Unfocus the [`TextEditor`].
1051    Unfocus,
1052    /// Copy the selection of the [`TextEditor`].
1053    Copy,
1054    /// Cut the selection of the [`TextEditor`].
1055    Cut,
1056    /// Paste the clipboard contents in the [`TextEditor`].
1057    Paste,
1058    /// Apply a [`Motion`].
1059    Move(Motion),
1060    /// Select text with a given [`Motion`].
1061    Select(Motion),
1062    /// Select the word at the current cursor.
1063    SelectWord,
1064    /// Select the line at the current cursor.
1065    SelectLine,
1066    /// Select the entire buffer.
1067    SelectAll,
1068    /// Insert the given character.
1069    Insert(char),
1070    /// Break the current line.
1071    Enter,
1072    /// Delete the previous character.
1073    Backspace,
1074    /// Delete the next character.
1075    Delete,
1076    /// A sequence of bindings to execute.
1077    Sequence(Vec<Self>),
1078    /// Produce the given message.
1079    Custom(Message),
1080}
1081
1082/// A key press.
1083#[derive(Debug, Clone, PartialEq, Eq)]
1084pub struct KeyPress {
1085    /// The original key pressed without modifiers applied to it.
1086    ///
1087    /// You should use this key for combinations (e.g. Ctrl+C).
1088    pub key: keyboard::Key,
1089    /// The key pressed with modifiers applied to it.
1090    ///
1091    /// You should use this key for any single key bindings (e.g. motions).
1092    pub modified_key: keyboard::Key,
1093    /// The physical key pressed.
1094    ///
1095    /// You should use this key for layout-independent bindings.
1096    pub physical_key: keyboard::key::Physical,
1097    /// The state of the keyboard modifiers.
1098    pub modifiers: keyboard::Modifiers,
1099    /// The text produced by the key press.
1100    pub text: Option<SmolStr>,
1101    /// The current [`Status`] of the [`TextEditor`].
1102    pub status: Status,
1103}
1104
1105impl<Message> Binding<Message> {
1106    /// Returns the default [`Binding`] for the given key press.
1107    pub fn from_key_press(event: KeyPress) -> Option<Self> {
1108        let KeyPress {
1109            key,
1110            modified_key,
1111            physical_key,
1112            modifiers,
1113            text,
1114            status,
1115        } = event;
1116
1117        if !matches!(status, Status::Focused { .. }) {
1118            return None;
1119        }
1120
1121        let combination = match key.to_latin(physical_key) {
1122            Some('c') if modifiers.command() => Some(Self::Copy),
1123            Some('x') if modifiers.command() => Some(Self::Cut),
1124            Some('v') if modifiers.command() && !modifiers.alt() => Some(Self::Paste),
1125            Some('a') if modifiers.command() => Some(Self::SelectAll),
1126            _ => None,
1127        };
1128
1129        if let Some(binding) = combination {
1130            return Some(binding);
1131        }
1132
1133        #[cfg(target_os = "macos")]
1134        let modified_key = convert_macos_shortcut(&key, modifiers).unwrap_or(modified_key);
1135
1136        match modified_key.as_ref() {
1137            keyboard::Key::Named(key::Named::Enter) => Some(Self::Enter),
1138            keyboard::Key::Named(key::Named::Backspace) => Some(Self::Backspace),
1139            keyboard::Key::Named(key::Named::Delete)
1140                if text.is_none() || text.as_deref() == Some("\u{7f}") =>
1141            {
1142                Some(Self::Delete)
1143            }
1144            keyboard::Key::Named(key::Named::Escape) => Some(Self::Unfocus),
1145            _ => {
1146                if let Some(text) = text {
1147                    let c = text.chars().find(|c| !c.is_control())?;
1148
1149                    Some(Self::Insert(c))
1150                } else if let keyboard::Key::Named(named_key) = key.as_ref() {
1151                    let motion = motion(named_key)?;
1152
1153                    let motion = if modifiers.macos_command() {
1154                        match motion {
1155                            Motion::Left => Motion::Home,
1156                            Motion::Right => Motion::End,
1157                            _ => motion,
1158                        }
1159                    } else {
1160                        motion
1161                    };
1162
1163                    let motion = if modifiers.jump() {
1164                        motion.widen()
1165                    } else {
1166                        motion
1167                    };
1168
1169                    Some(if modifiers.shift() {
1170                        Self::Select(motion)
1171                    } else {
1172                        Self::Move(motion)
1173                    })
1174                } else {
1175                    None
1176                }
1177            }
1178        }
1179    }
1180}
1181
1182enum Update<Message> {
1183    Click(mouse::Click),
1184    Drag(Point),
1185    Release,
1186    Scroll(f32),
1187    InputMethod(Ime),
1188    Binding(Binding<Message>),
1189}
1190
1191enum Ime {
1192    Toggle(bool),
1193    Preedit {
1194        content: String,
1195        selection: Option<ops::Range<usize>>,
1196    },
1197    Commit(String),
1198}
1199
1200impl<Message> Update<Message> {
1201    fn from_event<H: Highlighter>(
1202        event: &Event,
1203        state: &State<H>,
1204        bounds: Rectangle,
1205        padding: Padding,
1206        cursor: mouse::Cursor,
1207        key_binding: Option<&dyn Fn(KeyPress) -> Option<Binding<Message>>>,
1208    ) -> Option<Self> {
1209        let binding = |binding| Some(Update::Binding(binding));
1210
1211        match event {
1212            Event::Mouse(event) => match event {
1213                mouse::Event::ButtonPressed(mouse::Button::Left) => {
1214                    if let Some(cursor_position) = cursor.position_in(bounds) {
1215                        let cursor_position =
1216                            cursor_position - Vector::new(padding.left, padding.top);
1217
1218                        let click = mouse::Click::new(
1219                            cursor_position,
1220                            mouse::Button::Left,
1221                            state.last_click,
1222                        );
1223
1224                        Some(Update::Click(click))
1225                    } else if state.focus.is_some() {
1226                        binding(Binding::Unfocus)
1227                    } else {
1228                        None
1229                    }
1230                }
1231                mouse::Event::ButtonReleased(mouse::Button::Left) => Some(Update::Release),
1232                mouse::Event::CursorMoved { .. } => match state.drag_click {
1233                    Some(mouse::click::Kind::Single) => {
1234                        let cursor_position =
1235                            cursor.position_in(bounds)? - Vector::new(padding.left, padding.top);
1236
1237                        Some(Update::Drag(cursor_position))
1238                    }
1239                    _ => None,
1240                },
1241                mouse::Event::WheelScrolled { delta } if cursor.is_over(bounds) => {
1242                    Some(Update::Scroll(match delta {
1243                        mouse::ScrollDelta::Lines { y, .. } => {
1244                            if y.abs() > 0.0 {
1245                                y.signum() * -(y.abs() * 4.0).max(1.0)
1246                            } else {
1247                                0.0
1248                            }
1249                        }
1250                        mouse::ScrollDelta::Pixels { y, .. } => -y / 4.0,
1251                    }))
1252                }
1253                _ => None,
1254            },
1255            Event::InputMethod(event) => match event {
1256                input_method::Event::Opened | input_method::Event::Closed => Some(
1257                    Update::InputMethod(Ime::Toggle(matches!(event, input_method::Event::Opened))),
1258                ),
1259                input_method::Event::Preedit(content, selection) if state.focus.is_some() => {
1260                    Some(Update::InputMethod(Ime::Preedit {
1261                        content: content.clone(),
1262                        selection: selection.clone(),
1263                    }))
1264                }
1265                input_method::Event::Commit(content) if state.focus.is_some() => {
1266                    Some(Update::InputMethod(Ime::Commit(content.clone())))
1267                }
1268                _ => None,
1269            },
1270            Event::Keyboard(keyboard::Event::KeyPressed {
1271                key,
1272                modified_key,
1273                physical_key,
1274                modifiers,
1275                text,
1276                ..
1277            }) => {
1278                let status = if state.focus.is_some() {
1279                    Status::Focused {
1280                        is_hovered: cursor.is_over(bounds),
1281                    }
1282                } else {
1283                    Status::Active
1284                };
1285
1286                let key_press = KeyPress {
1287                    key: key.clone(),
1288                    modified_key: modified_key.clone(),
1289                    physical_key: *physical_key,
1290                    modifiers: *modifiers,
1291                    text: text.clone(),
1292                    status,
1293                };
1294
1295                if let Some(key_binding) = key_binding {
1296                    key_binding(key_press)
1297                } else {
1298                    Binding::from_key_press(key_press)
1299                }
1300                .map(Self::Binding)
1301            }
1302            _ => None,
1303        }
1304    }
1305}
1306
1307fn motion(key: key::Named) -> Option<Motion> {
1308    match key {
1309        key::Named::ArrowLeft => Some(Motion::Left),
1310        key::Named::ArrowRight => Some(Motion::Right),
1311        key::Named::ArrowUp => Some(Motion::Up),
1312        key::Named::ArrowDown => Some(Motion::Down),
1313        key::Named::Home => Some(Motion::Home),
1314        key::Named::End => Some(Motion::End),
1315        key::Named::PageUp => Some(Motion::PageUp),
1316        key::Named::PageDown => Some(Motion::PageDown),
1317        _ => None,
1318    }
1319}
1320
1321/// The possible status of a [`TextEditor`].
1322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1323pub enum Status {
1324    /// The [`TextEditor`] can be interacted with.
1325    Active,
1326    /// The [`TextEditor`] is being hovered.
1327    Hovered,
1328    /// The [`TextEditor`] is focused.
1329    Focused {
1330        /// Whether the [`TextEditor`] is hovered, while focused.
1331        is_hovered: bool,
1332    },
1333    /// The [`TextEditor`] cannot be interacted with.
1334    Disabled,
1335}
1336
1337/// The appearance of a text input.
1338#[derive(Debug, Clone, Copy, PartialEq)]
1339pub struct Style {
1340    /// The [`Background`] of the text input.
1341    pub background: Background,
1342    /// The [`Border`] of the text input.
1343    pub border: Border,
1344    /// The [`Color`] of the placeholder of the text input.
1345    pub placeholder: Color,
1346    /// The [`Color`] of the value of the text input.
1347    pub value: Color,
1348    /// The [`Color`] of the selection of the text input.
1349    pub selection: Color,
1350}
1351
1352/// The theme catalog of a [`TextEditor`].
1353pub trait Catalog: theme::Base {
1354    /// The item class of the [`Catalog`].
1355    type Class<'a>;
1356
1357    /// The default class produced by the [`Catalog`].
1358    fn default<'a>() -> Self::Class<'a>;
1359
1360    /// The [`Style`] of a class with the given status.
1361    fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
1362}
1363
1364/// A styling function for a [`TextEditor`].
1365pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme, Status) -> Style + 'a>;
1366
1367impl Catalog for Theme {
1368    type Class<'a> = StyleFn<'a, Self>;
1369
1370    fn default<'a>() -> Self::Class<'a> {
1371        Box::new(default)
1372    }
1373
1374    fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
1375        class(self, status)
1376    }
1377}
1378
1379/// The default style of a [`TextEditor`].
1380pub fn default(theme: &Theme, status: Status) -> Style {
1381    let palette = theme.extended_palette();
1382
1383    let active = Style {
1384        background: Background::Color(palette.background.base.color),
1385        border: Border {
1386            radius: 2.0.into(),
1387            width: 1.0,
1388            color: palette.background.strong.color,
1389        },
1390        placeholder: palette.secondary.base.color,
1391        value: palette.background.base.text,
1392        selection: palette.primary.weak.color,
1393    };
1394
1395    match status {
1396        Status::Active => active,
1397        Status::Hovered => Style {
1398            border: Border {
1399                color: palette.background.base.text,
1400                ..active.border
1401            },
1402            ..active
1403        },
1404        Status::Focused { .. } => Style {
1405            border: Border {
1406                color: palette.primary.strong.color,
1407                ..active.border
1408            },
1409            ..active
1410        },
1411        Status::Disabled => Style {
1412            background: Background::Color(palette.background.weak.color),
1413            value: active.placeholder,
1414            placeholder: palette.background.strongest.color,
1415            ..active
1416        },
1417    }
1418}
1419
1420#[cfg(target_os = "macos")]
1421pub(crate) fn convert_macos_shortcut(
1422    key: &keyboard::Key,
1423    modifiers: keyboard::Modifiers,
1424) -> Option<keyboard::Key> {
1425    if modifiers != keyboard::Modifiers::CTRL {
1426        return None;
1427    }
1428
1429    let key = match key.as_ref() {
1430        keyboard::Key::Character("b") => key::Named::ArrowLeft,
1431        keyboard::Key::Character("f") => key::Named::ArrowRight,
1432        keyboard::Key::Character("a") => key::Named::Home,
1433        keyboard::Key::Character("e") => key::Named::End,
1434        keyboard::Key::Character("h") => key::Named::Backspace,
1435        keyboard::Key::Character("d") => key::Named::Delete,
1436        _ => return None,
1437    };
1438
1439    Some(keyboard::Key::Named(key))
1440}