use crate::editable_text::{ TextBoundary, UnicodeTextStorage, notify::{TextChanged, TextHistoryPushed}, }; use gpui::{ App, AppContext, ClipboardItem, FocusHandle, Focusable, NavigationDirection, Pixels, Point, UTF16Selection, Window, }; use std::ops::Range; pub trait TextStateNotifier { fn notify_changed(&mut self); fn emit_text_changed(&mut self, event: TextChanged); fn emit_history(&mut self, event: TextHistoryPushed); } pub struct TextInputStateBase { storage: Box, /// The utf-8 character range that is currently selected by the user. /// Valid both when start < end and start > end (which dictates the direction of the selection). Empty when start==end. /// The start of this range is always the current position of the caret (input cursor). /// /// NOTE: because each input has its own selection state, its trivial for users to have multiple selections active across multiple inputs at the same time. /// This could be considered undesirable behavior, and could prompt the question of whether there should be a mechanism to clear selection when focus is lost. selected_range: Range, /// The utf-8 character range of `storage` which is being composed by IME marked_range: Option>, /// True while the user is in the act of highlighting a section of the text (e.g. during mouse pressed & dragging). is_selecting: bool, /// The last ui location relative to the element that the user clicked. Used to filter when a user clicks multiple times in the same area. last_click_position: Option>, /// The number of times the user has clicked `last_click_position`. Used to determine which click behavior to trigger, depending on single, double, or triple clicks. click_count: usize, focus_handle: FocusHandle, } impl Focusable for TextInputStateBase { fn focus_handle(&self, _: &App) -> FocusHandle { self.focus_handle.clone() } } impl TextInputStateBase { /// Creates a new `Input` with the specified multiline setting. /// Cursor blinking is enabled by default. pub fn new(storage: impl Into>, cx: &mut App) -> Self { Self { storage: storage.into(), selected_range: 0..0, marked_range: None, is_selecting: false, last_click_position: None, click_count: 0, focus_handle: cx.focus_handle(), } } pub fn storage(&self) -> &Box { &self.storage } /// Returns the utf-8 character range that is currently selected within the current state of the text. /// Internally converts the stored direction-aware range into a canonical range. pub fn selected_range(&self) -> Range { self.selected_range.start.min(self.selected_range.end) ..self.selected_range.start.max(self.selected_range.end) } pub fn selection_direction(&self) -> Option { match self.selected_range.start.cmp(&self.selected_range.end) { std::cmp::Ordering::Less => Some(NavigationDirection::Forward), std::cmp::Ordering::Equal => None, std::cmp::Ordering::Greater => Some(NavigationDirection::Back), } } pub fn caret_pos(&self) -> usize { self.selected_range.start } pub fn set_selected_range(&mut self, range: Range) { self.selected_range = range; } } impl TextInputStateBase { pub fn ime_text_for_range( &self, range_utf16: Range, adjusted_range: &mut Option>, ) -> Option { let range = self.storage.utf_range_16to8(&range_utf16); let storage_len_utf8 = self.storage.content_utf8().len(); let clamped_range = range.start.min(storage_len_utf8)..range.end.min(storage_len_utf8); adjusted_range.replace(self.storage.utf_range_8to16(&clamped_range)); Some(self.storage.content_utf8()[clamped_range].to_string()) } pub fn ime_selected_text_range(&self, _ignore_disabled_input: bool) -> Option { let selection_range = self.selected_range(); let direction = self.selection_direction(); Some(UTF16Selection { range: self.storage.utf_range_8to16(&selection_range), reversed: direction == Some(NavigationDirection::Back), }) } pub fn ime_marked_text_range(&self) -> Option> { self.marked_range .as_ref() .map(|range| self.storage.utf_range_8to16(range)) } pub fn ime_unmark_text(&mut self) { self.marked_range = None; } pub fn ime_resolve_range(&self, range_utf16: Option>) -> Range { // Use a series of fallbacks to pick the range to operate on. // Fallback order: IME provided range, active IME marked range, selection let range = range_utf16.map(|range_utf16| self.storage.utf_range_16to8(&range_utf16)); let range = range.or_else(|| self.marked_range.clone()); let range = range.unwrap_or_else(|| self.selected_range()); let storage_len_utf8 = self.storage().content_utf8().len(); range.start.min(storage_len_utf8)..range.end.min(storage_len_utf8) } pub fn replace_text(&mut self, range: &Range, new_text: &str) { let storage_len_utf8 = self.storage.content_utf8().len(); let start = range.start.min(storage_len_utf8); let end = range.end.max(start).min(storage_len_utf8); self.storage.replace_range(start..end, new_text); let new_caret = start + new_text.len(); self.selected_range = new_caret..new_caret; } fn emit_change_for_undo( &self, cx: &mut impl TextStateNotifier, range: Range, length: usize, ) { cx.emit_history(TextHistoryPushed::new( range.clone(), length, &*self.storage, self.selected_range.clone(), )); } pub fn replace_text_in_range_bytes( &mut self, range: Range, mut text_to_insert: &str, cx: &mut impl TextStateNotifier, ) { // TODO: Apply text sanitization // single-line fields should prune \n and \r // fields should be able to provide a max_length or other validations on text-input let max_length = None::; // Decide the effective new text up front (honouring `max_length`). // This avoids the "apply, then truncate" path which would leave the caret past the end. if let Some(cap) = max_length { let existing_len = self.storage().content_utf8().len() - (range.end - range.start); let room = cap.saturating_sub(existing_len); text_to_insert = &text_to_insert[..text_to_insert.len().min(room)]; } self.emit_change_for_undo(cx, range.clone(), text_to_insert.len()); self.storage.replace_range(range, text_to_insert); self.marked_range = None; } pub fn ime_mark_text_in_range(&mut self, range: &Range, text_len: usize) { self.marked_range = match text_len { 0 => None, _ => Some(range.start..range.start + text_len), }; } pub fn ime_mark_selected_range( &mut self, range_overwritten: &Range, new_selected_range_utf16: &Option>, text_len: usize, ) { // NOTE: Differs from yororen-ui // https://github.com/MeowLynxSea/yororen-ui/blob/346502ac654b77fdaff3be2d7444fca8783acfc9/crates/yororen-ui-core/src/headless/text_input_core.rs#L359-L371 self.selected_range = { let new_range = new_selected_range_utf16.as_ref(); let new_range = new_range.map(|range_utf16| self.storage.utf_range_16to8(range_utf16)); let new_range = new_range.map(|new_range| { new_range.start + range_overwritten.start..new_range.end + range_overwritten.start }); new_range.unwrap_or_else(|| { range_overwritten.start + text_len..range_overwritten.start + text_len }) }; } } impl TextInputStateBase { fn move_to(&mut self, caret_pos: usize) { //cx.emit(CursorTrigger::PauseBlinkingForUserAction); let caret_pos = caret_pos.min(self.storage.content_utf8().len()); self.selected_range = caret_pos..caret_pos; //self.scroll_to_cursor(); //cx.notify_changed(); } fn select_to(&mut self, caret_pos: usize) { //cx.emit(CursorTrigger::PauseBlinkingForUserAction); let caret_pos = caret_pos.min(self.storage().content_utf8().len()); self.selected_range = caret_pos..self.selected_range.start; //self.scroll_to_cursor(); //cx.notify_changed(); } pub fn delete( &mut self, direction: NavigationDirection, boundary: TextBoundary, cx: &mut impl TextStateNotifier, ) { let range = self.selected_range(); let range = match range.is_empty() { false => range, true => self .storage .range_from_caret(self.caret_pos(), direction, boundary), }; self.emit_change_for_undo(cx, range.clone(), 0); self.replace_text(&range, ""); self.marked_range = None; cx.emit_text_changed(TextChanged); cx.notify_changed(); } pub fn nav_linear( &mut self, direction: NavigationDirection, boundary: TextBoundary, _cx: &mut impl TextStateNotifier, ) { let caret_pos = match self.selected_range.is_empty() { false => match direction { NavigationDirection::Back => self.selected_range.start, NavigationDirection::Forward => self.selected_range.end, }, true => self .storage .offset_from_caret(self.caret_pos(), direction, boundary), }; self.move_to(caret_pos); } pub fn select_all(&mut self, _cx: &mut impl TextStateNotifier) { self.selected_range = 0..self.storage.content_utf8().len(); } pub fn select_linear( &mut self, direction: NavigationDirection, boundary: TextBoundary, _cx: &mut impl TextStateNotifier, ) { let caret_pos = self .storage .offset_from_caret(self.caret_pos(), direction, boundary); self.select_to(caret_pos); } pub fn cut(&mut self, cx: &mut T) where T: TextStateNotifier + std::ops::Deref, { if !self.selected_range.is_empty() { // Cut selected text let slice = &self.storage.content_utf8()[self.selected_range.clone()]; cx.write_to_clipboard(ClipboardItem::new_string(slice.to_string())); self.replace_text_in_range_bytes(self.selected_range.clone(), "", cx); } else { // No selection: cut the entire current line (including newline) let caret = self.caret_pos(); let line_start = self.storage.find_line_start(caret); let line_end = self.storage.find_line_end(caret); let storage_len_utf8 = self.storage.content_utf8().len(); // Include the newline character if there is one after the line let cut_end = if line_end < storage_len_utf8 { line_end + 1 // Include the newline } else if line_start > 0 { // Last line with no trailing newline - include preceding newline instead line_end } else { line_end }; // For last line, also remove the preceding newline if it exists let cut_start = if line_end >= storage_len_utf8 && line_start > 0 { line_start - 1 // Include preceding newline for last line } else { line_start }; self.selected_range = cut_start..cut_end; let slice = &self.storage.content_utf8()[self.selected_range.clone()]; cx.write_to_clipboard(ClipboardItem::new_string(slice.to_string())); self.replace_text_in_range_bytes(self.selected_range.clone(), "", cx); } cx.emit_text_changed(TextChanged); cx.notify_changed(); } pub fn copy(&mut self, app: &mut App) { if !self.selected_range.is_empty() { let slice = &self.storage.content_utf8()[self.selected_range.clone()]; app.write_to_clipboard(ClipboardItem::new_string(slice.to_string())); } } pub fn paste(&mut self, cx: &mut T) where T: TextStateNotifier + std::ops::Deref, { let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else { return; }; self.replace_text_in_range_bytes(self.ime_resolve_range(None), &text, cx); cx.emit_text_changed(TextChanged); cx.notify_changed(); } pub fn on_mouse_down( &mut self, position: Point, character_pos: usize, click_count: usize, shift: bool, window: &mut Window, cx: &mut Context, ) where Context: TextStateNotifier + std::ops::DerefMut, { window.focus(&self.focus_handle, cx); self.is_selecting = true; let is_same_position = self .last_click_position .map(|last| { let threshold = gpui::px(4.); (position.x - last.x).abs() < threshold && (position.y - last.y).abs() < threshold }) .unwrap_or(false); if is_same_position && click_count > 1 { self.click_count = click_count; } else { self.click_count = 1; } self.last_click_position = Some(position); match self.click_count { 2 => { let (word_start, word_end) = self.storage.word_range_at(character_pos); self.selected_range = word_start..word_end; //cx.notify(); } 3 => { let line_start = self.storage.find_line_start(character_pos); let line_end = self.storage.find_line_end(character_pos); let line_end_with_newline = if line_end < self.storage.content_utf8().len() { line_end + 1 } else { line_end }; self.selected_range = line_start..line_end_with_newline; //cx.notify(); } _ => { if shift { self.select_to(character_pos); } else { self.move_to(character_pos); } } } } pub fn on_mouse_up(&mut self) { self.is_selecting = false; } pub fn on_mouse_move(&mut self, character_pos: usize, _cx: &mut impl TextStateNotifier) { if self.is_selecting && self.click_count == 1 { self.select_to(character_pos); } } }