1use std::sync::Arc;
2
3use emath::{Rect, TSTransform};
4use epaint::{
5 StrokeKind,
6 text::{Galley, LayoutJob, cursor::CCursor},
7};
8
9use crate::{
10 Align, Align2, Color32, Context, CursorIcon, Event, EventFilter, FontSelection, Id, ImeEvent,
11 Key, KeyboardShortcut, Margin, Modifiers, NumExt as _, Response, Sense, Shape, TextBuffer,
12 TextStyle, TextWrapMode, Ui, Vec2, Widget, WidgetInfo, WidgetText, WidgetWithState, epaint,
13 os::OperatingSystem,
14 output::OutputEvent,
15 response, text_selection,
16 text_selection::{CCursorRange, text_cursor_state::cursor_rect, visuals::paint_text_selection},
17 vec2,
18};
19
20use super::{TextEditOutput, TextEditState};
21
22type LayouterFn<'t> = &'t mut dyn FnMut(&Ui, &dyn TextBuffer, f32) -> Arc<Galley>;
23
24#[must_use = "You should put this widget in a ui with `ui.add(widget);`"]
68pub struct TextEdit<'t> {
69 text: &'t mut dyn TextBuffer,
70 hint_text: WidgetText,
71 hint_text_font: Option<FontSelection>,
72 id: Option<Id>,
73 id_salt: Option<Id>,
74 font_selection: FontSelection,
75 text_color: Option<Color32>,
76 layouter: Option<LayouterFn<'t>>,
77 password: bool,
78 frame: bool,
79 margin: Margin,
80 multiline: bool,
81 interactive: bool,
82 desired_width: Option<f32>,
83 desired_height_rows: usize,
84 event_filter: EventFilter,
85 cursor_at_end: bool,
86 min_size: Vec2,
87 align: Align2,
88 clip_text: bool,
89 char_limit: usize,
90 return_key: Option<KeyboardShortcut>,
91 background_color: Option<Color32>,
92}
93
94impl WidgetWithState for TextEdit<'_> {
95 type State = TextEditState;
96}
97
98impl TextEdit<'_> {
99 pub fn load_state(ctx: &Context, id: Id) -> Option<TextEditState> {
100 TextEditState::load(ctx, id)
101 }
102
103 pub fn store_state(ctx: &Context, id: Id, state: TextEditState) {
104 state.store(ctx, id);
105 }
106}
107
108impl<'t> TextEdit<'t> {
109 pub fn singleline(text: &'t mut dyn TextBuffer) -> Self {
111 Self {
112 desired_height_rows: 1,
113 multiline: false,
114 clip_text: true,
115 ..Self::multiline(text)
116 }
117 }
118
119 pub fn multiline(text: &'t mut dyn TextBuffer) -> Self {
121 Self {
122 text,
123 hint_text: Default::default(),
124 hint_text_font: None,
125 id: None,
126 id_salt: None,
127 font_selection: Default::default(),
128 text_color: None,
129 layouter: None,
130 password: false,
131 frame: true,
132 margin: Margin::symmetric(4, 2),
133 multiline: true,
134 interactive: true,
135 desired_width: None,
136 desired_height_rows: 4,
137 event_filter: EventFilter {
138 horizontal_arrows: true,
140 vertical_arrows: true,
141 tab: false, ..Default::default()
143 },
144 cursor_at_end: true,
145 min_size: Vec2::ZERO,
146 align: Align2::LEFT_TOP,
147 clip_text: false,
148 char_limit: usize::MAX,
149 return_key: Some(KeyboardShortcut::new(Modifiers::NONE, Key::Enter)),
150 background_color: None,
151 }
152 }
153
154 pub fn code_editor(self) -> Self {
159 self.font(TextStyle::Monospace).lock_focus(true)
160 }
161
162 #[inline]
164 pub fn id(mut self, id: Id) -> Self {
165 self.id = Some(id);
166 self
167 }
168
169 #[inline]
171 pub fn id_source(self, id_salt: impl std::hash::Hash) -> Self {
172 self.id_salt(id_salt)
173 }
174
175 #[inline]
177 pub fn id_salt(mut self, id_salt: impl std::hash::Hash) -> Self {
178 self.id_salt = Some(Id::new(id_salt));
179 self
180 }
181
182 #[inline]
205 pub fn hint_text(mut self, hint_text: impl Into<WidgetText>) -> Self {
206 self.hint_text = hint_text.into();
207 self
208 }
209
210 #[inline]
213 pub fn background_color(mut self, color: Color32) -> Self {
214 self.background_color = Some(color);
215 self
216 }
217
218 #[inline]
220 pub fn hint_text_font(mut self, hint_text_font: impl Into<FontSelection>) -> Self {
221 self.hint_text_font = Some(hint_text_font.into());
222 self
223 }
224
225 #[inline]
227 pub fn password(mut self, password: bool) -> Self {
228 self.password = password;
229 self
230 }
231
232 #[inline]
234 pub fn font(mut self, font_selection: impl Into<FontSelection>) -> Self {
235 self.font_selection = font_selection.into();
236 self
237 }
238
239 #[inline]
240 pub fn text_color(mut self, text_color: Color32) -> Self {
241 self.text_color = Some(text_color);
242 self
243 }
244
245 #[inline]
246 pub fn text_color_opt(mut self, text_color: Option<Color32>) -> Self {
247 self.text_color = text_color;
248 self
249 }
250
251 #[inline]
275 pub fn layouter(
276 mut self,
277 layouter: &'t mut dyn FnMut(&Ui, &dyn TextBuffer, f32) -> Arc<Galley>,
278 ) -> Self {
279 self.layouter = Some(layouter);
280
281 self
282 }
283
284 #[inline]
288 pub fn interactive(mut self, interactive: bool) -> Self {
289 self.interactive = interactive;
290 self
291 }
292
293 #[inline]
295 pub fn frame(mut self, frame: bool) -> Self {
296 self.frame = frame;
297 self
298 }
299
300 #[inline]
302 pub fn margin(mut self, margin: impl Into<Margin>) -> Self {
303 self.margin = margin.into();
304 self
305 }
306
307 #[inline]
310 pub fn desired_width(mut self, desired_width: f32) -> Self {
311 self.desired_width = Some(desired_width);
312 self
313 }
314
315 #[inline]
319 pub fn desired_rows(mut self, desired_height_rows: usize) -> Self {
320 self.desired_height_rows = desired_height_rows;
321 self
322 }
323
324 #[inline]
330 pub fn lock_focus(mut self, tab_will_indent: bool) -> Self {
331 self.event_filter.tab = tab_will_indent;
332 self
333 }
334
335 #[inline]
339 pub fn cursor_at_end(mut self, b: bool) -> Self {
340 self.cursor_at_end = b;
341 self
342 }
343
344 #[inline]
350 pub fn clip_text(mut self, b: bool) -> Self {
351 if !self.multiline {
353 self.clip_text = b;
354 }
355 self
356 }
357
358 #[inline]
362 pub fn char_limit(mut self, limit: usize) -> Self {
363 self.char_limit = limit;
364 self
365 }
366
367 #[inline]
369 pub fn horizontal_align(mut self, align: Align) -> Self {
370 self.align.0[0] = align;
371 self
372 }
373
374 #[inline]
376 pub fn vertical_align(mut self, align: Align) -> Self {
377 self.align.0[1] = align;
378 self
379 }
380
381 #[inline]
383 pub fn min_size(mut self, min_size: Vec2) -> Self {
384 self.min_size = min_size;
385 self
386 }
387
388 #[inline]
395 pub fn return_key(mut self, return_key: impl Into<Option<KeyboardShortcut>>) -> Self {
396 self.return_key = return_key.into();
397 self
398 }
399}
400
401impl Widget for TextEdit<'_> {
404 fn ui(self, ui: &mut Ui) -> Response {
405 self.show(ui).response
406 }
407}
408
409impl TextEdit<'_> {
410 pub fn show(self, ui: &mut Ui) -> TextEditOutput {
426 let is_mutable = self.text.is_mutable();
427 let frame = self.frame;
428 let where_to_put_background = ui.painter().add(Shape::Noop);
429 let background_color = self
430 .background_color
431 .unwrap_or_else(|| ui.visuals().text_edit_bg_color());
432 let output = self.show_content(ui);
433
434 if frame {
435 let visuals = ui.style().interact(&output.response);
436 let frame_rect = output.response.rect.expand(visuals.expansion);
437 let shape = if is_mutable {
438 if output.response.has_focus() {
439 epaint::RectShape::new(
440 frame_rect,
441 visuals.corner_radius,
442 background_color,
443 ui.visuals().selection.stroke,
444 StrokeKind::Inside,
445 )
446 } else {
447 epaint::RectShape::new(
448 frame_rect,
449 visuals.corner_radius,
450 background_color,
451 visuals.bg_stroke, StrokeKind::Inside,
453 )
454 }
455 } else {
456 let visuals = &ui.style().visuals.widgets.inactive;
457 epaint::RectShape::stroke(
458 frame_rect,
459 visuals.corner_radius,
460 visuals.bg_stroke, StrokeKind::Inside,
462 )
463 };
464
465 ui.painter().set(where_to_put_background, shape);
466 }
467
468 output
469 }
470
471 fn show_content(self, ui: &mut Ui) -> TextEditOutput {
472 let TextEdit {
473 text,
474 hint_text,
475 hint_text_font,
476 id,
477 id_salt,
478 font_selection,
479 text_color,
480 layouter,
481 password,
482 frame: _,
483 margin,
484 multiline,
485 interactive,
486 desired_width,
487 desired_height_rows,
488 event_filter,
489 cursor_at_end,
490 min_size,
491 align,
492 clip_text,
493 char_limit,
494 return_key,
495 background_color: _,
496 } = self;
497
498 let text_color = text_color
499 .or(ui.visuals().override_text_color)
500 .unwrap_or_else(|| ui.visuals().widgets.inactive.text_color());
502
503 let prev_text = text.as_str().to_owned();
504 let hint_text_str = hint_text.text().to_owned();
505
506 let font_id = font_selection.resolve(ui.style());
507 let row_height = ui.fonts(|f| f.row_height(&font_id));
508 const MIN_WIDTH: f32 = 24.0; let available_width = (ui.available_width() - margin.sum().x).at_least(MIN_WIDTH);
510 let desired_width = desired_width.unwrap_or_else(|| ui.spacing().text_edit_width);
511 let wrap_width = if ui.layout().horizontal_justify() {
512 available_width
513 } else {
514 desired_width.min(available_width)
515 };
516
517 let font_id_clone = font_id.clone();
518 let mut default_layouter = move |ui: &Ui, text: &dyn TextBuffer, wrap_width: f32| {
519 let text = mask_if_password(password, text.as_str());
520 let layout_job = if multiline {
521 LayoutJob::simple(text, font_id_clone.clone(), text_color, wrap_width)
522 } else {
523 LayoutJob::simple_singleline(text, font_id_clone.clone(), text_color)
524 };
525 ui.fonts(|f| f.layout_job(layout_job))
526 };
527
528 let layouter = layouter.unwrap_or(&mut default_layouter);
529
530 let mut galley = layouter(ui, text, wrap_width);
531
532 let desired_inner_width = if clip_text {
533 wrap_width } else {
535 galley.size().x.max(wrap_width)
536 };
537 let desired_height = (desired_height_rows.at_least(1) as f32) * row_height;
538 let desired_inner_size = vec2(desired_inner_width, galley.size().y.max(desired_height));
539 let desired_outer_size = (desired_inner_size + margin.sum()).at_least(min_size);
540 let (auto_id, outer_rect) = ui.allocate_space(desired_outer_size);
541 let rect = outer_rect - margin; let id = id.unwrap_or_else(|| {
544 if let Some(id_salt) = id_salt {
545 ui.make_persistent_id(id_salt)
546 } else {
547 auto_id }
549 });
550 let mut state = TextEditState::load(ui.ctx(), id).unwrap_or_default();
551
552 let allow_drag_to_select =
557 ui.input(|i| !i.has_touch_screen()) || ui.memory(|mem| mem.has_focus(id));
558
559 let sense = if interactive {
560 if allow_drag_to_select {
561 Sense::click_and_drag()
562 } else {
563 Sense::click()
564 }
565 } else {
566 Sense::hover()
567 };
568 let mut response = ui.interact(outer_rect, id, sense);
569 response.intrinsic_size = Some(Vec2::new(desired_width, desired_outer_size.y));
570
571 response.flags -= response::Flags::FAKE_PRIMARY_CLICKED;
573 let text_clip_rect = rect;
574 let painter = ui.painter_at(text_clip_rect.expand(1.0)); if interactive {
577 if let Some(pointer_pos) = response.interact_pointer_pos() {
578 if response.hovered() && text.is_mutable() {
579 ui.output_mut(|o| o.mutable_text_under_cursor = true);
580 }
581
582 let singleline_offset = vec2(state.singleline_offset, 0.0);
585 let cursor_at_pointer =
586 galley.cursor_from_pos(pointer_pos - rect.min + singleline_offset);
587
588 if ui.visuals().text_cursor.preview
589 && response.hovered()
590 && ui.input(|i| i.pointer.is_moving())
591 {
592 let cursor_rect = TSTransform::from_translation(rect.min.to_vec2())
594 * cursor_rect(&galley, &cursor_at_pointer, row_height);
595 text_selection::visuals::paint_cursor_end(&painter, ui.visuals(), cursor_rect);
596 }
597
598 let is_being_dragged = ui.ctx().is_being_dragged(response.id);
599 let did_interact = state.cursor.pointer_interaction(
600 ui,
601 &response,
602 cursor_at_pointer,
603 &galley,
604 is_being_dragged,
605 );
606
607 if did_interact || response.clicked() {
608 ui.memory_mut(|mem| mem.request_focus(response.id));
609
610 state.last_interaction_time = ui.ctx().input(|i| i.time);
611 }
612 }
613 }
614
615 if interactive && response.hovered() {
616 ui.ctx().set_cursor_icon(CursorIcon::Text);
617 }
618
619 let mut cursor_range = None;
620 let prev_cursor_range = state.cursor.range(&galley);
621 if interactive && ui.memory(|mem| mem.has_focus(id)) {
622 ui.memory_mut(|mem| mem.set_focus_lock_filter(id, event_filter));
623
624 let default_cursor_range = if cursor_at_end {
625 CCursorRange::one(galley.end())
626 } else {
627 CCursorRange::default()
628 };
629
630 let (changed, new_cursor_range) = events(
631 ui,
632 &mut state,
633 text,
634 &mut galley,
635 layouter,
636 id,
637 wrap_width,
638 multiline,
639 password,
640 default_cursor_range,
641 char_limit,
642 event_filter,
643 return_key,
644 );
645
646 if changed {
647 response.mark_changed();
648 }
649 cursor_range = Some(new_cursor_range);
650 }
651
652 let mut galley_pos = align
653 .align_size_within_rect(galley.size(), rect)
654 .intersect(rect) .min;
656 let align_offset = rect.left() - galley_pos.x;
657
658 if clip_text && align_offset == 0.0 {
660 let cursor_pos = match (cursor_range, ui.memory(|mem| mem.has_focus(id))) {
661 (Some(cursor_range), true) => galley.pos_from_cursor(cursor_range.primary).min.x,
662 _ => 0.0,
663 };
664
665 let mut offset_x = state.singleline_offset;
666 let visible_range = offset_x..=offset_x + desired_inner_size.x;
667
668 if !visible_range.contains(&cursor_pos) {
669 if cursor_pos < *visible_range.start() {
670 offset_x = cursor_pos;
671 } else {
672 offset_x = cursor_pos - desired_inner_size.x;
673 }
674 }
675
676 offset_x = offset_x
677 .at_most(galley.size().x - desired_inner_size.x)
678 .at_least(0.0);
679
680 state.singleline_offset = offset_x;
681 galley_pos -= vec2(offset_x, 0.0);
682 } else {
683 state.singleline_offset = align_offset;
684 }
685
686 let selection_changed = if let (Some(cursor_range), Some(prev_cursor_range)) =
687 (cursor_range, prev_cursor_range)
688 {
689 prev_cursor_range != cursor_range
690 } else {
691 false
692 };
693
694 if ui.is_rect_visible(rect) {
695 if text.as_str().is_empty() && !hint_text.is_empty() {
696 let hint_text_color = ui.visuals().weak_text_color();
697 let hint_text_font_id = hint_text_font.unwrap_or(font_id.into());
698 let galley = if multiline {
699 hint_text.into_galley(
700 ui,
701 Some(TextWrapMode::Wrap),
702 desired_inner_size.x,
703 hint_text_font_id,
704 )
705 } else {
706 hint_text.into_galley(
707 ui,
708 Some(TextWrapMode::Extend),
709 f32::INFINITY,
710 hint_text_font_id,
711 )
712 };
713 let galley_pos = align
714 .align_size_within_rect(galley.size(), rect)
715 .intersect(rect)
716 .min;
717 painter.galley(galley_pos, galley, hint_text_color);
718 }
719
720 let has_focus = ui.memory(|mem| mem.has_focus(id));
721
722 if has_focus {
723 if let Some(cursor_range) = state.cursor.range(&galley) {
724 paint_text_selection(&mut galley, ui.visuals(), &cursor_range, None);
726 }
727 }
728
729 if !clip_text {
730 let extra_size = galley.size() - rect.size();
734 if extra_size.x > 0.0 || extra_size.y > 0.0 {
735 ui.allocate_rect(
736 Rect::from_min_size(outer_rect.max, extra_size),
737 Sense::hover(),
738 );
739 }
740 }
741
742 painter.galley(galley_pos, galley.clone(), text_color);
743
744 if has_focus {
745 if let Some(cursor_range) = state.cursor.range(&galley) {
746 let primary_cursor_rect =
747 cursor_rect(&galley, &cursor_range.primary, row_height)
748 .translate(galley_pos.to_vec2());
749
750 if response.changed() || selection_changed {
751 ui.scroll_to_rect(primary_cursor_rect + margin, None);
753 }
754
755 if text.is_mutable() && interactive {
756 let now = ui.ctx().input(|i| i.time);
757 if response.changed() || selection_changed {
758 state.last_interaction_time = now;
759 }
760
761 let viewport_has_focus = ui.ctx().input(|i| i.focused);
766 if viewport_has_focus {
767 text_selection::visuals::paint_text_cursor(
768 ui,
769 &painter,
770 primary_cursor_rect,
771 now - state.last_interaction_time,
772 );
773 }
774
775 let to_global = ui
777 .ctx()
778 .layer_transform_to_global(ui.layer_id())
779 .unwrap_or_default();
780
781 ui.ctx().output_mut(|o| {
782 o.ime = Some(crate::output::IMEOutput {
783 rect: to_global * rect,
784 cursor_rect: to_global * primary_cursor_rect,
785 });
786 });
787 }
788 }
789 }
790 }
791
792 if state.ime_enabled && (response.gained_focus() || response.lost_focus()) {
794 state.ime_enabled = false;
795 if let Some(mut ccursor_range) = state.cursor.char_range() {
796 ccursor_range.secondary.index = ccursor_range.primary.index;
797 state.cursor.set_char_range(Some(ccursor_range));
798 }
799 ui.input_mut(|i| i.events.retain(|e| !matches!(e, Event::Ime(_))));
800 }
801
802 state.clone().store(ui.ctx(), id);
803
804 if response.changed() {
805 response.widget_info(|| {
806 WidgetInfo::text_edit(
807 ui.is_enabled(),
808 mask_if_password(password, prev_text.as_str()),
809 mask_if_password(password, text.as_str()),
810 hint_text_str.as_str(),
811 )
812 });
813 } else if selection_changed {
814 let cursor_range = cursor_range.unwrap();
815 let char_range = cursor_range.primary.index..=cursor_range.secondary.index;
816 let info = WidgetInfo::text_selection_changed(
817 ui.is_enabled(),
818 char_range,
819 mask_if_password(password, text.as_str()),
820 );
821 response.output_event(OutputEvent::TextSelectionChanged(info));
822 } else {
823 response.widget_info(|| {
824 WidgetInfo::text_edit(
825 ui.is_enabled(),
826 mask_if_password(password, prev_text.as_str()),
827 mask_if_password(password, text.as_str()),
828 hint_text_str.as_str(),
829 )
830 });
831 }
832
833 #[cfg(feature = "accesskit")]
834 {
835 let role = if password {
836 accesskit::Role::PasswordInput
837 } else if multiline {
838 accesskit::Role::MultilineTextInput
839 } else {
840 accesskit::Role::TextInput
841 };
842
843 crate::text_selection::accesskit_text::update_accesskit_for_text_widget(
844 ui.ctx(),
845 id,
846 cursor_range,
847 role,
848 TSTransform::from_translation(galley_pos.to_vec2()),
849 &galley,
850 );
851 }
852
853 TextEditOutput {
854 response,
855 galley,
856 galley_pos,
857 text_clip_rect,
858 state,
859 cursor_range,
860 }
861 }
862}
863
864fn mask_if_password(is_password: bool, text: &str) -> String {
865 fn mask_password(text: &str) -> String {
866 std::iter::repeat_n(
867 epaint::text::PASSWORD_REPLACEMENT_CHAR,
868 text.chars().count(),
869 )
870 .collect::<String>()
871 }
872
873 if is_password {
874 mask_password(text)
875 } else {
876 text.to_owned()
877 }
878}
879
880#[expect(clippy::too_many_arguments)]
884fn events(
885 ui: &crate::Ui,
886 state: &mut TextEditState,
887 text: &mut dyn TextBuffer,
888 galley: &mut Arc<Galley>,
889 layouter: &mut dyn FnMut(&Ui, &dyn TextBuffer, f32) -> Arc<Galley>,
890 id: Id,
891 wrap_width: f32,
892 multiline: bool,
893 password: bool,
894 default_cursor_range: CCursorRange,
895 char_limit: usize,
896 event_filter: EventFilter,
897 return_key: Option<KeyboardShortcut>,
898) -> (bool, CCursorRange) {
899 let os = ui.ctx().os();
900
901 let mut cursor_range = state.cursor.range(galley).unwrap_or(default_cursor_range);
902
903 state.undoer.lock().feed_state(
906 ui.input(|i| i.time),
907 &(cursor_range, text.as_str().to_owned()),
908 );
909
910 let copy_if_not_password = |ui: &Ui, text: String| {
911 if !password {
912 ui.ctx().copy_text(text);
913 }
914 };
915
916 let mut any_change = false;
917
918 let mut events = ui.input(|i| i.filtered_events(&event_filter));
919
920 if state.ime_enabled {
921 remove_ime_incompatible_events(&mut events);
922 events.sort_by_key(|e| !matches!(e, Event::Ime(_)));
924 }
925
926 for event in &events {
927 let did_mutate_text = match event {
928 event if cursor_range.on_event(os, event, galley, id) => None,
930
931 Event::Copy => {
932 if cursor_range.is_empty() {
933 None
934 } else {
935 copy_if_not_password(ui, cursor_range.slice_str(text.as_str()).to_owned());
936 None
937 }
938 }
939 Event::Cut => {
940 if cursor_range.is_empty() {
941 None
942 } else {
943 copy_if_not_password(ui, cursor_range.slice_str(text.as_str()).to_owned());
944 Some(CCursorRange::one(text.delete_selected(&cursor_range)))
945 }
946 }
947 Event::Paste(text_to_insert) => {
948 if !text_to_insert.is_empty() {
949 let mut ccursor = text.delete_selected(&cursor_range);
950
951 text.insert_text_at(&mut ccursor, text_to_insert, char_limit);
952
953 Some(CCursorRange::one(ccursor))
954 } else {
955 None
956 }
957 }
958 Event::Text(text_to_insert) => {
959 if !text_to_insert.is_empty() && text_to_insert != "\n" && text_to_insert != "\r" {
961 let mut ccursor = text.delete_selected(&cursor_range);
962
963 text.insert_text_at(&mut ccursor, text_to_insert, char_limit);
964
965 Some(CCursorRange::one(ccursor))
966 } else {
967 None
968 }
969 }
970 Event::Key {
971 key: Key::Tab,
972 pressed: true,
973 modifiers,
974 ..
975 } if multiline => {
976 let mut ccursor = text.delete_selected(&cursor_range);
977 if modifiers.shift {
978 text.decrease_indentation(&mut ccursor);
980 } else {
981 text.insert_text_at(&mut ccursor, "\t", char_limit);
982 }
983 Some(CCursorRange::one(ccursor))
984 }
985 Event::Key {
986 key,
987 pressed: true,
988 modifiers,
989 ..
990 } if return_key.is_some_and(|return_key| {
991 *key == return_key.logical_key && modifiers.matches_logically(return_key.modifiers)
992 }) =>
993 {
994 if multiline {
995 let mut ccursor = text.delete_selected(&cursor_range);
996 text.insert_text_at(&mut ccursor, "\n", char_limit);
997 Some(CCursorRange::one(ccursor))
999 } else {
1000 ui.memory_mut(|mem| mem.surrender_focus(id)); break;
1002 }
1003 }
1004
1005 Event::Key {
1006 key,
1007 pressed: true,
1008 modifiers,
1009 ..
1010 } if (modifiers.matches_logically(Modifiers::COMMAND) && *key == Key::Y)
1011 || (modifiers.matches_logically(Modifiers::SHIFT | Modifiers::COMMAND)
1012 && *key == Key::Z) =>
1013 {
1014 if let Some((redo_ccursor_range, redo_txt)) = state
1015 .undoer
1016 .lock()
1017 .redo(&(cursor_range, text.as_str().to_owned()))
1018 {
1019 text.replace_with(redo_txt);
1020 Some(*redo_ccursor_range)
1021 } else {
1022 None
1023 }
1024 }
1025
1026 Event::Key {
1027 key: Key::Z,
1028 pressed: true,
1029 modifiers,
1030 ..
1031 } if modifiers.matches_logically(Modifiers::COMMAND) => {
1032 if let Some((undo_ccursor_range, undo_txt)) = state
1033 .undoer
1034 .lock()
1035 .undo(&(cursor_range, text.as_str().to_owned()))
1036 {
1037 text.replace_with(undo_txt);
1038 Some(*undo_ccursor_range)
1039 } else {
1040 None
1041 }
1042 }
1043
1044 Event::Key {
1045 modifiers,
1046 key,
1047 pressed: true,
1048 ..
1049 } => check_for_mutating_key_press(os, &cursor_range, text, galley, modifiers, *key),
1050
1051 Event::Ime(ime_event) => match ime_event {
1052 ImeEvent::Enabled => {
1053 state.ime_enabled = true;
1054 state.ime_cursor_range = cursor_range;
1055 None
1056 }
1057 ImeEvent::Preedit(text_mark) => {
1058 if text_mark == "\n" || text_mark == "\r" {
1059 None
1060 } else {
1061 let mut ccursor = text.delete_selected(&cursor_range);
1064 let start_cursor = ccursor;
1065 if !text_mark.is_empty() {
1066 text.insert_text_at(&mut ccursor, text_mark, char_limit);
1067 }
1068 state.ime_cursor_range = cursor_range;
1069 Some(CCursorRange::two(start_cursor, ccursor))
1070 }
1071 }
1072 ImeEvent::Commit(prediction) => {
1073 if prediction == "\n" || prediction == "\r" {
1074 None
1075 } else {
1076 state.ime_enabled = false;
1077
1078 if !prediction.is_empty()
1079 && cursor_range.secondary.index
1080 == state.ime_cursor_range.secondary.index
1081 {
1082 let mut ccursor = text.delete_selected(&cursor_range);
1083 text.insert_text_at(&mut ccursor, prediction, char_limit);
1084 Some(CCursorRange::one(ccursor))
1085 } else {
1086 let ccursor = cursor_range.primary;
1087 Some(CCursorRange::one(ccursor))
1088 }
1089 }
1090 }
1091 ImeEvent::Disabled => {
1092 state.ime_enabled = false;
1093 None
1094 }
1095 },
1096
1097 _ => None,
1098 };
1099
1100 if let Some(new_ccursor_range) = did_mutate_text {
1101 any_change = true;
1102
1103 *galley = layouter(ui, text, wrap_width);
1105
1106 cursor_range = new_ccursor_range;
1108 }
1109 }
1110
1111 state.cursor.set_char_range(Some(cursor_range));
1112
1113 state.undoer.lock().feed_state(
1114 ui.input(|i| i.time),
1115 &(cursor_range, text.as_str().to_owned()),
1116 );
1117
1118 (any_change, cursor_range)
1119}
1120
1121fn remove_ime_incompatible_events(events: &mut Vec<Event>) {
1124 events.retain(|event| {
1127 !matches!(
1128 event,
1129 Event::Key { repeat: true, .. }
1130 | Event::Key {
1131 key: Key::Backspace
1132 | Key::ArrowUp
1133 | Key::ArrowDown
1134 | Key::ArrowLeft
1135 | Key::ArrowRight,
1136 ..
1137 }
1138 )
1139 });
1140}
1141
1142fn check_for_mutating_key_press(
1146 os: OperatingSystem,
1147 cursor_range: &CCursorRange,
1148 text: &mut dyn TextBuffer,
1149 galley: &Galley,
1150 modifiers: &Modifiers,
1151 key: Key,
1152) -> Option<CCursorRange> {
1153 match key {
1154 Key::Backspace => {
1155 let ccursor = if modifiers.mac_cmd {
1156 text.delete_paragraph_before_cursor(galley, cursor_range)
1157 } else if let Some(cursor) = cursor_range.single() {
1158 if modifiers.alt || modifiers.ctrl {
1159 text.delete_previous_word(cursor)
1161 } else {
1162 text.delete_previous_char(cursor)
1163 }
1164 } else {
1165 text.delete_selected(cursor_range)
1166 };
1167 Some(CCursorRange::one(ccursor))
1168 }
1169
1170 Key::Delete if !modifiers.shift || os != OperatingSystem::Windows => {
1171 let ccursor = if modifiers.mac_cmd {
1172 text.delete_paragraph_after_cursor(galley, cursor_range)
1173 } else if let Some(cursor) = cursor_range.single() {
1174 if modifiers.alt || modifiers.ctrl {
1175 text.delete_next_word(cursor)
1177 } else {
1178 text.delete_next_char(cursor)
1179 }
1180 } else {
1181 text.delete_selected(cursor_range)
1182 };
1183 let ccursor = CCursor {
1184 prefer_next_row: true,
1185 ..ccursor
1186 };
1187 Some(CCursorRange::one(ccursor))
1188 }
1189
1190 Key::H if modifiers.ctrl => {
1191 let ccursor = text.delete_previous_char(cursor_range.primary);
1192 Some(CCursorRange::one(ccursor))
1193 }
1194
1195 Key::K if modifiers.ctrl => {
1196 let ccursor = text.delete_paragraph_after_cursor(galley, cursor_range);
1197 Some(CCursorRange::one(ccursor))
1198 }
1199
1200 Key::U if modifiers.ctrl => {
1201 let ccursor = text.delete_paragraph_before_cursor(galley, cursor_range);
1202 Some(CCursorRange::one(ccursor))
1203 }
1204
1205 Key::W if modifiers.ctrl => {
1206 let ccursor = if let Some(cursor) = cursor_range.single() {
1207 text.delete_previous_word(cursor)
1208 } else {
1209 text.delete_selected(cursor_range)
1210 };
1211 Some(CCursorRange::one(ccursor))
1212 }
1213
1214 _ => None,
1215 }
1216}