1use std::ops::Range;
2
3use gpui::{
4 actions, black, div, fill, hsla, opaque_grey, point, prelude::*, px, relative, rgb, rgba, size,
5 white, yellow, App, Application, Bounds, ClipboardItem, Context, CursorStyle, ElementId,
6 ElementInputHandler, Entity, EntityInputHandler, FocusHandle, Focusable, GlobalElementId,
7 KeyBinding, Keystroke, LayoutId, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
8 PaintQuad, Pixels, Point, ShapedLine, SharedString, Style, TextRun, UTF16Selection,
9 UnderlineStyle, Window, WindowBounds, WindowOptions,
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, _: &Copy, 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
369struct TextElement {
370 input: Entity<TextInput>,
371}
372
373struct PrepaintState {
374 line: Option<ShapedLine>,
375 cursor: Option<PaintQuad>,
376 selection: Option<PaintQuad>,
377}
378
379impl IntoElement for TextElement {
380 type Element = Self;
381
382 fn into_element(self) -> Self::Element {
383 self
384 }
385}
386
387impl Element for TextElement {
388 type RequestLayoutState = ();
389
390 type PrepaintState = PrepaintState;
391
392 fn id(&self) -> Option<ElementId> {
393 None
394 }
395
396 fn request_layout(
397 &mut self,
398 _id: Option<&GlobalElementId>,
399 window: &mut Window,
400 cx: &mut App,
401 ) -> (LayoutId, Self::RequestLayoutState) {
402 let mut style = Style::default();
403 style.size.width = relative(1.).into();
404 style.size.height = window.line_height().into();
405 (window.request_layout(style, [], cx), ())
406 }
407
408 fn prepaint(
409 &mut self,
410 _id: Option<&GlobalElementId>,
411 bounds: Bounds<Pixels>,
412 _request_layout: &mut Self::RequestLayoutState,
413 window: &mut Window,
414 cx: &mut App,
415 ) -> Self::PrepaintState {
416 let input = self.input.read(cx);
417 let content = input.content.clone();
418 let selected_range = input.selected_range.clone();
419 let cursor = input.cursor_offset();
420 let style = window.text_style();
421
422 let (display_text, text_color) = if content.is_empty() {
423 (input.placeholder.clone(), hsla(0., 0., 0., 0.2))
424 } else {
425 (content.clone(), style.color)
426 };
427
428 let run = TextRun {
429 len: display_text.len(),
430 font: style.font(),
431 color: text_color,
432 background_color: None,
433 underline: None,
434 strikethrough: None,
435 };
436 let runs = if let Some(marked_range) = input.marked_range.as_ref() {
437 vec![
438 TextRun {
439 len: marked_range.start,
440 ..run.clone()
441 },
442 TextRun {
443 len: marked_range.end - marked_range.start,
444 underline: Some(UnderlineStyle {
445 color: Some(run.color),
446 thickness: px(1.0),
447 wavy: false,
448 }),
449 ..run.clone()
450 },
451 TextRun {
452 len: display_text.len() - marked_range.end,
453 ..run.clone()
454 },
455 ]
456 .into_iter()
457 .filter(|run| run.len > 0)
458 .collect()
459 } else {
460 vec![run]
461 };
462
463 let font_size = style.font_size.to_pixels(window.rem_size());
464 let line = window
465 .text_system()
466 .shape_line(display_text, font_size, &runs)
467 .unwrap();
468
469 let cursor_pos = line.x_for_index(cursor);
470 let (selection, cursor) = if selected_range.is_empty() {
471 (
472 None,
473 Some(fill(
474 Bounds::new(
475 point(bounds.left() + cursor_pos, bounds.top()),
476 size(px(2.), bounds.bottom() - bounds.top()),
477 ),
478 gpui::blue(),
479 )),
480 )
481 } else {
482 (
483 Some(fill(
484 Bounds::from_corners(
485 point(
486 bounds.left() + line.x_for_index(selected_range.start),
487 bounds.top(),
488 ),
489 point(
490 bounds.left() + line.x_for_index(selected_range.end),
491 bounds.bottom(),
492 ),
493 ),
494 rgba(0x3311ff30),
495 )),
496 None,
497 )
498 };
499 PrepaintState {
500 line: Some(line),
501 cursor,
502 selection,
503 }
504 }
505
506 fn paint(
507 &mut self,
508 _id: Option<&GlobalElementId>,
509 bounds: Bounds<Pixels>,
510 _request_layout: &mut Self::RequestLayoutState,
511 prepaint: &mut Self::PrepaintState,
512 window: &mut Window,
513 cx: &mut App,
514 ) {
515 let focus_handle = self.input.read(cx).focus_handle.clone();
516 window.handle_input(
517 &focus_handle,
518 ElementInputHandler::new(bounds, self.input.clone()),
519 cx,
520 );
521 if let Some(selection) = prepaint.selection.take() {
522 window.paint_quad(selection)
523 }
524 let line = prepaint.line.take().unwrap();
525 line.paint(bounds.origin, window.line_height(), window, cx)
526 .unwrap();
527
528 if focus_handle.is_focused(window) {
529 if let Some(cursor) = prepaint.cursor.take() {
530 window.paint_quad(cursor);
531 }
532 }
533
534 self.input.update(cx, |input, _cx| {
535 input.last_layout = Some(line);
536 input.last_bounds = Some(bounds);
537 });
538 }
539}
540
541impl Render for TextInput {
542 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
543 div()
544 .flex()
545 .key_context("TextInput")
546 .track_focus(&self.focus_handle(cx))
547 .cursor(CursorStyle::IBeam)
548 .on_action(cx.listener(Self::backspace))
549 .on_action(cx.listener(Self::delete))
550 .on_action(cx.listener(Self::left))
551 .on_action(cx.listener(Self::right))
552 .on_action(cx.listener(Self::select_left))
553 .on_action(cx.listener(Self::select_right))
554 .on_action(cx.listener(Self::select_all))
555 .on_action(cx.listener(Self::home))
556 .on_action(cx.listener(Self::end))
557 .on_action(cx.listener(Self::show_character_palette))
558 .on_action(cx.listener(Self::paste))
559 .on_action(cx.listener(Self::cut))
560 .on_action(cx.listener(Self::copy))
561 .on_mouse_down(MouseButton::Left, cx.listener(Self::on_mouse_down))
562 .on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up))
563 .on_mouse_up_out(MouseButton::Left, cx.listener(Self::on_mouse_up))
564 .on_mouse_move(cx.listener(Self::on_mouse_move))
565 .bg(rgb(0xeeeeee))
566 .line_height(px(30.))
567 .text_size(px(24.))
568 .child(
569 div()
570 .h(px(30. + 4. * 2.))
571 .w_full()
572 .p(px(4.))
573 .bg(white())
574 .child(TextElement {
575 input: cx.entity().clone(),
576 }),
577 )
578 }
579}
580
581impl Focusable for TextInput {
582 fn focus_handle(&self, _: &App) -> FocusHandle {
583 self.focus_handle.clone()
584 }
585}
586
587struct InputExample {
588 text_input: Entity<TextInput>,
589 recent_keystrokes: Vec<Keystroke>,
590 focus_handle: FocusHandle,
591}
592
593impl Focusable for InputExample {
594 fn focus_handle(&self, _: &App) -> FocusHandle {
595 self.focus_handle.clone()
596 }
597}
598
599impl InputExample {
600 fn on_reset_click(&mut self, _: &MouseUpEvent, _window: &mut Window, cx: &mut Context<Self>) {
601 self.recent_keystrokes.clear();
602 self.text_input
603 .update(cx, |text_input, _cx| text_input.reset());
604 cx.notify();
605 }
606}
607
608impl Render for InputExample {
609 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
610 div()
611 .bg(rgb(0xaaaaaa))
612 .track_focus(&self.focus_handle(cx))
613 .flex()
614 .flex_col()
615 .size_full()
616 .child(
617 div()
618 .bg(white())
619 .border_b_1()
620 .border_color(black())
621 .flex()
622 .flex_row()
623 .justify_between()
624 .child(format!("Keyboard {}", cx.keyboard_layout()))
625 .child(
626 div()
627 .border_1()
628 .border_color(black())
629 .px_2()
630 .bg(yellow())
631 .child("Reset")
632 .hover(|style| {
633 style
634 .bg(yellow().blend(opaque_grey(0.5, 0.5)))
635 .cursor_pointer()
636 })
637 .on_mouse_up(MouseButton::Left, cx.listener(Self::on_reset_click)),
638 ),
639 )
640 .child(self.text_input.clone())
641 .children(self.recent_keystrokes.iter().rev().map(|ks| {
642 format!(
643 "{:} {}",
644 ks.unparse(),
645 if let Some(key_char) = ks.key_char.as_ref() {
646 format!("-> {:?}", key_char)
647 } else {
648 "".to_owned()
649 }
650 )
651 }))
652 }
653}
654
655fn main() {
656 Application::new().run(|cx: &mut App| {
657 let bounds = Bounds::centered(None, size(px(300.0), px(300.0)), cx);
658 cx.bind_keys([
659 KeyBinding::new("backspace", Backspace, None),
660 KeyBinding::new("delete", Delete, None),
661 KeyBinding::new("left", Left, None),
662 KeyBinding::new("right", Right, None),
663 KeyBinding::new("shift-left", SelectLeft, None),
664 KeyBinding::new("shift-right", SelectRight, None),
665 KeyBinding::new("cmd-a", SelectAll, None),
666 KeyBinding::new("cmd-v", Paste, None),
667 KeyBinding::new("cmd-c", Copy, None),
668 KeyBinding::new("cmd-x", Cut, None),
669 KeyBinding::new("home", Home, None),
670 KeyBinding::new("end", End, None),
671 KeyBinding::new("ctrl-cmd-space", ShowCharacterPalette, None),
672 ]);
673
674 let window = cx
675 .open_window(
676 WindowOptions {
677 window_bounds: Some(WindowBounds::Windowed(bounds)),
678 ..Default::default()
679 },
680 |_, cx| {
681 let text_input = cx.new(|cx| TextInput {
682 focus_handle: cx.focus_handle(),
683 content: "".into(),
684 placeholder: "Type here...".into(),
685 selected_range: 0..0,
686 selection_reversed: false,
687 marked_range: None,
688 last_layout: None,
689 last_bounds: None,
690 is_selecting: false,
691 });
692 cx.new(|cx| InputExample {
693 text_input,
694 recent_keystrokes: vec![],
695 focus_handle: cx.focus_handle(),
696 })
697 },
698 )
699 .unwrap();
700 let view = window.root(cx).unwrap();
701 cx.observe_keystrokes(move |ev, _, cx| {
702 view.update(cx, |view, cx| {
703 view.recent_keystrokes.push(ev.keystroke.clone());
704 cx.notify();
705 })
706 })
707 .detach();
708 cx.on_keyboard_layout_change({
709 move |cx| {
710 window.update(cx, |_, _, cx| cx.notify()).ok();
711 }
712 })
713 .detach();
714
715 window
716 .update(cx, |view, window, cx| {
717 window.focus(&view.text_input.focus_handle(cx));
718 cx.activate(true);
719 })
720 .unwrap();
721 });
722}