1use super::*;
4use crate::AppExt as _;
5
6pub(super) fn display_text(field: &TextField) -> (chip::Chipped, bool) {
9 if field.content.is_empty() {
10 (chip::Chipped::plain(field.placeholder.clone()), true)
11 } else {
12 (chip::chipped(&field.content, &field.chips), false)
13 }
14}
15
16fn chip_runs(mut runs: Vec<TextRun>, chipped: &chip::Chipped, color: gpui::Hsla) -> Vec<TextRun> {
19 for ((slot, _), title) in chipped.slots.iter().zip(&chipped.titles) {
20 runs = caret::recoloured(runs, &(slot.start..title.end), color);
21 runs = caret::recoloured(runs, slot, gpui::transparent_black());
22 runs = underlined(runs, title);
23 }
24 runs
25}
26
27pub fn coloured(
42 text: &str,
43 spans: &[(Range<usize>, HighlightKind)],
44 base: &TextRun,
45 palette: &SyntaxPalette,
46) -> Vec<TextRun> {
47 if spans.is_empty() {
48 return vec![TextRun {
49 len: text.len(),
50 ..base.clone()
51 }];
52 }
53 let mut runs = Vec::with_capacity(spans.len() * 2 + 1);
54 let mut at = 0;
55 for (range, kind) in spans {
56 if range.start < at
57 || range.end <= range.start
58 || range.end > text.len()
59 || !text.is_char_boundary(range.start)
60 || !text.is_char_boundary(range.end)
61 {
62 continue;
63 }
64 if range.start > at {
65 runs.push(TextRun {
66 len: range.start - at,
67 ..base.clone()
68 });
69 }
70 runs.push(TextRun {
71 len: range.end - range.start,
72 color: palette.color(*kind),
73 ..base.clone()
74 });
75 at = range.end;
76 }
77 if at < text.len() {
78 runs.push(TextRun {
79 len: text.len() - at,
80 ..base.clone()
81 });
82 }
83 runs
84}
85
86pub fn underlined(runs: Vec<TextRun>, marked: &Range<usize>) -> Vec<TextRun> {
90 let mut out = Vec::with_capacity(runs.len() + 2);
91 let mut at = 0;
92 for run in runs {
93 let end = at + run.len;
94 for (start, stop, mark) in [
95 (at, end.min(marked.start), false),
96 (at.max(marked.start), end.min(marked.end), true),
97 (at.max(marked.end), end, false),
98 ] {
99 if stop <= start {
100 continue;
101 }
102 out.push(TextRun {
103 len: stop - start,
104 underline: mark.then(|| UnderlineStyle {
105 color: Some(run.color),
106 thickness: px(1.0),
107 wavy: false,
108 }),
109 ..run.clone()
110 });
111 }
112 at = end;
113 }
114 out
115}
116
117pub(super) fn lines_from(lines: &[WrappedLine]) -> impl Iterator<Item = (usize, &WrappedLine)> {
126 lines.iter().scan(0usize, |start, line| {
127 let at = *start;
128 *start = at + line.len() + 1;
129 Some((at, line))
130 })
131}
132
133pub(super) fn rows(lines: &[WrappedLine], line_height: Pixels) -> Vec<(Range<usize>, Pixels)> {
138 let mut out = Vec::new();
139 let mut top = px(0.);
140 for (start, line) in lines_from(lines) {
141 let mut row_start = start;
142 for boundary in line.wrap_boundaries() {
143 let at = start + line.runs()[boundary.run_ix].glyphs[boundary.glyph_ix].index;
144 out.push((row_start..at, top));
145 row_start = at;
146 top += line_height;
147 }
148 out.push((row_start..start + line.len(), top));
149 top += line_height;
150 }
151 out
152}
153
154pub(super) fn position_for_offset(
156 lines: &[WrappedLine],
157 offset: usize,
158 line_height: Pixels,
159) -> Option<Point<Pixels>> {
160 let mut top = px(0.);
161 for (start, line) in lines_from(lines) {
162 if offset <= start + line.len() {
163 let local = line.position_for_index(offset.saturating_sub(start), line_height)?;
164 return Some(gpui::point(local.x, local.y + top));
165 }
166 top += line.size(line_height).height;
167 }
168 None
169}
170
171pub(super) fn offset_for_position(
173 lines: &[WrappedLine],
174 position: Point<Pixels>,
175 line_height: Pixels,
176) -> usize {
177 let mut top = px(0.);
178 let mut last = 0;
179 for (start, line) in lines_from(lines) {
180 let height = line.size(line_height).height;
181 last = start + line.len();
182 if position.y < top + height {
183 let local = gpui::point(position.x, position.y - top);
184 let (Ok(index) | Err(index)) = line.closest_index_for_position(local, line_height);
185 return start + index;
186 }
187 top += height;
188 }
189 last
190}
191
192pub(super) fn floor_boundary(text: &str, offset: usize) -> usize {
194 let mut offset = offset.min(text.len());
195 while !text.is_char_boundary(offset) {
196 offset -= 1;
197 }
198 offset
199}
200
201pub(super) fn selection_rows(
207 lines: &[WrappedLine],
208 range: &Range<usize>,
209 line_height: Pixels,
210) -> Vec<Bounds<Pixels>> {
211 rows(lines, line_height)
212 .into_iter()
213 .filter(|(row, _)| range.start <= row.end && range.end >= row.start)
214 .filter_map(|(row, top)| {
215 let left = if range.start <= row.start {
216 px(0.)
217 } else {
218 position_for_offset(lines, range.start, line_height)?.x
219 };
220 let right = position_for_offset(lines, range.end.min(row.end), line_height)?.x;
221 (right > left).then(|| {
222 Bounds::from_corners(
223 gpui::point(left, top),
224 gpui::point(right, top + line_height),
225 )
226 })
227 })
228 .collect()
229}
230
231impl Render for TextField {
232 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
233 if self.focus_handle.is_focused(_window) && cx.caret_blink() {
236 if self.blink.is_none() {
237 self.start_blink(cx);
238 }
239 } else {
240 self.blink = None;
241 self.caret_on = true;
242 }
243 let theme = Theme::of(cx);
244 let mut key_context = gpui::KeyContext::default();
245 key_context.add(KEY_CONTEXT);
246 if self.shape.is_multiline() {
247 key_context.add(MULTILINE_KEY_CONTEXT);
248 }
249 if let Some(extra) = self.key_context.clone() {
250 key_context.add(extra);
251 }
252 div()
253 .key_context(key_context)
254 .track_focus(&self.focus_handle(cx))
255 .cursor(CursorStyle::IBeam)
256 .on_action(cx.listener(Self::backspace))
257 .on_action(cx.listener(Self::delete))
258 .on_action(cx.listener(Self::left))
259 .on_action(cx.listener(Self::right))
260 .on_action(cx.listener(Self::select_left))
261 .on_action(cx.listener(Self::select_right))
262 .on_action(cx.listener(Self::select_all))
263 .on_action(cx.listener(Self::home))
264 .on_action(cx.listener(Self::end))
265 .on_action(cx.listener(Self::select_home))
266 .on_action(cx.listener(Self::select_end))
267 .on_action(cx.listener(Self::word_left))
268 .on_action(cx.listener(Self::word_right))
269 .on_action(cx.listener(Self::select_word_left))
270 .on_action(cx.listener(Self::select_word_right))
271 .on_action(cx.listener(Self::up))
272 .on_action(cx.listener(Self::down))
273 .on_action(cx.listener(Self::select_up))
274 .on_action(cx.listener(Self::select_down))
275 .on_action(cx.listener(Self::insert_newline))
276 .on_action(cx.listener(Self::undo))
277 .on_action(cx.listener(Self::redo))
278 .on_action(cx.listener(Self::delete_word_left))
279 .on_action(cx.listener(Self::delete_word_right))
280 .on_action(cx.listener(Self::delete_to_line_start))
281 .on_action(cx.listener(Self::delete_to_line_end))
282 .on_action(cx.listener(Self::show_character_palette))
283 .on_action(cx.listener(Self::paste))
284 .on_action(cx.listener(Self::cut))
285 .on_action(cx.listener(Self::copy))
286 .on_mouse_down(MouseButton::Left, cx.listener(Self::on_mouse_down))
287 .on_mouse_down(MouseButton::Right, cx.listener(Self::on_right_mouse_down))
288 .on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up))
289 .on_mouse_up_out(MouseButton::Left, cx.listener(Self::on_mouse_up))
290 .on_scroll_wheel(cx.listener(Self::on_scroll_wheel))
291 .w_full()
292 .when(self.frame, |field| {
293 field
294 .px(px(10.0))
295 .py(px(7.0))
296 .rounded(px(Theme::button_radius()))
297 .bg(theme.input_bg)
298 .border_1()
299 .border_color(if self.focus_handle.contains_focused(_window, cx) {
300 theme.ring
301 } else {
302 theme.border
303 })
304 })
305 .text_size(px(self.metrics.size()))
306 .font_weight(self.metrics.weight)
307 .line_height(px(self.metrics.line_height()))
308 .text_color(theme.text)
309 .child(TextFieldElement { field: cx.entity() })
310 .children(self.edit_menu(_window, cx))
311 }
312}
313
314pub(super) struct TextFieldElement {
318 field: Entity<TextField>,
319}
320
321pub(super) struct FieldPrepaint {
322 lines: Vec<WrappedLine>,
323 shown: Shown,
324 glyphs: Vec<(Range<usize>, icons::Icon)>,
326 glyph_color: gpui::Hsla,
327 font_size: Pixels,
328 origin: Point<Pixels>,
330 cursor: Option<PaintQuad>,
331 covered: Option<Covered>,
332 matches: Vec<PaintQuad>,
334 selection: Vec<PaintQuad>,
336}
337
338struct Covered {
340 layout: std::sync::Arc<gpui::LineLayout>,
341 range: Range<usize>,
343 at: Point<Pixels>,
345 color: gpui::Hsla,
346}
347
348impl IntoElement for TextFieldElement {
349 type Element = Self;
350
351 fn into_element(self) -> Self::Element {
352 self
353 }
354}
355
356impl Element for TextFieldElement {
357 type RequestLayoutState = ();
358 type PrepaintState = FieldPrepaint;
359
360 fn id(&self) -> Option<ElementId> {
361 None
362 }
363
364 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
365 None
366 }
367
368 fn request_layout(
369 &mut self,
370 _id: Option<&GlobalElementId>,
371 _inspector_id: Option<&gpui::InspectorElementId>,
372 window: &mut Window,
373 cx: &mut App,
374 ) -> (LayoutId, ()) {
375 let mut style = Style::default();
376 style.size.width = relative(1.).into();
377 let field = self.field.read(cx);
378 let line_height = field.line_height();
381 let shape = field.shape;
382
383 let (min, max) = match shape {
384 Shape::Line => {
385 style.size.height = line_height.into();
386 return (window.request_layout(style, [], cx), ());
387 }
388 Shape::Rows(rows) => {
389 style.size.height = (line_height * rows.max(1) as f32).into();
390 return (window.request_layout(style, [], cx), ());
391 }
392 Shape::Grow { min, max } => (min.max(1), max.max(min.max(1))),
396 };
397
398 let text = display_text(field).0.text;
399 let text_style = window.text_style();
402 let font_size = text_style.font_size.to_pixels(window.rem_size());
403 let id = window.request_measured_layout(style, move |known, available, window, _cx| {
404 let wrap_width = known.width.or(match available.width {
409 gpui::AvailableSpace::Definite(width) => Some(width),
410 _ => None,
411 });
412 let run = TextRun {
413 len: text.len(),
414 font: text_style.font(),
415 color: text_style.color,
416 background_color: None,
417 underline: None,
418 strikethrough: None,
419 };
420 let count = window
421 .text_system()
422 .shape_text(text.clone(), font_size, &[run], wrap_width, None)
423 .map(|lines| {
424 lines
425 .iter()
426 .map(|line| line.wrap_boundaries().len() + 1)
427 .sum::<usize>()
428 })
429 .unwrap_or(1);
430 gpui::size(
431 wrap_width.unwrap_or(px(0.)),
432 line_height * count.clamp(min, max) as f32,
433 )
434 });
435 (id, ())
436 }
437
438 fn prepaint(
439 &mut self,
440 _id: Option<&GlobalElementId>,
441 _inspector_id: Option<&gpui::InspectorElementId>,
442 bounds: Bounds<Pixels>,
443 _request_layout: &mut Self::RequestLayoutState,
444 window: &mut Window,
445 cx: &mut App,
446 ) -> FieldPrepaint {
447 let theme = Theme::of(cx).clone();
448 let field = self.field.read(cx);
449 let (chipped, is_placeholder) = display_text(field);
450 let shown = chipped.shown.clone();
452 let selected_range = shown.range(&field.selected_range);
453 let cursor = shown.at(field.cursor_offset());
454 let shape = field.shape;
455 let marked_range = field.marked_range.as_ref().map(|range| shown.range(range));
456 let matches: Vec<_> = field
457 .matches
458 .iter()
459 .filter(|range| {
460 range.start <= range.end
461 && field.content.is_char_boundary(range.start)
462 && field.content.is_char_boundary(range.end)
463 })
464 .map(|range| shown.range(range))
465 .collect();
466 let scrolled = field.scroll;
467 let caret_shape = cx.caret_shape();
468 let caret_height = cx.caret_height();
469 let at_start = !shape.is_multiline() && !field.focus_handle.contains_focused(window, cx);
471 let follow_caret =
472 !at_start && (field.follow_caret || caret_shape != field.last_caret_shape);
473 let style = window.text_style();
474
475 let text = chipped.text.clone();
476 let text_color = if is_placeholder {
477 theme.text_faint
478 } else {
479 style.color
480 };
481
482 let run = TextRun {
483 len: text.len(),
484 font: style.font(),
485 color: text_color,
486 background_color: None,
487 underline: None,
488 strikethrough: None,
489 };
490 let runs = if is_placeholder {
494 vec![run]
495 } else {
496 let spans: Vec<_> = field
497 .spans
498 .iter()
499 .map(|(range, kind)| (shown.range(range), *kind))
500 .collect();
501 chip_runs(
502 coloured(&text, &spans, &run, &theme.syntax),
503 &chipped,
504 text_color,
505 )
506 };
507 let runs = match marked_range.as_ref() {
508 Some(marked) => underlined(runs, marked),
509 None => runs,
510 };
511
512 let font_size = style.font_size.to_pixels(window.rem_size());
513 let line_height = field.line_height();
514 let wrap_width = shape.is_multiline().then_some(bounds.size.width);
517 let lines = window
518 .text_system()
519 .shape_text(text.clone(), font_size, &runs, wrap_width, None)
520 .map(|lines| lines.into_vec())
521 .unwrap_or_default();
522
523 let content_height: Pixels = lines.iter().map(|l| l.size(line_height).height).sum();
530 let content_width = lines.iter().map(|l| l.width()).fold(px(0.), Pixels::max);
531 let slot = (caret_shape != CaretShape::Bar)
534 .then(|| caret::zero_width(style.font(), font_size, window));
535 let follows = (!is_placeholder)
537 .then(|| {
538 lines_from(&lines)
539 .find_map(|(start, line)| {
540 (cursor <= start + line.len()).then(|| {
541 caret::character_advance(line, &line.text, cursor.saturating_sub(start))
542 })
543 })
544 .flatten()
545 })
546 .flatten();
547 let advance = slot.map(|slot| follows.unwrap_or(slot));
548 let hollow = !window.is_window_active();
549 let caret_width = caret_shape
550 .quad(
551 Bounds::new(
552 gpui::point(px(0.), px(0.)),
553 gpui::size(CARET_WIDTH, font_size),
554 ),
555 line_height,
556 caret_height,
557 advance.unwrap_or_default(),
558 theme.caret,
559 hollow,
560 )
561 .bounds
562 .size
563 .width;
564 let max = gpui::point(
566 match shape.is_multiline() {
567 true => px(0.),
568 false => (content_width + slot.unwrap_or_default() - bounds.size.width).max(px(0.)),
569 },
570 (content_height - bounds.size.height).max(px(0.)),
571 );
572 let mut scroll = gpui::point(
573 scrolled.x.clamp(px(0.), max.x),
574 scrolled.y.clamp(px(0.), max.y),
575 );
576 if follow_caret && let Some(at) = position_for_offset(&lines, cursor, line_height) {
577 if at.y < scroll.y {
578 scroll.y = at.y;
579 } else if at.y + line_height > scroll.y + bounds.size.height {
580 scroll.y = at.y + line_height - bounds.size.height;
581 }
582 if at.x < scroll.x {
585 scroll.x = at.x;
586 } else if at.x + caret_width > scroll.x + bounds.size.width {
587 scroll.x = at.x + caret_width - bounds.size.width;
588 }
589 scroll.x = scroll.x.clamp(px(0.), max.x);
590 scroll.y = scroll.y.clamp(px(0.), max.y);
591 }
592 if at_start {
593 scroll.x = px(0.);
594 }
595 self.field.update(cx, |field, _| {
596 field.scroll = scroll;
597 field.follow_caret = false;
598 field.last_caret_shape = caret_shape;
599 });
600 let origin = bounds.origin - scroll;
601
602 let matches = if is_placeholder {
603 Vec::new()
604 } else {
605 matches
606 .iter()
607 .flat_map(|range| selection_rows(&lines, range, line_height))
608 .map(|rect| {
609 fill(
610 Bounds::new(origin + rect.origin, rect.size),
611 theme.warning.opacity(0.25),
612 )
613 })
614 .collect()
615 };
616
617 let caret_shown = caret_shape.shown(!hollow, crate::input::caret::inactive_caret(cx));
618 let covered =
619 (selected_range.is_empty() && follows.is_some() && caret_shape.cuts_out(hollow))
620 .then(|| {
621 let (start, line) =
622 lines_from(&lines).find(|(start, line)| cursor <= start + line.len())?;
623 let at = position_for_offset(&lines, cursor, line_height)?;
624 Some(Covered {
625 layout: line.unwrapped_layout.clone(),
626 range: cursor - start..next_boundary(&text, cursor) - start,
627 at: origin + at,
628 color: theme.bg,
629 })
630 })
631 .flatten();
632 let (selection, cursor) = if selected_range.is_empty() {
633 let at = position_for_offset(&lines, cursor, line_height).unwrap_or_default();
634 (
635 Vec::new(),
636 caret_shown.then(|| {
637 caret_shape.quad(
638 Bounds::new(
641 origin + at + gpui::point(px(0.), (line_height - font_size) / 2.),
642 gpui::size(CARET_WIDTH, font_size),
643 ),
644 line_height,
645 caret_height,
646 advance.unwrap_or_default(),
647 theme.caret,
648 hollow,
649 )
650 }),
651 )
652 } else {
653 (
654 selection_rows(&lines, &selected_range, line_height)
655 .into_iter()
656 .map(|rect| {
657 fill(
658 Bounds::new(origin + rect.origin, rect.size),
659 theme.selection,
660 )
661 })
662 .collect(),
663 None,
664 )
665 };
666
667 FieldPrepaint {
668 lines,
669 shown,
670 glyphs: chipped.slots,
671 glyph_color: theme.text_muted,
672 font_size,
673 origin,
674 cursor,
675 covered,
676 matches,
677 selection,
678 }
679 }
680
681 fn paint(
682 &mut self,
683 _id: Option<&GlobalElementId>,
684 _inspector_id: Option<&gpui::InspectorElementId>,
685 bounds: Bounds<Pixels>,
686 _request_layout: &mut Self::RequestLayoutState,
687 prepaint: &mut Self::PrepaintState,
688 window: &mut Window,
689 cx: &mut App,
690 ) {
691 let focus_handle = self.field.read(cx).focus_handle.clone();
692 let caret_on = self.field.read(cx).caret_on;
693 window.handle_input(
694 &focus_handle,
695 ElementInputHandler::new(bounds, self.field.clone()),
696 cx,
697 );
698 let line_height = self.field.read(cx).line_height();
699 let dragged = self.field.clone();
709 window.on_mouse_event(move |event: &MouseMoveEvent, phase, _window, cx| {
710 if phase != DispatchPhase::Bubble || !event.dragging() {
715 return;
716 }
717 dragged.update(cx, |field, cx| {
718 field.drag_to(event.position, line_height, cx);
719 });
720 });
721 let lines = std::mem::take(&mut prepaint.lines);
722 let matches = std::mem::take(&mut prepaint.matches);
723 let selection = match focus_handle.contains_focused(window, cx) {
726 true => std::mem::take(&mut prepaint.selection),
727 false => Vec::new(),
728 };
729 let cursor = prepaint.cursor.take();
730 let origin = prepaint.origin;
731
732 window.with_content_mask(Some(gpui::ContentMask::new(bounds)), |window| {
735 for quad in matches.into_iter().chain(selection) {
736 window.paint_quad(quad);
737 }
738
739 let mut top = origin;
740 for line in &lines {
741 line.paint(top, line_height, gpui::TextAlign::Left, None, window, cx)
742 .ok();
743 top.y += line.size(line_height).height;
744 }
745
746 if focus_handle.is_focused(window)
749 && caret_on
750 && let Some(cursor) = cursor
751 {
752 window.paint_quad(cursor);
753 if let Some(covered) = &prepaint.covered {
754 caret::paint_covered(
755 &covered.layout,
756 &covered.range,
757 covered.at,
758 line_height,
759 covered.color,
760 window,
761 );
762 }
763 }
764
765 for (slot, glyph) in &prepaint.glyphs {
766 let Some(data) = glyph.data() else { continue };
767 let (Some(start), Some(end)) = (
768 position_for_offset(&lines, slot.start, line_height),
769 position_for_offset(&lines, slot.end, line_height),
770 ) else {
771 continue;
772 };
773 let side = (end.x - start.x).min(prepaint.font_size);
774 let bounds = Bounds::new(
775 origin + start + gpui::point(px(0.), (line_height - side) / 2.),
776 gpui::size(side, side),
777 );
778 let path = SharedString::from(format!("field-glyph-{:p}", data.as_ptr()));
779 window
780 .paint_svg(
781 bounds,
782 path,
783 Some(data),
784 gpui::TransformationMatrix::unit(),
785 prepaint.glyph_color,
786 cx,
787 )
788 .ok();
789 }
790 });
791
792 let shown = std::mem::take(&mut prepaint.shown);
793 self.field.update(cx, |field, _| {
794 field.last_layout = lines;
795 field.last_shown = shown;
796 field.last_bounds = Some(bounds);
797 });
798 }
799}