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            }
993        }
994    }
995
996    fn mouse_interaction(
997        &self,
998        _tree: &widget::Tree,
999        layout: Layout<'_>,
1000        cursor: mouse::Cursor,
1001        _viewport: &Rectangle,
1002        _renderer: &Renderer,
1003    ) -> mouse::Interaction {
1004        let is_disabled = self.on_edit.is_none();
1005
1006        if cursor.is_over(layout.bounds()) {
1007            if is_disabled {
1008                mouse::Interaction::NotAllowed
1009            } else {
1010                mouse::Interaction::Text
1011            }
1012        } else {
1013            mouse::Interaction::default()
1014        }
1015    }
1016
1017    fn operate(
1018        &mut self,
1019        tree: &mut widget::Tree,
1020        layout: Layout<'_>,
1021        _renderer: &Renderer,
1022        operation: &mut dyn widget::Operation,
1023    ) {
1024        let state = tree.state.downcast_mut::<State<Highlighter>>();
1025
1026        operation.focusable(self.id.as_ref(), layout.bounds(), state);
1027    }
1028}
1029
1030impl<'a, Highlighter, Message, Theme, Renderer>
1031    From<TextEditor<'a, Highlighter, Message, Theme, Renderer>>
1032    for Element<'a, Message, Theme, Renderer>
1033where
1034    Highlighter: text::Highlighter,
1035    Message: 'a,
1036    Theme: Catalog + 'a,
1037    Renderer: text::Renderer,
1038{
1039    fn from(text_editor: TextEditor<'a, Highlighter, Message, Theme, Renderer>) -> Self {
1040        Self::new(text_editor)
1041    }
1042}
1043
1044/// A binding to an action in the [`TextEditor`].
1045#[derive(Debug, Clone, PartialEq)]
1046pub enum Binding<Message> {
1047    /// Unfocus the [`TextEditor`].
1048    Unfocus,
1049    /// Copy the selection of the [`TextEditor`].
1050    Copy,
1051    /// Cut the selection of the [`TextEditor`].
1052    Cut,
1053    /// Paste the clipboard contents in the [`TextEditor`].
1054    Paste,
1055    /// Apply a [`Motion`].
1056    Move(Motion),
1057    /// Select text with a given [`Motion`].
1058    Select(Motion),
1059    /// Select the word at the current cursor.
1060    SelectWord,
1061    /// Select the line at the current cursor.
1062    SelectLine,
1063    /// Select the entire buffer.
1064    SelectAll,
1065    /// Insert the given character.
1066    Insert(char),
1067    /// Break the current line.
1068    Enter,
1069    /// Delete the previous character.
1070    Backspace,
1071    /// Delete the next character.
1072    Delete,
1073    /// A sequence of bindings to execute.
1074    Sequence(Vec<Self>),
1075    /// Produce the given message.
1076    Custom(Message),
1077}
1078
1079/// A key press.
1080#[derive(Debug, Clone, PartialEq, Eq)]
1081pub struct KeyPress {
1082    /// The original key pressed without modifiers applied to it.
1083    ///
1084    /// You should use this key for combinations (e.g. Ctrl+C).
1085    pub key: keyboard::Key,
1086    /// The key pressed with modifiers applied to it.
1087    ///
1088    /// You should use this key for any single key bindings (e.g. motions).
1089    pub modified_key: keyboard::Key,
1090    /// The physical key pressed.
1091    ///
1092    /// You should use this key for layout-independent bindings.
1093    pub physical_key: keyboard::key::Physical,
1094    /// The state of the keyboard modifiers.
1095    pub modifiers: keyboard::Modifiers,
1096    /// The text produced by the key press.
1097    pub text: Option<SmolStr>,
1098    /// The current [`Status`] of the [`TextEditor`].
1099    pub status: Status,
1100}
1101
1102impl<Message> Binding<Message> {
1103    /// Returns the default [`Binding`] for the given key press.
1104    pub fn from_key_press(event: KeyPress) -> Option<Self> {
1105        let KeyPress {
1106            key,
1107            modified_key,
1108            physical_key,
1109            modifiers,
1110            text,
1111            status,
1112        } = event;
1113
1114        if !matches!(status, Status::Focused { .. }) {
1115            return None;
1116        }
1117
1118        let combination = match key.to_latin(physical_key) {
1119            Some('c') if modifiers.command() => Some(Self::Copy),
1120            Some('x') if modifiers.command() => Some(Self::Cut),
1121            Some('v') if modifiers.command() && !modifiers.alt() => Some(Self::Paste),
1122            Some('a') if modifiers.command() => Some(Self::SelectAll),
1123            _ => None,
1124        };
1125
1126        if let Some(binding) = combination {
1127            return Some(binding);
1128        }
1129
1130        #[cfg(target_os = "macos")]
1131        let modified_key = convert_macos_shortcut(&key, modifiers).unwrap_or(modified_key);
1132
1133        match modified_key.as_ref() {
1134            keyboard::Key::Named(key::Named::Enter) => Some(Self::Enter),
1135            keyboard::Key::Named(key::Named::Backspace) => Some(Self::Backspace),
1136            keyboard::Key::Named(key::Named::Delete)
1137                if text.is_none() || text.as_deref() == Some("\u{7f}") =>
1138            {
1139                Some(Self::Delete)
1140            }
1141            keyboard::Key::Named(key::Named::Escape) => Some(Self::Unfocus),
1142            _ => {
1143                if let Some(text) = text {
1144                    let c = text.chars().find(|c| !c.is_control())?;
1145
1146                    Some(Self::Insert(c))
1147                } else if let keyboard::Key::Named(named_key) = key.as_ref() {
1148                    let motion = motion(named_key)?;
1149
1150                    let motion = if modifiers.macos_command() {
1151                        match motion {
1152                            Motion::Left => Motion::Home,
1153                            Motion::Right => Motion::End,
1154                            _ => motion,
1155                        }
1156                    } else {
1157                        motion
1158                    };
1159
1160                    let motion = if modifiers.jump() {
1161                        motion.widen()
1162                    } else {
1163                        motion
1164                    };
1165
1166                    Some(if modifiers.shift() {
1167                        Self::Select(motion)
1168                    } else {
1169                        Self::Move(motion)
1170                    })
1171                } else {
1172                    None
1173                }
1174            }
1175        }
1176    }
1177}
1178
1179enum Update<Message> {
1180    Click(mouse::Click),
1181    Drag(Point),
1182    Release,
1183    Scroll(f32),
1184    InputMethod(Ime),
1185    Binding(Binding<Message>),
1186}
1187
1188enum Ime {
1189    Toggle(bool),
1190    Preedit {
1191        content: String,
1192        selection: Option<ops::Range<usize>>,
1193    },
1194    Commit(String),
1195}
1196
1197impl<Message> Update<Message> {
1198    fn from_event<H: Highlighter>(
1199        event: &Event,
1200        state: &State<H>,
1201        bounds: Rectangle,
1202        padding: Padding,
1203        cursor: mouse::Cursor,
1204        key_binding: Option<&dyn Fn(KeyPress) -> Option<Binding<Message>>>,
1205    ) -> Option<Self> {
1206        let binding = |binding| Some(Update::Binding(binding));
1207
1208        match event {
1209            Event::Mouse(event) => match event {
1210                mouse::Event::ButtonPressed(mouse::Button::Left) => {
1211                    if let Some(cursor_position) = cursor.position_in(bounds) {
1212                        let cursor_position =
1213                            cursor_position - Vector::new(padding.left, padding.top);
1214
1215                        let click = mouse::Click::new(
1216                            cursor_position,
1217                            mouse::Button::Left,
1218                            state.last_click,
1219                        );
1220
1221                        Some(Update::Click(click))
1222                    } else if state.focus.is_some() {
1223                        binding(Binding::Unfocus)
1224                    } else {
1225                        None
1226                    }
1227                }
1228                mouse::Event::ButtonReleased(mouse::Button::Left) => Some(Update::Release),
1229                mouse::Event::CursorMoved { .. } => match state.drag_click {
1230                    Some(mouse::click::Kind::Single) => {
1231                        let cursor_position =
1232                            cursor.position_in(bounds)? - Vector::new(padding.left, padding.top);
1233
1234                        Some(Update::Drag(cursor_position))
1235                    }
1236                    _ => None,
1237                },
1238                mouse::Event::WheelScrolled { delta } if cursor.is_over(bounds) => {
1239                    Some(Update::Scroll(match delta {
1240                        mouse::ScrollDelta::Lines { y, .. } => {
1241                            if y.abs() > 0.0 {
1242                                y.signum() * -(y.abs() * 4.0).max(1.0)
1243                            } else {
1244                                0.0
1245                            }
1246                        }
1247                        mouse::ScrollDelta::Pixels { y, .. } => -y / 4.0,
1248                    }))
1249                }
1250                _ => None,
1251            },
1252            Event::InputMethod(event) => match event {
1253                input_method::Event::Opened | input_method::Event::Closed => Some(
1254                    Update::InputMethod(Ime::Toggle(matches!(event, input_method::Event::Opened))),
1255                ),
1256                input_method::Event::Preedit(content, selection) if state.focus.is_some() => {
1257                    Some(Update::InputMethod(Ime::Preedit {
1258                        content: content.clone(),
1259                        selection: selection.clone(),
1260                    }))
1261                }
1262                input_method::Event::Commit(content) if state.focus.is_some() => {
1263                    Some(Update::InputMethod(Ime::Commit(content.clone())))
1264                }
1265                _ => None,
1266            },
1267            Event::Keyboard(keyboard::Event::KeyPressed {
1268                key,
1269                modified_key,
1270                physical_key,
1271                modifiers,
1272                text,
1273                ..
1274            }) => {
1275                let status = if state.focus.is_some() {
1276                    Status::Focused {
1277                        is_hovered: cursor.is_over(bounds),
1278                    }
1279                } else {
1280                    Status::Active
1281                };
1282
1283                let key_press = KeyPress {
1284                    key: key.clone(),
1285                    modified_key: modified_key.clone(),
1286                    physical_key: *physical_key,
1287                    modifiers: *modifiers,
1288                    text: text.clone(),
1289                    status,
1290                };
1291
1292                if let Some(key_binding) = key_binding {
1293                    key_binding(key_press)
1294                } else {
1295                    Binding::from_key_press(key_press)
1296                }
1297                .map(Self::Binding)
1298            }
1299            _ => None,
1300        }
1301    }
1302}
1303
1304fn motion(key: key::Named) -> Option<Motion> {
1305    match key {
1306        key::Named::ArrowLeft => Some(Motion::Left),
1307        key::Named::ArrowRight => Some(Motion::Right),
1308        key::Named::ArrowUp => Some(Motion::Up),
1309        key::Named::ArrowDown => Some(Motion::Down),
1310        key::Named::Home => Some(Motion::Home),
1311        key::Named::End => Some(Motion::End),
1312        key::Named::PageUp => Some(Motion::PageUp),
1313        key::Named::PageDown => Some(Motion::PageDown),
1314        _ => None,
1315    }
1316}
1317
1318/// The possible status of a [`TextEditor`].
1319#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1320pub enum Status {
1321    /// The [`TextEditor`] can be interacted with.
1322    Active,
1323    /// The [`TextEditor`] is being hovered.
1324    Hovered,
1325    /// The [`TextEditor`] is focused.
1326    Focused {
1327        /// Whether the [`TextEditor`] is hovered, while focused.
1328        is_hovered: bool,
1329    },
1330    /// The [`TextEditor`] cannot be interacted with.
1331    Disabled,
1332}
1333
1334/// The appearance of a text input.
1335#[derive(Debug, Clone, Copy, PartialEq)]
1336pub struct Style {
1337    /// The [`Background`] of the text input.
1338    pub background: Background,
1339    /// The [`Border`] of the text input.
1340    pub border: Border,
1341    /// The [`Color`] of the placeholder of the text input.
1342    pub placeholder: Color,
1343    /// The [`Color`] of the value of the text input.
1344    pub value: Color,
1345    /// The [`Color`] of the selection of the text input.
1346    pub selection: Color,
1347}
1348
1349/// The theme catalog of a [`TextEditor`].
1350pub trait Catalog: theme::Base {
1351    /// The item class of the [`Catalog`].
1352    type Class<'a>;
1353
1354    /// The default class produced by the [`Catalog`].
1355    fn default<'a>() -> Self::Class<'a>;
1356
1357    /// The [`Style`] of a class with the given status.
1358    fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
1359}
1360
1361/// A styling function for a [`TextEditor`].
1362pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme, Status) -> Style + 'a>;
1363
1364impl Catalog for Theme {
1365    type Class<'a> = StyleFn<'a, Self>;
1366
1367    fn default<'a>() -> Self::Class<'a> {
1368        Box::new(default)
1369    }
1370
1371    fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
1372        class(self, status)
1373    }
1374}
1375
1376/// The default style of a [`TextEditor`].
1377pub fn default(theme: &Theme, status: Status) -> Style {
1378    let palette = theme.extended_palette();
1379
1380    let active = Style {
1381        background: Background::Color(palette.background.base.color),
1382        border: Border {
1383            radius: 2.0.into(),
1384            width: 1.0,
1385            color: palette.background.strong.color,
1386        },
1387        placeholder: palette.secondary.base.color,
1388        value: palette.background.base.text,
1389        selection: palette.primary.weak.color,
1390    };
1391
1392    match status {
1393        Status::Active => active,
1394        Status::Hovered => Style {
1395            border: Border {
1396                color: palette.background.base.text,
1397                ..active.border
1398            },
1399            ..active
1400        },
1401        Status::Focused { .. } => Style {
1402            border: Border {
1403                color: palette.primary.strong.color,
1404                ..active.border
1405            },
1406            ..active
1407        },
1408        Status::Disabled => Style {
1409            background: Background::Color(palette.background.weak.color),
1410            value: active.placeholder,
1411            placeholder: palette.background.strongest.color,
1412            ..active
1413        },
1414    }
1415}
1416
1417#[cfg(target_os = "macos")]
1418pub(crate) fn convert_macos_shortcut(
1419    key: &keyboard::Key,
1420    modifiers: keyboard::Modifiers,
1421) -> Option<keyboard::Key> {
1422    if modifiers != keyboard::Modifiers::CTRL {
1423        return None;
1424    }
1425
1426    let key = match key.as_ref() {
1427        keyboard::Key::Character("b") => key::Named::ArrowLeft,
1428        keyboard::Key::Character("f") => key::Named::ArrowRight,
1429        keyboard::Key::Character("a") => key::Named::Home,
1430        keyboard::Key::Character("e") => key::Named::End,
1431        keyboard::Key::Character("h") => key::Named::Backspace,
1432        keyboard::Key::Character("d") => key::Named::Delete,
1433        _ => return None,
1434    };
1435
1436    Some(keyboard::Key::Named(key))
1437}