1use std::cell::RefCell;
6use std::rc::Rc;
7
8use embedder_traits::{
9 ClipboardAction, EditingAction, EditingDirection, EditingMotion, EmbedderMsg, InputEventResult,
10 ModifySelection, MouseButton,
11};
12use js::context::{JSContext, NoGC};
13use keyboard_types::{
14 CompositionEvent, CompositionState, Key, KeyState, KeyboardEvent as KeyboardTypesEvent,
15 Modifiers, NamedKey, ShortcutMatcher,
16};
17use layout_api::{QueryMsg, SegmentGranularity};
18use script_bindings::codegen::GenericBindings::DocumentBinding::DocumentMethods;
19use script_bindings::codegen::GenericBindings::EventBinding::EventMethods;
20use script_bindings::codegen::GenericBindings::SelectionBinding::SelectionMethods;
21use script_bindings::codegen::GenericBindings::UIEventBinding::UIEventMethods as _;
22use script_bindings::dom::UnrootedDom;
23use script_bindings::inheritance::Castable;
24use script_bindings::root::DomRoot;
25use script_bindings::str::DOMString;
26use servo_base::generic_channel::GenericCallback;
27
28use crate::dom::clipboardevent::ClipboardEventType;
29use crate::dom::event::{EventBubbles, EventCancelable};
30use crate::dom::execcommand::execcommands::DocumentExecCommandSupport;
31use crate::dom::inputevent::HitTestResult;
32use crate::dom::selection_range::{RootedSelectionBoundary, SelectionRange};
33use crate::dom::text_control::TextControlElement;
34use crate::dom::text_input::InputEventType;
35use crate::dom::types::{
36 ClipboardEvent, DataTransfer, Event, EventTarget, HTMLInputElement, HTMLTextAreaElement,
37 MouseEvent, UIEvent,
38};
39use crate::dom::{Document, Node, NodeTraits};
40use crate::drag::document_selection_drag::{
41 DocumentDragSegment, DocumentSelectionDragHandler, adjust_anchor_for_user_select,
42};
43use crate::drag::drag_data_store::{DragDataStore, Kind, Mode};
44use crate::drag::drag_gesture::{DragGesture, DragHandler};
45
46#[cfg(target_os = "macos")]
47pub(crate) const CMD_OR_CONTROL: Modifiers = Modifiers::META;
48#[cfg(not(target_os = "macos"))]
49pub(crate) const CMD_OR_CONTROL: Modifiers = Modifiers::CONTROL;
50
51#[cfg(target_os = "macos")]
52pub(crate) const ALT_OR_CONTROL: Modifiers = Modifiers::ALT;
53#[cfg(not(target_os = "macos"))]
54pub(crate) const ALT_OR_CONTROL: Modifiers = Modifiers::CONTROL;
55
56#[derive(Clone, Copy, Debug, PartialEq)]
58pub(crate) enum MouseButtonSelectionAction {
59 MoveCursor,
62 SelectRange(SegmentGranularity),
64}
65
66impl MouseButtonSelectionAction {
67 pub(crate) fn from_mouse_event(mouse_event: &MouseEvent) -> Option<Self> {
68 match mouse_event.button() {
69 MouseButton::Primary => {}, MouseButton::Auxiliary => return Some(Self::MoveCursor),
71 _ => return None,
72 }
73
74 let click_count = mouse_event.upcast::<UIEvent>().Detail();
83 match click_count {
84 1 => Some(Self::MoveCursor),
85 2 => Some(Self::SelectRange(SegmentGranularity::Word)),
86 3 => Some(Self::SelectRange(SegmentGranularity::HardLineBreak)),
87 _ => None,
88 }
89 }
90}
91
92impl Document {
93 pub(crate) fn editing_context(&self, no_gc: &NoGC, node: &Node) -> EditingContext {
94 if let Ok(editing_context) = EditingContext::try_from(node) {
95 return editing_context;
96 }
97
98 let mut current_node = UnrootedDom::from_ref(node, no_gc);
99 while let Some(parent) = current_node.parent_in_flat_tree(no_gc).into_parent() {
100 if let Ok(editing_context) = EditingContext::try_from(&**parent) {
101 return editing_context;
102 }
103 current_node = parent;
104 }
105
106 EditingContext::Document(DomRoot::from_ref(self))
107 }
108
109 pub(crate) fn handle_clipboard_action(
111 &self,
112 cx: &mut JSContext,
113 editing_context: &EditingContext,
114 action: ClipboardAction,
115 ) -> InputEventResult {
116 let clipboard_event_type = match action {
117 ClipboardAction::Copy => ClipboardEventType::Copy,
118 ClipboardAction::Cut => ClipboardEventType::Cut,
119 ClipboardAction::Paste => ClipboardEventType::Paste,
120 };
121
122 let script_triggered = false;
124
125 let script_may_access_clipboard = false;
129
130 if script_triggered && !script_may_access_clipboard {
132 return InputEventResult::empty();
133 }
134
135 let event_target = editing_context.event_target();
137 let clipboard_event = self.fire_clipboard_event(cx, &event_target, clipboard_event_type);
138
139 let event = clipboard_event.upcast::<Event>();
140 if !event.DefaultPrevented() {
141 match clipboard_event.clipboard_event_type() {
143 ClipboardEventType::Copy if editing_context.copying_enabled() => {
144 if let Some(selection) = editing_context.selection_content(cx) {
148 self.send_to_embedder(EmbedderMsg::SetClipboardText(
149 self.webview_id(),
150 selection,
151 ));
152 }
153 self.fire_clipboard_event(cx, &event_target, ClipboardEventType::Change);
155
156 event.mark_as_handled();
158 },
159 ClipboardEventType::Cut => {
160 if let Some(selection) = editing_context.selection_content(cx) &&
161 editing_context.cutting_enabled()
162 {
163 let canceled = editing_context.fire_cut_beforeinput_event(cx);
164 if canceled {
165 return InputEventResult::empty();
166 }
167
168 self.send_to_embedder(EmbedderMsg::SetClipboardText(
174 self.webview_id(),
175 selection,
176 ));
177
178 editing_context.remove_the_contents_of_the_selection(cx);
181
182 self.fire_clipboard_event(cx, &event_target, ClipboardEventType::Change);
184
185 editing_context.fire_cut_events();
189
190 event.mark_as_handled();
192 }
193 },
194 ClipboardEventType::Paste => {
195 if editing_context.has_selection_or_cursor() &&
196 editing_context.pasting_enabled() &&
197 let Some(text_content) = clipboard_event.text_content()
198 {
199 let canceled =
200 editing_context.fire_paste_beforeinput_event(cx, &text_content);
201 if canceled {
202 return InputEventResult::empty();
203 }
204
205 editing_context.insert_content(cx, &text_content);
210
211 editing_context.fire_paste_events(&text_content);
215
216 event.mark_as_handled();
218 }
219 },
220 _ => (),
221 }
222 } else {
223 match clipboard_event.clipboard_event_type() {
225 ClipboardEventType::Copy => {
226 if let Some(clipboard_data) = clipboard_event.clipboard_data() {
229 let drag_data_store =
230 clipboard_data.data_store().expect("This shouldn't fail");
231 self.write_content_to_the_clipboard(&drag_data_store);
232 }
233 },
234 ClipboardEventType::Cut => {
235 if let Some(clipboard_data) = clipboard_event.clipboard_data() {
238 let drag_data_store =
239 clipboard_data.data_store().expect("This shouldn't fail");
240 self.write_content_to_the_clipboard(&drag_data_store);
241 }
242
243 self.fire_clipboard_event(cx, &event_target, ClipboardEventType::Change);
245 },
246 ClipboardEventType::Paste => (),
248 _ => (),
249 }
250 }
251
252 event.flags().into()
255 }
256
257 fn fire_clipboard_event(
259 &self,
260 cx: &mut JSContext,
261 target: &EventTarget,
262 clipboard_event_type: ClipboardEventType,
263 ) -> DomRoot<ClipboardEvent> {
264 let clipboard_event = ClipboardEvent::new(
265 cx,
266 self.window(),
267 None,
268 clipboard_event_type,
269 EventBubbles::Bubbles,
270 EventCancelable::Cancelable,
271 None,
272 );
273
274 let mut drag_data_store = DragDataStore::new();
277
278 let trusted = true;
282
283 match clipboard_event.clipboard_event_type() {
287 ClipboardEventType::Copy | ClipboardEventType::Cut => {
288 drag_data_store.set_mode(Mode::ReadWrite);
290 },
291 ClipboardEventType::Paste => {
292 let (callback, receiver) =
293 GenericCallback::new_blocking().expect("Could not create callback");
294 self.send_to_embedder(EmbedderMsg::GetClipboardText(self.webview_id(), callback));
295 let text_contents = receiver
296 .recv()
297 .map(Result::unwrap_or_default)
298 .unwrap_or_default();
299
300 drag_data_store.set_mode(Mode::ReadOnly);
302 if trusted {
304 let data = DOMString::from(text_contents);
308 let type_ = DOMString::from_static("text/plain");
309 let _ = drag_data_store.add(Kind::Text { data, type_ });
310
311 }
317 },
318 ClipboardEventType::Change | ClipboardEventType::Other(..) => (),
319 }
320
321 let clipboard_event_data = DataTransfer::new(
323 cx,
324 self.window(),
325 Rc::new(RefCell::new(Some(drag_data_store))),
326 );
327
328 clipboard_event.set_clipboard_data(Some(&clipboard_event_data));
330
331 let event = clipboard_event.upcast::<Event>();
333 event.set_trusted(trusted);
334
335 event.set_composed(true);
337
338 event.dispatch(cx, target, false);
340
341 DomRoot::from(clipboard_event)
342 }
343
344 fn write_content_to_the_clipboard(&self, drag_data_store: &DragDataStore) {
346 if drag_data_store.list_len() > 0 {
348 self.send_to_embedder(EmbedderMsg::ClearClipboard(self.webview_id()));
350 for item in drag_data_store.iter_item_list() {
352 match item {
353 Kind::Text { data, .. } => {
354 self.send_to_embedder(EmbedderMsg::SetClipboardText(
358 self.webview_id(),
359 data.to_string(),
360 ));
361 },
362 Kind::File { .. } => {
363 },
367 }
368 }
369 } else {
370 if drag_data_store.clear_was_called {
372 self.send_to_embedder(EmbedderMsg::ClearClipboard(self.webview_id()));
374 }
377 }
378 }
379
380 pub(crate) fn perform_editing_action(
386 &self,
387 cx: &mut JSContext,
388 editing_action: &EditingAction,
389 ) -> bool {
390 if !servo_config::pref!(dom_exec_command_enabled) {
391 return false;
392 }
393
394 let (command, argument) = match editing_action {
397 EditingAction::MoveCursor(..) |
399 EditingAction::StartComposition |
400 EditingAction::EndComposition(..) => return false,
401 EditingAction::SelectAll | EditingAction::Clipboard(_) => {
402 unreachable!("Should have been handled before this point.")
403 },
404 EditingAction::InsertNewline => {
405 (DOMString::from_static("insertlinebreak"), DOMString::new())
411 },
412 EditingAction::InsertParagraph => {
413 (DOMString::from_static("insertparagraph"), DOMString::new())
418 },
419 EditingAction::Backspace(..) => (DOMString::from_static("delete"), DOMString::new()),
426 EditingAction::Delete => (DOMString::from_static("forwarddelete"), DOMString::new()),
431 EditingAction::InsertText(text) | EditingAction::InsertCompositionText(text) => (
439 DOMString::from_static("inserttext"),
440 DOMString::from(text.as_str()),
441 ),
442 };
443
444 self.exec_command_for_command_id(cx, command, argument)
445 }
446
447 fn handle_mousedown_event(
448 &self,
449 cx: &mut JSContext,
450 mouse_event: &MouseEvent,
451 hit_test_result: &HitTestResult,
452 ) {
453 assert_eq!(mouse_event.upcast::<Event>().type_(), atom!("mousedown"));
454
455 let Some(selection) = self.GetSelection(cx) else {
456 return;
457 };
458
459 if mouse_event.button() == MouseButton::Auxiliary {
460 let _ = selection.Collapse(cx, None, 0);
461 mouse_event.upcast::<Event>().mark_as_handled();
462 return;
463 }
464
465 if mouse_event.button() != MouseButton::Primary {
466 return;
467 }
468
469 let Some(action) = MouseButtonSelectionAction::from_mouse_event(mouse_event) else {
470 return;
471 };
472
473 let boundary = hit_test_result
477 .dom_position_for_selection
478 .clone()
479 .unwrap_or_else(|| RootedSelectionBoundary::start_of(&hit_test_result.node));
480 let Some((boundary, user_select_contain_node)) =
481 adjust_anchor_for_user_select(cx, boundary)
482 else {
483 return;
484 };
485
486 let segment_data = match action {
487 MouseButtonSelectionAction::MoveCursor => {
488 selection.collapse_to_dom_position(cx, &boundary);
489 None
490 },
491 MouseButtonSelectionAction::SelectRange(granularity) => self
492 .window()
493 .query_text_segment(
494 cx,
495 &boundary.container,
496 boundary.utf32_offset(),
497 granularity,
498 )
499 .map(|(start, end)| {
500 selection.set_anchor_and_focus(cx, &start, &end);
501 (granularity, start, end)
502 }),
503 };
504
505 self.event_handler().install_drag_gesture(DragGesture::new(
506 DragHandler::DocumentSelection(DocumentSelectionDragHandler::new(
507 self,
508 user_select_contain_node.as_deref(),
509 segment_data.map(|(granularity, start, end)| DocumentDragSegment {
510 granularity,
511 range: SelectionRange::new_from_rooted(start, end),
512 }),
513 )),
514 ));
515
516 mouse_event.upcast::<Event>().mark_as_handled();
517 }
518}
519
520pub(crate) enum TextControlElementEditingContext {
521 TextArea(DomRoot<HTMLTextAreaElement>),
522 Input(DomRoot<HTMLInputElement>),
523}
524
525impl TextControlElementEditingContext {
526 fn text_control_element(&self) -> &dyn TextControlElement {
527 match self {
528 TextControlElementEditingContext::TextArea(text_area) => &**text_area,
529 TextControlElementEditingContext::Input(input) => &**input,
530 }
531 }
532
533 fn handle_mousedown_event(&self, mouse_event: &MouseEvent, hit_test_result: &HitTestResult) {
534 let text_control = self.text_control_element();
535 if text_control.text_input_mut().handle_mousedown_event(
536 text_control.as_element(),
537 mouse_event,
538 hit_test_result,
539 ) {
540 text_control.maybe_update_shared_selection();
541 mouse_event.upcast::<Event>().mark_as_handled();
542 }
543 }
544}
545
546pub(crate) enum EditingContext {
547 TextControl(TextControlElementEditingContext),
548 Document(DomRoot<Document>),
549}
550
551impl TryFrom<&Node> for EditingContext {
552 type Error = ();
553
554 fn try_from(node: &Node) -> Result<Self, Self::Error> {
555 if let Some(text_area) = node.downcast::<HTMLTextAreaElement>() {
556 return Ok(EditingContext::TextControl(
557 TextControlElementEditingContext::TextArea(DomRoot::from_ref(text_area)),
558 ));
559 }
560 if let Some(input) = node.downcast::<HTMLInputElement>() &&
561 input.is_textual_or_password()
562 {
563 return Ok(EditingContext::TextControl(
564 TextControlElementEditingContext::Input(DomRoot::from_ref(input)),
565 ));
566 }
567 Err(())
568 }
569}
570
571impl EditingContext {
572 pub(crate) fn event_target(&self) -> DomRoot<EventTarget> {
573 match self {
574 EditingContext::TextControl(element) => match element {
575 TextControlElementEditingContext::TextArea(text_area) => {
576 DomRoot::from_ref(text_area.upcast())
577 },
578 TextControlElementEditingContext::Input(input) => DomRoot::from_ref(input.upcast()),
579 },
580 EditingContext::Document(document) => {
581 document.event_handler().target_for_events_following_focus()
582 },
583 }
584 }
585
586 pub(crate) fn document(&self) -> DomRoot<Document> {
587 match self {
588 EditingContext::TextControl(element) => match element {
589 TextControlElementEditingContext::TextArea(element) => element.owner_document(),
590 TextControlElementEditingContext::Input(element) => element.owner_document(),
591 },
592 EditingContext::Document(document) => document.clone(),
593 }
594 }
595
596 pub(crate) fn selection_content(&self, cx: &mut JSContext) -> Option<String> {
597 match self {
598 EditingContext::TextControl(element) => element
599 .text_control_element()
600 .text_input()
601 .selection_content(),
602 EditingContext::Document(document) => document
603 .selection()
604 .map(|selection| selection.Stringifier(cx).to_string())
605 .filter(|selection| !selection.is_empty()),
606 }
607 }
608
609 pub(crate) fn has_uncollapsed_selection(&self) -> bool {
610 match self {
611 EditingContext::TextControl(element) => {
612 element.text_control_element().has_uncollapsed_selection()
613 },
614 EditingContext::Document(document) => document
615 .selection()
616 .is_some_and(|selection| !selection.collapsed()),
617 }
618 }
619
620 pub(crate) fn has_selectable_text(&self) -> bool {
621 match self {
622 EditingContext::TextControl(element) => {
623 element.text_control_element().has_selectable_text()
624 },
625 EditingContext::Document(..) => true,
626 }
627 }
628
629 pub(crate) fn has_selection_or_cursor(&self) -> bool {
630 match self {
631 EditingContext::TextControl(..) => true,
632 EditingContext::Document(document) => document
633 .selection()
634 .is_some_and(|selection| selection.RangeCount() > 0),
635 }
636 }
637
638 pub(crate) fn copying_enabled(&self) -> bool {
639 match self {
640 EditingContext::TextControl(element) => {
641 !element.text_control_element().is_password_field()
642 },
643 EditingContext::Document(..) => true,
644 }
645 }
646
647 pub(crate) fn cutting_enabled(&self) -> bool {
648 self.copying_enabled() && self.pasting_enabled()
651 }
652
653 pub(crate) fn pasting_enabled(&self) -> bool {
654 match self {
655 EditingContext::TextControl(element) => {
656 !element.text_control_element().read_only_or_disabled()
657 },
658 EditingContext::Document(..) => {
659 false
661 },
662 }
663 }
664
665 pub(crate) fn remove_the_contents_of_the_selection(&self, cx: &mut JSContext) {
666 match self {
667 EditingContext::TextControl(element) => {
668 element
669 .text_control_element()
670 .remove_the_contents_of_the_selection(cx);
671 },
672 EditingContext::Document(..) => {
673 },
675 }
676 }
677
678 pub(crate) fn fire_cut_beforeinput_event(&self, cx: &mut JSContext) -> bool {
680 match self {
681 EditingContext::TextControl(element) => element
682 .text_control_element()
683 .fire_beforeinput_event(cx, None, InputEventType::DeleteByCut),
684 EditingContext::Document(..) => false,
685 }
686 }
687
688 pub(crate) fn fire_paste_beforeinput_event(&self, cx: &mut JSContext, text: &str) -> bool {
690 match self {
691 EditingContext::TextControl(element) => element
692 .text_control_element()
693 .fire_beforeinput_event(cx, Some(text), InputEventType::InsertFromPaste),
694 EditingContext::Document(..) => false,
695 }
696 }
697
698 pub(crate) fn fire_cut_events(&self) {
699 match self {
700 EditingContext::TextControl(element) => {
701 element
702 .text_control_element()
703 .queue_input_event(None, InputEventType::DeleteByCut);
704 },
705 EditingContext::Document(..) => {},
706 }
707 }
708
709 pub(crate) fn insert_content(&self, cx: &mut JSContext, text_content: &str) {
710 match self {
711 EditingContext::TextControl(element) => {
712 element
713 .text_control_element()
714 .insert_content(cx, text_content);
715 },
716 EditingContext::Document(..) => {
717 },
719 }
720 }
721
722 pub(crate) fn fire_paste_events(&self, text_content: &str) {
723 match self {
724 EditingContext::TextControl(element) => {
725 element.text_control_element().queue_input_event(
726 Some(text_content.to_owned()),
727 InputEventType::InsertFromPaste,
728 );
729 },
730 EditingContext::Document(..) => {},
731 }
732 }
733
734 pub(crate) fn select_all(&self, cx: &mut JSContext) {
735 match self {
736 EditingContext::TextControl(element) => element.text_control_element().select_all(),
737 EditingContext::Document(document) => {
738 let Some(selection) = document.GetSelection(cx) else {
739 return;
740 };
741 if let Some(node) = document
742 .GetBody()
743 .map(DomRoot::upcast::<Node>)
744 .or_else(|| document.GetDocumentElement().map(DomRoot::upcast::<Node>))
745 {
746 let _ = selection.SelectAllChildren(cx, &node);
747 }
748 },
749 }
750 }
751
752 pub(crate) fn perform_editing_action(&self, cx: &mut JSContext, action: EditingAction) -> bool {
753 if let Some(node) = self.event_target().downcast::<Node>() {
754 node.owner_window().layout_reflow(cx, QueryMsg::StyleQuery);
759 if !node.is_being_rendered_or_delegates_rendering(None) {
760 return false;
761 }
762 }
763
764 if let EditingAction::Clipboard(clipboard_action) = action {
768 return self
769 .document()
770 .handle_clipboard_action(cx, self, clipboard_action)
771 .contains(InputEventResult::Consumed);
772 }
773
774 if let EditingAction::SelectAll = action {
775 self.select_all(cx);
776 return true;
777 }
778
779 match self {
780 EditingContext::TextControl(element) => element
781 .text_control_element()
782 .perform_editing_action(cx, action),
783 EditingContext::Document(document) => document.perform_editing_action(cx, &action),
784 }
785 }
786
787 pub(crate) fn handle_mousedown_event(
788 &self,
789 cx: &mut JSContext,
790 mouse_event: &MouseEvent,
791 hit_test_result: &HitTestResult,
792 ) {
793 match self {
794 EditingContext::TextControl(element) => {
795 element.handle_mousedown_event(mouse_event, hit_test_result)
796 },
797 EditingContext::Document(document) => {
798 document.handle_mousedown_event(cx, mouse_event, hit_test_result)
799 },
800 }
801 }
802}
803
804pub(crate) fn editing_action_from_keyboard_event(
805 event: &KeyboardTypesEvent,
806) -> Option<EditingAction> {
807 let mut modifiers = event.modifiers;
808 if let Some(action) = ShortcutMatcher::new(event.state, event.key.clone(), modifiers)
809 .shortcut(CMD_OR_CONTROL, 'A', || Some(EditingAction::SelectAll))
810 .shortcut(CMD_OR_CONTROL, 'C', || {
811 Some(EditingAction::Clipboard(ClipboardAction::Copy))
812 })
813 .shortcut(CMD_OR_CONTROL, 'X', || {
814 Some(EditingAction::Clipboard(ClipboardAction::Cut))
815 })
816 .shortcut(CMD_OR_CONTROL, 'V', || {
817 Some(EditingAction::Clipboard(ClipboardAction::Paste))
818 })
819 .shortcut(Modifiers::SHIFT, Key::Named(NamedKey::Enter), || {
823 Some(EditingAction::InsertNewline)
824 })
825 .shortcut(Modifiers::empty(), Key::Named(NamedKey::Enter), || {
826 Some(EditingAction::InsertParagraph)
827 })
828 .otherwise(|| None)
829 .flatten()
830 {
831 return Some(action);
832 };
833
834 let update_selection = if modifiers.contains(Modifiers::SHIFT) {
835 ModifySelection::Yes
836 } else {
837 ModifySelection::No
838 };
839 modifiers.remove(Modifiers::SHIFT);
840
841 ShortcutMatcher::new(KeyState::Down, event.key.clone(), modifiers)
842 .shortcut(Modifiers::empty(), Key::Named(NamedKey::ArrowLeft), || {
843 Some(EditingAction::MoveCursor(
844 EditingDirection::Backward,
845 EditingMotion::Grapheme,
846 update_selection,
847 ))
848 })
849 .shortcut(Modifiers::empty(), Key::Named(NamedKey::ArrowRight), || {
850 Some(EditingAction::MoveCursor(
851 EditingDirection::Forward,
852 EditingMotion::Grapheme,
853 update_selection,
854 ))
855 })
856 .shortcut(Modifiers::empty(), Key::Named(NamedKey::ArrowUp), || {
857 Some(EditingAction::MoveCursor(
858 EditingDirection::Backward,
859 EditingMotion::Line,
860 update_selection,
861 ))
862 })
863 .shortcut(Modifiers::empty(), Key::Named(NamedKey::ArrowDown), || {
864 Some(EditingAction::MoveCursor(
865 EditingDirection::Forward,
866 EditingMotion::Line,
867 update_selection,
868 ))
869 })
870 .shortcut(Modifiers::CONTROL | Modifiers::ALT, 'B', || {
871 Some(EditingAction::MoveCursor(
872 EditingDirection::Backward,
873 EditingMotion::Word,
874 update_selection,
875 ))
876 })
877 .shortcut(ALT_OR_CONTROL, Key::Named(NamedKey::ArrowLeft), || {
878 Some(EditingAction::MoveCursor(
879 EditingDirection::Backward,
880 EditingMotion::Word,
881 update_selection,
882 ))
883 })
884 .shortcut(Modifiers::CONTROL | Modifiers::ALT, 'F', || {
885 Some(EditingAction::MoveCursor(
886 EditingDirection::Forward,
887 EditingMotion::Word,
888 update_selection,
889 ))
890 })
891 .shortcut(ALT_OR_CONTROL, Key::Named(NamedKey::ArrowRight), || {
892 Some(EditingAction::MoveCursor(
893 EditingDirection::Forward,
894 EditingMotion::Word,
895 update_selection,
896 ))
897 })
898 .shortcut(Modifiers::empty(), Key::Named(NamedKey::Home), || {
899 Some(EditingAction::MoveCursor(
900 EditingDirection::Backward,
901 EditingMotion::LineStartOrEnd,
902 update_selection,
903 ))
904 })
905 .optional_shortcut(cfg!(target_os = "macos"), Modifiers::CONTROL, 'A', || {
906 Some(EditingAction::MoveCursor(
907 EditingDirection::Backward,
908 EditingMotion::LineStartOrEnd,
909 update_selection,
910 ))
911 })
912 .shortcut(Modifiers::empty(), Key::Named(NamedKey::End), || {
913 Some(EditingAction::MoveCursor(
914 EditingDirection::Forward,
915 EditingMotion::LineStartOrEnd,
916 update_selection,
917 ))
918 })
919 .optional_shortcut(cfg!(target_os = "macos"), Modifiers::CONTROL, 'E', || {
920 Some(EditingAction::MoveCursor(
921 EditingDirection::Backward,
922 EditingMotion::LineStartOrEnd,
923 update_selection,
924 ))
925 })
926 .optional_shortcut(
927 cfg!(target_os = "macos"),
928 Modifiers::META,
929 Key::Named(NamedKey::ArrowLeft),
930 || {
931 Some(EditingAction::MoveCursor(
932 EditingDirection::Backward,
933 EditingMotion::LineStartOrEnd,
934 update_selection,
935 ))
936 },
937 )
938 .optional_shortcut(
939 cfg!(target_os = "macos"),
940 Modifiers::META,
941 Key::Named(NamedKey::ArrowRight),
942 || {
943 Some(EditingAction::MoveCursor(
944 EditingDirection::Forward,
945 EditingMotion::LineStartOrEnd,
946 update_selection,
947 ))
948 },
949 )
950 .shortcut(Modifiers::empty(), Key::Named(NamedKey::PageUp), || {
951 Some(EditingAction::MoveCursor(
952 EditingDirection::Backward,
953 EditingMotion::Page,
954 update_selection,
955 ))
956 })
957 .shortcut(Modifiers::empty(), Key::Named(NamedKey::PageDown), || {
958 Some(EditingAction::MoveCursor(
959 EditingDirection::Forward,
960 EditingMotion::Page,
961 update_selection,
962 ))
963 })
964 .shortcut(Modifiers::empty(), Key::Named(NamedKey::Delete), || {
965 Some(EditingAction::Delete)
966 })
967 .shortcut(Modifiers::empty(), Key::Named(NamedKey::Backspace), || {
968 Some(EditingAction::Backspace(EditingMotion::Grapheme))
969 })
970 .shortcut(ALT_OR_CONTROL, Key::Named(NamedKey::Backspace), || {
971 Some(EditingAction::Backspace(EditingMotion::Word))
972 })
973 .optional_shortcut(
974 cfg!(target_os = "macos"),
975 Modifiers::META,
976 Key::Named(NamedKey::Backspace),
977 || Some(EditingAction::Backspace(EditingMotion::Line)),
978 )
979 .otherwise(|| match &event.key {
980 Key::Character(character) if modifiers.is_empty() => {
981 Some(EditingAction::InsertText(character.to_string()))
982 },
983 _ => None,
984 })
985 .flatten()
986}
987
988pub(crate) fn editing_action_from_composition_event(event: &CompositionEvent) -> EditingAction {
989 match event.state {
990 CompositionState::Start => EditingAction::StartComposition,
991 CompositionState::Update => EditingAction::InsertCompositionText(event.data.to_string()),
992 CompositionState::End => EditingAction::EndComposition(event.data.to_string()),
993 }
994}