1use std::ops::Range;
2
3use gpui::{
4 App, Application, Bounds, ClipboardItem, Context, CursorStyle, ElementId, ElementInputHandler,
5 Entity, EntityInputHandler, FocusHandle, Focusable, GlobalElementId, KeyBinding, Keystroke,
6 LayoutId, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad, Pixels, Point,
7 ShapedLine, SharedString, Style, TextRun, UTF16Selection, UnderlineStyle, Window, WindowBounds,
8 WindowOptions, actions, black, div, fill, hsla, opaque_grey, point, prelude::*, px, relative,
9 rgb, rgba, size, white, yellow,
10};
11use unicode_segmentation::*;
12
13actions!(
14 text_input,
15 [
16 Backspace,
17 Delete,
18 Left,
19 Right,
20 SelectLeft,
21 SelectRight,
22 SelectAll,
23 Home,
24 End,
25 ShowCharacterPalette,
26 Paste,
27 Cut,
28 Copy,
29 ]
30);
31
32struct TextInput {
33 focus_handle: FocusHandle,
34 content: SharedString,
35 placeholder: SharedString,
36 selected_range: Range<usize>,
37 selection_reversed: bool,
38 marked_range: Option<Range<usize>>,
39 last_layout: Option<ShapedLine>,
40 last_bounds: Option<Bounds<Pixels>>,
41 is_selecting: bool,
42}
43
44impl TextInput {
45 fn left(&mut self, _: &Left, _: &mut Window, cx: &mut Context<Self>) {
46 if self.selected_range.is_empty() {
47 self.move_to(self.previous_boundary(self.cursor_offset()), cx);
48 } else {
49 self.move_to(self.selected_range.start, cx)
50 }
51 }
52
53 fn right(&mut self, _: &Right, _: &mut Window, cx: &mut Context<Self>) {
54 if self.selected_range.is_empty() {
55 self.move_to(self.next_boundary(self.selected_range.end), cx);
56 } else {
57 self.move_to(self.selected_range.end, cx)
58 }
59 }
60
61 fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
62 self.select_to(self.previous_boundary(self.cursor_offset()), cx);
63 }
64
65 fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
66 self.select_to(self.next_boundary(self.cursor_offset()), cx);
67 }
68
69 fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
70 self.move_to(0, cx);
71 self.select_to(self.content.len(), cx)
72 }
73
74 fn home(&mut self, _: &Home, _: &mut Window, cx: &mut Context<Self>) {
75 self.move_to(0, cx);
76 }
77
78 fn end(&mut self, _: &End, _: &mut Window, cx: &mut Context<Self>) {
79 self.move_to(self.content.len(), cx);
80 }
81
82 fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
83 if self.selected_range.is_empty() {
84 self.select_to(self.previous_boundary(self.cursor_offset()), cx)
85 }
86 self.replace_text_in_range(None, "", window, cx)
87 }
88
89 fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
90 if self.selected_range.is_empty() {
91 self.select_to(self.next_boundary(self.cursor_offset()), cx)
92 }
93 self.replace_text_in_range(None, "", window, cx)
94 }
95
96 fn on_mouse_down(
97 &mut self,
98 event: &MouseDownEvent,
99 _window: &mut Window,
100 cx: &mut Context<Self>,
101 ) {
102 self.is_selecting = true;
103
104 if event.modifiers.shift {
105 self.select_to(self.index_for_mouse_position(event.position), cx);
106 } else {
107 self.move_to(self.index_for_mouse_position(event.position), cx)
108 }
109 }
110
111 fn on_mouse_up(&mut self, _: &MouseUpEvent, _window: &mut Window, _: &mut Context<Self>) {
112 self.is_selecting = false;
113 }
114
115 fn on_mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context<Self>) {
116 if self.is_selecting {
117 self.select_to(self.index_for_mouse_position(event.position), cx);
118 }
119 }
120
121 fn show_character_palette(
122 &mut self,
123 _: &ShowCharacterPalette,
124 window: &mut Window,
125 _: &mut Context<Self>,
126 ) {
127 window.show_character_palette();
128 }
129
130 fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
131 if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) {
132 self.replace_text_in_range(None, &text.replace("\n", " "), window, cx);
133 }
134 }
135
136 fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
137 if !self.selected_range.is_empty() {
138 cx.write_to_clipboard(ClipboardItem::new_string(
139 (&self.content[self.selected_range.clone()]).to_string(),
140 ));
141 }
142 }
143 fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
144 if !self.selected_range.is_empty() {
145 cx.write_to_clipboard(ClipboardItem::new_string(
146 (&self.content[self.selected_range.clone()]).to_string(),
147 ));
148 self.replace_text_in_range(None, "", window, cx)
149 }
150 }
151
152 fn move_to(&mut self, offset: usize, cx: &mut Context<Self>) {
153 self.selected_range = offset..offset;
154 cx.notify()
155 }
156
157 fn cursor_offset(&self) -> usize {
158 if self.selection_reversed {
159 self.selected_range.start
160 } else {
161 self.selected_range.end
162 }
163 }
164
165 fn index_for_mouse_position(&self, position: Point<Pixels>) -> usize {
166 if self.content.is_empty() {
167 return 0;
168 }
169
170 let (Some(bounds), Some(line)) = (self.last_bounds.as_ref(), self.last_layout.as_ref())
171 else {
172 return 0;
173 };
174 if position.y < bounds.top() {
175 return 0;
176 }
177 if position.y > bounds.bottom() {
178 return self.content.len();
179 }
180 line.closest_index_for_x(position.x - bounds.left())
181 }
182
183 fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
184 if self.selection_reversed {
185 self.selected_range.start = offset
186 } else {
187 self.selected_range.end = offset
188 };
189 if self.selected_range.end < self.selected_range.start {
190 self.selection_reversed = !self.selection_reversed;
191 self.selected_range = self.selected_range.end..self.selected_range.start;
192 }
193 cx.notify()
194 }
195
196 fn offset_from_utf16(&self, offset: usize) -> usize {
197 let mut utf8_offset = 0;
198 let mut utf16_count = 0;
199
200 for ch in self.content.chars() {
201 if utf16_count >= offset {
202 break;
203 }
204 utf16_count += ch.len_utf16();
205 utf8_offset += ch.len_utf8();
206 }
207
208 utf8_offset
209 }
210
211 fn offset_to_utf16(&self, offset: usize) -> usize {
212 let mut utf16_offset = 0;
213 let mut utf8_count = 0;
214
215 for ch in self.content.chars() {
216 if utf8_count >= offset {
217 break;
218 }
219 utf8_count += ch.len_utf8();
220 utf16_offset += ch.len_utf16();
221 }
222
223 utf16_offset
224 }
225
226 fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
227 self.offset_to_utf16(range.start)..self.offset_to_utf16(range.end)
228 }
229
230 fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
231 self.offset_from_utf16(range_utf16.start)..self.offset_from_utf16(range_utf16.end)
232 }
233
234 fn previous_boundary(&self, offset: usize) -> usize {
235 self.content
236 .grapheme_indices(true)
237 .rev()
238 .find_map(|(idx, _)| (idx < offset).then_some(idx))
239 .unwrap_or(0)
240 }
241
242 fn next_boundary(&self, offset: usize) -> usize {
243 self.content
244 .grapheme_indices(true)
245 .find_map(|(idx, _)| (idx > offset).then_some(idx))
246 .unwrap_or(self.content.len())
247 }
248
249 fn reset(&mut self) {
250 self.content = "".into();
251 self.selected_range = 0..0;
252 self.selection_reversed = false;
253 self.marked_range = None;
254 self.last_layout = None;
255 self.last_bounds = None;
256 self.is_selecting = false;
257 }
258}
259
260impl EntityInputHandler for TextInput {
261 fn text_for_range(
262 &mut self,
263 range_utf16: Range<usize>,
264 actual_range: &mut Option<Range<usize>>,
265 _window: &mut Window,
266 _cx: &mut Context<Self>,
267 ) -> Option<String> {
268 let range = self.range_from_utf16(&range_utf16);
269 actual_range.replace(self.range_to_utf16(&range));
270 Some(self.content[range].to_string())
271 }
272
273 fn selected_text_range(
274 &mut self,
275 _ignore_disabled_input: bool,
276 _window: &mut Window,
277 _cx: &mut Context<Self>,
278 ) -> Option<UTF16Selection> {
279 Some(UTF16Selection {
280 range: self.range_to_utf16(&self.selected_range),
281 reversed: self.selection_reversed,
282 })
283 }
284
285 fn marked_text_range(
286 &self,
287 _window: &mut Window,
288 _cx: &mut Context<Self>,
289 ) -> Option<Range<usize>> {
290 self.marked_range
291 .as_ref()
292 .map(|range| self.range_to_utf16(range))
293 }
294
295 fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
296 self.marked_range = None;
297 }
298
299 fn replace_text_in_range(
300 &mut self,
301 range_utf16: Option<Range<usize>>,
302 new_text: &str,
303 _: &mut Window,
304 cx: &mut Context<Self>,
305 ) {
306 let range = range_utf16
307 .as_ref()
308 .map(|range_utf16| self.range_from_utf16(range_utf16))
309 .or(self.marked_range.clone())
310 .unwrap_or(self.selected_range.clone());
311
312 self.content =
313 (self.content[0..range.start].to_owned() + new_text + &self.content[range.end..])
314 .into();
315 self.selected_range = range.start + new_text.len()..range.start + new_text.len();
316 self.marked_range.take();
317 cx.notify();
318 }
319
320 fn replace_and_mark_text_in_range(
321 &mut self,
322 range_utf16: Option<Range<usize>>,
323 new_text: &str,
324 new_selected_range_utf16: Option<Range<usize>>,
325 _window: &mut Window,
326 cx: &mut Context<Self>,
327 ) {
328 let range = range_utf16
329 .as_ref()
330 .map(|range_utf16| self.range_from_utf16(range_utf16))
331 .or(self.marked_range.clone())
332 .unwrap_or(self.selected_range.clone());
333
334 self.content =
335 (self.content[0..range.start].to_owned() + new_text + &self.content[range.end..])
336 .into();
337 self.marked_range = Some(range.start..range.start + new_text.len());
338 self.selected_range = new_selected_range_utf16
339 .as_ref()
340 .map(|range_utf16| self.range_from_utf16(range_utf16))
341 .map(|new_range| new_range.start + range.start..new_range.end + range.end)
342 .unwrap_or_else(|| range.start + new_text.len()..range.start + new_text.len());
343
344 cx.notify();
345 }
346
347 fn bounds_for_range(
348 &mut self,
349 range_utf16: Range<usize>,
350 bounds: Bounds<Pixels>,
351 _window: &mut Window,
352 _cx: &mut Context<Self>,
353 ) -> Option<Bounds<Pixels>> {
354 let last_layout = self.last_layout.as_ref()?;
355 let range = self.range_from_utf16(&range_utf16);
356 Some(Bounds::from_corners(
357 point(
358 bounds.left() + last_layout.x_for_index(range.start),
359 bounds.top(),
360 ),
361 point(
362 bounds.left() + last_layout.x_for_index(range.end),
363 bounds.bottom(),
364 ),
365 ))
366 }
367
368 fn character_index_for_point(
369 &mut self,
370 point: gpui::Point<Pixels>,
371 _window: &mut Window,
372 _cx: &mut Context<Self>,
373 ) -> Option<usize> {
374 let line_point = self.last_bounds?.localize(&point)?;
375 let last_layout = self.last_layout.as_ref()?;
376
377 assert_eq!(last_layout.text, self.content);
378 let utf8_index = last_layout.index_for_x(point.x - line_point.x)?;
379 Some(self.offset_to_utf16(utf8_index))
380 }
381}
382
383struct TextElement {
384 input: Entity<TextInput>,
385}
386
387struct PrepaintState {
388 line: Option<ShapedLine>,
389 cursor: Option<PaintQuad>,
390 selection: Option<PaintQuad>,
391}
392
393impl IntoElement for TextElement {
394 type Element = Self;
395
396 fn into_element(self) -> Self::Element {
397 self
398 }
399}
400
401impl Element for TextElement {
402 type RequestLayoutState = ();
403
404 type PrepaintState = PrepaintState;
405
406 fn id(&self) -> Option<ElementId> {
407 None
408 }
409
410 fn request_layout(
411 &mut self,
412 _id: Option<&GlobalElementId>,
413 window: &mut Window,
414 cx: &mut App,
415 ) -> (LayoutId, Self::RequestLayoutState) {
416 let mut style = Style::default();
417 style.size.width = relative(1.).into();
418 style.size.height = window.line_height().into();
419 (window.request_layout(style, [], cx), ())
420 }
421
422 fn prepaint(
423 &mut self,
424 _id: Option<&GlobalElementId>,
425 bounds: Bounds<Pixels>,
426 _request_layout: &mut Self::RequestLayoutState,
427 window: &mut Window,
428 cx: &mut App,
429 ) -> Self::PrepaintState {
430 let input = self.input.read(cx);
431 let content = input.content.clone();
432 let selected_range = input.selected_range.clone();
433 let cursor = input.cursor_offset();
434 let style = window.text_style();
435
436 let (display_text, text_color) = if content.is_empty() {
437 (input.placeholder.clone(), hsla(0., 0., 0., 0.2))
438 } else {
439 (content.clone(), style.color)
440 };
441
442 let run = TextRun {
443 len: display_text.len(),
444 font: style.font(),
445 color: text_color,
446 background_color: None,
447 underline: None,
448 strikethrough: None,
449 };
450 let runs = if let Some(marked_range) = input.marked_range.as_ref() {
451 vec![
452 TextRun {
453 len: marked_range.start,
454 ..run.clone()
455 },
456 TextRun {
457 len: marked_range.end - marked_range.start,
458 underline: Some(UnderlineStyle {
459 color: Some(run.color),
460 thickness: px(1.0),
461 wavy: false,
462 }),
463 ..run.clone()
464 },
465 TextRun {
466 len: display_text.len() - marked_range.end,
467 ..run.clone()
468 },
469 ]
470 .into_iter()
471 .filter(|run| run.len > 0)
472 .collect()
473 } else {
474 vec![run]
475 };
476
477 let font_size = style.font_size.to_pixels(window.rem_size());
478 let line = window
479 .text_system()
480 .shape_line(display_text, font_size, &runs)
481 .unwrap();
482
483 let cursor_pos = line.x_for_index(cursor);
484 let (selection, cursor) = if selected_range.is_empty() {
485 (
486 None,
487 Some(fill(
488 Bounds::new(
489 point(bounds.left() + cursor_pos, bounds.top()),
490 size(px(2.), bounds.bottom() - bounds.top()),
491 ),
492 gpui::blue(),
493 )),
494 )
495 } else {
496 (
497 Some(fill(
498 Bounds::from_corners(
499 point(
500 bounds.left() + line.x_for_index(selected_range.start),
501 bounds.top(),
502 ),
503 point(
504 bounds.left() + line.x_for_index(selected_range.end),
505 bounds.bottom(),
506 ),
507 ),
508 rgba(0x3311ff30),
509 )),
510 None,
511 )
512 };
513 PrepaintState {
514 line: Some(line),
515 cursor,
516 selection,
517 }
518 }
519
520 fn paint(
521 &mut self,
522 _id: Option<&GlobalElementId>,
523 bounds: Bounds<Pixels>,
524 _request_layout: &mut Self::RequestLayoutState,
525 prepaint: &mut Self::PrepaintState,
526 window: &mut Window,
527 cx: &mut App,
528 ) {
529 let focus_handle = self.input.read(cx).focus_handle.clone();
530 window.handle_input(
531 &focus_handle,
532 ElementInputHandler::new(bounds, self.input.clone()),
533 cx,
534 );
535 if let Some(selection) = prepaint.selection.take() {
536 window.paint_quad(selection)
537 }
538 let line = prepaint.line.take().unwrap();
539 line.paint(bounds.origin, window.line_height(), window, cx)
540 .unwrap();
541
542 if focus_handle.is_focused(window) {
543 if let Some(cursor) = prepaint.cursor.take() {
544 window.paint_quad(cursor);
545 }
546 }
547
548 self.input.update(cx, |input, _cx| {
549 input.last_layout = Some(line);
550 input.last_bounds = Some(bounds);
551 });
552 }
553}
554
555impl Render for TextInput {
556 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
557 div()
558 .flex()
559 .key_context("TextInput")
560 .track_focus(&self.focus_handle(cx))
561 .cursor(CursorStyle::IBeam)
562 .on_action(cx.listener(Self::backspace))
563 .on_action(cx.listener(Self::delete))
564 .on_action(cx.listener(Self::left))
565 .on_action(cx.listener(Self::right))
566 .on_action(cx.listener(Self::select_left))
567 .on_action(cx.listener(Self::select_right))
568 .on_action(cx.listener(Self::select_all))
569 .on_action(cx.listener(Self::home))
570 .on_action(cx.listener(Self::end))
571 .on_action(cx.listener(Self::show_character_palette))
572 .on_action(cx.listener(Self::paste))
573 .on_action(cx.listener(Self::cut))
574 .on_action(cx.listener(Self::copy))
575 .on_mouse_down(MouseButton::Left, cx.listener(Self::on_mouse_down))
576 .on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up))
577 .on_mouse_up_out(MouseButton::Left, cx.listener(Self::on_mouse_up))
578 .on_mouse_move(cx.listener(Self::on_mouse_move))
579 .bg(rgb(0xeeeeee))
580 .line_height(px(30.))
581 .text_size(px(24.))
582 .child(
583 div()
584 .h(px(30. + 4. * 2.))
585 .w_full()
586 .p(px(4.))
587 .bg(white())
588 .child(TextElement {
589 input: cx.entity().clone(),
590 }),
591 )
592 }
593}
594
595impl Focusable for TextInput {
596 fn focus_handle(&self, _: &App) -> FocusHandle {
597 self.focus_handle.clone()
598 }
599}
600
601struct InputExample {
602 text_input: Entity<TextInput>,
603 recent_keystrokes: Vec<Keystroke>,
604 focus_handle: FocusHandle,
605}
606
607impl Focusable for InputExample {
608 fn focus_handle(&self, _: &App) -> FocusHandle {
609 self.focus_handle.clone()
610 }
611}
612
613impl InputExample {
614 fn on_reset_click(&mut self, _: &MouseUpEvent, _window: &mut Window, cx: &mut Context<Self>) {
615 self.recent_keystrokes.clear();
616 self.text_input
617 .update(cx, |text_input, _cx| text_input.reset());
618 cx.notify();
619 }
620}
621
622impl Render for InputExample {
623 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
624 div()
625 .bg(rgb(0xaaaaaa))
626 .track_focus(&self.focus_handle(cx))
627 .flex()
628 .flex_col()
629 .size_full()
630 .child(
631 div()
632 .bg(white())
633 .border_b_1()
634 .border_color(black())
635 .flex()
636 .flex_row()
637 .justify_between()
638 .child(format!("Keyboard {}", cx.keyboard_layout().name()))
639 .child(
640 div()
641 .border_1()
642 .border_color(black())
643 .px_2()
644 .bg(yellow())
645 .child("Reset")
646 .hover(|style| {
647 style
648 .bg(yellow().blend(opaque_grey(0.5, 0.5)))
649 .cursor_pointer()
650 })
651 .on_mouse_up(MouseButton::Left, cx.listener(Self::on_reset_click)),
652 ),
653 )
654 .child(self.text_input.clone())
655 .children(self.recent_keystrokes.iter().rev().map(|ks| {
656 format!(
657 "{:} {}",
658 ks.unparse(),
659 if let Some(key_char) = ks.key_char.as_ref() {
660 format!("-> {:?}", key_char)
661 } else {
662 "".to_owned()
663 }
664 )
665 }))
666 }
667}
668
669fn main() {
670 Application::new().run(|cx: &mut App| {
671 let bounds = Bounds::centered(None, size(px(300.0), px(300.0)), cx);
672 cx.bind_keys([
673 KeyBinding::new("backspace", Backspace, None),
674 KeyBinding::new("delete", Delete, None),
675 KeyBinding::new("left", Left, None),
676 KeyBinding::new("right", Right, None),
677 KeyBinding::new("shift-left", SelectLeft, None),
678 KeyBinding::new("shift-right", SelectRight, None),
679 KeyBinding::new("cmd-a", SelectAll, None),
680 KeyBinding::new("cmd-v", Paste, None),
681 KeyBinding::new("cmd-c", Copy, None),
682 KeyBinding::new("cmd-x", Cut, None),
683 KeyBinding::new("home", Home, None),
684 KeyBinding::new("end", End, None),
685 KeyBinding::new("ctrl-cmd-space", ShowCharacterPalette, None),
686 ]);
687
688 let window = cx
689 .open_window(
690 WindowOptions {
691 window_bounds: Some(WindowBounds::Windowed(bounds)),
692 ..Default::default()
693 },
694 |_, cx| {
695 let text_input = cx.new(|cx| TextInput {
696 focus_handle: cx.focus_handle(),
697 content: "".into(),
698 placeholder: "Type here...".into(),
699 selected_range: 0..0,
700 selection_reversed: false,
701 marked_range: None,
702 last_layout: None,
703 last_bounds: None,
704 is_selecting: false,
705 });
706 cx.new(|cx| InputExample {
707 text_input,
708 recent_keystrokes: vec![],
709 focus_handle: cx.focus_handle(),
710 })
711 },
712 )
713 .unwrap();
714 let view = window.update(cx, |_, _, cx| cx.entity()).unwrap();
715 cx.observe_keystrokes(move |ev, _, cx| {
716 view.update(cx, |view, cx| {
717 view.recent_keystrokes.push(ev.keystroke.clone());
718 cx.notify();
719 })
720 })
721 .detach();
722 cx.on_keyboard_layout_change({
723 move |cx| {
724 window.update(cx, |_, _, cx| cx.notify()).ok();
725 }
726 })
727 .detach();
728
729 window
730 .update(cx, |view, window, cx| {
731 window.focus(&view.text_input.focus_handle(cx));
732 cx.activate(true);
733 })
734 .unwrap();
735 });
736}