1use std::borrow::Cow;
9use std::cell::{Cell, LazyCell};
10
11use crate::ext::ColorExt;
12use crate::theme::THEME;
13
14use super::cursor;
15pub use super::cursor::Cursor;
16use super::editor::Editor;
17use super::style::StyleSheet;
18pub use super::value::Value;
19
20use apply::Apply;
21use iced::Limits;
22use iced::clipboard::dnd::{DndAction, DndEvent, OfferEvent, SourceEvent};
23use iced::clipboard::mime::AsMimeTypes;
24use iced_core::event::Event;
25use iced_core::input_method::{self, InputMethod, Preedit};
26use iced_core::mouse::{self, click};
27use iced_core::overlay::Group;
28use iced_core::renderer::{self, Renderer as CoreRenderer};
29use iced_core::text::{self, Paragraph, Renderer, Text};
30use iced_core::time::{Duration, Instant};
31use iced_core::widget::Id;
32use iced_core::widget::operation::{self, Operation};
33use iced_core::widget::tree::{self, Tree};
34use iced_core::{
35 Background, Border, Clipboard, Color, Element, Layout, Length, Padding, Pixels, Point,
36 Rectangle, Shadow, Shell, Size, Vector, Widget, alignment, keyboard, layout, overlay, touch,
37 window,
38};
39use iced_runtime::{Action, Task, task};
40
41thread_local! {
42 static LAST_FOCUS_UPDATE: LazyCell<Cell<Instant>> = LazyCell::new(|| Cell::new(Instant::now()));
44}
45
46pub fn notify_focus_change() {
49 LAST_FOCUS_UPDATE.with(|x| x.set(Instant::now()));
50}
51
52pub fn text_input<'a, Message>(
56 placeholder: impl Into<Cow<'a, str>>,
57 value: impl Into<Cow<'a, str>>,
58) -> TextInput<'a, Message>
59where
60 Message: Clone + 'static,
61{
62 TextInput::new(placeholder, value)
63}
64
65pub fn editable_input<'a, Message: Clone + 'static>(
67 placeholder: impl Into<Cow<'a, str>>,
68 text: impl Into<Cow<'a, str>>,
69 editing: bool,
70 on_toggle_edit: impl Fn(bool) -> Message + 'a,
71) -> TextInput<'a, Message> {
72 TextInput::new(placeholder, text)
75 .style(crate::theme::TextInput::EditableText)
76 .editable()
77 .editing(editing)
78 .on_toggle_edit(on_toggle_edit)
79 .trailing_icon(
80 crate::widget::icon::from_name("edit-symbolic")
81 .size(16)
82 .apply(crate::widget::container)
83 .padding(8)
84 .into(),
85 )
86}
87
88pub fn search_input<'a, Message>(
92 placeholder: impl Into<Cow<'a, str>>,
93 value: impl Into<Cow<'a, str>>,
94) -> TextInput<'a, Message>
95where
96 Message: Clone + 'static,
97{
98 let spacing = THEME.lock().unwrap().cosmic().space_xxs();
99
100 TextInput::new(placeholder, value)
101 .padding([0, spacing])
102 .style(crate::theme::TextInput::Search)
103 .leading_icon(
104 crate::widget::icon::from_name("system-search-symbolic")
105 .size(16)
106 .apply(crate::widget::container)
107 .padding(8)
108 .into(),
109 )
110}
111pub fn secure_input<'a, Message>(
115 placeholder: impl Into<Cow<'a, str>>,
116 value: impl Into<Cow<'a, str>>,
117 on_visible_toggle: Option<Message>,
118 hidden: bool,
119) -> TextInput<'a, Message>
120where
121 Message: Clone + 'static,
122{
123 let spacing = THEME.lock().unwrap().cosmic().space_xxs();
124 let mut input = TextInput::new(placeholder, value)
125 .padding([0, spacing])
126 .style(crate::theme::TextInput::Default)
127 .leading_icon(
128 crate::widget::icon::from_name("system-lock-screen-symbolic")
129 .size(16)
130 .apply(crate::widget::container)
131 .padding(8)
132 .into(),
133 );
134 if hidden {
135 input = input.password();
136 }
137 if let Some(msg) = on_visible_toggle {
138 input.trailing_icon(
139 crate::widget::icon::from_name(if hidden {
140 "document-properties-symbolic"
141 } else {
142 "image-red-eye-symbolic"
143 })
144 .size(16)
145 .apply(crate::widget::button::custom)
146 .class(crate::theme::Button::Icon)
147 .on_press(msg)
148 .padding(8)
149 .into(),
150 )
151 } else {
152 input
153 }
154}
155
156pub fn inline_input<'a, Message>(
160 placeholder: impl Into<Cow<'a, str>>,
161 value: impl Into<Cow<'a, str>>,
162) -> TextInput<'a, Message>
163where
164 Message: Clone + 'static,
165{
166 let spacing = THEME.lock().unwrap().cosmic().space_xxs();
167
168 TextInput::new(placeholder, value)
169 .style(crate::theme::TextInput::Inline)
170 .padding(spacing)
171}
172
173pub(crate) const SUPPORTED_TEXT_MIME_TYPES: &[&str; 6] = &[
174 "text/plain;charset=utf-8",
175 "text/plain;charset=UTF-8",
176 "UTF8_STRING",
177 "STRING",
178 "text/plain",
179 "TEXT",
180];
181
182#[allow(missing_debug_implementations)]
184#[must_use]
185pub struct TextInput<'a, Message> {
186 id: Id,
187 placeholder: Cow<'a, str>,
188 value: Value,
189 is_secure: bool,
190 is_editable_variant: bool,
191 is_read_only: bool,
192 select_on_focus: bool,
193 double_click_select_delimiter: Option<char>,
194 font: Option<<crate::Renderer as iced_core::text::Renderer>::Font>,
195 width: Length,
196 padding: Padding,
197 size: Option<f32>,
198 helper_size: f32,
199 label: Option<Cow<'a, str>>,
200 helper_text: Option<Cow<'a, str>>,
201 error: Option<Cow<'a, str>>,
202 on_focus: Option<Message>,
203 on_unfocus: Option<Message>,
204 on_input: Option<Box<dyn Fn(String) -> Message + 'a>>,
205 on_paste: Option<Box<dyn Fn(String) -> Message + 'a>>,
206 on_tab: Option<Message>,
207 on_submit: Option<Box<dyn Fn(String) -> Message + 'a>>,
208 on_toggle_edit: Option<Box<dyn Fn(bool) -> Message + 'a>>,
209 leading_icon: Option<Element<'a, Message, crate::Theme, crate::Renderer>>,
210 trailing_icon: Option<Element<'a, Message, crate::Theme, crate::Renderer>>,
211 style: <crate::Theme as StyleSheet>::Style,
212 on_create_dnd_source: Option<Box<dyn Fn(State) -> Message + 'a>>,
213 surface_ids: Option<(window::Id, window::Id)>,
214 dnd_icon: bool,
215 line_height: text::LineHeight,
216 helper_line_height: text::LineHeight,
217 always_active: bool,
218 manage_value: bool,
220 drag_threshold: f32,
221 window_id: window::Id,
222}
223
224impl<'a, Message> TextInput<'a, Message>
225where
226 Message: Clone + 'static,
227{
228 pub fn new(placeholder: impl Into<Cow<'a, str>>, value: impl Into<Cow<'a, str>>) -> Self {
234 let spacing = THEME.lock().unwrap().cosmic().space_xxs();
235
236 let v: Cow<'a, str> = value.into();
237 TextInput {
238 id: Id::unique(),
239 placeholder: placeholder.into(),
240 value: Value::new(v.as_ref()),
241 is_secure: false,
242 is_editable_variant: false,
243 is_read_only: false,
244 select_on_focus: false,
245 double_click_select_delimiter: None,
246 font: None,
247 width: Length::Fill,
248 padding: spacing.into(),
249 size: None,
250 helper_size: 10.0,
251 helper_line_height: text::LineHeight::Absolute(14.0.into()),
252 on_focus: None,
253 on_unfocus: None,
254 on_input: None,
255 on_paste: None,
256 on_submit: None,
257 on_tab: None,
258 on_toggle_edit: None,
259 leading_icon: None,
260 trailing_icon: None,
261 error: None,
262 style: crate::theme::TextInput::default(),
263 on_create_dnd_source: None,
264 surface_ids: None,
265 dnd_icon: false,
266 line_height: text::LineHeight::default(),
267 label: None,
268 helper_text: None,
269 always_active: false,
270 manage_value: false,
271 drag_threshold: 20.0,
272 window_id: crate::widget::text_context_menu::current_window_id(),
273 }
274 }
275
276 #[inline]
277 fn dnd_id(&self) -> u128 {
278 match &self.id.0 {
279 iced_core::id::Internal::Custom(id, _) | iced_core::id::Internal::Unique(id) => {
280 *id as u128
281 }
282 _ => unreachable!(),
283 }
284 }
285
286 #[inline]
289 pub const fn always_active(mut self) -> Self {
290 self.always_active = true;
291 self
292 }
293
294 pub fn label(mut self, label: impl Into<Cow<'a, str>>) -> Self {
296 self.label = Some(label.into());
297 self
298 }
299
300 pub fn helper_text(mut self, helper_text: impl Into<Cow<'a, str>>) -> Self {
302 self.helper_text = Some(helper_text.into());
303 self
304 }
305
306 #[inline]
308 pub fn id(mut self, id: Id) -> Self {
309 self.id = id;
310 self
311 }
312
313 pub fn error(mut self, error: impl Into<Cow<'a, str>>) -> Self {
315 self.error = Some(error.into());
316 self
317 }
318
319 pub fn line_height(mut self, line_height: impl Into<text::LineHeight>) -> Self {
321 self.line_height = line_height.into();
322 self
323 }
324
325 #[inline]
327 pub const fn password(mut self) -> Self {
328 self.is_secure = true;
329 self
330 }
331
332 #[inline]
334 pub(crate) const fn editable(mut self) -> Self {
335 self.is_editable_variant = true;
336 self
337 }
338
339 #[inline]
340 pub const fn editing(mut self, enable: bool) -> Self {
341 self.is_read_only = !enable;
342 self
343 }
344
345 #[inline]
347 pub const fn select_on_focus(mut self, select_on_focus: bool) -> Self {
348 self.select_on_focus = select_on_focus;
349 self
350 }
351
352 #[inline]
358 pub const fn double_click_select_delimiter(mut self, delimiter: char) -> Self {
359 self.double_click_select_delimiter = Some(delimiter);
360 self
361 }
362
363 #[inline]
367 pub fn on_focus(mut self, on_focus: Message) -> Self {
368 self.on_focus = Some(on_focus);
369 self
370 }
371
372 #[inline]
376 pub fn on_unfocus(mut self, on_unfocus: Message) -> Self {
377 self.on_unfocus = Some(on_unfocus);
378 self
379 }
380
381 pub fn on_input(mut self, callback: impl Fn(String) -> Message + 'a) -> Self {
386 self.on_input = Some(Box::new(callback));
387 self
388 }
389
390 pub fn on_submit(mut self, callback: impl Fn(String) -> Message + 'a) -> Self {
392 self.on_submit = Some(Box::new(callback));
393 self
394 }
395
396 pub fn on_submit_maybe(self, callback: Option<impl Fn(String) -> Message + 'a>) -> Self {
398 if let Some(callback) = callback {
399 self.on_submit(callback)
400 } else {
401 self
402 }
403 }
404
405 #[inline]
409 pub fn on_tab(mut self, on_tab: Message) -> Self {
410 self.on_tab = Some(on_tab);
411 self
412 }
413
414 pub fn on_toggle_edit(mut self, callback: impl Fn(bool) -> Message + 'a) -> Self {
416 self.on_toggle_edit = Some(Box::new(callback));
417 self
418 }
419
420 pub fn on_paste(mut self, on_paste: impl Fn(String) -> Message + 'a) -> Self {
423 self.on_paste = Some(Box::new(on_paste));
424 self
425 }
426
427 #[inline]
431 pub const fn font(
432 mut self,
433 font: <crate::Renderer as iced_core::text::Renderer>::Font,
434 ) -> Self {
435 self.font = Some(font);
436 self
437 }
438
439 #[inline]
441 pub fn leading_icon(
442 mut self,
443 icon: Element<'a, Message, crate::Theme, crate::Renderer>,
444 ) -> Self {
445 self.leading_icon = Some(icon);
446 self
447 }
448
449 #[inline]
451 pub fn trailing_icon(
452 mut self,
453 icon: Element<'a, Message, crate::Theme, crate::Renderer>,
454 ) -> Self {
455 self.trailing_icon = Some(icon);
456 self
457 }
458
459 pub fn width(mut self, width: impl Into<Length>) -> Self {
461 self.width = width.into();
462 self
463 }
464
465 pub fn padding(mut self, padding: impl Into<Padding>) -> Self {
467 self.padding = padding.into();
468 self
469 }
470
471 pub fn size(mut self, size: impl Into<Pixels>) -> Self {
473 self.size = Some(size.into().0);
474 self
475 }
476
477 pub fn style(mut self, style: impl Into<<crate::Theme as StyleSheet>::Style>) -> Self {
479 self.style = style.into();
480 self
481 }
482
483 #[inline]
485 pub const fn manage_value(mut self, manage_value: bool) -> Self {
486 self.manage_value = manage_value;
487 self
488 }
489
490 #[allow(clippy::too_many_arguments)]
495 #[inline]
496 pub fn draw(
497 &self,
498 tree: &Tree,
499 renderer: &mut crate::Renderer,
500 theme: &crate::Theme,
501 layout: Layout<'_>,
502 cursor_position: mouse::Cursor,
503 value: Option<&Value>,
504 style: &renderer::Style,
505 ) {
506 let text_layout = self.text_layout(layout);
507 draw(
508 renderer,
509 theme,
510 layout,
511 text_layout,
512 cursor_position,
513 tree,
514 value.unwrap_or(&self.value),
515 &self.placeholder,
516 self.size,
517 self.font,
518 self.on_input.is_none(),
519 self.is_secure,
520 self.leading_icon.as_ref(),
521 self.trailing_icon.as_ref(),
522 &self.style,
523 self.dnd_icon,
524 self.line_height,
525 self.error.as_deref(),
526 self.label.as_deref(),
527 self.helper_text.as_deref(),
528 self.helper_size,
529 self.helper_line_height,
530 &layout.bounds(),
531 style,
532 );
533 }
534
535 #[cfg(wayland_platform)]
537 pub fn on_start_dnd(mut self, on_start_dnd: impl Fn(State) -> Message + 'a) -> Self {
538 self.on_create_dnd_source = Some(Box::new(on_start_dnd));
539 self
540 }
541
542 #[inline]
546 pub const fn surface_ids(mut self, window_id: (window::Id, window::Id)) -> Self {
547 self.surface_ids = Some(window_id);
548 self
549 }
550
551 #[inline]
553 pub const fn dnd_icon(mut self, dnd_icon: bool) -> Self {
554 self.dnd_icon = dnd_icon;
555 self
556 }
557
558 pub fn on_clear(self, on_clear: Message) -> Self {
559 self.trailing_icon(
560 crate::widget::icon::from_name("edit-clear-symbolic")
561 .size(16)
562 .apply(crate::widget::button::custom)
563 .class(crate::theme::Button::Icon)
564 .on_press(on_clear)
565 .padding(8)
566 .into(),
567 )
568 }
569
570 fn text_layout<'b>(&'a self, layout: Layout<'b>) -> Layout<'b> {
572 if self.dnd_icon {
573 layout
574 } else if self.label.is_some() {
575 let mut nodes = layout.children();
576 nodes.next();
577 nodes.next().unwrap()
578 } else {
579 layout.children().next().unwrap()
580 }
581 }
582
583 pub fn drag_threshold(mut self, drag_threshold: f32) -> Self {
585 self.drag_threshold = drag_threshold;
586 self
587 }
588
589 fn uses_popup_context_menu(&self) -> bool {
590 #[cfg(all(wayland_platform, feature = "winit"))]
591 if matches!(
592 crate::app::cosmic::WINDOWING_SYSTEM.get(),
593 Some(crate::app::cosmic::WindowingSystem::Wayland)
594 ) {
595 return true;
596 }
597 false
598 }
599}
600
601impl<Message> Widget<Message, crate::Theme, crate::Renderer> for TextInput<'_, Message>
602where
603 Message: Clone + 'static,
604{
605 #[inline]
606 fn tag(&self) -> tree::Tag {
607 tree::Tag::of::<State>()
608 }
609
610 #[inline]
611 fn state(&self) -> tree::State {
612 tree::State::new(State::new(
613 self.is_secure,
614 self.is_read_only,
615 self.always_active,
616 self.select_on_focus,
617 ))
618 }
619
620 fn diff(&mut self, tree: &mut Tree) {
621 let state = tree.state.downcast_mut::<State>();
622
623 if !self.manage_value || !self.value.is_empty() && state.tracked_value != self.value {
624 state.tracked_value = self.value.clone();
625 } else if self.value.is_empty() {
626 self.value = state.tracked_value.clone();
627 }
629 state.double_click_select_delimiter = self.double_click_select_delimiter;
630 if self.on_input.is_none() && !self.manage_value {
632 state.last_click = None;
633 state.is_focused = state.is_focused.map(|mut f| {
634 f.focused = false;
635 f
636 });
637 state.is_pasting = None;
638 state.dragging_state = None;
639 }
640 let old_value = state
641 .value
642 .raw()
643 .buffer()
644 .lines
645 .iter()
646 .map(|l| l.text())
647 .collect::<String>();
648 if state.is_secure != self.is_secure
649 || old_value != self.value.to_string()
650 || state
651 .label
652 .raw()
653 .buffer()
654 .lines
655 .iter()
656 .map(|l| l.text())
657 .collect::<String>()
658 != self.label.as_deref().unwrap_or_default()
659 || state
660 .helper_text
661 .raw()
662 .buffer()
663 .lines
664 .iter()
665 .map(|l| l.text())
666 .collect::<String>()
667 != self.helper_text.as_deref().unwrap_or_default()
668 {
669 state.is_secure = self.is_secure;
670 state.dirty = true;
671 }
672
673 if self.always_active && !state.is_focused() {
674 let now = Instant::now();
675 LAST_FOCUS_UPDATE.with(|x| x.set(now));
676 state.is_focused = Some(Focus {
677 updated_at: now,
678 now,
679 focused: true,
680 needs_update: false,
681 });
682 }
683
684 let old_value = Value::new(&old_value);
686 if state.is_focused()
687 && let cursor::State::Index(index) = state.cursor.state(&old_value)
688 && index == old_value.len()
689 {
690 state.cursor.move_to(self.value.len());
691 }
692
693 if let Some(f) = state.is_focused.as_ref().filter(|f| f.focused)
694 && f.updated_at != LAST_FOCUS_UPDATE.with(|f| f.get())
695 {
696 state.unfocus();
697 state.emit_unfocus = true;
698 }
699
700 if self.is_editable_variant {
701 if !state.is_focused() {
702 state.is_read_only = self.is_read_only;
704 } else {
705 self.is_read_only = state.is_read_only;
707 }
708
709 let editing = !self.is_read_only;
710 let icon_name = if editing {
711 if self.value.is_empty() {
712 "window-close-symbolic"
713 } else {
714 "edit-clear-symbolic"
715 }
716 } else {
717 "edit-symbolic"
718 };
719
720 self.trailing_icon = Some(
721 crate::widget::icon::from_name(icon_name)
722 .size(16)
723 .apply(crate::widget::container)
724 .padding(8)
725 .into(),
726 );
727 } else {
728 self.is_read_only = state.is_read_only;
729 }
730
731 if !self.manage_value && self.on_input.is_none() {
733 state.is_pasting = None;
734 }
735
736 let mut children: Vec<_> = self
737 .leading_icon
738 .iter_mut()
739 .chain(self.trailing_icon.iter_mut())
740 .map(iced_core::Element::as_widget_mut)
741 .collect();
742 tree.diff_children(children.as_mut_slice());
743 }
744
745 fn children(&self) -> Vec<Tree> {
746 self.leading_icon
747 .iter()
748 .chain(self.trailing_icon.iter())
749 .map(|icon| Tree::new(icon))
750 .collect()
751 }
752
753 #[inline]
754 fn size(&self) -> Size<Length> {
755 Size {
756 width: self.width,
757 height: Length::Shrink,
758 }
759 }
760
761 fn layout(
762 &mut self,
763 tree: &mut Tree,
764 renderer: &crate::Renderer,
765 limits: &layout::Limits,
766 ) -> layout::Node {
767 let font = self.font.unwrap_or_else(|| renderer.default_font());
768 if self.dnd_icon {
769 let state = tree.state.downcast_mut::<State>();
770 let limits = limits.width(Length::Shrink).height(Length::Shrink);
771
772 let size = self.size.unwrap_or_else(|| renderer.default_size().0);
773
774 let bounds = limits.resolve(Length::Shrink, Length::Fill, Size::INFINITE);
775 let value_paragraph = &mut state.value;
776 let v = self.value.to_string();
777 value_paragraph.update(Text {
778 content: if self.value.is_empty() {
779 self.placeholder.as_ref()
780 } else {
781 &v
782 },
783 font,
784 bounds,
785 size: iced::Pixels(size),
786 align_x: text::Alignment::Left,
787 align_y: alignment::Vertical::Center,
788 line_height: text::LineHeight::default(),
789 shaping: text::Shaping::Advanced,
790 wrapping: text::Wrapping::None,
791 ellipsize: text::Ellipsize::None,
792 });
793
794 let Size { width, height } =
795 limits.resolve(Length::Shrink, Length::Shrink, value_paragraph.min_bounds());
796
797 let size = limits.resolve(width, height, Size::new(width, height));
798 layout::Node::with_children(size, vec![layout::Node::new(size)])
799 } else {
800 let res = layout(
801 renderer,
802 limits,
803 self.width,
804 self.padding,
805 self.size,
806 self.leading_icon.as_mut(),
807 self.trailing_icon.as_mut(),
808 self.line_height,
809 self.label.as_deref(),
810 self.helper_text.as_deref(),
811 self.helper_size,
812 self.helper_line_height,
813 font,
814 tree,
815 );
816
817 let size = self.size.unwrap_or_else(|| renderer.default_size().0);
819 let line_height = self.line_height;
820 let state = tree.state.downcast_mut::<State>();
821 if state.dirty {
822 state.dirty = false;
823 let value = if self.is_secure {
824 &self.value.secure()
825 } else {
826 &self.value
827 };
828 replace_paragraph(
829 state,
830 Layout::new(&res),
831 value,
832 font,
833 iced::Pixels(size),
834 line_height,
835 limits,
836 );
837 }
838 res
839 }
840 }
841
842 fn operate(
843 &mut self,
844 tree: &mut Tree,
845 layout: Layout<'_>,
846 _renderer: &crate::Renderer,
847 operation: &mut dyn Operation,
848 ) {
849 operation.container(Some(&self.id), layout.bounds());
850 let state = tree.state.downcast_mut::<State>();
851
852 operation.focusable(Some(&self.id), layout.bounds(), state);
853 operation.text_input(Some(&self.id), layout.bounds(), state);
854 }
855
856 fn overlay<'b>(
857 &'b mut self,
858 tree: &'b mut Tree,
859 layout: Layout<'b>,
860 renderer: &crate::Renderer,
861 viewport: &Rectangle,
862 translation: Vector,
863 ) -> Option<overlay::Element<'b, Message, crate::Theme, crate::Renderer>> {
864 if !self.uses_popup_context_menu() {
865 let has_context_menu = tree
866 .state
867 .downcast_ref::<State>()
868 .context_menu_position
869 .is_some();
870 if has_context_menu {
871 let menu_bar_state = tree.state.downcast_ref::<State>().menu_bar_state.clone();
872 return crate::widget::text_context_menu::context_menu_overlay(
873 self,
874 tree,
875 self.on_input.as_deref(),
876 translation,
877 menu_bar_state,
878 );
879 }
880 }
881
882 let mut layout_ = Vec::with_capacity(2);
883 if self.leading_icon.is_some() {
884 let mut children = self.text_layout(layout).children();
885 children.next();
886 layout_.push(children.next().unwrap());
887 }
888 if self.trailing_icon.is_some() {
889 let mut children = self.text_layout(layout).children();
890 children.next();
891 if self.leading_icon.is_some() {
892 children.next();
893 }
894 layout_.push(children.next().unwrap());
895 };
896 let children: Vec<overlay::Element<'_, Message, crate::Theme, crate::Renderer>> = self
897 .leading_icon
898 .iter_mut()
899 .chain(self.trailing_icon.iter_mut())
900 .zip(&mut tree.children)
901 .zip(layout_)
902 .filter_map(|((child, state), layout)| {
903 child
904 .as_widget_mut()
905 .overlay(state, layout, renderer, viewport, translation)
906 })
907 .collect();
908
909 (!children.is_empty()).then(|| Group::with_children(children).overlay())
910 }
911
912 fn update(
913 &mut self,
914 tree: &mut Tree,
915 event: &Event,
916 layout: Layout<'_>,
917 cursor_position: mouse::Cursor,
918 renderer: &crate::Renderer,
919 clipboard: &mut dyn Clipboard,
920 shell: &mut Shell<'_, Message>,
921 viewport: &Rectangle,
922 ) {
923 #[cfg(all(wayland_platform, feature = "winit"))]
924 if self.uses_popup_context_menu() {
925 let menu_bar_state = tree.state.downcast_ref::<State>().menu_bar_state.clone();
926 crate::widget::text_context_menu::dismiss_popup_on_event(
927 &menu_bar_state,
928 event,
929 self.window_id,
930 );
931 }
932
933 let text_layout = self.text_layout(layout);
934 let mut trailing_icon_layout = None;
935 let font = self.font.unwrap_or_else(|| renderer.default_font());
936 let size = self.size.unwrap_or_else(|| renderer.default_size().0);
937 let line_height = self.line_height;
938
939 if self.is_editable_variant
941 && let Some(ref on_edit) = self.on_toggle_edit
942 {
943 let state = tree.state.downcast_mut::<State>();
944 if !state.is_read_only && state.is_focused.is_some_and(|f| !f.focused) {
945 state.is_read_only = true;
946 shell.publish((on_edit)(false));
947 } else if let Some(f) = state.is_focused.as_mut().filter(|f| f.needs_update) {
948 f.needs_update = false;
950 state.is_read_only = true;
951 shell.publish((on_edit)(f.focused));
952 }
953 }
954
955 if !tree.children.is_empty() {
957 let index = tree.children.len() - 1;
958 if let (Some(trailing_icon), Some(tree)) =
959 (self.trailing_icon.as_mut(), tree.children.get_mut(index))
960 {
961 trailing_icon_layout = Some(text_layout.children().last().unwrap());
962
963 if !self.is_editable_variant
965 && let Some(trailing_layout) = trailing_icon_layout
966 {
967 trailing_icon.as_widget_mut().update(
968 tree,
969 event,
970 trailing_layout,
971 cursor_position,
972 renderer,
973 clipboard,
974 shell,
975 viewport,
976 );
977
978 if shell.is_event_captured() {
979 return;
980 }
981 }
982 }
983 }
984
985 if matches!(
987 event,
988 Event::Mouse(mouse::Event::ButtonPressed(_))
989 | Event::Touch(touch::Event::FingerPressed { .. })
990 ) && cursor_position.position_over(layout.bounds()).is_none()
991 {
992 let state = tree.state.downcast_mut::<State>();
993 state.is_focused = None;
994 state.context_menu_position = None;
995 state.dragging_state = None;
996 if let Some(on_unfocus) = self.on_unfocus.as_ref() {
997 shell.publish(on_unfocus.clone());
998 }
999 return;
1000 }
1001
1002 let state = tree.state.downcast_mut::<State>();
1003
1004 if let Some(on_unfocus) = self.on_unfocus.as_ref()
1005 && state.emit_unfocus
1006 {
1007 state.emit_unfocus = false;
1008 shell.publish(on_unfocus.clone());
1009 }
1010
1011 let dnd_id = self.dnd_id();
1012 let id = Widget::id(self);
1013 update(
1014 id,
1015 event,
1016 text_layout.children().next().unwrap(),
1017 trailing_icon_layout,
1018 cursor_position,
1019 clipboard,
1020 shell,
1021 &mut self.value,
1022 size,
1023 font,
1024 self.is_editable_variant,
1025 self.is_secure,
1026 self.on_focus.as_ref(),
1027 self.on_unfocus.as_ref(),
1028 self.on_input.as_deref(),
1029 self.on_paste.as_deref(),
1030 self.on_submit.as_deref(),
1031 self.on_tab.as_ref(),
1032 self.on_toggle_edit.as_deref(),
1033 || tree.state.downcast_mut::<State>(),
1034 self.on_create_dnd_source.as_deref(),
1035 dnd_id,
1036 line_height,
1037 layout,
1038 self.manage_value,
1039 self.drag_threshold,
1040 self.always_active,
1041 );
1042
1043 #[cfg(all(wayland_platform, feature = "winit"))]
1045 if matches!(
1046 crate::app::cosmic::WINDOWING_SYSTEM.get(),
1047 Some(crate::app::cosmic::WindowingSystem::Wayland)
1048 ) {
1049 let state = tree.state.downcast_ref::<State>();
1050 if let Some(click_position) = state.context_menu_position {
1051 let selected_text = state
1052 .cursor()
1053 .selection(&state.tracked_value)
1054 .map(|(start, end)| state.tracked_value.select(start, end).to_string());
1055 let has_selection = selected_text.is_some();
1056 let has_text = !state.tracked_value.is_empty();
1057 let clipboard_has_text = state.clipboard_has_text;
1058 let menu_bar_state = state.menu_bar_state.clone();
1059 let pending_action = state.pending_action.clone();
1060
1061 crate::widget::text_context_menu::create_text_context_popup(
1062 click_position,
1063 selected_text,
1064 true,
1065 has_selection,
1066 has_text,
1067 clipboard_has_text,
1068 &menu_bar_state,
1069 &pending_action,
1070 renderer,
1071 viewport,
1072 cursor_position,
1073 self.window_id,
1074 );
1075
1076 let state = tree.state.downcast_mut::<State>();
1077 state.context_menu_position = None;
1078 }
1079
1080 let state = tree.state.downcast_ref::<State>();
1082 let pending_action = state.pending_action.clone();
1083 if let Some(action) =
1084 crate::widget::text_context_menu::take_pending_action(&pending_action)
1085 {
1086 let state = tree.state.downcast_mut::<State>();
1087 match action {
1088 crate::widget::text_context_menu::TextCtxAction::Copy => {}
1089 crate::widget::text_context_menu::TextCtxAction::Cut => {
1090 let contents = state.delete_selection();
1091 if let Some(on_input) = self.on_input.as_deref() {
1092 shell.publish((on_input)(contents));
1093 }
1094 }
1095 crate::widget::text_context_menu::TextCtxAction::Paste => {
1096 let content: String = clipboard
1097 .read(iced_core::clipboard::Kind::Standard)
1098 .unwrap_or_default();
1099 let filtered: String =
1100 content.chars().filter(|c| !c.is_control()).collect();
1101 let contents = state.paste_text(&filtered);
1102 if let Some(on_input) = self.on_input.as_deref() {
1103 shell.publish((on_input)(contents));
1104 }
1105 }
1106 crate::widget::text_context_menu::TextCtxAction::SelectAll => {
1107 state.select_all();
1108 }
1109 }
1110 }
1111 }
1112
1113 let state = tree.state.downcast_mut::<State>();
1114 let value = if self.is_secure {
1115 self.value.secure()
1116 } else {
1117 self.value.clone()
1118 };
1119 state.scroll_offset = offset(
1120 text_layout.children().next().unwrap().bounds(),
1121 &value,
1122 state,
1123 );
1124 }
1125
1126 #[inline]
1127 fn draw(
1128 &self,
1129 tree: &Tree,
1130 renderer: &mut crate::Renderer,
1131 theme: &crate::Theme,
1132 style: &renderer::Style,
1133 layout: Layout<'_>,
1134 cursor_position: mouse::Cursor,
1135 viewport: &Rectangle,
1136 ) {
1137 let text_layout = self.text_layout(layout);
1138 draw(
1139 renderer,
1140 theme,
1141 layout,
1142 text_layout,
1143 cursor_position,
1144 tree,
1145 &self.value,
1146 &self.placeholder,
1147 self.size,
1148 self.font,
1149 self.on_input.is_none() && !self.manage_value,
1150 self.is_secure,
1151 self.leading_icon.as_ref(),
1152 self.trailing_icon.as_ref(),
1153 &self.style,
1154 self.dnd_icon,
1155 self.line_height,
1156 self.error.as_deref(),
1157 self.label.as_deref(),
1158 self.helper_text.as_deref(),
1159 self.helper_size,
1160 self.helper_line_height,
1161 viewport,
1162 style,
1163 );
1164 }
1165
1166 fn mouse_interaction(
1167 &self,
1168 state: &Tree,
1169 layout: Layout<'_>,
1170 cursor_position: mouse::Cursor,
1171 viewport: &Rectangle,
1172 renderer: &crate::Renderer,
1173 ) -> mouse::Interaction {
1174 let layout = self.text_layout(layout);
1175 let mut index = 0;
1176 if let (Some(leading_icon), Some(tree)) =
1177 (self.leading_icon.as_ref(), state.children.get(index))
1178 {
1179 let leading_icon_layout = layout.children().nth(1).unwrap();
1180
1181 if cursor_position.is_over(leading_icon_layout.bounds()) {
1182 return leading_icon.as_widget().mouse_interaction(
1183 tree,
1184 layout,
1185 cursor_position,
1186 viewport,
1187 renderer,
1188 );
1189 }
1190 index += 1;
1191 }
1192
1193 if self.trailing_icon.is_some() {
1194 let mut children = layout.children();
1195 children.next();
1196 if self.leading_icon.is_some() {
1198 children.next();
1199 }
1200 let trailing_icon_layout = children.next().unwrap();
1201
1202 if cursor_position.is_over(trailing_icon_layout.bounds()) {
1203 if self.is_editable_variant {
1204 return mouse::Interaction::Pointer;
1205 }
1206
1207 if let Some((trailing_icon, tree)) =
1208 self.trailing_icon.as_ref().zip(state.children.get(index))
1209 {
1210 return trailing_icon.as_widget().mouse_interaction(
1211 tree,
1212 layout,
1213 cursor_position,
1214 viewport,
1215 renderer,
1216 );
1217 }
1218 }
1219 }
1220 let mut children = layout.children();
1221 let layout = children.next().unwrap();
1222 mouse_interaction(
1223 layout,
1224 cursor_position,
1225 self.on_input.is_none() && !self.manage_value,
1226 )
1227 }
1228
1229 #[inline]
1230 fn id(&self) -> Option<Id> {
1231 Some(self.id.clone())
1232 }
1233
1234 #[inline]
1235 fn set_id(&mut self, id: Id) {
1236 self.id = id;
1237 }
1238
1239 fn drag_destinations(
1240 &self,
1241 _state: &Tree,
1242 layout: Layout<'_>,
1243 _renderer: &crate::Renderer,
1244 dnd_rectangles: &mut iced_core::clipboard::DndDestinationRectangles,
1245 ) {
1246 if let Some(input) = layout.children().last() {
1247 let Rectangle {
1248 x,
1249 y,
1250 width,
1251 height,
1252 } = input.bounds();
1253 dnd_rectangles.push(iced::clipboard::dnd::DndDestinationRectangle {
1254 id: self.dnd_id(),
1255 rectangle: iced::clipboard::dnd::Rectangle {
1256 x: x as f64,
1257 y: y as f64,
1258 width: width as f64,
1259 height: height as f64,
1260 },
1261 mime_types: SUPPORTED_TEXT_MIME_TYPES
1262 .iter()
1263 .map(|s| Cow::Borrowed(*s))
1264 .collect(),
1265 actions: DndAction::Move,
1266 preferred: DndAction::Move,
1267 });
1268 }
1269 }
1270}
1271
1272impl<'a, Message> From<TextInput<'a, Message>>
1273 for Element<'a, Message, crate::Theme, crate::Renderer>
1274where
1275 Message: 'static + Clone,
1276{
1277 fn from(
1278 text_input: TextInput<'a, Message>,
1279 ) -> Element<'a, Message, crate::Theme, crate::Renderer> {
1280 Element::new(text_input)
1281 }
1282}
1283
1284pub fn focus<Message: 'static>(id: Id) -> Task<Message> {
1286 task::effect(Action::widget(operation::focusable::focus(id)))
1287}
1288
1289pub fn move_cursor_to_end<Message: 'static>(id: Id) -> Task<Message> {
1292 task::effect(Action::widget(operation::text_input::move_cursor_to_end(
1293 id,
1294 )))
1295}
1296
1297pub fn move_cursor_to_front<Message: 'static>(id: Id) -> Task<Message> {
1300 task::effect(Action::widget(operation::text_input::move_cursor_to_front(
1301 id,
1302 )))
1303}
1304
1305pub fn move_cursor_to<Message: 'static>(id: Id, position: usize) -> Task<Message> {
1308 task::effect(Action::widget(operation::text_input::move_cursor_to(
1309 id, position,
1310 )))
1311}
1312
1313pub fn select_all<Message: 'static>(id: Id) -> Task<Message> {
1315 task::effect(Action::widget(operation::text_input::select_all(id)))
1316}
1317
1318pub fn select_range<Message: 'static>(id: Id, start: usize, end: usize) -> Task<Message> {
1321 task::effect(Action::widget(operation::text_input::select_range(
1322 id, start, end,
1323 )))
1324}
1325
1326pub fn select_until_last<Message: 'static>(id: Id, value: &str, ch: char) -> Task<Message> {
1329 let v = Value::new(value);
1330 let end = v.rfind_char(ch).unwrap_or(v.len());
1331 select_range(id, 0, end)
1332}
1333
1334#[allow(clippy::cast_precision_loss)]
1336#[allow(clippy::too_many_arguments)]
1337#[allow(clippy::too_many_lines)]
1338pub fn layout<Message>(
1339 renderer: &crate::Renderer,
1340 limits: &layout::Limits,
1341 width: Length,
1342 padding: Padding,
1343 size: Option<f32>,
1344 leading_icon: Option<&mut Element<'_, Message, crate::Theme, crate::Renderer>>,
1345 trailing_icon: Option<&mut Element<'_, Message, crate::Theme, crate::Renderer>>,
1346 line_height: text::LineHeight,
1347 label: Option<&str>,
1348 helper_text: Option<&str>,
1349 helper_text_size: f32,
1350 helper_text_line_height: text::LineHeight,
1351 font: iced_core::Font,
1352 tree: &mut Tree,
1353) -> layout::Node {
1354 let limits = limits.width(width);
1355 let spacing = THEME.lock().unwrap().cosmic().space_xxs();
1356 let mut nodes = Vec::with_capacity(3);
1357
1358 let text_pos = if let Some(label) = label {
1359 let text_bounds = limits.resolve(width, Length::Shrink, Size::INFINITE);
1360 let state = tree.state.downcast_mut::<State>();
1361 let label_paragraph = &mut state.label;
1362 label_paragraph.update(Text {
1363 content: label,
1364 font,
1365 bounds: text_bounds,
1366 size: iced::Pixels(size.unwrap_or_else(|| renderer.default_size().0)),
1367 align_x: text::Alignment::Left,
1368 align_y: alignment::Vertical::Center,
1369 line_height,
1370 shaping: text::Shaping::Advanced,
1371 wrapping: text::Wrapping::None,
1372 ellipsize: text::Ellipsize::None,
1373 });
1374 let label_size = label_paragraph.min_bounds();
1375
1376 nodes.push(layout::Node::new(label_size));
1377 Vector::new(0.0, label_size.height + f32::from(spacing))
1378 } else {
1379 Vector::ZERO
1380 };
1381
1382 let text_size = size.unwrap_or_else(|| renderer.default_size().0);
1383 let mut text_input_height = line_height.to_absolute(text_size.into()).0;
1384 let padding = padding.fit(Size::ZERO, limits.max());
1385
1386 let helper_pos = if leading_icon.is_some() || trailing_icon.is_some() {
1387 let children = &mut tree.children;
1388 let limits_copy = limits;
1390
1391 let limits = limits.shrink(padding);
1392 let icon_spacing = 8.0;
1393 let mut c_i = 0;
1394 let (leading_icon_width, mut leading_icon) =
1395 if let Some((icon, tree)) = leading_icon.zip(children.get_mut(c_i)) {
1396 let size = icon.as_widget().size();
1397 let icon_node = icon.as_widget_mut().layout(
1398 tree,
1399 renderer,
1400 &Limits::NONE.width(size.width).height(size.height),
1401 );
1402 text_input_height = text_input_height.max(icon_node.bounds().height);
1403 c_i += 1;
1404 (icon_node.bounds().width + icon_spacing, Some(icon_node))
1405 } else {
1406 (0.0, None)
1407 };
1408
1409 let (trailing_icon_width, mut trailing_icon) =
1410 if let Some((icon, tree)) = trailing_icon.zip(children.get_mut(c_i)) {
1411 let size = icon.as_widget().size();
1412 let icon_node = icon.as_widget_mut().layout(
1413 tree,
1414 renderer,
1415 &Limits::NONE.width(size.width).height(size.height),
1416 );
1417 text_input_height = text_input_height.max(icon_node.bounds().height);
1418 (icon_node.bounds().width + icon_spacing, Some(icon_node))
1419 } else {
1420 (0.0, None)
1421 };
1422 let text_limits = limits
1423 .width(width)
1424 .height(line_height.to_absolute(text_size.into()));
1425 let text_bounds = text_limits.resolve(Length::Shrink, Length::Shrink, Size::INFINITE);
1426 let text_node = layout::Node::new(
1427 text_bounds - Size::new(leading_icon_width + trailing_icon_width, 0.0),
1428 )
1429 .move_to(Point::new(
1430 padding.left + leading_icon_width,
1431 padding.top
1432 + ((text_input_height - line_height.to_absolute(text_size.into()).0) / 2.0)
1433 .max(0.0),
1434 ));
1435 let mut node_list: Vec<_> = Vec::with_capacity(3);
1436
1437 let text_node_bounds = text_node.bounds();
1438 node_list.push(text_node);
1439
1440 if let Some(leading_icon) = leading_icon.take() {
1441 node_list.push(leading_icon.clone().move_to(Point::new(
1442 padding.left,
1443 padding.top + ((text_input_height - leading_icon.bounds().height) / 2.0).max(0.0),
1444 )));
1445 }
1446 if let Some(trailing_icon) = trailing_icon.take() {
1447 let trailing_icon = trailing_icon.clone().move_to(Point::new(
1448 text_node_bounds.x + text_node_bounds.width + f32::from(spacing),
1449 padding.top + ((text_input_height - trailing_icon.bounds().height) / 2.0).max(0.0),
1450 ));
1451 node_list.push(trailing_icon);
1452 }
1453
1454 let text_input_size = Size::new(
1455 text_node_bounds.x + text_node_bounds.width + trailing_icon_width,
1456 text_input_height,
1457 )
1458 .expand(padding);
1459
1460 let input_limits = limits_copy
1461 .width(width)
1462 .height(text_input_height.max(text_input_size.height))
1463 .min_width(text_input_size.width);
1464 let input_bounds = input_limits.resolve(
1465 width,
1466 text_input_height.max(text_input_size.height),
1467 text_input_size,
1468 );
1469 let input_node = layout::Node::with_children(input_bounds, node_list).translate(text_pos);
1470 let y_pos = input_node.bounds().y + input_node.bounds().height + f32::from(spacing);
1471 nodes.push(input_node);
1472
1473 Vector::new(0.0, y_pos)
1474 } else {
1475 let limits = limits
1476 .width(width)
1477 .height(text_input_height + padding.y())
1478 .shrink(padding);
1479 let text_bounds = limits.resolve(Length::Shrink, Length::Shrink, Size::INFINITE);
1480
1481 let text = layout::Node::new(text_bounds).move_to(Point::new(padding.left, padding.top));
1482
1483 let node = layout::Node::with_children(text_bounds.expand(padding), vec![text])
1484 .translate(text_pos);
1485 let y_pos = node.bounds().y + node.bounds().height + f32::from(spacing);
1486
1487 nodes.push(node);
1488
1489 Vector::new(0.0, y_pos)
1490 };
1491
1492 if let Some(helper_text) = helper_text {
1493 let limits = limits
1494 .width(width)
1495 .shrink(padding)
1496 .height(helper_text_line_height.to_absolute(helper_text_size.into()));
1497 let text_bounds = limits.resolve(width, Length::Shrink, Size::INFINITE);
1498 let state = tree.state.downcast_mut::<State>();
1499 let helper_text_paragraph = &mut state.helper_text;
1500 helper_text_paragraph.update(Text {
1501 content: helper_text,
1502 font,
1503 bounds: text_bounds,
1504 size: iced::Pixels(helper_text_size),
1505 align_x: text::Alignment::Left,
1506 align_y: alignment::Vertical::Center,
1507 line_height: helper_text_line_height,
1508 shaping: text::Shaping::Advanced,
1509 wrapping: text::Wrapping::None,
1510 ellipsize: text::Ellipsize::None,
1511 });
1512 let helper_text_size = helper_text_paragraph.min_bounds();
1513 let helper_text_node = layout::Node::new(helper_text_size).translate(helper_pos);
1514 nodes.push(helper_text_node);
1515 };
1516
1517 let mut size = nodes.iter().fold(Size::ZERO, |size, node| {
1518 Size::new(
1519 size.width.max(node.bounds().width),
1520 size.height + node.bounds().height,
1521 )
1522 });
1523 size.height += (nodes.len() - 1) as f32 * f32::from(spacing);
1524
1525 let limits = limits
1526 .width(width)
1527 .height(size.height)
1528 .min_width(size.width);
1529
1530 layout::Node::with_children(limits.resolve(width, size.height, size), nodes)
1531}
1532
1533#[allow(clippy::too_many_arguments)]
1537#[allow(clippy::too_many_lines)]
1538#[allow(clippy::missing_panics_doc)]
1539#[allow(clippy::cast_lossless)]
1540#[allow(clippy::cast_possible_truncation)]
1541pub fn update<'a, Message: Clone + 'static>(
1542 id: Option<Id>,
1543 event: &Event,
1544 text_layout: Layout<'_>,
1545 edit_button_layout: Option<Layout<'_>>,
1546 cursor: mouse::Cursor,
1547 clipboard: &mut dyn Clipboard,
1548 shell: &mut Shell<'_, Message>,
1549 value: &mut Value,
1550 size: f32,
1551 font: <crate::Renderer as iced_core::text::Renderer>::Font,
1552 is_editable_variant: bool,
1553 is_secure: bool,
1554 on_focus: Option<&Message>,
1555 on_unfocus: Option<&Message>,
1556 on_input: Option<&dyn Fn(String) -> Message>,
1557 on_paste: Option<&dyn Fn(String) -> Message>,
1558 on_submit: Option<&dyn Fn(String) -> Message>,
1559 on_tab: Option<&Message>,
1560 on_toggle_edit: Option<&dyn Fn(bool) -> Message>,
1561 state: impl FnOnce() -> &'a mut State,
1562 #[allow(unused_variables)] on_start_dnd_source: Option<&dyn Fn(State) -> Message>,
1563 #[allow(unused_variables)] dnd_id: u128,
1564 line_height: text::LineHeight,
1565 layout: Layout<'_>,
1566 manage_value: bool,
1567 drag_threshold: f32,
1568 always_active: bool,
1569) {
1570 let update_cache = |state, value| {
1571 replace_paragraph(
1572 state,
1573 layout,
1574 value,
1575 font,
1576 iced::Pixels(size),
1577 line_height,
1578 &Limits::NONE.max_width(text_layout.bounds().width),
1579 );
1580 };
1581
1582 let mut secured_value = if is_secure {
1583 value.secure()
1584 } else {
1585 value.clone()
1586 };
1587 let unsecured_value = value;
1588 let value = &mut secured_value;
1589
1590 #[inline]
1594 #[cold]
1595 fn cold() {}
1596
1597 let state = state();
1598
1599 if matches!(
1601 event,
1602 Event::Mouse(mouse::Event::ButtonPressed(_))
1603 | Event::Touch(touch::Event::FingerPressed { .. })
1604 ) && cursor.position_over(layout.bounds()).is_none()
1605 {
1606 state.is_focused = None;
1607 state.context_menu_position = None;
1608 state.dragging_state = None;
1609 if let Some(on_unfocus) = on_unfocus {
1610 shell.publish(on_unfocus.clone());
1611 }
1612 return;
1613 }
1614
1615 match event {
1616 Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Right)) => {
1617 if let Some(pos) = cursor.position_over(layout.bounds()) {
1618 if !state.is_focused() {
1619 state.focus();
1620 }
1621 state.context_menu_position = Some(pos);
1622 state.clipboard_has_text = iced_core::widget::text::clipboard_has_text(clipboard);
1623 shell.capture_event();
1624 }
1625 }
1626
1627 Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
1628 | Event::Touch(touch::Event::FingerPressed { .. }) => {
1629 cold();
1630
1631 if state.context_menu_position.take().is_some() {
1632 shell.capture_event();
1633 return;
1634 }
1635
1636 let click_position = if on_input.is_some() || manage_value {
1637 cursor.position_over(layout.bounds())
1638 } else {
1639 None
1640 };
1641
1642 if let Some(cursor_position) = click_position {
1643 if state.dragging_state.is_none()
1645 && edit_button_layout.is_some_and(|l| cursor.is_over(l.bounds()))
1646 {
1647 if is_editable_variant {
1648 let has_content = !unsecured_value.is_empty();
1649 let is_editing = !state.is_read_only;
1650
1651 if is_editing && has_content {
1652 if let Some(on_input) = on_input {
1653 shell.publish((on_input)(String::new()));
1654 }
1655
1656 if manage_value {
1657 *unsecured_value = Value::new("");
1658 state.tracked_value = unsecured_value.clone();
1659
1660 let cleared_value = if is_secure {
1661 unsecured_value.secure()
1662 } else {
1663 unsecured_value.clone()
1664 };
1665
1666 update_cache(state, &cleared_value);
1667 }
1668
1669 state.move_cursor_to_end();
1670 } else if is_editing {
1671 state.is_read_only = true;
1673 state.unfocus();
1674
1675 if let Some(on_toggle_edit) = on_toggle_edit {
1676 shell.publish(on_toggle_edit(false));
1677 }
1678 } else {
1679 state.is_read_only = false;
1681 state.cursor.select_range(0, value.len());
1682
1683 if let Some(on_toggle_edit) = on_toggle_edit {
1684 shell.publish(on_toggle_edit(true));
1685 }
1686
1687 let now = Instant::now();
1688 LAST_FOCUS_UPDATE.with(|x| x.set(now));
1689 state.is_focused = Some(Focus {
1690 updated_at: now,
1691 now,
1692 focused: true,
1693 needs_update: false,
1694 });
1695 }
1696 }
1697
1698 shell.capture_event();
1699 return;
1700 }
1701
1702 let target = {
1703 let text_bounds = text_layout.bounds();
1704
1705 let alignment_offset = alignment_offset(
1706 text_bounds.width,
1707 state.value.raw().min_width(),
1708 effective_alignment(state.value.raw()),
1709 );
1710
1711 cursor_position.x - text_bounds.x - alignment_offset
1712 };
1713
1714 let click =
1715 mouse::Click::new(cursor_position, mouse::Button::Left, state.last_click);
1716
1717 match (
1718 &state.dragging_state,
1719 click.kind(),
1720 state.cursor().state(value),
1721 ) {
1722 #[cfg(wayland_platform)]
1723 (None, click::Kind::Single, cursor::State::Selection { start, end }) => {
1724 let left = start.min(end);
1725 let right = end.max(start);
1726
1727 let (left_position, _left_offset) = measure_cursor_and_scroll_offset(
1728 state.value.raw(),
1729 text_layout.bounds(),
1730 left,
1731 value,
1732 state.cursor.affinity(),
1733 state.scroll_offset,
1734 );
1735
1736 let (right_position, _right_offset) = measure_cursor_and_scroll_offset(
1737 state.value.raw(),
1738 text_layout.bounds(),
1739 right,
1740 value,
1741 state.cursor.affinity(),
1742 state.scroll_offset,
1743 );
1744
1745 let selection_start = left_position.min(right_position);
1746 let width = (right_position - left_position).abs();
1747 let alignment_offset = alignment_offset(
1748 text_layout.bounds().width,
1749 state.value.raw().min_width(),
1750 effective_alignment(state.value.raw()),
1751 );
1752 let selection_bounds = Rectangle {
1753 x: text_layout.bounds().x + alignment_offset + selection_start
1754 - state.scroll_offset,
1755 y: text_layout.bounds().y,
1756 width,
1757 height: text_layout.bounds().height,
1758 };
1759
1760 if cursor.is_over(selection_bounds) && (on_input.is_some() || manage_value)
1761 {
1762 state.dragging_state = Some(DraggingState::PrepareDnd(cursor_position));
1763 shell.capture_event();
1764 return;
1765 }
1766 update_cache(state, value);
1768 state.setting_selection(value, text_layout.bounds(), target);
1769 state.dragging_state = None;
1770 shell.capture_event();
1771 return;
1772 }
1773 (None, click::Kind::Single, _) => {
1774 state.setting_selection(value, text_layout.bounds(), target);
1775 }
1776 (None | Some(DraggingState::Selection), click::Kind::Double, _) => {
1777 update_cache(state, value);
1778
1779 if is_secure {
1780 state.cursor.select_all(value);
1781 } else {
1782 let (position, affinity) =
1783 find_cursor_position(text_layout.bounds(), value, state, target)
1784 .unwrap_or((0, text::Affinity::Before));
1785
1786 state.cursor.set_affinity(affinity);
1787
1788 if let Some(delimiter) = state.double_click_select_delimiter {
1789 if let Some(delim_pos) = value.rfind_char(delimiter) {
1790 if position <= delim_pos {
1791 state.cursor.select_range(0, delim_pos);
1792 } else {
1793 state.cursor.select_range(delim_pos + 1, value.len());
1794 }
1795 } else {
1796 state.cursor.select_all(value);
1797 }
1798 } else {
1799 state.cursor.select_range(
1800 value.previous_start_of_word(position),
1801 value.next_end_of_word(position),
1802 );
1803 }
1804 }
1805 state.dragging_state = Some(DraggingState::Selection);
1806 }
1807 (None | Some(DraggingState::Selection), click::Kind::Triple, _) => {
1808 update_cache(state, value);
1809 state.cursor.select_all(value);
1810 state.dragging_state = Some(DraggingState::Selection);
1811 }
1812 _ => {
1813 state.dragging_state = None;
1814 }
1815 }
1816
1817 if matches!(state.dragging_state, None | Some(DraggingState::Selection))
1819 && (!state.is_focused() || (is_editable_variant && state.is_read_only))
1820 {
1821 if !state.is_focused()
1822 && let Some(on_focus) = on_focus
1823 {
1824 shell.publish(on_focus.clone());
1825 }
1826
1827 if state.is_read_only {
1828 state.is_read_only = false;
1829 state.cursor.select_range(0, value.len());
1830 if let Some(on_toggle_edit) = on_toggle_edit {
1831 let message = (on_toggle_edit)(true);
1832 shell.publish(message);
1833 }
1834 }
1835
1836 let now = Instant::now();
1837 LAST_FOCUS_UPDATE.with(|x| x.set(now));
1838
1839 state.is_focused = Some(Focus {
1840 updated_at: now,
1841 now,
1842 focused: true,
1843 needs_update: false,
1844 });
1845 }
1846
1847 state.last_click = Some(click);
1848
1849 shell.request_redraw();
1850 shell.capture_event();
1851 } else {
1852 state.unfocus();
1853
1854 if let Some(on_unfocus) = on_unfocus {
1855 shell.publish(on_unfocus.clone());
1856 }
1857 }
1858 }
1859 Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
1860 | Event::Touch(touch::Event::FingerLifted { .. } | touch::Event::FingerLost { .. }) => {
1861 cold();
1862 #[cfg(wayland_platform)]
1863 if matches!(state.dragging_state, Some(DraggingState::PrepareDnd(_))) {
1864 update_cache(state, value);
1866 if let Some(position) = cursor.position_over(layout.bounds()) {
1867 let target = {
1868 let text_bounds = text_layout.bounds();
1869
1870 let alignment_offset = alignment_offset(
1871 text_bounds.width,
1872 state.value.raw().min_width(),
1873 effective_alignment(state.value.raw()),
1874 );
1875
1876 position.x - text_bounds.x - alignment_offset
1877 };
1878 state.setting_selection(value, text_layout.bounds(), target);
1879 }
1880 }
1881 state.dragging_state = None;
1882 if cursor.is_over(layout.bounds()) {
1883 shell.capture_event();
1884 }
1885 }
1886 Event::Mouse(mouse::Event::CursorMoved { position })
1887 | Event::Touch(touch::Event::FingerMoved { position, .. }) => {
1888 if matches!(state.dragging_state, Some(DraggingState::Selection)) {
1889 let target = {
1890 let text_bounds = text_layout.bounds();
1891
1892 let alignment_offset = alignment_offset(
1893 text_bounds.width,
1894 state.value.raw().min_width(),
1895 effective_alignment(state.value.raw()),
1896 );
1897
1898 position.x - text_bounds.x - alignment_offset
1899 };
1900
1901 update_cache(state, value);
1902 let (position, affinity) =
1903 find_cursor_position(text_layout.bounds(), value, state, target)
1904 .unwrap_or((0, text::Affinity::Before));
1905
1906 state.cursor.set_affinity(affinity);
1907 state
1908 .cursor
1909 .select_range(state.cursor.start(value), position);
1910
1911 shell.request_redraw();
1912 shell.capture_event();
1913 return;
1914 }
1915 #[cfg(wayland_platform)]
1916 if let Some(DraggingState::PrepareDnd(start_position)) = state.dragging_state {
1917 let distance = ((position.x - start_position.x).powi(2)
1918 + (position.y - start_position.y).powi(2))
1919 .sqrt();
1920
1921 if distance >= drag_threshold {
1922 if is_secure {
1923 return;
1924 }
1925
1926 let input_text = state.selected_text(&value.to_string()).unwrap_or_default();
1927 state.dragging_state =
1928 Some(DraggingState::Dnd(DndAction::empty(), input_text.clone()));
1929 let mut editor = Editor::new(unsecured_value, &mut state.cursor);
1930 editor.delete();
1931
1932 let contents = editor.contents();
1933 let unsecured_value = Value::new(&contents);
1934 state.tracked_value = unsecured_value.clone();
1935 if let Some(on_input) = on_input {
1936 let message = (on_input)(contents);
1937 shell.publish(message);
1938 }
1939 if let Some(on_start_dnd) = on_start_dnd_source {
1940 shell.publish(on_start_dnd(state.clone()));
1941 }
1942 let state_clone = state.clone();
1943
1944 iced_core::clipboard::start_dnd(
1945 clipboard,
1946 false,
1947 id.map(iced_core::clipboard::DndSource::Widget),
1948 Some(iced_core::clipboard::IconSurface::new(
1949 Element::from(
1950 TextInput::<'static, ()>::new("", input_text.clone())
1951 .dnd_icon(true),
1952 ),
1953 iced_core::widget::tree::State::new(state_clone),
1954 Vector::ZERO,
1955 )),
1956 Box::new(TextInputString(input_text)),
1957 DndAction::Move,
1958 );
1959
1960 update_cache(state, &unsecured_value);
1961 } else {
1962 state.dragging_state = Some(DraggingState::PrepareDnd(start_position));
1963 }
1964
1965 shell.capture_event();
1966 }
1967 }
1968 Event::Keyboard(keyboard::Event::KeyPressed {
1969 key,
1970 text,
1971 physical_key,
1972 modifiers,
1973 ..
1974 }) => {
1975 state.keyboard_modifiers = *modifiers;
1976
1977 if let Some(focus) = state.is_focused.as_mut().filter(|f| f.focused) {
1978 if state.is_read_only || (!manage_value && on_input.is_none()) {
1979 return;
1980 };
1981 let modifiers = state.keyboard_modifiers;
1982 focus.updated_at = Instant::now();
1983 LAST_FOCUS_UPDATE.with(|x| x.set(focus.updated_at));
1984
1985 let clip_key = match key.as_ref() {
1987 keyboard::Key::Named(keyboard::key::Named::Insert) if modifiers.shift() => {
1988 Some('v')
1989 }
1990 keyboard::Key::Named(keyboard::key::Named::Insert) if modifiers.command() => {
1991 Some('c')
1992 }
1993 keyboard::Key::Named(keyboard::key::Named::Delete) if modifiers.shift() => {
1994 Some('x')
1995 }
1996 _ if modifiers.command() => key.to_latin(*physical_key),
1997 _ => None,
1998 };
1999 {
2000 match clip_key {
2001 Some('c') => {
2002 if !is_secure && let Some((start, end)) = state.cursor.selection(value)
2003 {
2004 clipboard.write(
2005 iced_core::clipboard::Kind::Standard,
2006 value.select(start, end).to_string(),
2007 );
2008 }
2009 }
2010 Some('x') => {
2013 if !is_secure {
2014 if let Some((start, end)) = state.cursor.selection(value) {
2015 clipboard.write(
2016 iced_core::clipboard::Kind::Standard,
2017 value.select(start, end).to_string(),
2018 );
2019 }
2020
2021 let mut editor = Editor::new(value, &mut state.cursor);
2022 editor.delete();
2023 let content = editor.contents();
2024 state.tracked_value = Value::new(&content);
2025 if let Some(on_input) = on_input {
2026 let message = (on_input)(content);
2027 shell.publish(message);
2028 }
2029 }
2030 }
2031 Some('v') => {
2032 let content = if let Some(content) = state.is_pasting.take() {
2033 content
2034 } else {
2035 let content: String = clipboard
2036 .read(iced_core::clipboard::Kind::Standard)
2037 .unwrap_or_default()
2038 .chars()
2039 .filter(|c| !c.is_control())
2040 .collect();
2041
2042 Value::new(&content)
2043 };
2044
2045 let mut editor = Editor::new(unsecured_value, &mut state.cursor);
2046
2047 editor.paste(content.clone());
2048
2049 let contents = editor.contents();
2050 let unsecured_value = Value::new(&contents);
2051 state.tracked_value = unsecured_value.clone();
2052
2053 if let Some(on_input) = on_input {
2054 let message = if let Some(paste) = &on_paste {
2055 (paste)(contents)
2056 } else {
2057 (on_input)(contents)
2058 };
2059
2060 shell.publish(message);
2061 }
2062
2063 state.is_pasting = Some(content);
2064
2065 let value = if is_secure {
2066 unsecured_value.secure()
2067 } else {
2068 unsecured_value
2069 };
2070
2071 update_cache(state, &value);
2072 shell.capture_event();
2073 return;
2074 }
2075
2076 Some('a') => {
2077 state.cursor.select_all(value);
2078 shell.capture_event();
2079 return;
2080 }
2081
2082 _ => {}
2083 }
2084 }
2085
2086 if let Some(c) = text
2088 .as_ref()
2089 .and_then(|t| t.chars().next().filter(|c| !c.is_control()))
2090 {
2091 if state.is_read_only || (!manage_value && on_input.is_none()) {
2092 return;
2093 };
2094
2095 state.is_pasting = None;
2096
2097 if !state.keyboard_modifiers.command() && !modifiers.control() {
2098 let mut editor = Editor::new(unsecured_value, &mut state.cursor);
2099
2100 editor.insert(c);
2101
2102 let contents = editor.contents();
2103 let unsecured_value = Value::new(&contents);
2104 state.tracked_value = unsecured_value.clone();
2105
2106 if let Some(on_input) = on_input {
2107 let message = (on_input)(contents);
2108 shell.publish(message);
2109 }
2110
2111 focus.updated_at = Instant::now();
2112 LAST_FOCUS_UPDATE.with(|x| x.set(focus.updated_at));
2113
2114 let value = if is_secure {
2115 unsecured_value.secure()
2116 } else {
2117 unsecured_value
2118 };
2119
2120 update_cache(state, &value);
2121
2122 shell.capture_event();
2123 return;
2124 }
2125 }
2126
2127 match key.as_ref() {
2128 keyboard::Key::Named(keyboard::key::Named::Enter) => {
2129 if let Some(on_submit) = on_submit {
2130 shell.publish((on_submit)(unsecured_value.to_string()));
2131 }
2132 }
2133 keyboard::Key::Named(keyboard::key::Named::Backspace) => {
2134 if platform::is_jump_modifier_pressed(modifiers)
2135 && state.cursor.selection(value).is_none()
2136 {
2137 if is_secure {
2138 let cursor_pos = state.cursor.end(value);
2139 state.cursor.select_range(0, cursor_pos);
2140 } else {
2141 state.cursor.select_left_by_words(value);
2142 }
2143 }
2144
2145 let mut editor = Editor::new(unsecured_value, &mut state.cursor);
2146 editor.backspace();
2147
2148 let contents = editor.contents();
2149 let unsecured_value = Value::new(&contents);
2150 state.tracked_value = unsecured_value.clone();
2151 if let Some(on_input) = on_input {
2152 let message = (on_input)(editor.contents());
2153 shell.publish(message);
2154 }
2155 let value = if is_secure {
2156 unsecured_value.secure()
2157 } else {
2158 unsecured_value
2159 };
2160 update_cache(state, &value);
2161 }
2162 keyboard::Key::Named(keyboard::key::Named::Delete) => {
2163 if platform::is_jump_modifier_pressed(modifiers)
2164 && state.cursor.selection(value).is_none()
2165 {
2166 if is_secure {
2167 let cursor_pos = state.cursor.end(unsecured_value);
2168 state.cursor.select_range(cursor_pos, unsecured_value.len());
2169 } else {
2170 state.cursor.select_right_by_words(unsecured_value);
2171 }
2172 }
2173
2174 let mut editor = Editor::new(unsecured_value, &mut state.cursor);
2175 editor.delete();
2176 let contents = editor.contents();
2177 let unsecured_value = Value::new(&contents);
2178 if let Some(on_input) = on_input {
2179 let message = (on_input)(contents);
2180 state.tracked_value = unsecured_value.clone();
2181 shell.publish(message);
2182 }
2183
2184 let value = if is_secure {
2185 unsecured_value.secure()
2186 } else {
2187 unsecured_value
2188 };
2189
2190 update_cache(state, &value);
2191 }
2192 keyboard::Key::Named(keyboard::key::Named::ArrowLeft) => {
2193 let rtl = state.value.raw().is_rtl(0).unwrap_or(false);
2194 let by_words = platform::is_jump_modifier_pressed(modifiers) && !is_secure;
2195
2196 if modifiers.shift() {
2197 state.cursor.select_visual(false, by_words, rtl, value);
2198 } else {
2199 state.cursor.move_visual(false, by_words, rtl, value);
2200 }
2201 }
2202 keyboard::Key::Named(keyboard::key::Named::ArrowRight) => {
2203 let rtl = state.value.raw().is_rtl(0).unwrap_or(false);
2204 let by_words = platform::is_jump_modifier_pressed(modifiers) && !is_secure;
2205
2206 if modifiers.shift() {
2207 state.cursor.select_visual(true, by_words, rtl, value);
2208 } else {
2209 state.cursor.move_visual(true, by_words, rtl, value);
2210 }
2211 }
2212 keyboard::Key::Named(keyboard::key::Named::Home) => {
2213 if modifiers.shift() {
2214 state.cursor.select_range(state.cursor.start(value), 0);
2215 } else {
2216 state.cursor.move_to(0);
2217 }
2218 }
2219 keyboard::Key::Named(keyboard::key::Named::End) => {
2220 if modifiers.shift() {
2221 state
2222 .cursor
2223 .select_range(state.cursor.start(value), value.len());
2224 } else {
2225 state.cursor.move_to(value.len());
2226 }
2227 }
2228 keyboard::Key::Named(keyboard::key::Named::Escape) => {
2229 state.unfocus();
2230 state.is_read_only = true;
2231
2232 if let Some(on_unfocus) = on_unfocus {
2233 shell.publish(on_unfocus.clone());
2234 }
2235
2236 shell.request_redraw();
2237 return;
2238 }
2239
2240 keyboard::Key::Named(keyboard::key::Named::Tab) => {
2241 if let Some(on_tab) = on_tab {
2242 shell.publish(on_tab.clone());
2246 } else {
2247 state.is_read_only = true;
2248
2249 if let Some(on_unfocus) = on_unfocus {
2250 shell.publish(on_unfocus.clone());
2251 }
2252
2253 return;
2254 };
2255 }
2256
2257 keyboard::Key::Named(
2258 keyboard::key::Named::ArrowUp | keyboard::key::Named::ArrowDown,
2259 ) => {
2260 return;
2261 }
2262 _ => {}
2263 }
2264
2265 shell.request_redraw();
2266 shell.capture_event();
2267 }
2268 }
2269 Event::Keyboard(keyboard::Event::KeyReleased { key, .. }) => {
2270 if state.is_focused() {
2271 match key {
2272 keyboard::Key::Character(c) if "v" == c => {
2273 state.is_pasting = None;
2274 }
2275 keyboard::Key::Named(keyboard::key::Named::Insert) => {
2276 state.is_pasting = None;
2277 }
2278 keyboard::Key::Named(keyboard::key::Named::Tab)
2279 | keyboard::Key::Named(keyboard::key::Named::ArrowUp)
2280 | keyboard::Key::Named(keyboard::key::Named::ArrowDown) => {
2281 return;
2282 }
2283 _ => {}
2284 }
2285
2286 shell.capture_event();
2287 }
2288 }
2289 Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) => {
2290 state.keyboard_modifiers = *modifiers;
2291 }
2292 Event::InputMethod(event) => match event {
2293 input_method::Event::Opened | input_method::Event::Closed => {
2294 state.preedit =
2295 matches!(event, input_method::Event::Opened).then(input_method::Preedit::new);
2296 shell.capture_event();
2297 }
2298 input_method::Event::Preedit(content, selection) => {
2299 if state.is_focused() {
2300 state.preedit = Some(input_method::Preedit {
2301 content: content.to_owned(),
2302 selection: selection.clone(),
2303 text_size: Some(size.into()),
2304 });
2305 shell.capture_event();
2306 }
2307 }
2308 input_method::Event::Commit(text) => {
2309 let Some(focus) = state.is_focused.as_mut().filter(|f| f.focused) else {
2310 return;
2311 };
2312 let Some(on_input) = on_input else {
2313 return;
2314 };
2315 if state.is_read_only {
2316 return;
2317 }
2318
2319 focus.updated_at = Instant::now();
2320 LAST_FOCUS_UPDATE.with(|x| x.set(focus.updated_at));
2321
2322 let mut editor = Editor::new(unsecured_value, &mut state.cursor);
2323 editor.paste(Value::new(text));
2324
2325 let contents = editor.contents();
2326 let unsecured_value = Value::new(&contents);
2327 let message = if let Some(paste) = &on_paste {
2328 (paste)(contents)
2329 } else {
2330 (on_input)(contents)
2331 };
2332 shell.publish(message);
2333
2334 state.is_pasting = None;
2335 let value = if is_secure {
2336 unsecured_value.secure()
2337 } else {
2338 unsecured_value
2339 };
2340
2341 update_cache(state, &value);
2342 shell.capture_event();
2343 }
2344 },
2345 Event::Window(window::Event::RedrawRequested(now)) => {
2346 if let Some(focus) = state.is_focused.as_mut().filter(|f| f.focused) {
2347 focus.now = *now;
2348
2349 let millis_until_redraw = CURSOR_BLINK_INTERVAL_MILLIS
2350 - (*now - focus.updated_at).as_millis() % CURSOR_BLINK_INTERVAL_MILLIS;
2351 shell.request_redraw_at(window::RedrawRequest::At(
2352 now.checked_add(Duration::from_millis(millis_until_redraw as u64))
2353 .unwrap_or(*now),
2354 ));
2355
2356 shell.request_input_method(&input_method(state, text_layout, unsecured_value));
2357 } else if always_active {
2358 shell.request_redraw();
2359 }
2360 }
2361 #[cfg(wayland_platform)]
2362 Event::Dnd(DndEvent::Source(SourceEvent::Finished | SourceEvent::Cancelled)) => {
2363 cold();
2364 if matches!(state.dragging_state, Some(DraggingState::Dnd(..))) {
2365 state.dragging_state = None;
2367 shell.capture_event();
2368 }
2369 }
2370 #[cfg(wayland_platform)]
2371 Event::Dnd(DndEvent::Offer(
2372 rectangle,
2373 OfferEvent::Enter {
2374 x,
2375 y,
2376 mime_types,
2377 surface,
2378 },
2379 )) if *rectangle == Some(dnd_id) => {
2380 cold();
2381 let _is_clicked = text_layout.bounds().contains(Point {
2382 x: *x as f32,
2383 y: *y as f32,
2384 });
2385
2386 let mut accepted = false;
2387 for m in mime_types {
2388 if SUPPORTED_TEXT_MIME_TYPES.contains(&m.as_str()) {
2389 let _clone = m.clone();
2390 accepted = true;
2391 }
2392 }
2393 if accepted {
2394 let target = {
2395 let text_bounds = text_layout.bounds();
2396
2397 let alignment_offset = alignment_offset(
2398 text_bounds.width,
2399 state.value.raw().min_width(),
2400 effective_alignment(state.value.raw()),
2401 );
2402
2403 *x as f32 - text_bounds.x - alignment_offset
2404 };
2405 state.dnd_offer =
2406 DndOfferState::HandlingOffer(mime_types.clone(), DndAction::empty());
2407 update_cache(state, value);
2409 let (position, affinity) =
2410 find_cursor_position(text_layout.bounds(), value, state, target)
2411 .unwrap_or((0, text::Affinity::Before));
2412
2413 state.cursor.set_affinity(affinity);
2414 state.cursor.move_to(position);
2415 shell.capture_event();
2416 }
2417 }
2418 #[cfg(wayland_platform)]
2419 Event::Dnd(DndEvent::Offer(rectangle, OfferEvent::Motion { x, y }))
2420 if *rectangle == Some(dnd_id) =>
2421 {
2422 let target = {
2423 let text_bounds = text_layout.bounds();
2424
2425 let alignment_offset = alignment_offset(
2426 text_bounds.width,
2427 state.value.raw().min_width(),
2428 effective_alignment(state.value.raw()),
2429 );
2430
2431 *x as f32 - text_bounds.x - alignment_offset
2432 };
2433 update_cache(state, value);
2435 let (position, affinity) =
2436 find_cursor_position(text_layout.bounds(), value, state, target)
2437 .unwrap_or((0, text::Affinity::Before));
2438
2439 state.cursor.set_affinity(affinity);
2440 state.cursor.move_to(position);
2441 shell.capture_event();
2442 }
2443 #[cfg(wayland_platform)]
2444 Event::Dnd(DndEvent::Offer(rectangle, OfferEvent::Drop)) if *rectangle == Some(dnd_id) => {
2445 cold();
2446 if let DndOfferState::HandlingOffer(mime_types, _action) = state.dnd_offer.clone() {
2447 let Some(_mime_type) = SUPPORTED_TEXT_MIME_TYPES
2448 .iter()
2449 .find(|&&m| mime_types.iter().any(|t| t == m))
2450 else {
2451 state.dnd_offer = DndOfferState::None;
2452 shell.capture_event();
2453 return;
2454 };
2455 state.dnd_offer = DndOfferState::Dropped;
2456 }
2457 }
2458 #[cfg(wayland_platform)]
2459 Event::Dnd(DndEvent::Offer(id, OfferEvent::LeaveDestination)) if Some(dnd_id) != *id => {}
2460 #[cfg(wayland_platform)]
2461 Event::Dnd(DndEvent::Offer(
2462 _rectangle,
2463 OfferEvent::Leave | OfferEvent::LeaveDestination,
2464 )) => {
2465 cold();
2466 match state.dnd_offer {
2469 DndOfferState::Dropped => {}
2470 _ => {
2471 state.dnd_offer = DndOfferState::None;
2472 }
2473 };
2474 shell.capture_event();
2475 }
2476 #[cfg(wayland_platform)]
2477 Event::Dnd(DndEvent::Offer(rectangle, OfferEvent::Data { data, mime_type }))
2478 if *rectangle == Some(dnd_id) =>
2479 {
2480 cold();
2481 if matches!(&state.dnd_offer, DndOfferState::Dropped) {
2482 state.dnd_offer = DndOfferState::None;
2483 if !SUPPORTED_TEXT_MIME_TYPES.contains(&mime_type.as_str()) || data.is_empty() {
2484 shell.capture_event();
2485 return;
2486 }
2487 let Ok(content) = String::from_utf8(data.clone()) else {
2488 shell.capture_event();
2489 return;
2490 };
2491
2492 let mut editor = Editor::new(unsecured_value, &mut state.cursor);
2493
2494 editor.paste(Value::new(content.as_str()));
2495 let contents = editor.contents();
2496 let unsecured_value = Value::new(&contents);
2497 state.tracked_value = unsecured_value.clone();
2498 if let Some(on_paste) = on_paste.as_ref() {
2499 let message = (on_paste)(contents);
2500 shell.publish(message);
2501 }
2502
2503 let value = if is_secure {
2504 unsecured_value.secure()
2505 } else {
2506 unsecured_value
2507 };
2508 update_cache(state, &value);
2509 shell.capture_event();
2510 }
2511 }
2512 _ => {}
2513 }
2514}
2515
2516fn input_method<'b>(
2517 state: &'b State,
2518 text_layout: Layout<'_>,
2519 value: &Value,
2520) -> InputMethod<&'b str> {
2521 if !state.is_focused() {
2522 return InputMethod::Disabled;
2523 };
2524
2525 let text_bounds = text_layout.bounds();
2526 let cursor_index = match state.cursor.state(value) {
2527 cursor::State::Index(position) => position,
2528 cursor::State::Selection { start, end } => start.min(end),
2529 };
2530 let (cursor, offset) = measure_cursor_and_scroll_offset(
2531 state.value.raw(),
2532 text_bounds,
2533 cursor_index,
2534 value,
2535 state.cursor.affinity(),
2536 state.scroll_offset,
2537 );
2538 InputMethod::Enabled {
2539 cursor: Rectangle::new(
2540 Point::new(text_bounds.x + cursor - offset, text_bounds.y),
2541 Size::new(1.0, text_bounds.height),
2542 ),
2543 purpose: if state.is_secure {
2544 input_method::Purpose::Secure
2545 } else {
2546 input_method::Purpose::Normal
2547 },
2548 preedit: state.preedit.as_ref().map(input_method::Preedit::as_ref),
2549 }
2550}
2551
2552#[allow(clippy::too_many_arguments)]
2557#[allow(clippy::too_many_lines)]
2558#[allow(clippy::missing_panics_doc)]
2559pub fn draw<'a, Message>(
2560 renderer: &mut crate::Renderer,
2561 theme: &crate::Theme,
2562 layout: Layout<'_>,
2563 text_layout: Layout<'_>,
2564 cursor_position: mouse::Cursor,
2565 tree: &Tree,
2566 value: &Value,
2567 placeholder: &str,
2568 size: Option<f32>,
2569 font: Option<<crate::Renderer as iced_core::text::Renderer>::Font>,
2570 is_disabled: bool,
2571 is_secure: bool,
2572 icon: Option<&Element<'a, Message, crate::Theme, crate::Renderer>>,
2573 trailing_icon: Option<&Element<'a, Message, crate::Theme, crate::Renderer>>,
2574 style: &<crate::Theme as StyleSheet>::Style,
2575 dnd_icon: bool,
2576 line_height: text::LineHeight,
2577 error: Option<&str>,
2578 label: Option<&str>,
2579 helper_text: Option<&str>,
2580 helper_text_size: f32,
2581 helper_line_height: text::LineHeight,
2582 viewport: &Rectangle,
2583 renderer_style: &renderer::Style,
2584) {
2585 let children = &tree.children;
2587
2588 let state = tree.state.downcast_ref::<State>();
2589 let secure_value = is_secure.then(|| value.secure());
2590 let value = secure_value.as_ref().unwrap_or(value);
2591
2592 let mut children_layout = layout.children();
2593
2594 let (label_layout, layout, helper_text_layout) = if label.is_some() && helper_text.is_some() {
2595 let label_layout = children_layout.next();
2596 let layout = children_layout.next().unwrap();
2597 let helper_text_layout = children_layout.next();
2598 (label_layout, layout, helper_text_layout)
2599 } else if label.is_some() {
2600 let label_layout = children_layout.next();
2601 let layout = children_layout.next().unwrap();
2602 (label_layout, layout, None)
2603 } else if helper_text.is_some() {
2604 let layout = children_layout.next().unwrap();
2605 let helper_text_layout = children_layout.next();
2606 (None, layout, helper_text_layout)
2607 } else {
2608 let layout = children_layout.next().unwrap();
2609
2610 (None, layout, None)
2611 };
2612
2613 let mut children_layout = layout.children();
2614 let bounds = layout.bounds();
2615 let text_bounds = children_layout.next().unwrap_or(text_layout).bounds();
2617
2618 let is_mouse_over = cursor_position.is_over(bounds);
2619
2620 let appearance = if is_disabled {
2621 theme.disabled(style)
2622 } else if error.is_some() {
2623 theme.error(style)
2624 } else if state.is_focused() {
2625 theme.focused(style)
2626 } else if is_mouse_over {
2627 theme.hovered(style)
2628 } else {
2629 theme.active(style)
2630 };
2631
2632 let mut icon_color = appearance.icon_color.unwrap_or(renderer_style.icon_color);
2633 let mut text_color = appearance.text_color.unwrap_or(renderer_style.text_color);
2634
2635 if is_disabled {
2637 let background = theme.current_container().component.base.into();
2638 icon_color = icon_color.blend_alpha(background, 0.5);
2639 text_color = text_color.blend_alpha(background, 0.5);
2640 }
2641
2642 if let Some(border_offset) = appearance.border_offset {
2644 let offset_bounds = Rectangle {
2645 x: bounds.x - border_offset,
2646 y: bounds.y - border_offset,
2647 width: border_offset.mul_add(2.0, bounds.width),
2648 height: border_offset.mul_add(2.0, bounds.height),
2649 };
2650 renderer.fill_quad(
2651 renderer::Quad {
2652 bounds,
2653 border: Border {
2654 radius: appearance.border_radius,
2655 width: appearance.border_width,
2656 ..Default::default()
2657 },
2658 shadow: Shadow {
2659 offset: Vector::new(0.0, 1.0),
2660 color: Color::TRANSPARENT,
2661 blur_radius: 0.0,
2662 },
2663 snap: true,
2664 },
2665 appearance.background,
2666 );
2667 renderer.fill_quad(
2668 renderer::Quad {
2669 bounds: offset_bounds,
2670 border: Border {
2671 width: appearance.border_width,
2672 color: appearance.border_color,
2673 radius: appearance.border_radius,
2674 },
2675 shadow: Shadow {
2676 offset: Vector::new(0.0, 1.0),
2677 color: Color::TRANSPARENT,
2678 blur_radius: 0.0,
2679 },
2680 snap: true,
2681 },
2682 Background::Color(Color::TRANSPARENT),
2683 );
2684 } else {
2685 renderer.fill_quad(
2686 renderer::Quad {
2687 bounds,
2688 border: Border {
2689 width: appearance.border_width,
2690 color: appearance.border_color,
2691 radius: appearance.border_radius,
2692 },
2693 shadow: Shadow {
2694 offset: Vector::new(0.0, 1.0),
2695 color: Color::TRANSPARENT,
2696 blur_radius: 0.0,
2697 },
2698 snap: true,
2699 },
2700 appearance.background,
2701 );
2702 }
2703
2704 if let (Some(label_layout), Some(label)) = (label_layout, label) {
2706 renderer.fill_text(
2707 Text {
2708 content: label.to_string(),
2709 size: iced::Pixels(size.unwrap_or_else(|| renderer.default_size().0)),
2710 font: font.unwrap_or_else(|| renderer.default_font()),
2711 bounds: label_layout.bounds().size(),
2712 align_x: text::Alignment::Left,
2713 align_y: alignment::Vertical::Top,
2714 line_height,
2715 shaping: text::Shaping::Advanced,
2716 wrapping: text::Wrapping::None,
2717 ellipsize: text::Ellipsize::None,
2718 },
2719 label_layout.bounds().position(),
2720 appearance.label_color,
2721 *viewport,
2722 );
2723 }
2724 let mut child_index = 0;
2725 let leading_icon_tree = children.get(child_index);
2726 let has_start_icon = icon.is_some();
2728 if let (Some(icon), Some(tree)) = (icon, leading_icon_tree) {
2729 let mut children = text_layout.children();
2730 let _ = children.next().unwrap();
2731 let icon_layout = children.next().unwrap();
2732
2733 icon.as_widget().draw(
2734 tree,
2735 renderer,
2736 theme,
2737 &renderer::Style {
2738 icon_color,
2739 text_color,
2740 scale_factor: renderer_style.scale_factor,
2741 },
2742 icon_layout,
2743 cursor_position,
2744 viewport,
2745 );
2746 child_index += 1;
2747 }
2748
2749 let text = value.to_string();
2750 let font = font.unwrap_or_else(|| renderer.default_font());
2751 let size = size.unwrap_or_else(|| renderer.default_size().0);
2752 let text_width = state.value.min_width();
2753 let actual_width = text_width.max(text_bounds.width);
2754
2755 let radius_0 = THEME.lock().unwrap().cosmic().corner_radii.radius_0.into();
2756 #[cfg(wayland_platform)]
2757 let handling_dnd_offer = !matches!(state.dnd_offer, DndOfferState::None);
2758 #[cfg(not(wayland_platform))]
2759 let handling_dnd_offer = false;
2760 let (cursors, offset, is_selecting) = if let Some(focus) =
2761 state.is_focused.filter(|f| f.focused).or_else(|| {
2762 let now = Instant::now();
2763 handling_dnd_offer.then_some(Focus {
2764 needs_update: false,
2765 updated_at: now,
2766 now,
2767 focused: true,
2768 })
2769 }) {
2770 match state.cursor.state(value) {
2771 cursor::State::Index(position) => {
2772 let (text_value_width, _) = measure_cursor_and_scroll_offset(
2773 state.value.raw(),
2774 text_bounds,
2775 position,
2776 value,
2777 state.cursor.affinity(),
2778 state.scroll_offset,
2779 );
2780 let is_cursor_visible = handling_dnd_offer
2781 || ((focus.now - focus.updated_at).as_millis() / CURSOR_BLINK_INTERVAL_MILLIS)
2782 .is_multiple_of(2);
2783
2784 if is_cursor_visible && !dnd_icon {
2785 (
2786 vec![(
2787 renderer::Quad {
2788 bounds: Rectangle {
2789 x: (text_bounds.x + text_value_width)
2790 .floor()
2791 .max(text_bounds.x),
2792 y: text_bounds.y,
2793 width: 1.0,
2794 height: text_bounds.height,
2795 },
2796 border: Border {
2797 width: 0.0,
2798 color: Color::TRANSPARENT,
2799 radius: radius_0,
2800 },
2801 shadow: Shadow {
2802 offset: Vector::ZERO,
2803 color: Color::TRANSPARENT,
2804 blur_radius: 0.0,
2805 },
2806 snap: true,
2807 },
2808 text_color,
2809 )],
2810 state.scroll_offset,
2811 false,
2812 )
2813 } else {
2814 (
2815 Vec::<(renderer::Quad, Color)>::new(),
2816 if dnd_icon { 0.0 } else { state.scroll_offset },
2817 false,
2818 )
2819 }
2820 }
2821 cursor::State::Selection { start, end } => {
2822 let left = start.min(end);
2823 let right = end.max(start);
2824
2825 if dnd_icon {
2826 (Vec::<(renderer::Quad, Color)>::new(), 0.0, true)
2827 } else {
2828 let lo_byte = value.byte_index_at_grapheme(left);
2829 let hi_byte = value.byte_index_at_grapheme(right);
2830
2831 let rects = state.value.raw().highlight(
2832 0,
2833 (lo_byte, text::Affinity::After),
2834 (hi_byte, text::Affinity::Before),
2835 );
2836
2837 let cursors: Vec<(renderer::Quad, Color)> = rects
2838 .into_iter()
2839 .map(|r| {
2840 (
2841 renderer::Quad {
2842 bounds: Rectangle {
2843 x: text_bounds.x + r.x,
2844 y: text_bounds.y,
2845 width: r.width,
2846 height: text_bounds.height,
2847 },
2848 border: Border {
2849 width: 0.0,
2850 color: Color::TRANSPARENT,
2851 radius: radius_0,
2852 },
2853 shadow: Shadow {
2854 offset: Vector::ZERO,
2855 color: Color::TRANSPARENT,
2856 blur_radius: 0.0,
2857 },
2858 snap: true,
2859 },
2860 appearance.selected_fill,
2861 )
2862 })
2863 .collect();
2864
2865 (cursors, state.scroll_offset, true)
2866 }
2867 }
2868 }
2869 } else {
2870 let unfocused_offset = match effective_alignment(state.value.raw()) {
2871 alignment::Horizontal::Right => {
2872 (state.value.raw().min_width() - text_bounds.width).max(0.0)
2873 }
2874 _ => 0.0,
2875 };
2876
2877 (
2878 Vec::<(renderer::Quad, Color)>::new(),
2879 unfocused_offset,
2880 false,
2881 )
2882 };
2883
2884 let render = |renderer: &mut crate::Renderer| {
2885 let alignment_offset = alignment_offset(
2886 text_bounds.width,
2887 state.value.raw().min_width(),
2888 effective_alignment(state.value.raw()),
2889 );
2890
2891 let shift = Vector::new(alignment_offset - offset, 0.0);
2892 let fill_cursors = |renderer: &mut crate::Renderer| {
2893 renderer.with_translation(shift, |renderer| {
2894 for (quad, color) in &cursors {
2895 renderer.fill_quad(*quad, *color);
2896 }
2897 });
2898 };
2899
2900 let bounds = Rectangle {
2901 x: text_bounds.x + alignment_offset - offset,
2902 y: text_bounds.center_y(),
2903 width: actual_width,
2904 ..text_bounds
2905 };
2906 let color = if text.is_empty() {
2907 appearance.placeholder_color
2908 } else {
2909 text_color
2910 };
2911
2912 let text = Text {
2913 content: if text.is_empty() {
2914 placeholder.to_string()
2915 } else {
2916 text.clone()
2917 },
2918 font,
2919 bounds: bounds.size(),
2920 size: iced::Pixels(size),
2921 align_x: text::Alignment::Default,
2922 align_y: alignment::Vertical::Center,
2923 line_height: text::LineHeight::default(),
2924 shaping: text::Shaping::Advanced,
2925 wrapping: text::Wrapping::None,
2926 ellipsize: text::Ellipsize::None,
2927 };
2928 renderer.fill_text(text.clone(), bounds.position(), color, text_bounds);
2929
2930 if !is_selecting {
2931 renderer.with_layer(text_bounds, |renderer| fill_cursors(renderer));
2932 }
2933
2934 if is_selecting {
2937 fill_cursors(renderer);
2938 for (quad, _) in &cursors {
2939 renderer.with_layer(quad.bounds + shift, |renderer| {
2940 renderer.fill_text(
2941 text.clone(),
2942 bounds.position(),
2943 appearance.selected_text_color,
2944 text_bounds,
2945 );
2946 });
2947 }
2948 }
2949 };
2950
2951 renderer.with_layer(text_bounds, render);
2954
2955 let trailing_icon_tree = children.get(child_index);
2956
2957 if let (Some(icon), Some(tree)) = (trailing_icon, trailing_icon_tree) {
2959 let mut children = text_layout.children();
2960 let _ = children.next();
2961 if has_start_icon {
2962 let _ = children.next();
2963 }
2964 let icon_layout = children.next().unwrap();
2965
2966 icon.as_widget().draw(
2967 tree,
2968 renderer,
2969 theme,
2970 &renderer::Style {
2971 icon_color,
2972 text_color,
2973 scale_factor: renderer_style.scale_factor,
2974 },
2975 icon_layout,
2976 cursor_position,
2977 viewport,
2978 );
2979 }
2980
2981 if let (Some(helper_text_layout), Some(helper_text)) = (helper_text_layout, helper_text) {
2983 renderer.fill_text(
2984 Text {
2985 content: helper_text.to_string(), size: iced::Pixels(helper_text_size),
2987 font,
2988 bounds: helper_text_layout.bounds().size(),
2989 align_x: text::Alignment::Left,
2990 align_y: alignment::Vertical::Top,
2991 line_height: helper_line_height,
2992 shaping: text::Shaping::Advanced,
2993 wrapping: text::Wrapping::None,
2994 ellipsize: text::Ellipsize::None,
2995 },
2996 helper_text_layout.bounds().position(),
2997 text_color,
2998 *viewport,
2999 );
3000 }
3001}
3002
3003#[must_use]
3005pub fn mouse_interaction(
3006 layout: Layout<'_>,
3007 cursor_position: mouse::Cursor,
3008 is_disabled: bool,
3009) -> mouse::Interaction {
3010 if cursor_position.is_over(layout.bounds()) {
3011 if is_disabled {
3012 mouse::Interaction::NotAllowed
3013 } else {
3014 mouse::Interaction::Text
3015 }
3016 } else {
3017 mouse::Interaction::default()
3018 }
3019}
3020
3021#[derive(Debug, Clone)]
3023pub struct TextInputString(pub String);
3024
3025#[cfg(wayland_platform)]
3026impl AsMimeTypes for TextInputString {
3027 fn available(&self) -> Cow<'static, [String]> {
3028 Cow::Owned(
3029 SUPPORTED_TEXT_MIME_TYPES
3030 .iter()
3031 .cloned()
3032 .map(String::from)
3033 .collect::<Vec<_>>(),
3034 )
3035 }
3036
3037 fn as_bytes(&self, mime_type: &str) -> Option<Cow<'static, [u8]>> {
3038 if SUPPORTED_TEXT_MIME_TYPES.contains(&mime_type) {
3039 Some(Cow::Owned(self.0.clone().into_bytes()))
3040 } else {
3041 None
3042 }
3043 }
3044}
3045
3046#[derive(Debug, Clone, PartialEq)]
3047pub(crate) enum DraggingState {
3048 Selection,
3049 #[cfg(wayland_platform)]
3050 PrepareDnd(Point),
3051 #[cfg(wayland_platform)]
3052 Dnd(DndAction, String),
3053}
3054
3055#[cfg(wayland_platform)]
3056#[derive(Debug, Default, Clone)]
3057pub(crate) enum DndOfferState {
3058 #[default]
3059 None,
3060 HandlingOffer(Vec<String>, DndAction),
3061 Dropped,
3062}
3063#[derive(Debug, Default, Clone)]
3064#[cfg(not(wayland_platform))]
3065pub(crate) struct DndOfferState;
3066
3067#[derive(Default, Clone)]
3069#[must_use]
3070pub struct State {
3071 pub tracked_value: Value,
3072 pub value: crate::Plain,
3073 pub placeholder: crate::Plain,
3074 pub label: crate::Plain,
3075 pub helper_text: crate::Plain,
3076 pub dirty: bool,
3077 pub is_secure: bool,
3078 pub is_read_only: bool,
3079 pub emit_unfocus: bool,
3080 select_on_focus: bool,
3081 double_click_select_delimiter: Option<char>,
3082 is_focused: Option<Focus>,
3083 dragging_state: Option<DraggingState>,
3084 dnd_offer: DndOfferState,
3085 is_pasting: Option<Value>,
3086 last_click: Option<mouse::Click>,
3087 cursor: Cursor,
3088 preedit: Option<Preedit>,
3089 keyboard_modifiers: keyboard::Modifiers,
3090 scroll_offset: f32,
3091 context_menu_position: Option<iced_core::Point>,
3092 clipboard_has_text: bool,
3093 pub(crate) menu_bar_state: crate::widget::menu::MenuBarState,
3094 pub(crate) pending_action: crate::widget::text_context_menu::PendingAction,
3095}
3096
3097impl std::fmt::Debug for State {
3098 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3099 f.debug_struct("State")
3100 .field("is_secure", &self.is_secure)
3101 .field("is_read_only", &self.is_read_only)
3102 .field("dirty", &self.dirty)
3103 .finish_non_exhaustive()
3104 }
3105}
3106
3107#[derive(Debug, Clone, Copy)]
3108struct Focus {
3109 updated_at: Instant,
3110 now: Instant,
3111 focused: bool,
3112 needs_update: bool,
3113}
3114
3115impl State {
3116 pub fn new(
3118 is_secure: bool,
3119 is_read_only: bool,
3120 always_active: bool,
3121 select_on_focus: bool,
3122 ) -> Self {
3123 Self {
3124 is_secure,
3125 is_read_only,
3126 is_focused: always_active.then(|| {
3127 let now = Instant::now();
3128 Focus {
3129 updated_at: now,
3130 now,
3131 focused: true,
3132 needs_update: false,
3133 }
3134 }),
3135 select_on_focus,
3136 ..Self::default()
3137 }
3138 }
3139
3140 #[must_use]
3142 pub fn selected_text(&self, text: &str) -> Option<String> {
3143 let value = Value::new(text);
3144 match self.cursor.state(&value) {
3145 cursor::State::Index(_) => None,
3146 cursor::State::Selection { start, end } => {
3147 let left = start.min(end);
3148 let right = end.max(start);
3149 Some(value.select(left, right).to_string())
3150 }
3151 }
3152 }
3153
3154 #[cfg(wayland_platform)]
3155 #[must_use]
3157 pub fn dragged_text(&self) -> Option<String> {
3158 match self.dragging_state.as_ref() {
3159 Some(DraggingState::Dnd(_, text)) => Some(text.clone()),
3160 _ => None,
3161 }
3162 }
3163
3164 pub fn focused(is_secure: bool, is_read_only: bool) -> Self {
3166 Self {
3167 tracked_value: Value::default(),
3168 is_secure,
3169 value: crate::Plain::default(),
3170 placeholder: crate::Plain::default(),
3171 label: crate::Plain::default(),
3172 helper_text: crate::Plain::default(),
3173 is_read_only,
3174 emit_unfocus: false,
3175 is_focused: None,
3176 select_on_focus: false,
3177 double_click_select_delimiter: None,
3178 dragging_state: None,
3179 dnd_offer: DndOfferState::default(),
3180 is_pasting: None,
3181 last_click: None,
3182 cursor: Cursor::default(),
3183 preedit: None,
3184 keyboard_modifiers: keyboard::Modifiers::default(),
3185 scroll_offset: 0.0,
3186 dirty: false,
3187 context_menu_position: None,
3188 clipboard_has_text: false,
3189 menu_bar_state: crate::widget::menu::MenuBarState::default(),
3190 pending_action: crate::widget::text_context_menu::pending_action(),
3191 }
3192 }
3193
3194 #[inline]
3196 #[must_use]
3197 pub fn is_focused(&self) -> bool {
3198 self.is_focused.is_some_and(|f| f.focused)
3199 }
3200
3201 #[inline]
3203 #[must_use]
3204 pub fn cursor(&self) -> Cursor {
3205 self.cursor
3206 }
3207
3208 #[cold]
3210 pub fn focus(&mut self) {
3211 let now = Instant::now();
3212 LAST_FOCUS_UPDATE.with(|x| x.set(now));
3213 let was_focused = self.is_focused.is_some_and(|f| f.focused);
3214 self.is_read_only = false;
3215 self.is_focused = Some(Focus {
3216 updated_at: now,
3217 now,
3218 focused: true,
3219 needs_update: false,
3220 });
3221
3222 if was_focused {
3223 return;
3224 }
3225 if self.select_on_focus {
3226 self.select_all()
3227 } else {
3228 self.move_cursor_to_end();
3229 }
3230 }
3231
3232 #[cold]
3234 pub(super) fn unfocus(&mut self) {
3235 self.cursor.clear_selection();
3236 self.last_click = None;
3237 self.is_focused = self.is_focused.map(|mut f| {
3238 f.focused = false;
3239 f.needs_update = false;
3240 f
3241 });
3242 self.dragging_state = None;
3243 self.is_pasting = None;
3244 self.keyboard_modifiers = keyboard::Modifiers::default();
3245 }
3246
3247 #[inline]
3249 pub fn move_cursor_to_front(&mut self) {
3250 self.cursor.move_to(0);
3251 }
3252
3253 #[inline]
3255 pub fn move_cursor_to_end(&mut self) {
3256 self.cursor.move_to(usize::MAX);
3257 }
3258
3259 #[inline]
3261 pub fn move_cursor_to(&mut self, position: usize) {
3262 self.cursor.move_to(position);
3263 }
3264
3265 #[inline]
3267 pub fn select_all(&mut self) {
3268 self.cursor.select_range(0, usize::MAX);
3269 }
3270
3271 #[inline]
3273 pub fn select_range(&mut self, start: usize, end: usize) {
3274 self.cursor.select_range(start, end);
3275 }
3276
3277 pub fn context_menu_position(&self) -> Option<iced_core::Point> {
3279 self.context_menu_position
3280 }
3281
3282 pub fn set_context_menu_position(&mut self, pos: Option<iced_core::Point>) {
3284 self.context_menu_position = pos;
3285 }
3286
3287 pub fn delete_selection(&mut self) -> String {
3289 let mut editor = super::editor::Editor::new(&mut self.tracked_value, &mut self.cursor);
3290 editor.delete();
3291 editor.contents()
3292 }
3293
3294 pub fn paste_text(&mut self, text: &str) -> String {
3296 let paste_value = super::value::Value::new(text);
3297 let mut editor = super::editor::Editor::new(&mut self.tracked_value, &mut self.cursor);
3298 editor.paste(paste_value);
3299 let contents = editor.contents();
3300 self.tracked_value = super::value::Value::new(&contents);
3301 contents
3302 }
3303
3304 pub(super) fn setting_selection(&mut self, value: &Value, bounds: Rectangle<f32>, target: f32) {
3305 let (position, affinity) = find_cursor_position(bounds, value, self, target)
3306 .unwrap_or((0, text::Affinity::Before));
3307
3308 self.cursor.set_affinity(affinity);
3309 self.cursor.move_to(position);
3310 self.dragging_state = Some(DraggingState::Selection);
3311 }
3312}
3313
3314impl operation::Focusable for State {
3315 #[inline]
3316 fn is_focused(&self) -> bool {
3317 Self::is_focused(self)
3318 }
3319
3320 #[inline]
3321 fn focus(&mut self) {
3322 Self::focus(self);
3323 if let Some(focus) = self.is_focused.as_mut() {
3324 focus.needs_update = true;
3325 }
3326 }
3327
3328 #[inline]
3329 fn unfocus(&mut self) {
3330 Self::unfocus(self);
3331 if let Some(focus) = self.is_focused.as_mut() {
3332 focus.needs_update = true;
3333 }
3334 }
3335}
3336
3337impl operation::TextInput for State {
3338 #[inline]
3339 fn move_cursor_to_front(&mut self) {
3340 Self::move_cursor_to_front(self);
3341 }
3342
3343 #[inline]
3344 fn move_cursor_to_end(&mut self) {
3345 Self::move_cursor_to_end(self);
3346 }
3347
3348 #[inline]
3349 fn move_cursor_to(&mut self, position: usize) {
3350 Self::move_cursor_to(self, position);
3351 }
3352
3353 #[inline]
3354 fn select_all(&mut self) {
3355 Self::select_all(self);
3356 }
3357
3358 fn text(&self) -> &str {
3359 todo!()
3360 }
3361
3362 #[inline]
3363 fn select_range(&mut self, start: usize, end: usize) {
3364 Self::select_range(self, start, end);
3365 }
3366}
3367
3368#[inline(never)]
3369fn measure_cursor_and_scroll_offset(
3370 paragraph: &impl text::Paragraph,
3371 text_bounds: Rectangle,
3372 cursor_index: usize,
3373 value: &Value,
3374 affinity: text::Affinity,
3375 current_offset: f32,
3376) -> (f32, f32) {
3377 let byte_index = value.byte_index_at_grapheme(cursor_index);
3378 let position = paragraph
3379 .cursor_position(0, byte_index, affinity)
3380 .unwrap_or(Point::ORIGIN);
3381
3382 let offset = if position.x > current_offset + text_bounds.width - 5.0 {
3386 (position.x + 5.0) - text_bounds.width
3388 } else if position.x < current_offset + 5.0 {
3389 position.x - 5.0
3391 } else {
3392 current_offset
3394 };
3395
3396 let max_offset = (paragraph.min_width() - text_bounds.width).max(0.0);
3397 let offset = offset.clamp(0.0, max_offset);
3398
3399 (position.x, offset)
3400}
3401
3402#[inline(never)]
3405fn find_cursor_position(
3406 text_bounds: Rectangle,
3407 value: &Value,
3408 state: &State,
3409 x: f32,
3410) -> Option<(usize, text::Affinity)> {
3411 let value_str = value.to_string();
3412
3413 let hit = state.value.raw().hit_test(Point::new(
3414 x + state.scroll_offset,
3415 text_bounds.height / 2.0,
3416 ))?;
3417 let char_offset = hit.cursor();
3418 let affinity = hit.affinity();
3419
3420 let grapheme_count = unicode_segmentation::UnicodeSegmentation::graphemes(
3421 &value_str[..char_offset.min(value_str.len())],
3422 true,
3423 )
3424 .count();
3425
3426 Some((grapheme_count, affinity))
3427}
3428
3429#[inline(never)]
3430fn replace_paragraph(
3431 state: &mut State,
3432 layout: Layout<'_>,
3433 value: &Value,
3434 font: <crate::Renderer as iced_core::text::Renderer>::Font,
3435 text_size: Pixels,
3436 line_height: text::LineHeight,
3437 limits: &layout::Limits,
3438) {
3439 let mut children_layout = layout.children();
3440 let text_bounds = children_layout.next().unwrap();
3441 let bounds = limits.resolve(
3442 Length::Shrink,
3443 Length::Fill,
3444 Size::new(0., text_bounds.bounds().height),
3445 );
3446
3447 state.value = crate::Plain::new(Text {
3448 font,
3449 line_height,
3450 content: value.to_string(),
3451 bounds,
3452 size: text_size,
3453 align_x: text::Alignment::Default,
3454 align_y: alignment::Vertical::Top,
3455 shaping: text::Shaping::Advanced,
3456 wrapping: text::Wrapping::None,
3457 ellipsize: text::Ellipsize::None,
3458 });
3459}
3460
3461const CURSOR_BLINK_INTERVAL_MILLIS: u128 = 500;
3462
3463mod platform {
3464 use iced_core::keyboard;
3465
3466 #[inline]
3467 pub fn is_jump_modifier_pressed(modifiers: keyboard::Modifiers) -> bool {
3468 if cfg!(target_os = "macos") {
3469 modifiers.alt()
3470 } else {
3471 modifiers.control()
3472 }
3473 }
3474}
3475
3476#[inline(never)]
3477fn offset(text_bounds: Rectangle, value: &Value, state: &State) -> f32 {
3478 if state.is_focused() {
3479 let cursor = state.cursor();
3480
3481 let focus_position = match cursor.state(value) {
3482 cursor::State::Index(i) => i,
3483 cursor::State::Selection { end, .. } => end,
3484 };
3485
3486 let (_, offset) = measure_cursor_and_scroll_offset(
3487 state.value.raw(),
3488 text_bounds,
3489 focus_position,
3490 value,
3491 state.cursor().affinity(),
3492 state.scroll_offset,
3493 );
3494
3495 offset
3496 } else {
3497 match effective_alignment(state.value.raw()) {
3498 alignment::Horizontal::Right => {
3499 (state.value.raw().min_width() - text_bounds.width).max(0.0)
3500 }
3501 _ => 0.0,
3502 }
3503 }
3504}
3505
3506#[inline(never)]
3507fn alignment_offset(
3508 text_bounds_width: f32,
3509 text_min_width: f32,
3510 alignment: alignment::Horizontal,
3511) -> f32 {
3512 if text_min_width > text_bounds_width {
3513 0.0
3514 } else {
3515 match alignment {
3516 alignment::Horizontal::Left => 0.0,
3517 alignment::Horizontal::Center => (text_bounds_width - text_min_width) / 2.0,
3518 alignment::Horizontal::Right => text_bounds_width - text_min_width,
3519 }
3520 }
3521}
3522
3523#[inline(never)]
3524fn effective_alignment(paragraph: &impl text::Paragraph) -> alignment::Horizontal {
3525 if paragraph.is_rtl(0).unwrap_or(false) {
3526 alignment::Horizontal::Right
3527 } else {
3528 alignment::Horizontal::Left
3529 }
3530}
3531
3532use iced_core::widget::tree::Tree as WidgetTree;
3533
3534impl<Message: Clone + 'static> iced_core::widget::text::HasSelectableText
3535 for TextInput<'_, Message>
3536{
3537 fn selected_text(&self, tree: &WidgetTree) -> Option<String> {
3538 let state = tree.state.downcast_ref::<State>();
3539 let (start, end) = state.cursor().selection(&state.tracked_value)?;
3540 Some(state.tracked_value.select(start, end).to_string())
3541 }
3542
3543 fn select_all(&self, tree: &mut WidgetTree) {
3544 let state = tree.state.downcast_mut::<State>();
3545 state.select_all();
3546 }
3547
3548 fn is_editable(&self) -> bool {
3549 true
3550 }
3551
3552 fn has_text(&self, tree: &WidgetTree) -> bool {
3553 !tree.state.downcast_ref::<State>().tracked_value.is_empty()
3554 }
3555
3556 fn clipboard_has_text(&self, tree: &WidgetTree) -> bool {
3557 tree.state.downcast_ref::<State>().clipboard_has_text
3558 }
3559
3560 fn is_focused(&self, tree: &WidgetTree) -> bool {
3561 tree.state.downcast_ref::<State>().is_focused()
3562 }
3563
3564 fn context_menu_position(&self, tree: &WidgetTree) -> Option<iced_core::Point> {
3565 tree.state.downcast_ref::<State>().context_menu_position
3566 }
3567
3568 fn set_context_menu_position(&self, tree: &mut WidgetTree, pos: Option<iced_core::Point>) {
3569 tree.state.downcast_mut::<State>().context_menu_position = pos;
3570 }
3571
3572 fn delete_selection(&self, tree: &mut WidgetTree) -> Option<String> {
3573 let state = tree.state.downcast_mut::<State>();
3574 Some(state.delete_selection())
3575 }
3576
3577 fn paste_text(&self, tree: &mut WidgetTree, text: &str) -> Option<String> {
3578 let filtered: String = text.chars().filter(|c| !c.is_control()).collect();
3579 let state = tree.state.downcast_mut::<State>();
3580 Some(state.paste_text(&filtered))
3581 }
3582}