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.shape == Shape::Fill, |field| field.h_full())
293 .when(self.frame, |field| {
294 field
295 .px(px(10.0))
296 .py(px(7.0))
297 .rounded(px(Theme::button_radius()))
298 .bg(theme.input_bg)
299 .border_1()
300 .border_color(if self.focus_handle.contains_focused(_window, cx) {
301 theme.ring
302 } else {
303 theme.border
304 })
305 })
306 .when(self.mono, |field| {
307 field.font_family(theme.font_mono.clone())
308 })
309 .text_size(px(self.metrics.size()))
310 .font_weight(self.metrics.weight)
311 .line_height(px(self.metrics.line_height()))
312 .text_color(theme.text)
313 .child(TextFieldElement { field: cx.entity() })
314 .children(self.edit_menu(_window, cx))
315 }
316}
317
318pub(super) struct TextFieldElement {
322 field: Entity<TextField>,
323}
324
325pub(super) struct FieldPrepaint {
326 lines: Vec<WrappedLine>,
327 shown: Shown,
328 glyphs: Vec<(Range<usize>, icons::Icon)>,
330 glyph_color: gpui::Hsla,
331 font_size: Pixels,
332 origin: Point<Pixels>,
334 cursor: Option<PaintQuad>,
335 covered: Option<Covered>,
336 under: Vec<PaintQuad>,
339 overdraws: Vec<overdraw::Overdraw>,
341}
342
343struct Covered {
345 layout: std::sync::Arc<gpui::LineLayout>,
346 range: Range<usize>,
348 at: Point<Pixels>,
350 color: gpui::Hsla,
351}
352
353impl IntoElement for TextFieldElement {
354 type Element = Self;
355
356 fn into_element(self) -> Self::Element {
357 self
358 }
359}
360
361impl Element for TextFieldElement {
362 type RequestLayoutState = ();
363 type PrepaintState = FieldPrepaint;
364
365 fn id(&self) -> Option<ElementId> {
366 None
367 }
368
369 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
370 None
371 }
372
373 fn request_layout(
374 &mut self,
375 _id: Option<&GlobalElementId>,
376 _inspector_id: Option<&gpui::InspectorElementId>,
377 window: &mut Window,
378 cx: &mut App,
379 ) -> (LayoutId, ()) {
380 let mut style = Style::default();
381 style.size.width = relative(1.).into();
382 let field = self.field.read(cx);
383 let line_height = field.line_height();
386 let shape = field.shape;
387
388 let (min, max) = match shape {
389 Shape::Line => {
390 style.size.height = line_height.into();
391 return (window.request_layout(style, [], cx), ());
392 }
393 Shape::Rows(rows) => {
394 style.size.height = (line_height * rows.max(1) as f32).into();
395 return (window.request_layout(style, [], cx), ());
396 }
397 Shape::Fill => {
398 style.size.height = relative(1.).into();
399 return (window.request_layout(style, [], cx), ());
400 }
401 Shape::Grow { min, max } => (min.max(1), max.max(min.max(1))),
405 };
406
407 let text = display_text(field).0.text;
408 let text_style = window.text_style();
411 let font_size = text_style.font_size.to_pixels(window.rem_size());
412 let id = window.request_measured_layout(style, move |known, available, window, _cx| {
413 let wrap_width = known.width.or(match available.width {
418 gpui::AvailableSpace::Definite(width) => Some(width),
419 _ => None,
420 });
421 let run = TextRun {
422 len: text.len(),
423 font: text_style.font(),
424 color: text_style.color,
425 background_color: None,
426 underline: None,
427 strikethrough: None,
428 };
429 let count = window
430 .text_system()
431 .shape_text(text.clone(), font_size, &[run], wrap_width, None)
432 .map(|lines| {
433 lines
434 .iter()
435 .map(|line| line.wrap_boundaries().len() + 1)
436 .sum::<usize>()
437 })
438 .unwrap_or(1);
439 gpui::size(
440 wrap_width.unwrap_or(px(0.)),
441 line_height * count.clamp(min, max) as f32,
442 )
443 });
444 (id, ())
445 }
446
447 fn prepaint(
448 &mut self,
449 _id: Option<&GlobalElementId>,
450 _inspector_id: Option<&gpui::InspectorElementId>,
451 bounds: Bounds<Pixels>,
452 _request_layout: &mut Self::RequestLayoutState,
453 window: &mut Window,
454 cx: &mut App,
455 ) -> FieldPrepaint {
456 let theme = Theme::of(cx).clone();
457 let field = self.field.read(cx);
458 let (chipped, is_placeholder) = display_text(field);
459 let shown = chipped.shown.clone();
461 let selected_range = shown.range(&field.selected_range);
462 let cursor = shown.at(field.cursor_offset());
463 let shape = field.shape;
464 let marked_range = field.marked_range.as_ref().map(|range| shown.range(range));
465 let matches: Vec<_> = field
466 .matches
467 .iter()
468 .filter(|range| {
469 range.start <= range.end
470 && field.content.is_char_boundary(range.start)
471 && field.content.is_char_boundary(range.end)
472 })
473 .map(|range| shown.range(range))
474 .collect();
475 let scrolled = field.scroll;
476 let caret_shape = cx.caret_shape();
477 let caret_height = cx.caret_height();
478 let at_start = !shape.is_multiline() && !field.focus_handle.contains_focused(window, cx);
480 let follow_caret =
481 !at_start && (field.follow_caret || caret_shape != field.last_caret_shape);
482 let style = window.text_style();
483
484 let text = chipped.text.clone();
485 let text_color = if is_placeholder {
486 theme.text_faint
487 } else {
488 style.color
489 };
490
491 let run = TextRun {
492 len: text.len(),
493 font: style.font(),
494 color: text_color,
495 background_color: None,
496 underline: None,
497 strikethrough: None,
498 };
499 let runs = if is_placeholder {
503 vec![run]
504 } else {
505 let spans: Vec<_> = field
506 .spans
507 .iter()
508 .map(|(range, kind)| (shown.range(range), *kind))
509 .collect();
510 chip_runs(
511 coloured(&text, &spans, &run, &theme.syntax),
512 &chipped,
513 text_color,
514 )
515 };
516 let runs = match marked_range.as_ref() {
517 Some(marked) => underlined(runs, marked),
518 None => runs,
519 };
520 let match_wash = theme.warning.opacity(0.25);
521 let focused = field.focus_handle.contains_focused(window, cx);
522 let mut layers = overdraw::Layers::new();
523 if !is_placeholder {
524 for range in matches.iter() {
525 layers = layers.wash(range.clone(), match_wash, ());
526 }
527 }
528 if focused && !selected_range.is_empty() {
531 layers = layers.select(selected_range.clone(), theme.selection, ());
532 }
533 let overdraws = match is_placeholder {
534 true => Vec::new(),
535 false => overdraw::overdraws(&runs, theme.bg, &layers),
536 };
537
538 let font_size = style.font_size.to_pixels(window.rem_size());
539 let line_height = field.line_height();
540 let wrap_width = shape.is_multiline().then_some(bounds.size.width);
543 let lines = window
544 .text_system()
545 .shape_text(text.clone(), font_size, &runs, wrap_width, None)
546 .map(|lines| lines.into_vec())
547 .unwrap_or_default();
548
549 let content_height: Pixels = lines.iter().map(|l| l.size(line_height).height).sum();
556 let content_width = lines.iter().map(|l| l.width()).fold(px(0.), Pixels::max);
557 let slot = (caret_shape != CaretShape::Bar)
560 .then(|| caret::zero_width(style.font(), font_size, window));
561 let follows = (!is_placeholder)
563 .then(|| {
564 lines_from(&lines)
565 .find_map(|(start, line)| {
566 (cursor <= start + line.len()).then(|| {
567 caret::character_advance(line, &line.text, cursor.saturating_sub(start))
568 })
569 })
570 .flatten()
571 })
572 .flatten();
573 let advance = slot.map(|slot| follows.unwrap_or(slot));
574 let hollow = !window.is_window_active();
575 let caret_width = caret_shape
576 .quad(
577 Bounds::new(
578 gpui::point(px(0.), px(0.)),
579 gpui::size(CARET_WIDTH, font_size),
580 ),
581 line_height,
582 caret_height,
583 advance.unwrap_or_default(),
584 theme.caret,
585 hollow,
586 )
587 .bounds
588 .size
589 .width;
590 let max = gpui::point(
592 match shape.is_multiline() {
593 true => px(0.),
594 false => (content_width + slot.unwrap_or_default() - bounds.size.width).max(px(0.)),
595 },
596 (content_height - bounds.size.height).max(px(0.)),
597 );
598 let mut scroll = gpui::point(
599 scrolled.x.clamp(px(0.), max.x),
600 scrolled.y.clamp(px(0.), max.y),
601 );
602 if follow_caret && let Some(at) = position_for_offset(&lines, cursor, line_height) {
603 if at.y < scroll.y {
604 scroll.y = at.y;
605 } else if at.y + line_height > scroll.y + bounds.size.height {
606 scroll.y = at.y + line_height - bounds.size.height;
607 }
608 if at.x < scroll.x {
611 scroll.x = at.x;
612 } else if at.x + caret_width > scroll.x + bounds.size.width {
613 scroll.x = at.x + caret_width - bounds.size.width;
614 }
615 scroll.x = scroll.x.clamp(px(0.), max.x);
616 scroll.y = scroll.y.clamp(px(0.), max.y);
617 }
618 if at_start {
619 scroll.x = px(0.);
620 }
621 self.field.update(cx, |field, _| {
622 field.scroll = scroll;
623 field.follow_caret = false;
624 field.last_caret_shape = caret_shape;
625 });
626 let origin = bounds.origin - scroll;
627
628 let under = layers
629 .painted()
630 .flat_map(|(range, color, _)| {
631 selection_rows(&lines, range, line_height)
632 .into_iter()
633 .map(move |rect| fill(Bounds::new(origin + rect.origin, rect.size), color))
634 })
635 .collect();
636
637 let caret_shown = caret_shape.shown(!hollow, crate::input::caret::inactive_caret(cx));
638 let covered =
639 (selected_range.is_empty() && follows.is_some() && caret_shape.cuts_out(hollow))
640 .then(|| {
641 let (start, line) =
642 lines_from(&lines).find(|(start, line)| cursor <= start + line.len())?;
643 let at = position_for_offset(&lines, cursor, line_height)?;
644 Some(Covered {
645 layout: line.unwrapped_layout.clone(),
646 range: cursor - start..next_boundary(&text, cursor) - start,
647 at: origin + at,
648 color: caret::cover(&runs, cursor, theme.bg, &layers, theme.caret),
649 })
650 })
651 .flatten();
652 let cursor = if selected_range.is_empty() {
653 let at = position_for_offset(&lines, cursor, line_height).unwrap_or_default();
654 caret_shown.then(|| {
655 caret_shape.quad(
656 Bounds::new(
659 origin + at + gpui::point(px(0.), (line_height - font_size) / 2.),
660 gpui::size(CARET_WIDTH, font_size),
661 ),
662 line_height,
663 caret_height,
664 advance.unwrap_or_default(),
665 theme.caret,
666 hollow,
667 )
668 })
669 } else {
670 None
671 };
672
673 FieldPrepaint {
674 lines,
675 shown,
676 glyphs: chipped.slots,
677 glyph_color: theme.text_muted,
678 font_size,
679 origin,
680 cursor,
681 covered,
682 under,
683 overdraws,
684 }
685 }
686
687 fn paint(
688 &mut self,
689 _id: Option<&GlobalElementId>,
690 _inspector_id: Option<&gpui::InspectorElementId>,
691 bounds: Bounds<Pixels>,
692 _request_layout: &mut Self::RequestLayoutState,
693 prepaint: &mut Self::PrepaintState,
694 window: &mut Window,
695 cx: &mut App,
696 ) {
697 let focus_handle = self.field.read(cx).focus_handle.clone();
698 let caret_on = self.field.read(cx).caret_on;
699 window.handle_input(
700 &focus_handle,
701 ElementInputHandler::new(bounds, self.field.clone()),
702 cx,
703 );
704 let line_height = self.field.read(cx).line_height();
705 let dragged = self.field.clone();
715 window.on_mouse_event(move |event: &MouseMoveEvent, phase, _window, cx| {
716 if phase != DispatchPhase::Bubble || !event.dragging() {
721 return;
722 }
723 dragged.update(cx, |field, cx| {
724 field.drag_to(event.position, line_height, cx);
725 });
726 });
727 let lines = std::mem::take(&mut prepaint.lines);
728 let under = std::mem::take(&mut prepaint.under);
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 under {
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 overdraw::paint(
746 lines.iter().map(|line| &***line),
747 origin,
748 line_height,
749 px(0.),
750 &prepaint.overdraws,
751 window,
752 );
753
754 if focus_handle.is_focused(window)
757 && caret_on
758 && let Some(cursor) = cursor
759 {
760 window.paint_quad(cursor);
761 if let Some(covered) = &prepaint.covered {
762 caret::paint_covered(
763 &covered.layout,
764 &covered.range,
765 covered.at,
766 line_height,
767 covered.color,
768 window,
769 );
770 }
771 }
772
773 for (slot, glyph) in &prepaint.glyphs {
774 let Some(data) = glyph.data() else { continue };
775 let (Some(start), Some(end)) = (
776 position_for_offset(&lines, slot.start, line_height),
777 position_for_offset(&lines, slot.end, line_height),
778 ) else {
779 continue;
780 };
781 let side = (end.x - start.x).min(prepaint.font_size);
782 let bounds = Bounds::new(
783 origin + start + gpui::point(px(0.), (line_height - side) / 2.),
784 gpui::size(side, side),
785 );
786 let path = SharedString::from(format!("field-glyph-{:p}", data.as_ptr()));
787 window
788 .paint_svg(
789 bounds,
790 path,
791 Some(data),
792 gpui::TransformationMatrix::unit(),
793 prepaint.glyph_color,
794 cx,
795 )
796 .ok();
797 }
798 });
799
800 let shown = std::mem::take(&mut prepaint.shown);
801 self.field.update(cx, |field, _| {
802 field.last_layout = lines;
803 field.last_shown = shown;
804 field.last_bounds = Some(bounds);
805 });
806 }
807}