BlueGit

ict rusty-teams

feat(composer): show Small, Large, superscript and subscript at real size while typing

- The input shapes a row as fragments of equal scale on one baseline;
  rows without scaled text keep the single shaped-line path.
- Caret, click, selection, up/down, wrap, IME bounds and scroll work across fragments.
- Sizes come from the message renderer, so input and sent message match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-09 · 7 weeks ago

Hash
6bf26611f7313502672a1209c0b6de21dc95d530
Parent
2e0d2924
13 files changed +1439 −110
ROADMAP.md +4 −4
@@ -2,7 +2,7 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 66 %** (54 done, 4 partial, 27 missing of 85). Partial counts half.
5 **Parity: 67 %** (55 done, 4 partial, 26 missing of 85). Partial counts half.
6 6
7 7 ## By area
8 8
@@ -10,7 +10,7 @@ Feature parity with the Microsoft Teams desktop client.
10 10 |---|---|---|---|---|
11 11 | [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
12 12 | [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
13 | [Reading](#reading) | 82 % | 15 | 1 | 3 |
13 | [Reading](#reading) | 87 % | 16 | 1 | 2 |
14 14 | [Writing](#writing) | 75 % | 10 | 1 | 3 |
15 15 | [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16 16 | [Channels](#channels) | 36 % | 2 | 1 | 4 |
@@ -64,7 +64,7 @@ Feature parity with the Microsoft Teams desktop client.
64 64 | Code: inline pill, block with language, copy and syntax colors | Done | |
65 65 | Lists: nested, numbered with start | Done | |
66 66 | Tables, rules, block quotes, highlight and text color | Done | |
67 | Superscript, subscript, font size | Missing | Shown as plain text |
67 | Superscript, subscript, font size | Done | Real size and baseline shift; Teams sizes xx-small 9px, x-large 24px |
68 68 | Quotes and replies | Done | |
69 69 | Reactions shown | Done | |
70 70 | Edited and deleted markers | Done | |
@@ -93,7 +93,7 @@ Feature parity with the Microsoft Teams desktop client.
93 93 | Delete own message | Done | |
94 94 | React to a message | Done | Hover bar, emoji picker, click a chip to toggle |
95 95 | Emoji picker | Partial | For reactions; composer still uses colon codes |
96 | Formatting toolbar, Ctrl+B and Ctrl+I | Done | Bar over a selection; Ctrl+U, Ctrl+Shift+X/C, Ctrl+K link; lists, quote, code block |
96 | Formatting toolbar, Ctrl+B and Ctrl+I | Done | Bar over a selection; Ctrl+U, Ctrl+Shift+X/C, Ctrl+K link; lists, quote, code block; superscript, subscript (Ctrl+Shift+= / Ctrl+=) and Small/Large shown at real size while typing |
97 97 | Attach a file, paste or drag an image | Done | Images sit in the text at the cursor as a large preview and send at that spot; files via OneDrive or the channel's Files |
98 98 | GIFs and stickers | Missing | |
99 99 | Schedule send | Missing | |
@@ -2,7 +2,7 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 66 %** (54 done, 4 partial, 27 missing of 85). Partial counts half.
5**Parity: 67 %** (55 done, 4 partial, 26 missing of 85). Partial counts half.
6
6
7## By area
7## By area
8
8
@@ -10,7 +10,7 @@ Feature parity with the Microsoft Teams desktop client.
10|---|---|---|---|---|
10|---|---|---|---|---|
11| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
11| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
12| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
12| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
13| [Reading](#reading) | 82 % | 15 | 1 | 3 |
13| [Reading](#reading) | 87 % | 16 | 1 | 2 |
14| [Writing](#writing) | 75 % | 10 | 1 | 3 |
14| [Writing](#writing) | 75 % | 10 | 1 | 3 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16| [Channels](#channels) | 36 % | 2 | 1 | 4 |
16| [Channels](#channels) | 36 % | 2 | 1 | 4 |
@@ -64,7 +64,7 @@ Feature parity with the Microsoft Teams desktop client.
64| Code: inline pill, block with language, copy and syntax colors | Done | |
64| Code: inline pill, block with language, copy and syntax colors | Done | |
65| Lists: nested, numbered with start | Done | |
65| Lists: nested, numbered with start | Done | |
66| Tables, rules, block quotes, highlight and text color | Done | |
66| Tables, rules, block quotes, highlight and text color | Done | |
67| Superscript, subscript, font size | Missing | Shown as plain text |
67| Superscript, subscript, font size | Done | Real size and baseline shift; Teams sizes xx-small 9px, x-large 24px |
68| Quotes and replies | Done | |
68| Quotes and replies | Done | |
69| Reactions shown | Done | |
69| Reactions shown | Done | |
70| Edited and deleted markers | Done | |
70| Edited and deleted markers | Done | |
@@ -93,7 +93,7 @@ Feature parity with the Microsoft Teams desktop client.
93| Delete own message | Done | |
93| Delete own message | Done | |
94| React to a message | Done | Hover bar, emoji picker, click a chip to toggle |
94| React to a message | Done | Hover bar, emoji picker, click a chip to toggle |
95| Emoji picker | Partial | For reactions; composer still uses colon codes |
95| Emoji picker | Partial | For reactions; composer still uses colon codes |
96| Formatting toolbar, Ctrl+B and Ctrl+I | Done | Bar over a selection; Ctrl+U, Ctrl+Shift+X/C, Ctrl+K link; lists, quote, code block |
96| Formatting toolbar, Ctrl+B and Ctrl+I | Done | Bar over a selection; Ctrl+U, Ctrl+Shift+X/C, Ctrl+K link; lists, quote, code block; superscript, subscript (Ctrl+Shift+= / Ctrl+=) and Small/Large shown at real size while typing |
97| Attach a file, paste or drag an image | Done | Images sit in the text at the cursor as a large preview and send at that spot; files via OneDrive or the channel's Files |
97| Attach a file, paste or drag an image | Done | Images sit in the text at the cursor as a large preview and send at that spot; files via OneDrive or the channel's Files |
98| GIFs and stickers | Missing | |
98| GIFs and stickers | Missing | |
99| Schedule send | Missing | |
99| Schedule send | Missing | |
crates/app/src/views/draft_style.rs +23 −6
@@ -2,8 +2,9 @@ use std::ops::Range;
2 2
3 3 use gpui_kit::component::input::{RangeDecoration, RangeDecorationStyle, TextDecoration};
4 4 use gpui_kit::*;
5 use teams_core::{Draft, LineKind, MarkKind, SizeStep};
5 use teams_core::{Draft, FontSize, LineKind, MarkKind, SizeStep};
6 6
7 use crate::render::blocks::{Script, StyleFlags};
7 8 use crate::theme;
8 9
9 10 const CODE_PILL_RADIUS: f32 = 4.;
@@ -60,10 +61,7 @@ fn mark_style(kind: &MarkKind) -> HighlightStyle {
60 61 color: None,
61 62 });
62 63 }
63 MarkKind::Superscript | MarkKind::Subscript | MarkKind::Size(SizeStep::Small) => {
64 style.color = Some(theme::text_soft());
65 }
66 MarkKind::Size(SizeStep::Large) => style.font_weight = Some(FontWeight::SEMIBOLD),
64 MarkKind::Superscript | MarkKind::Subscript | MarkKind::Size(_) => {}
67 65 MarkKind::Code => style.color = Some(theme::text_strong()),
68 66 MarkKind::Link(_) => {
69 67 style.color = Some(theme::accent_text());
@@ -73,6 +71,18 @@ fn mark_style(kind: &MarkKind) -> HighlightStyle {
73 71 style
74 72 }
75 73
74 fn size_flags(kind: &MarkKind) -> StyleFlags {
75 let mut flags = StyleFlags::default();
76 match kind {
77 MarkKind::Superscript => flags.script = Some(Script::Super),
78 MarkKind::Subscript => flags.script = Some(Script::Sub),
79 MarkKind::Size(SizeStep::Small) => flags.size = Some(FontSize::Small),
80 MarkKind::Size(SizeStep::Large) => flags.size = Some(FontSize::Large),
81 _ => {}
82 }
83 flags
84 }
85
76 86 /// From the start of the first line of `lines` to the end of the last; Block and Bar cover
77 87 /// every line starting inside it, ends included, so empty lines count too.
78 88 fn block_range(draft: &Draft, lines: Range<usize>) -> Range<usize> {
@@ -92,7 +102,14 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
92 102 .filter(|(_, indent)| *indent > px(0.))
93 103 .collect();
94 104 for mark in draft.marks() {
95 let decoration = TextDecoration::new(mark.range.clone(), mark_style(&mark.kind));
105 let mut decoration = TextDecoration::new(mark.range.clone(), mark_style(&mark.kind));
106 let flags = size_flags(&mark.kind);
107 if flags.is_flowed() {
108 decoration = decoration.with_font_scale(flags.font_scale());
109 if flags.baseline_raise() != 0. {
110 decoration = decoration.with_baseline_shift(flags.baseline_raise());
111 }
112 }
96 113 if mark.kind == MarkKind::Code {
97 114 text.push(decoration.with_font_family(mono.clone()));
98 115 ranges.push(
@@ -2,8 +2,9 @@ use std::ops::Range;
2
2
3use gpui_kit::component::input::{RangeDecoration, RangeDecorationStyle, TextDecoration};
3use gpui_kit::component::input::{RangeDecoration, RangeDecorationStyle, TextDecoration};
4use gpui_kit::*;
4use gpui_kit::*;
5use teams_core::{Draft, LineKind, MarkKind, SizeStep};
5use teams_core::{Draft, FontSize, LineKind, MarkKind, SizeStep};
6
6
7use crate::render::blocks::{Script, StyleFlags};
7use crate::theme;
8use crate::theme;
8
9
9const CODE_PILL_RADIUS: f32 = 4.;
10const CODE_PILL_RADIUS: f32 = 4.;
@@ -60,10 +61,7 @@ fn mark_style(kind: &MarkKind) -> HighlightStyle {
60 color: None,
61 color: None,
61 });
62 });
62 }
63 }
63 MarkKind::Superscript | MarkKind::Subscript | MarkKind::Size(SizeStep::Small) => {
64 MarkKind::Superscript | MarkKind::Subscript | MarkKind::Size(_) => {}
64 style.color = Some(theme::text_soft());
65 }
66 MarkKind::Size(SizeStep::Large) => style.font_weight = Some(FontWeight::SEMIBOLD),
67 MarkKind::Code => style.color = Some(theme::text_strong()),
65 MarkKind::Code => style.color = Some(theme::text_strong()),
68 MarkKind::Link(_) => {
66 MarkKind::Link(_) => {
69 style.color = Some(theme::accent_text());
67 style.color = Some(theme::accent_text());
@@ -73,6 +71,18 @@ fn mark_style(kind: &MarkKind) -> HighlightStyle {
73 style
71 style
74}
72}
75
73
74fn size_flags(kind: &MarkKind) -> StyleFlags {
75 let mut flags = StyleFlags::default();
76 match kind {
77 MarkKind::Superscript => flags.script = Some(Script::Super),
78 MarkKind::Subscript => flags.script = Some(Script::Sub),
79 MarkKind::Size(SizeStep::Small) => flags.size = Some(FontSize::Small),
80 MarkKind::Size(SizeStep::Large) => flags.size = Some(FontSize::Large),
81 _ => {}
82 }
83 flags
84}
85
76/// From the start of the first line of `lines` to the end of the last; Block and Bar cover
86/// From the start of the first line of `lines` to the end of the last; Block and Bar cover
77/// every line starting inside it, ends included, so empty lines count too.
87/// every line starting inside it, ends included, so empty lines count too.
78fn block_range(draft: &Draft, lines: Range<usize>) -> Range<usize> {
88fn block_range(draft: &Draft, lines: Range<usize>) -> Range<usize> {
@@ -92,7 +102,14 @@ pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
92 .filter(|(_, indent)| *indent > px(0.))
102 .filter(|(_, indent)| *indent > px(0.))
93 .collect();
103 .collect();
94 for mark in draft.marks() {
104 for mark in draft.marks() {
95 let decoration = TextDecoration::new(mark.range.clone(), mark_style(&mark.kind));
105 let mut decoration = TextDecoration::new(mark.range.clone(), mark_style(&mark.kind));
106 let flags = size_flags(&mark.kind);
107 if flags.is_flowed() {
108 decoration = decoration.with_font_scale(flags.font_scale());
109 if flags.baseline_raise() != 0. {
110 decoration = decoration.with_baseline_shift(flags.baseline_raise());
111 }
112 }
96 if mark.kind == MarkKind::Code {
113 if mark.kind == MarkKind::Code {
97 text.push(decoration.with_font_family(mono.clone()));
114 text.push(decoration.with_font_family(mono.clone()));
98 ranges.push(
115 ranges.push(
vendor/gpui-base/PATCH.md +7 −0
@@ -29,12 +29,19 @@ Upstream: crates.io `gpui-base 0.7.1` (git `87d10ae5`, `crates/base`). Wired in
29 29 | `src/input/base/state.rs`, `movement.rs`, `mode.rs` | `scroll_to`, hit testing, IME bounds, `line_and_position_for_offset` and Up / Down use the row helpers; `update_auto_grow(display_map, line_height)` counts `content_rows` | click, scroll and arrow keys land on the right row; auto grow fits the image |
30 30 | `src/input/base/mode.rs`, `element.rs` | `update_auto_grow` lets the auto-grow height exceed `max_rows` by the rows block tokens add, up to `BLOCK_GROWTH_FACTOR` (2) times `max_rows`; the textarea min height uses `mode.rows()` | an image does not use up the text row budget |
31 31 | `src/input/base/element.rs` | `layout_cursors` also follows the caret on a frame where an auto-grow viewport changed height (`viewport_changed`), not only when the selection changed | text typed after a block token, or loaded content, stays visible while the viewport is still growing |
32 | `src/input/editor/decorations.rs` | `TextDecoration.font_scale` / `baseline_shift`, `with_font_scale()` / `with_baseline_shift()`, `FontOverride.scale` / `raise`, `product_spans()` (scales multiply, first raise wins) | per-range font size and baseline shift |
33 | `src/input/editor/display_map/scaled_text.rs` (new) | `scale_pieces()`, `scaled_row()`, `row_box()`: pieces of equal scale, a shared baseline, row height = max of the base box and every piece box (Small never shrinks a row) | one rule for wrapper and painter |
34 | `src/input/editor/display_map/text_wrapper.rs`, `wrap_map.rs`, `display_map.rs` | `set_line_height()`, wrap measures every scale piece at its own size, rows taller than the line height are stored in `LineItem.blocks`, `_update(.., row_heights)` | wrap width and row tops follow the real glyph sizes |
35 | `src/input/editor/display_map/inline_line.rs` | `InlineFragment.placement` (paint offset and height), `InputLine.inline_offset` | fragments of a scaled row paint on one baseline; atomic tokens sit on it too |
36 | `src/input/base/element.rs` | `scale_font()`, `push_text_fragments()`; `layout_lines` / `layout_token_lines` build `InputLine::inline` rows for rows with scaled pieces, `prepaint_tokens` adds `inline_offset`, prepaint sets the wrapper line height | rows without scaled pieces keep the single `ShapedLine` path |
32 37
33 38 ## Limits
34 39
35 40 - Syntax-highlight (tree-sitter / LSP) bold or italic still wraps with the base font; only decorations feed wrapping.
36 41 - Hanging-indent markers are dropped by an edit inside them; the app sets them again on change.
37 42 - The unwrapped longest-line width (soft wrap off) ignores font overrides.
43 - Scaled text needs a multi-line input; an empty line has no range to scale and stays one line high.
44 - The caret is as tall as its row, not as tall as the glyph at the caret.
38 45 - Block tokens are textarea-only and need soft wrap: no folds, line numbers, ghost text or touch handles. Without soft wrap a block token shares its row with text.
39 46
40 47 ## Re-apply on a gpui-kit upgrade
@@ -29,12 +29,19 @@ Upstream: crates.io `gpui-base 0.7.1` (git `87d10ae5`, `crates/base`). Wired in
29| `src/input/base/state.rs`, `movement.rs`, `mode.rs` | `scroll_to`, hit testing, IME bounds, `line_and_position_for_offset` and Up / Down use the row helpers; `update_auto_grow(display_map, line_height)` counts `content_rows` | click, scroll and arrow keys land on the right row; auto grow fits the image |
29| `src/input/base/state.rs`, `movement.rs`, `mode.rs` | `scroll_to`, hit testing, IME bounds, `line_and_position_for_offset` and Up / Down use the row helpers; `update_auto_grow(display_map, line_height)` counts `content_rows` | click, scroll and arrow keys land on the right row; auto grow fits the image |
30| `src/input/base/mode.rs`, `element.rs` | `update_auto_grow` lets the auto-grow height exceed `max_rows` by the rows block tokens add, up to `BLOCK_GROWTH_FACTOR` (2) times `max_rows`; the textarea min height uses `mode.rows()` | an image does not use up the text row budget |
30| `src/input/base/mode.rs`, `element.rs` | `update_auto_grow` lets the auto-grow height exceed `max_rows` by the rows block tokens add, up to `BLOCK_GROWTH_FACTOR` (2) times `max_rows`; the textarea min height uses `mode.rows()` | an image does not use up the text row budget |
31| `src/input/base/element.rs` | `layout_cursors` also follows the caret on a frame where an auto-grow viewport changed height (`viewport_changed`), not only when the selection changed | text typed after a block token, or loaded content, stays visible while the viewport is still growing |
31| `src/input/base/element.rs` | `layout_cursors` also follows the caret on a frame where an auto-grow viewport changed height (`viewport_changed`), not only when the selection changed | text typed after a block token, or loaded content, stays visible while the viewport is still growing |
32| `src/input/editor/decorations.rs` | `TextDecoration.font_scale` / `baseline_shift`, `with_font_scale()` / `with_baseline_shift()`, `FontOverride.scale` / `raise`, `product_spans()` (scales multiply, first raise wins) | per-range font size and baseline shift |
33| `src/input/editor/display_map/scaled_text.rs` (new) | `scale_pieces()`, `scaled_row()`, `row_box()`: pieces of equal scale, a shared baseline, row height = max of the base box and every piece box (Small never shrinks a row) | one rule for wrapper and painter |
34| `src/input/editor/display_map/text_wrapper.rs`, `wrap_map.rs`, `display_map.rs` | `set_line_height()`, wrap measures every scale piece at its own size, rows taller than the line height are stored in `LineItem.blocks`, `_update(.., row_heights)` | wrap width and row tops follow the real glyph sizes |
35| `src/input/editor/display_map/inline_line.rs` | `InlineFragment.placement` (paint offset and height), `InputLine.inline_offset` | fragments of a scaled row paint on one baseline; atomic tokens sit on it too |
36| `src/input/base/element.rs` | `scale_font()`, `push_text_fragments()`; `layout_lines` / `layout_token_lines` build `InputLine::inline` rows for rows with scaled pieces, `prepaint_tokens` adds `inline_offset`, prepaint sets the wrapper line height | rows without scaled pieces keep the single `ShapedLine` path |
32
37
33## Limits
38## Limits
34
39
35- Syntax-highlight (tree-sitter / LSP) bold or italic still wraps with the base font; only decorations feed wrapping.
40- Syntax-highlight (tree-sitter / LSP) bold or italic still wraps with the base font; only decorations feed wrapping.
36- Hanging-indent markers are dropped by an edit inside them; the app sets them again on change.
41- Hanging-indent markers are dropped by an edit inside them; the app sets them again on change.
37- The unwrapped longest-line width (soft wrap off) ignores font overrides.
42- The unwrapped longest-line width (soft wrap off) ignores font overrides.
43- Scaled text needs a multi-line input; an empty line has no range to scale and stays one line high.
44- The caret is as tall as its row, not as tall as the glyph at the caret.
38- Block tokens are textarea-only and need soft wrap: no folds, line numbers, ghost text or touch handles. Without soft wrap a block token shares its row with text.
45- Block tokens are textarea-only and need soft wrap: no folds, line numbers, ghost text or touch handles. Without soft wrap a block token shares its row with text.
39
46
40## Re-apply on a gpui-kit upgrade
47## Re-apply on a gpui-kit upgrade
vendor/gpui-base/src/input/base/element.rs +195 −53
@@ -21,8 +21,11 @@ use crate::{
21 21 input::{
22 22 RopeExt as _,
23 23 blink_cursor::CURSOR_WIDTH,
24 decorations::font_override_spans,
25 display_map::{InlineMetric, LineLayout, split_run_by_font_overrides},
24 decorations::{FontOverride, font_override_spans},
25 display_map::{
26 InlineFragment, InlineMetric, InputLine, LineLayout, ScaledRow, scaled_row,
27 split_run_by_font_overrides,
28 },
26 29 },
27 30 };
28 31
@@ -1936,14 +1939,15 @@ impl<M: InputModeKind> TextElement<M> {
1936 1939 last_layout: &LastLayout,
1937 1940 font_size: Pixels,
1938 1941 runs: &[TextRun],
1942 font_overrides: &[(Range<usize>, FontOverride)],
1939 1943 window: &mut Window,
1940 1944 ) -> Vec<LineLayout> {
1941 use crate::input::display_map::{InlineFragment, InputLine};
1942 1945 let spans = state.token_spans();
1943 1946 let cache = state
1944 1947 .token_layout_cache
1945 1948 .as_ref()
1946 1949 .expect("tokens measured before shaping");
1950 let scale_font = scale_font(font_overrides, window);
1947 1951 let mut run_offset = 0;
1948 1952 last_layout
1949 1953 .visible_buffer_lines
@@ -1963,6 +1967,16 @@ impl<M: InputModeKind> TextElement<M> {
1963 1967 };
1964 1968 let mut lines: SmallVec<[InputLine; 1]> = SmallVec::new();
1965 1969 for range in ranges {
1970 let scaled = scale_font.as_ref().and_then(|font| {
1971 scaled_row(
1972 window.text_system(),
1973 font,
1974 font_size,
1975 last_layout.line_height,
1976 line_start + range.start..line_start + range.end,
1977 font_overrides,
1978 )
1979 });
1966 1980 let mut fragments = Vec::new();
1967 1981 let mut block_height = None;
1968 1982 let mut offset = range.start;
@@ -1975,21 +1989,18 @@ impl<M: InputModeKind> TextElement<M> {
1975 1989 {
1976 1990 let local = span.range().start - line_start..span.range().end - line_start;
1977 1991 if offset < local.start {
1978 let part = offset..local.start;
1979 let shaped = window.text_system().shape_line(
1980 text[part.clone()].to_owned().into(),
1992 push_text_fragments(
1993 window,
1994 &text,
1995 offset..local.start,
1996 range.start,
1997 line_start,
1998 scaled.as_ref(),
1981 1999 font_size,
1982 &runs_for_range(runs, run_offset, &part),
1983 None,
2000 |part| runs_for_range(runs, run_offset, part),
2001 &mut x,
2002 &mut fragments,
1984 2003 );
1985 let width = shaped.width;
1986 fragments.push(InlineFragment {
1987 range: part.start - range.start..part.end - range.start,
1988 x,
1989 width,
1990 text: Some(shaped),
1991 });
1992 x += width;
1993 2004 }
1994 2005 let token_size = cache.sizes.get(span.token()).copied().unwrap_or_default();
1995 2006 let width = token_size.width;
@@ -2001,30 +2012,36 @@ impl<M: InputModeKind> TextElement<M> {
2001 2012 x,
2002 2013 width,
2003 2014 text: None,
2015 placement: None,
2004 2016 });
2005 2017 x += width;
2006 2018 offset = local.end;
2007 2019 }
2008 2020 if offset < range.end {
2009 let part = offset..range.end;
2010 let shaped = window.text_system().shape_line(
2011 text[part.clone()].to_owned().into(),
2021 push_text_fragments(
2022 window,
2023 &text,
2024 offset..range.end,
2025 range.start,
2026 line_start,
2027 scaled.as_ref(),
2012 2028 font_size,
2013 &runs_for_range(runs, run_offset, &part),
2014 None,
2029 |part| runs_for_range(runs, run_offset, part),
2030 &mut x,
2031 &mut fragments,
2015 2032 );
2016 let width = shaped.width;
2017 fragments.push(InlineFragment {
2018 range: part.start - range.start..part.end - range.start,
2019 x,
2020 width,
2021 text: Some(shaped),
2022 });
2023 2033 }
2024 lines.push(
2025 InputLine::inline(text[range].to_owned().into(), fragments)
2026 .with_height(block_height),
2027 );
2034 let mut line = InputLine::inline(text[range].to_owned().into(), fragments)
2035 .with_height(block_height);
2036 if let Some(scaled) = &scaled {
2037 let row_box = scaled.row_box;
2038 line = line
2039 .with_height(
2040 block_height.or(row_box.custom_height(last_layout.line_height)),
2041 )
2042 .with_inline_offset(row_box.baseline - row_box.base_baseline);
2043 }
2044 lines.push(line);
2028 2045 }
2029 2046 let indent = state.display_map.line(row).map_or(0, |line| line.indent);
2030 2047 let wrap_indent = if indent > 0 && lines.len() > 1 {
@@ -2083,9 +2100,13 @@ impl<M: InputModeKind> TextElement<M> {
2083 2100 if let Some(position) =
2084 2101 layout.lines[ix].position_for_index(span.range().start - start, layout, false)
2085 2102 {
2103 let baseline_offset =
2104 layout.lines[ix].inline_offset_at(position.y, layout.line_height);
2086 2105 placements.push((
2087 2106 state.token_context(span, layout.line_height, width),
2088 bounds.origin + position + point(layout.line_number_width, y),
2107 bounds.origin
2108 + position
2109 + point(layout.line_number_width, y + baseline_offset),
2089 2110 ));
2090 2111 }
2091 2112 }
@@ -2130,13 +2151,21 @@ impl<M: InputModeKind> TextElement<M> {
2130 2151 last_layout: &LastLayout,
2131 2152 font_size: Pixels,
2132 2153 runs: &[TextRun],
2154 font_overrides: &[(Range<usize>, FontOverride)],
2133 2155 bg_segments: &[(Range<usize>, Hsla)],
2134 2156 whitespace_indicators: Option<WhitespaceIndicators>,
2135 2157 window: &mut Window,
2136 2158 ) -> Vec<LineLayout> {
2137 2159 let is_single_line = state.is_single_line();
2138 2160 if state.tokens_visible() {
2139 return Self::layout_token_lines(state, last_layout, font_size, runs, window);
2161 return Self::layout_token_lines(
2162 state,
2163 last_layout,
2164 font_size,
2165 runs,
2166 font_overrides,
2167 window,
2168 );
2140 2169 }
2141 2170
2142 2171 if is_single_line {
@@ -2179,6 +2208,7 @@ impl<M: InputModeKind> TextElement<M> {
2179 2208 return vec![line_layout];
2180 2209 }
2181 2210
2211 let scale_font = scale_font(font_overrides, window);
2182 2212 let mut lines = Vec::with_capacity(last_layout.visible_buffer_lines.len());
2183 2213 // run_offset tracks position in the runs vec coordinate space (only visible line bytes).
2184 2214 // This is separate from the visible_text offset because runs from highlight_lines
@@ -2194,30 +2224,68 @@ impl<M: InputModeKind> TextElement<M> {
2194 2224
2195 2225 debug_assert_eq!(line_item.len(), line_text.len());
2196 2226
2197 let mut wrapped_lines: SmallVec<[ShapedLine; 1]> = SmallVec::with_capacity(1);
2227 let mut wrapped_lines: SmallVec<[InputLine; 1]> = SmallVec::with_capacity(1);
2198 2228 let mut line_has_background = false;
2229 let line_start = last_layout.visible_line_byte_offsets[vi];
2199 2230
2200 2231 for range in &line_item.wrapped_lines {
2201 let line_runs = runs_for_range(runs, run_offset, &range);
2202 let line_runs = if bg_segments.is_empty() {
2203 line_runs
2204 } else {
2205 split_runs_by_bg_segments(
2206 last_layout.visible_line_byte_offsets[vi] + (range.start),
2207 &line_runs,
2208 bg_segments,
2232 let scaled = scale_font.as_ref().and_then(|font| {
2233 scaled_row(
2234 window.text_system(),
2235 font,
2236 font_size,
2237 last_layout.line_height,
2238 line_start + range.start..line_start + range.end,
2239 font_overrides,
2209 2240 )
2241 });
2242 let part_runs = |part: &Range<usize>| {
2243 let line_runs = runs_for_range(runs, run_offset, part);
2244 let line_runs = if bg_segments.is_empty() {
2245 line_runs
2246 } else {
2247 split_runs_by_bg_segments(line_start + part.start, &line_runs, bg_segments)
2248 };
2249 align_runs_to_char_boundaries(&line_text[part.clone()], &line_runs)
2250 .unwrap_or(line_runs)
2210 2251 };
2211 2252
2253 if let Some(scaled) = scaled {
2254 let mut fragments = Vec::new();
2255 let mut x = px(0.);
2256 push_text_fragments(
2257 window,
2258 &line_text,
2259 range.clone(),
2260 range.start,
2261 line_start,
2262 Some(&scaled),
2263 font_size,
2264 |part| {
2265 let line_runs = part_runs(part);
2266 line_has_background |= has_background(&line_runs);
2267 line_runs
2268 },
2269 &mut x,
2270 &mut fragments,
2271 );
2272 let row_box = scaled.row_box;
2273 wrapped_lines.push(
2274 InputLine::inline(line_text[range.clone()].to_string().into(), fragments)
2275 .with_height(row_box.custom_height(last_layout.line_height))
2276 .with_inline_offset(row_box.baseline - row_box.base_baseline),
2277 );
2278 continue;
2279 }
2280
2281 let line_runs = part_runs(range);
2212 2282 let sub_line: SharedString = line_text[range.clone()].to_string().into();
2213 let line_runs =
2214 align_runs_to_char_boundaries(&sub_line, &line_runs).unwrap_or(line_runs);
2215 2283 let shaped_line = window
2216 2284 .text_system()
2217 2285 .shape_line(sub_line, font_size, &line_runs, None);
2218 2286
2219 2287 line_has_background |= has_background(&line_runs);
2220 wrapped_lines.push(shaped_line);
2288 wrapped_lines.push(shaped_line.into());
2221 2289 }
2222 2290
2223 2291 // Use the first visual line's indentation width for continuation lines.
@@ -2233,13 +2301,9 @@ impl<M: InputModeKind> TextElement<M> {
2233 2301 };
2234 2302
2235 2303 let line_layout = LineLayout::new()
2236 .lines(wrapped_lines)
2304 .inline_lines(wrapped_lines)
2237 2305 .wrap_indent(wrap_indent)
2238 .first_indent(
2239 state
2240 .display_map
2241 .line_indent(last_layout.visible_line_byte_offsets[vi]),
2242 )
2306 .first_indent(state.display_map.line_indent(line_start))
2243 2307 .with_background(line_has_background)
2244 2308 .with_whitespaces(whitespace_indicators.clone());
2245 2309 lines.push(line_layout);
@@ -2650,7 +2714,7 @@ impl<M: InputModeKind> Element for TextElement<M> {
2650 2714 // At least `rows` tall (auto grow: the content's rows, capped at
2651 2715 // `max_rows` plus the rows of block tokens); a taller parent still fills it.
2652 2716 let rows = state.mode.rows();
2653 style.min_size.height = (rows * line_height).into();
2717 style.min_size.height = (rows * line_height + state.mode.grow_extra()).into();
2654 2718 } else {
2655 2719 // For single-line inputs, the minimum height should be the line height
2656 2720 style.size.height = line_height.into();
@@ -2688,10 +2752,20 @@ impl<M: InputModeKind> Element for TextElement<M> {
2688 2752 };
2689 2753 self.state.update(cx, |state, cx| {
2690 2754 state.display_map.set_font(font, text_size, cx);
2755 state.display_map.set_line_height(window.line_height(), cx);
2691 2756 state.display_map.ensure_text_prepared(&state.text, cx);
2692 2757 state
2693 2758 .display_map
2694 2759 .set_font_overrides(font_overrides.clone(), cx);
2760 if state.mode.is_auto_grow() {
2761 let (rows, extra) = (state.mode.rows(), state.mode.grow_extra());
2762 state
2763 .mode
2764 .update_auto_grow(&state.display_map, window.line_height());
2765 if (state.mode.rows(), state.mode.grow_extra()) != (rows, extra) {
2766 cx.notify();
2767 }
2768 }
2695 2769 });
2696 2770
2697 2771 let state = self.state.read(cx);
@@ -2887,6 +2961,7 @@ impl<M: InputModeKind> Element for TextElement<M> {
2887 2961 &last_layout,
2888 2962 text_size,
2889 2963 &runs,
2964 &font_overrides,
2890 2965 &document_colors,
2891 2966 whitespace_indicators,
2892 2967 window,
@@ -3522,6 +3597,69 @@ fn placeholder_line_runs<'a>(
3522 3597 result
3523 3598 }
3524 3599
3600 fn scale_font(
3601 font_overrides: &[(Range<usize>, FontOverride)],
3602 window: &Window,
3603 ) -> Option<gpui::Font> {
3604 font_overrides
3605 .iter()
3606 .any(|(_, font_override)| font_override.scale.is_some() || font_override.raise.is_some())
3607 .then(|| window.text_style().font())
3608 }
3609
3610 #[allow(clippy::too_many_arguments)]
3611 fn push_text_fragments(
3612 window: &Window,
3613 line_text: &str,
3614 part: Range<usize>,
3615 row_start: usize,
3616 line_start: usize,
3617 scaled: Option<&ScaledRow>,
3618 font_size: Pixels,
3619 mut part_runs: impl FnMut(&Range<usize>) -> Vec<TextRun>,
3620 x: &mut Pixels,
3621 fragments: &mut Vec<InlineFragment>,
3622 ) {
3623 let mut push =
3624 |local: Range<usize>, size: Pixels, placement_of: Option<(&ScaledRow, Pixels)>| {
3625 let shaped = window.text_system().shape_line(
3626 line_text[local.clone()].to_owned().into(),
3627 size,
3628 &part_runs(&local),
3629 None,
3630 );
3631 let width = shaped.width;
3632 let placement = placement_of.map(|(scaled, raise)| {
3633 (
3634 scaled.row_box.baseline - raise - shaped.ascent,
3635 shaped.ascent + shaped.descent,
3636 )
3637 });
3638 fragments.push(InlineFragment {
3639 range: local.start - row_start..local.end - row_start,
3640 x: *x,
3641 width,
3642 text: Some(shaped),
3643 placement,
3644 });
3645 *x += width;
3646 };
3647 match scaled {
3648 None => push(part, font_size, None),
3649 Some(scaled) => {
3650 for (range, row_piece) in
3651 scaled.pieces_in(line_start + part.start..line_start + part.end)
3652 {
3653 push(
3654 range.start - line_start..range.end - line_start,
3655 font_size * row_piece.piece.scale,
3656 Some((scaled, scaled.raise_pixels(row_piece))),
3657 );
3658 }
3659 }
3660 }
3661 }
3662
3525 3663 /// Get the runs for the given range.
3526 3664 ///
3527 3665 /// The range is the byte range of the wrapped line.
@@ -5206,3 +5344,7 @@ mod tests {
5206 5344 );
5207 5345 }
5208 5346 }
5347
5348 #[cfg(test)]
5349 #[path = "element/scaled_tests.rs"]
5350 mod scaled_tests;
@@ -21,8 +21,11 @@ use crate::{
21 input::{
21 input::{
22 RopeExt as _,
22 RopeExt as _,
23 blink_cursor::CURSOR_WIDTH,
23 blink_cursor::CURSOR_WIDTH,
24 decorations::font_override_spans,
24 decorations::{FontOverride, font_override_spans},
25 display_map::{InlineMetric, LineLayout, split_run_by_font_overrides},
25 display_map::{
26 InlineFragment, InlineMetric, InputLine, LineLayout, ScaledRow, scaled_row,
27 split_run_by_font_overrides,
28 },
26 },
29 },
27};
30};
28
31
@@ -1936,14 +1939,15 @@ impl<M: InputModeKind> TextElement<M> {
1936 last_layout: &LastLayout,
1939 last_layout: &LastLayout,
1937 font_size: Pixels,
1940 font_size: Pixels,
1938 runs: &[TextRun],
1941 runs: &[TextRun],
1942 font_overrides: &[(Range<usize>, FontOverride)],
1939 window: &mut Window,
1943 window: &mut Window,
1940 ) -> Vec<LineLayout> {
1944 ) -> Vec<LineLayout> {
1941 use crate::input::display_map::{InlineFragment, InputLine};
1942 let spans = state.token_spans();
1945 let spans = state.token_spans();
1943 let cache = state
1946 let cache = state
1944 .token_layout_cache
1947 .token_layout_cache
1945 .as_ref()
1948 .as_ref()
1946 .expect("tokens measured before shaping");
1949 .expect("tokens measured before shaping");
1950 let scale_font = scale_font(font_overrides, window);
1947 let mut run_offset = 0;
1951 let mut run_offset = 0;
1948 last_layout
1952 last_layout
1949 .visible_buffer_lines
1953 .visible_buffer_lines
@@ -1963,6 +1967,16 @@ impl<M: InputModeKind> TextElement<M> {
1963 };
1967 };
1964 let mut lines: SmallVec<[InputLine; 1]> = SmallVec::new();
1968 let mut lines: SmallVec<[InputLine; 1]> = SmallVec::new();
1965 for range in ranges {
1969 for range in ranges {
1970 let scaled = scale_font.as_ref().and_then(|font| {
1971 scaled_row(
1972 window.text_system(),
1973 font,
1974 font_size,
1975 last_layout.line_height,
1976 line_start + range.start..line_start + range.end,
1977 font_overrides,
1978 )
1979 });
1966 let mut fragments = Vec::new();
1980 let mut fragments = Vec::new();
1967 let mut block_height = None;
1981 let mut block_height = None;
1968 let mut offset = range.start;
1982 let mut offset = range.start;
@@ -1975,21 +1989,18 @@ impl<M: InputModeKind> TextElement<M> {
1975 {
1989 {
1976 let local = span.range().start - line_start..span.range().end - line_start;
1990 let local = span.range().start - line_start..span.range().end - line_start;
1977 if offset < local.start {
1991 if offset < local.start {
1978 let part = offset..local.start;
1992 push_text_fragments(
1979 let shaped = window.text_system().shape_line(
1993 window,
1980 text[part.clone()].to_owned().into(),
1994 &text,
1995 offset..local.start,
1996 range.start,
1997 line_start,
1998 scaled.as_ref(),
1981 font_size,
1999 font_size,
1982 &runs_for_range(runs, run_offset, &part),
2000 |part| runs_for_range(runs, run_offset, part),
1983 None,
2001 &mut x,
2002 &mut fragments,
1984 );
2003 );
1985 let width = shaped.width;
1986 fragments.push(InlineFragment {
1987 range: part.start - range.start..part.end - range.start,
1988 x,
1989 width,
1990 text: Some(shaped),
1991 });
1992 x += width;
1993 }
2004 }
1994 let token_size = cache.sizes.get(span.token()).copied().unwrap_or_default();
2005 let token_size = cache.sizes.get(span.token()).copied().unwrap_or_default();
1995 let width = token_size.width;
2006 let width = token_size.width;
@@ -2001,30 +2012,36 @@ impl<M: InputModeKind> TextElement<M> {
2001 x,
2012 x,
2002 width,
2013 width,
2003 text: None,
2014 text: None,
2015 placement: None,
2004 });
2016 });
2005 x += width;
2017 x += width;
2006 offset = local.end;
2018 offset = local.end;
2007 }
2019 }
2008 if offset < range.end {
2020 if offset < range.end {
2009 let part = offset..range.end;
2021 push_text_fragments(
2010 let shaped = window.text_system().shape_line(
2022 window,
2011 text[part.clone()].to_owned().into(),
2023 &text,
2024 offset..range.end,
2025 range.start,
2026 line_start,
2027 scaled.as_ref(),
2012 font_size,
2028 font_size,
2013 &runs_for_range(runs, run_offset, &part),
2029 |part| runs_for_range(runs, run_offset, part),
2014 None,
2030 &mut x,
2031 &mut fragments,
2015 );
2032 );
2016 let width = shaped.width;
2017 fragments.push(InlineFragment {
2018 range: part.start - range.start..part.end - range.start,
2019 x,
2020 width,
2021 text: Some(shaped),
2022 });
2023 }
2033 }
2024 lines.push(
2034 let mut line = InputLine::inline(text[range].to_owned().into(), fragments)
2025 InputLine::inline(text[range].to_owned().into(), fragments)
2035 .with_height(block_height);
2026 .with_height(block_height),
2036 if let Some(scaled) = &scaled {
2027 );
2037 let row_box = scaled.row_box;
2038 line = line
2039 .with_height(
2040 block_height.or(row_box.custom_height(last_layout.line_height)),
2041 )
2042 .with_inline_offset(row_box.baseline - row_box.base_baseline);
2043 }
2044 lines.push(line);
2028 }
2045 }
2029 let indent = state.display_map.line(row).map_or(0, |line| line.indent);
2046 let indent = state.display_map.line(row).map_or(0, |line| line.indent);
2030 let wrap_indent = if indent > 0 && lines.len() > 1 {
2047 let wrap_indent = if indent > 0 && lines.len() > 1 {
@@ -2083,9 +2100,13 @@ impl<M: InputModeKind> TextElement<M> {
2083 if let Some(position) =
2100 if let Some(position) =
2084 layout.lines[ix].position_for_index(span.range().start - start, layout, false)
2101 layout.lines[ix].position_for_index(span.range().start - start, layout, false)
2085 {
2102 {
2103 let baseline_offset =
2104 layout.lines[ix].inline_offset_at(position.y, layout.line_height);
2086 placements.push((
2105 placements.push((
2087 state.token_context(span, layout.line_height, width),
2106 state.token_context(span, layout.line_height, width),
2088 bounds.origin + position + point(layout.line_number_width, y),
2107 bounds.origin
2108 + position
2109 + point(layout.line_number_width, y + baseline_offset),
2089 ));
2110 ));
2090 }
2111 }
2091 }
2112 }
@@ -2130,13 +2151,21 @@ impl<M: InputModeKind> TextElement<M> {
2130 last_layout: &LastLayout,
2151 last_layout: &LastLayout,
2131 font_size: Pixels,
2152 font_size: Pixels,
2132 runs: &[TextRun],
2153 runs: &[TextRun],
2154 font_overrides: &[(Range<usize>, FontOverride)],
2133 bg_segments: &[(Range<usize>, Hsla)],
2155 bg_segments: &[(Range<usize>, Hsla)],
2134 whitespace_indicators: Option<WhitespaceIndicators>,
2156 whitespace_indicators: Option<WhitespaceIndicators>,
2135 window: &mut Window,
2157 window: &mut Window,
2136 ) -> Vec<LineLayout> {
2158 ) -> Vec<LineLayout> {
2137 let is_single_line = state.is_single_line();
2159 let is_single_line = state.is_single_line();
2138 if state.tokens_visible() {
2160 if state.tokens_visible() {
2139 return Self::layout_token_lines(state, last_layout, font_size, runs, window);
2161 return Self::layout_token_lines(
2162 state,
2163 last_layout,
2164 font_size,
2165 runs,
2166 font_overrides,
2167 window,
2168 );
2140 }
2169 }
2141
2170
2142 if is_single_line {
2171 if is_single_line {
@@ -2179,6 +2208,7 @@ impl<M: InputModeKind> TextElement<M> {
2179 return vec![line_layout];
2208 return vec![line_layout];
2180 }
2209 }
2181
2210
2211 let scale_font = scale_font(font_overrides, window);
2182 let mut lines = Vec::with_capacity(last_layout.visible_buffer_lines.len());
2212 let mut lines = Vec::with_capacity(last_layout.visible_buffer_lines.len());
2183 // run_offset tracks position in the runs vec coordinate space (only visible line bytes).
2213 // run_offset tracks position in the runs vec coordinate space (only visible line bytes).
2184 // This is separate from the visible_text offset because runs from highlight_lines
2214 // This is separate from the visible_text offset because runs from highlight_lines
@@ -2194,30 +2224,68 @@ impl<M: InputModeKind> TextElement<M> {
2194
2224
2195 debug_assert_eq!(line_item.len(), line_text.len());
2225 debug_assert_eq!(line_item.len(), line_text.len());
2196
2226
2197 let mut wrapped_lines: SmallVec<[ShapedLine; 1]> = SmallVec::with_capacity(1);
2227 let mut wrapped_lines: SmallVec<[InputLine; 1]> = SmallVec::with_capacity(1);
2198 let mut line_has_background = false;
2228 let mut line_has_background = false;
2229 let line_start = last_layout.visible_line_byte_offsets[vi];
2199
2230
2200 for range in &line_item.wrapped_lines {
2231 for range in &line_item.wrapped_lines {
2201 let line_runs = runs_for_range(runs, run_offset, &range);
2232 let scaled = scale_font.as_ref().and_then(|font| {
2202 let line_runs = if bg_segments.is_empty() {
2233 scaled_row(
2203 line_runs
2234 window.text_system(),
2204 } else {
2235 font,
2205 split_runs_by_bg_segments(
2236 font_size,
2206 last_layout.visible_line_byte_offsets[vi] + (range.start),
2237 last_layout.line_height,
2207 &line_runs,
2238 line_start + range.start..line_start + range.end,
2208 bg_segments,
2239 font_overrides,
2209 )
2240 )
2241 });
2242 let part_runs = |part: &Range<usize>| {
2243 let line_runs = runs_for_range(runs, run_offset, part);
2244 let line_runs = if bg_segments.is_empty() {
2245 line_runs
2246 } else {
2247 split_runs_by_bg_segments(line_start + part.start, &line_runs, bg_segments)
2248 };
2249 align_runs_to_char_boundaries(&line_text[part.clone()], &line_runs)
2250 .unwrap_or(line_runs)
2210 };
2251 };
2211
2252
2253 if let Some(scaled) = scaled {
2254 let mut fragments = Vec::new();
2255 let mut x = px(0.);
2256 push_text_fragments(
2257 window,
2258 &line_text,
2259 range.clone(),
2260 range.start,
2261 line_start,
2262 Some(&scaled),
2263 font_size,
2264 |part| {
2265 let line_runs = part_runs(part);
2266 line_has_background |= has_background(&line_runs);
2267 line_runs
2268 },
2269 &mut x,
2270 &mut fragments,
2271 );
2272 let row_box = scaled.row_box;
2273 wrapped_lines.push(
2274 InputLine::inline(line_text[range.clone()].to_string().into(), fragments)
2275 .with_height(row_box.custom_height(last_layout.line_height))
2276 .with_inline_offset(row_box.baseline - row_box.base_baseline),
2277 );
2278 continue;
2279 }
2280
2281 let line_runs = part_runs(range);
2212 let sub_line: SharedString = line_text[range.clone()].to_string().into();
2282 let sub_line: SharedString = line_text[range.clone()].to_string().into();
2213 let line_runs =
2214 align_runs_to_char_boundaries(&sub_line, &line_runs).unwrap_or(line_runs);
2215 let shaped_line = window
2283 let shaped_line = window
2216 .text_system()
2284 .text_system()
2217 .shape_line(sub_line, font_size, &line_runs, None);
2285 .shape_line(sub_line, font_size, &line_runs, None);
2218
2286
2219 line_has_background |= has_background(&line_runs);
2287 line_has_background |= has_background(&line_runs);
2220 wrapped_lines.push(shaped_line);
2288 wrapped_lines.push(shaped_line.into());
2221 }
2289 }
2222
2290
2223 // Use the first visual line's indentation width for continuation lines.
2291 // Use the first visual line's indentation width for continuation lines.
@@ -2233,13 +2301,9 @@ impl<M: InputModeKind> TextElement<M> {
2233 };
2301 };
2234
2302
2235 let line_layout = LineLayout::new()
2303 let line_layout = LineLayout::new()
2236 .lines(wrapped_lines)
2304 .inline_lines(wrapped_lines)
2237 .wrap_indent(wrap_indent)
2305 .wrap_indent(wrap_indent)
2238 .first_indent(
2306 .first_indent(state.display_map.line_indent(line_start))
2239 state
2240 .display_map
2241 .line_indent(last_layout.visible_line_byte_offsets[vi]),
2242 )
2243 .with_background(line_has_background)
2307 .with_background(line_has_background)
2244 .with_whitespaces(whitespace_indicators.clone());
2308 .with_whitespaces(whitespace_indicators.clone());
2245 lines.push(line_layout);
2309 lines.push(line_layout);
@@ -2650,7 +2714,7 @@ impl<M: InputModeKind> Element for TextElement<M> {
2650 // At least `rows` tall (auto grow: the content's rows, capped at
2714 // At least `rows` tall (auto grow: the content's rows, capped at
2651 // `max_rows` plus the rows of block tokens); a taller parent still fills it.
2715 // `max_rows` plus the rows of block tokens); a taller parent still fills it.
2652 let rows = state.mode.rows();
2716 let rows = state.mode.rows();
2653 style.min_size.height = (rows * line_height).into();
2717 style.min_size.height = (rows * line_height + state.mode.grow_extra()).into();
2654 } else {
2718 } else {
2655 // For single-line inputs, the minimum height should be the line height
2719 // For single-line inputs, the minimum height should be the line height
2656 style.size.height = line_height.into();
2720 style.size.height = line_height.into();
@@ -2688,10 +2752,20 @@ impl<M: InputModeKind> Element for TextElement<M> {
2688 };
2752 };
2689 self.state.update(cx, |state, cx| {
2753 self.state.update(cx, |state, cx| {
2690 state.display_map.set_font(font, text_size, cx);
2754 state.display_map.set_font(font, text_size, cx);
2755 state.display_map.set_line_height(window.line_height(), cx);
2691 state.display_map.ensure_text_prepared(&state.text, cx);
2756 state.display_map.ensure_text_prepared(&state.text, cx);
2692 state
2757 state
2693 .display_map
2758 .display_map
2694 .set_font_overrides(font_overrides.clone(), cx);
2759 .set_font_overrides(font_overrides.clone(), cx);
2760 if state.mode.is_auto_grow() {
2761 let (rows, extra) = (state.mode.rows(), state.mode.grow_extra());
2762 state
2763 .mode
2764 .update_auto_grow(&state.display_map, window.line_height());
2765 if (state.mode.rows(), state.mode.grow_extra()) != (rows, extra) {
2766 cx.notify();
2767 }
2768 }
2695 });
2769 });
2696
2770
2697 let state = self.state.read(cx);
2771 let state = self.state.read(cx);
@@ -2887,6 +2961,7 @@ impl<M: InputModeKind> Element for TextElement<M> {
2887 &last_layout,
2961 &last_layout,
2888 text_size,
2962 text_size,
2889 &runs,
2963 &runs,
2964 &font_overrides,
2890 &document_colors,
2965 &document_colors,
2891 whitespace_indicators,
2966 whitespace_indicators,
2892 window,
2967 window,
@@ -3522,6 +3597,69 @@ fn placeholder_line_runs<'a>(
3522 result
3597 result
3523}
3598}
3524
3599
3600fn scale_font(
3601 font_overrides: &[(Range<usize>, FontOverride)],
3602 window: &Window,
3603) -> Option<gpui::Font> {
3604 font_overrides
3605 .iter()
3606 .any(|(_, font_override)| font_override.scale.is_some() || font_override.raise.is_some())
3607 .then(|| window.text_style().font())
3608}
3609
3610#[allow(clippy::too_many_arguments)]
3611fn push_text_fragments(
3612 window: &Window,
3613 line_text: &str,
3614 part: Range<usize>,
3615 row_start: usize,
3616 line_start: usize,
3617 scaled: Option<&ScaledRow>,
3618 font_size: Pixels,
3619 mut part_runs: impl FnMut(&Range<usize>) -> Vec<TextRun>,
3620 x: &mut Pixels,
3621 fragments: &mut Vec<InlineFragment>,
3622) {
3623 let mut push =
3624 |local: Range<usize>, size: Pixels, placement_of: Option<(&ScaledRow, Pixels)>| {
3625 let shaped = window.text_system().shape_line(
3626 line_text[local.clone()].to_owned().into(),
3627 size,
3628 &part_runs(&local),
3629 None,
3630 );
3631 let width = shaped.width;
3632 let placement = placement_of.map(|(scaled, raise)| {
3633 (
3634 scaled.row_box.baseline - raise - shaped.ascent,
3635 shaped.ascent + shaped.descent,
3636 )
3637 });
3638 fragments.push(InlineFragment {
3639 range: local.start - row_start..local.end - row_start,
3640 x: *x,
3641 width,
3642 text: Some(shaped),
3643 placement,
3644 });
3645 *x += width;
3646 };
3647 match scaled {
3648 None => push(part, font_size, None),
3649 Some(scaled) => {
3650 for (range, row_piece) in
3651 scaled.pieces_in(line_start + part.start..line_start + part.end)
3652 {
3653 push(
3654 range.start - line_start..range.end - line_start,
3655 font_size * row_piece.piece.scale,
3656 Some((scaled, scaled.raise_pixels(row_piece))),
3657 );
3658 }
3659 }
3660 }
3661}
3662
3525/// Get the runs for the given range.
3663/// Get the runs for the given range.
3526///
3664///
3527/// The range is the byte range of the wrapped line.
3665/// The range is the byte range of the wrapped line.
@@ -5206,3 +5344,7 @@ mod tests {
5206 );
5344 );
5207 }
5345 }
5208}
5346}
5347
5348#[cfg(test)]
5349#[path = "element/scaled_tests.rs"]
5350mod scaled_tests;
vendor/gpui-base/src/input/base/element/scaled_tests.rs added +526 −0
@@ -0,0 +1,526 @@
1 #![cfg(target_os = "linux")]
2
3 use std::ops::Range;
4
5 use gpui::{
6 AppContext as _, Context, Entity, EntityInputHandler as _, HighlightStyle, IntoElement,
7 ParentElement as _, Pixels, Render, Styled as _, TestAppContext, TextRun, VisualTestContext,
8 Window, div, point, px, size,
9 };
10
11 use super::TextElement;
12 use crate::input::{
13 InlineToken, InlineTokenPresentation, InputContent, MoveDown, MoveUp, TextDecoration,
14 TextareaMode, TextareaState,
15 };
16
17 const LARGE: f32 = 24. / 14.;
18 const SMALL: f32 = 9. / 14.;
19
20 struct Harness(Entity<TextareaState>);
21
22 impl Render for Harness {
23 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
24 div().size_full().child(self.0.clone())
25 }
26 }
27
28 fn scaled(range: Range<usize>, scale: f32) -> TextDecoration {
29 TextDecoration::new(range, HighlightStyle::default()).with_font_scale(scale)
30 }
31
32 fn raised(range: Range<usize>, scale: f32, raise: f32) -> TextDecoration {
33 scaled(range, scale).with_baseline_shift(raise)
34 }
35
36 fn near(left: Pixels, right: Pixels) -> bool {
37 (left - right).abs() < px(0.05)
38 }
39
40 fn draw(visual: &mut VisualTestContext) {
41 visual.update(|window, cx| window.draw(cx).clear(cx));
42 visual.update(|window, cx| window.draw(cx).clear(cx));
43 }
44
45 fn view(
46 text: &str,
47 width: f32,
48 height: f32,
49 decorations: Vec<TextDecoration>,
50 ) -> (Entity<TextareaState>, VisualTestContext) {
51 build(text, width, height, decorations, |state| state.rows(8))
52 }
53
54 fn build(
55 text: &str,
56 width: f32,
57 height: f32,
58 decorations: Vec<TextDecoration>,
59 configure: impl FnOnce(TextareaState) -> TextareaState,
60 ) -> (Entity<TextareaState>, VisualTestContext) {
61 let platform = gpui_platform::current_platform(true);
62 let mut cx = TestAppContext::build_with_text_system(
63 gpui::TestDispatcher::new(0),
64 None,
65 platform.text_system(),
66 );
67 cx.update(crate::init);
68 let mut textarea = None;
69 let window = cx.open_window(size(px(width), px(height)), |window, cx| {
70 let state =
71 cx.new(|cx| configure(TextareaState::new(window, cx)).default_value(text.to_owned()));
72 textarea = Some(state.clone());
73 Harness(state)
74 });
75 let textarea = textarea.unwrap();
76 let mut visual = VisualTestContext::from_window(window.into(), &cx);
77 visual.update(|window, cx| {
78 textarea.update(cx, |state, cx| {
79 state.create_decorations_collection(decorations, cx);
80 });
81 window.draw(cx).clear(cx);
82 });
83 draw(&mut visual);
84 (textarea, visual)
85 }
86
87 fn base_size(visual: &mut VisualTestContext) -> Pixels {
88 visual.update(|window, _| window.text_style().font_size.to_pixels(window.rem_size()))
89 }
90
91 fn shaped_width(visual: &mut VisualTestContext, text: &str, font_size: Pixels) -> Pixels {
92 visual.update(|window, _| {
93 window
94 .text_system()
95 .shape_line(
96 text.to_owned().into(),
97 font_size,
98 &[TextRun {
99 len: text.len(),
100 font: window.text_style().font(),
101 color: gpui::black(),
102 background_color: None,
103 underline: None,
104 strikethrough: None,
105 }],
106 None,
107 )
108 .width
109 })
110 }
111
112 fn line_height(textarea: &Entity<TextareaState>, visual: &VisualTestContext) -> Pixels {
113 textarea.read_with(visual, |state, _| state.line_height().unwrap())
114 }
115
116 #[test]
117 fn scaled_ranges_become_baseline_aligned_fragments_of_their_own_size() {
118 let (textarea, mut visual) = view("abc DEF ghi", 400., 200., vec![scaled(4..7, LARGE)]);
119 let font_size = base_size(&mut visual);
120 let large_width = shaped_width(&mut visual, "DEF", font_size * LARGE);
121 let large_first = shaped_width(&mut visual, "D", font_size * LARGE);
122 let plain_width = shaped_width(&mut visual, "abc ", font_size);
123 let lh = line_height(&textarea, &visual);
124 textarea.read_with(&visual, |state, _| {
125 let layout = state.last_layout.as_ref().unwrap();
126 let row = &layout.lines[0].wrapped_lines[0];
127 let fragments = row.fragments().expect("scaled row is fragmented");
128 assert_eq!(fragments.len(), 3);
129 assert_eq!(fragments[0].range, 0..4);
130 assert_eq!(fragments[1].range, 4..7);
131 assert!(near(fragments[1].x, plain_width));
132 assert!(near(fragments[1].width, large_width));
133 assert!(near(row.x_for_index(4), fragments[1].x));
134 assert!(near(row.x_for_index(7), fragments[2].x));
135 assert!(near(row.x_for_index(5), fragments[1].x + large_first));
136 let height = row.height.expect("Large grows the row");
137 assert!(height > lh * 1.5, "{height:?} vs {lh:?}");
138 let baselines: Vec<_> = fragments
139 .iter()
140 .map(|fragment| {
141 let (y, paint_height) = fragment.placement.unwrap();
142 let shaped = fragment.text.as_ref().unwrap();
143 assert!(near(paint_height, shaped.ascent + shaped.descent));
144 y + shaped.ascent
145 })
146 .collect();
147 assert!(near(baselines[0], baselines[1]) && near(baselines[1], baselines[2]));
148 assert_eq!(state.display_map.row_height(0, layout.line_height), height);
149 });
150 }
151
152 #[test]
153 fn small_text_never_shrinks_the_row() {
154 let (textarea, mut visual) = view("abc DEF ghi", 400., 200., vec![scaled(4..7, SMALL)]);
155 let font_size = base_size(&mut visual);
156 let small_width = shaped_width(&mut visual, "DEF", font_size * SMALL);
157 let lh = line_height(&textarea, &visual);
158 textarea.read_with(&visual, |state, _| {
159 let layout = state.last_layout.as_ref().unwrap();
160 let row = &layout.lines[0].wrapped_lines[0];
161 assert!(near(row.fragments().unwrap()[1].width, small_width));
162 assert_eq!(row.height, None);
163 assert_eq!(state.display_map.row_height(0, lh), lh);
164 assert_eq!(state.display_map.content_height(lh), lh);
165 });
166 }
167
168 #[test]
169 fn superscript_and_subscript_shift_the_baseline_and_grow_the_row() {
170 let (textarea, mut visual) = view(
171 "H2O x2",
172 400.,
173 200.,
174 vec![raised(1..2, 0.75, -0.2), raised(5..6, 0.75, 0.35)],
175 );
176 let font_size = base_size(&mut visual);
177 let lh = line_height(&textarea, &visual);
178 textarea.read_with(&visual, |state, _| {
179 let layout = state.last_layout.as_ref().unwrap();
180 let row = &layout.lines[0].wrapped_lines[0];
181 let fragments = row.fragments().unwrap();
182 let baseline = |index: usize| {
183 let fragment = &fragments[index];
184 fragment.placement.unwrap().0 + fragment.text.as_ref().unwrap().ascent
185 };
186 assert_eq!(fragments.len(), 4);
187 assert!(near(baseline(1) - baseline(0), font_size * 0.2));
188 assert!(near(baseline(0) - baseline(3), font_size * 0.35));
189 assert!(row.height.unwrap() > lh);
190 assert_eq!(state.display_map.row_height(0, lh), row.height.unwrap());
191 });
192 }
193
194 #[test]
195 fn plain_lines_keep_the_shaped_line_path_and_row_heights_agree_with_the_wrapper() {
196 let text = "plain\nabc DEF\n\nplain";
197 let (textarea, visual) = view(text, 400., 300., vec![scaled(10..13, LARGE)]);
198 let lh = line_height(&textarea, &visual);
199 textarea.read_with(&visual, |state, _| {
200 let layout = state.last_layout.as_ref().unwrap();
201 for (index, plain) in [(0, true), (1, false), (2, true), (3, true)] {
202 let row = &layout.lines[index].wrapped_lines[0];
203 assert_eq!(row.fragments().is_none(), plain, "line {index}");
204 assert_eq!(row.height.is_none(), plain, "line {index}");
205 }
206 let large = layout.lines[1].wrapped_lines[0].height.unwrap();
207 assert_eq!(state.display_map.row_height(1, lh), large);
208 assert_eq!(state.display_map.row_top(2, lh), lh + large);
209 assert_eq!(state.display_map.content_height(lh), lh * 3. + large);
210 assert_eq!(layout.lines[1].size(lh).height, large);
211 });
212 }
213
214 #[test]
215 fn removing_the_scale_restores_plain_rows() {
216 let (textarea, mut visual) = view("abc DEF", 400., 200., vec![]);
217 let lh = line_height(&textarea, &visual);
218 let collection = visual.update(|_, cx| {
219 textarea.update(cx, |state, cx| {
220 state.create_decorations_collection(vec![scaled(4..7, LARGE)], cx)
221 })
222 });
223 draw(&mut visual);
224 textarea.read_with(&visual, |state, _| {
225 assert!(state.display_map.row_height(0, lh) > lh);
226 });
227 visual.update(|_, cx| collection.clear(cx));
228 draw(&mut visual);
229 textarea.read_with(&visual, |state, _| {
230 assert_eq!(state.display_map.row_height(0, lh), lh);
231 let layout = state.last_layout.as_ref().unwrap();
232 assert!(layout.lines[0].wrapped_lines[0].fragments().is_none());
233 });
234 }
235
236 #[test]
237 fn mixed_sizes_wrap_by_their_real_widths() {
238 let text = "aaaa bbbb cccc dddd eeee ffff gggg hhhh";
239 let (plain, plain_visual) = view(text, 200., 300., vec![]);
240 let (mixed, mixed_visual) = view(text, 200., 300., vec![scaled(10..24, LARGE)]);
241 let plain_rows = plain.read_with(&plain_visual, |state, _| {
242 state.last_layout.as_ref().unwrap().lines[0]
243 .wrapped_lines
244 .len()
245 });
246 mixed.read_with(&mixed_visual, |state, _| {
247 let layout = state.last_layout.as_ref().unwrap();
248 let line = &layout.lines[0];
249 assert!(line.wrapped_lines.len() > plain_rows);
250 for row in &line.wrapped_lines {
251 assert!(row.width <= layout.wrap_width.unwrap(), "{:?}", row.width);
252 }
253 let wrapper_rows = state.display_map.line(0).unwrap().wrapped_lines.clone();
254 assert_eq!(wrapper_rows.len(), line.wrapped_lines.len());
255 for (index, range) in wrapper_rows.iter().enumerate() {
256 assert_eq!(line.wrapped_lines[index].len, range.len());
257 assert_eq!(
258 state.display_map.row_height(index, layout.line_height),
259 line.row_height(index, layout.line_height)
260 );
261 }
262 assert!(line.size(layout.line_height).height > layout.line_height * plain_rows as f32);
263 });
264 }
265
266 #[test]
267 fn offsets_map_to_pixels_and_back_across_a_size_change() {
268 let text = "ab cd EF gh";
269 let (textarea, visual) = view(text, 600., 200., vec![scaled(6..8, LARGE)]);
270 textarea.read_with(&visual, |state, _| {
271 let layout = state.last_layout.as_ref().unwrap();
272 let line = &layout.lines[0];
273 let mut previous = px(-1.);
274 for offset in 0..=text.len() {
275 let position = line.position_for_index(offset, layout, false).unwrap();
276 assert!(position.x > previous, "offset {offset}");
277 previous = position.x;
278 let (hit, _) = line.closest_index_for_position(position, layout).unwrap();
279 assert_eq!(hit, offset);
280 assert_eq!(line.index_for_position(position, layout), Some(offset));
281 }
282 let before = line.position_for_index(6, layout, false).unwrap();
283 let after = line.position_for_index(8, layout, false).unwrap();
284 let (middle, _) = line
285 .closest_index_for_position(point((before.x + after.x) / 2. + px(1.), before.y), layout)
286 .unwrap();
287 assert_eq!(middle, 8);
288 });
289 }
290
291 #[test]
292 fn the_caret_on_a_large_line_spans_its_row() {
293 let (textarea, mut visual) = view(
294 "one\ntwo BIG\nthree",
295 400.,
296 300.,
297 vec![scaled(8..11, LARGE)],
298 );
299 let lh = line_height(&textarea, &visual);
300 let mut carets = Vec::new();
301 for offset in [8, 9] {
302 visual.update(|_, cx| {
303 textarea.update(cx, |state, cx| state.set_selected_range(offset..offset, cx))
304 });
305 draw(&mut visual);
306 carets.push(textarea.read_with(&visual, |state, _| state.cursor_layout().unwrap().0));
307 }
308 textarea.read_with(&visual, |state, _| {
309 let layout = state.last_layout.as_ref().unwrap();
310 let row_height = layout.lines[1].wrapped_lines[0].height.unwrap();
311 assert!(near(carets[0].size.height, row_height), "{:?}", carets[0]);
312 assert!(carets[0].size.height > lh * 1.4);
313 let row_top = layout.visible_top + layout.lines[0].size(lh).height;
314 let origin = state.text_bounds().unwrap().origin;
315 assert!(near(carets[0].origin.y - origin.y, row_top));
316 assert!(near(carets[0].origin.y, carets[1].origin.y));
317 let line = &layout.lines[1];
318 let step = line.position_for_index(5, layout, false).unwrap().x
319 - line.position_for_index(4, layout, false).unwrap().x;
320 assert!(near(carets[1].origin.x - carets[0].origin.x, step));
321 });
322 }
323
324 #[test]
325 fn vertical_movement_keeps_the_pixel_column_between_a_large_and_a_normal_line() {
326 let text = "iiiiiiii\nBBBBBBBB\niiiiiiii";
327 let (textarea, mut visual) = view(text, 400., 300., vec![scaled(9..17, LARGE)]);
328 visual.update(|_, cx| textarea.update(cx, |state, cx| state.set_selected_range(4..4, cx)));
329 draw(&mut visual);
330 let expected = |direction_row: usize, source_row: usize, source_offset: usize| {
331 textarea.read_with(&visual, |state, _| {
332 let layout = state.last_layout.as_ref().unwrap();
333 let x = layout.lines[source_row]
334 .position_for_index(source_offset - 9 * source_row, layout, false)
335 .unwrap()
336 .x;
337 let (index, _) = layout.lines[direction_row]
338 .closest_index_for_position(point(x, px(0.)), layout)
339 .unwrap();
340 9 * direction_row + index
341 })
342 };
343 let down_target = expected(1, 0, 4);
344 visual.update(|window, cx| textarea.update(cx, |state, cx| state.down(&MoveDown, window, cx)));
345 let landed = textarea.read_with(&visual, |state, _| state.cursor());
346 assert_eq!(landed, down_target);
347 assert!((9..=17).contains(&landed));
348 draw(&mut visual);
349 visual.update(|window, cx| textarea.update(cx, |state, cx| state.down(&MoveDown, window, cx)));
350 let landed_below = textarea.read_with(&visual, |state, _| state.cursor());
351 assert!(landed_below >= 18);
352 visual.update(|window, cx| textarea.update(cx, |state, cx| state.up(&MoveUp, window, cx)));
353 visual.update(|window, cx| textarea.update(cx, |state, cx| state.up(&MoveUp, window, cx)));
354 let landed_top = textarea.read_with(&visual, |state, _| state.cursor());
355 assert!(landed_top < 9);
356 }
357
358 #[test]
359 fn selection_boxes_follow_each_rows_height_across_sizes() {
360 let text = "ab CD ef\ngh ij";
361 let (textarea, visual) = view(text, 400., 300., vec![scaled(3..5, LARGE)]);
362 textarea.read_with(&visual, |state, _| {
363 let layout = state.last_layout.as_ref().unwrap();
364 let corners = TextElement::<TextareaMode>::layout_range_corners(&(1..12), layout).unwrap();
365 assert_eq!(corners.len(), 2);
366 let first_height = layout.lines[0].wrapped_lines[0].height.unwrap();
367 assert!(near(
368 corners[0].bottom_left.y - corners[0].top_left.y,
369 first_height
370 ));
371 assert!(near(
372 corners[1].bottom_left.y - corners[1].top_left.y,
373 layout.line_height
374 ));
375 assert!(near(corners[1].top_left.y, first_height));
376 let row = &layout.lines[0].wrapped_lines[0];
377 assert!(near(corners[0].top_left.x, row.x_for_index(1)));
378 assert!(near(
379 corners[0].top_right.x,
380 row.x_for_index(8) + layout.space_width
381 ));
382
383 let inside = TextElement::<TextareaMode>::layout_range_corners(&(1..7), layout).unwrap();
384 assert_eq!(inside.len(), 1);
385 assert!(near(inside[0].top_right.x, row.x_for_index(7)));
386 assert!(near(
387 inside[0].bottom_right.y - inside[0].top_right.y,
388 first_height
389 ));
390 });
391 }
392
393 #[test]
394 fn ime_bounds_and_hit_testing_use_the_fragment_geometry() {
395 let (textarea, mut visual) = view("ab CD ef", 400., 300., vec![scaled(3..5, LARGE)]);
396 let bounds = textarea.read_with(&visual, |state, _| state.text_bounds().unwrap());
397 let (row_height, x_start, x_end, line_number_width) =
398 textarea.read_with(&visual, |state, _| {
399 let layout = state.last_layout.as_ref().unwrap();
400 let row = &layout.lines[0].wrapped_lines[0];
401 (
402 row.height.unwrap(),
403 row.x_for_index(3),
404 row.x_for_index(5),
405 layout.line_number_width,
406 )
407 });
408 let range = visual.update(|window, cx| {
409 textarea.update(cx, |state, cx| {
410 state.bounds_for_range(3..5, bounds, window, cx).unwrap()
411 })
412 });
413 assert!(near(
414 range.origin.x - bounds.origin.x - line_number_width,
415 x_start
416 ));
417 assert!(near(range.size.height, row_height));
418 assert!(near(range.right() - range.left(), x_end - x_start));
419 let probe = bounds.origin
420 + point(
421 line_number_width + x_start + (x_end - x_start) * 0.9,
422 row_height / 2.,
423 );
424 let index = visual.update(|window, cx| {
425 textarea.update(cx, |state, cx| {
426 state.character_index_for_point(probe, window, cx)
427 })
428 });
429 assert_eq!(index, Some(5));
430 }
431
432 #[test]
433 fn inline_tokens_in_a_scaled_row_share_the_baseline() {
434 let (textarea, mut visual) = view("", 400., 300., vec![]);
435 visual.update(|window, cx| {
436 textarea.update(cx, |state, cx| {
437 state.set_token_presentation(
438 InlineTokenPresentation::default().token(|_, _, _| div().w(px(30.)).h(px(18.))),
439 );
440 let content = InputContent::new("ab[x]cd")
441 .with_token(2..5, InlineToken::new("x", "[x]"))
442 .unwrap();
443 state.set_value(content, window, cx);
444 state.create_decorations_collection(vec![scaled(0..7, LARGE)], cx);
445 });
446 });
447 draw(&mut visual);
448 let lh = line_height(&textarea, &visual);
449 textarea.read_with(&visual, |state, _| {
450 let layout = state.last_layout.as_ref().unwrap();
451 let row = &layout.lines[0].wrapped_lines[0];
452 let fragments = row.fragments().unwrap();
453 assert_eq!(fragments.len(), 3);
454 assert!(fragments[1].text.is_none());
455 assert!(near(fragments[1].width, px(30.)));
456 assert!(near(fragments[2].x, fragments[1].x + px(30.)));
457 assert!(row.height.unwrap() > lh);
458 assert!(row.inline_offset > px(0.));
459 assert!(near(row.x_for_index(5), fragments[2].x));
460 assert_eq!(state.display_map.row_height(0, lh), row.height.unwrap());
461 let (token_bounds, _) = state
462 .token_bounds
463 .iter()
464 .next()
465 .map(|(_, bounds)| (*bounds, ()))
466 .unwrap();
467 let top = state.text_bounds().unwrap().origin.y + layout.visible_top;
468 assert!(near(token_bounds.origin.y - top, row.inline_offset));
469 });
470 }
471
472 #[test]
473 fn the_caret_stays_in_view_when_large_lines_fill_the_viewport() {
474 let text = "WWW\n".repeat(10) + "end";
475 let (textarea, mut visual) = view(&text, 300., 120., vec![scaled(0..text.len(), LARGE)]);
476 visual.update(|_, cx| {
477 textarea.update(cx, |state, cx| {
478 state.set_selected_range(text.len()..text.len(), cx)
479 })
480 });
481 draw(&mut visual);
482 textarea.read_with(&visual, |state, _| {
483 let (caret, _) = state.cursor_layout().unwrap();
484 let bounds = state.input_bounds();
485 let scroll = state.scroll_handle.offset().y;
486 assert!(
487 caret.bottom() + scroll <= bounds.bottom() + px(1.),
488 "{caret:?} {bounds:?} {scroll:?}"
489 );
490 assert!(
491 caret.top() + scroll >= bounds.top() - px(1.),
492 "{caret:?} {bounds:?} {scroll:?}"
493 );
494 });
495 }
496
497 #[test]
498 fn an_empty_composer_with_a_scale_decoration_still_shows_its_placeholder() {
499 let (textarea, mut visual) = view("", 300., 120., vec![scaled(0..0, LARGE)]);
500 let lh = line_height(&textarea, &visual);
501 draw(&mut visual);
502 textarea.read_with(&visual, |state, _| {
503 assert_eq!(state.display_map.content_height(lh), lh);
504 });
505 }
506
507 #[test]
508 fn auto_grow_follows_scaled_rows_by_their_exact_extra() {
509 for (decoration, taller_than_a_row) in [
510 (raised(1..2, 0.75, -0.2), false),
511 (scaled(1..2, LARGE), true),
512 ] {
513 let (textarea, visual) = build("a2b", 300., 400., vec![decoration], |state| {
514 state.auto_grow(1, 5)
515 });
516 let lh = line_height(&textarea, &visual);
517 textarea.read_with(&visual, |state, _| {
518 let layout = state.last_layout.as_ref().unwrap();
519 let row_height = layout.lines[0].wrapped_lines[0].height.unwrap();
520 assert_eq!(state.mode.rows(), 1);
521 assert!(near(state.mode.grow_extra(), row_height - lh));
522 assert_eq!(row_height > lh * 1.5, taller_than_a_row);
523 assert!(row_height < lh * 2.);
524 });
525 }
526 }
@@ -0,0 +1,526 @@
1#![cfg(target_os = "linux")]
2
3use std::ops::Range;
4
5use gpui::{
6 AppContext as _, Context, Entity, EntityInputHandler as _, HighlightStyle, IntoElement,
7 ParentElement as _, Pixels, Render, Styled as _, TestAppContext, TextRun, VisualTestContext,
8 Window, div, point, px, size,
9};
10
11use super::TextElement;
12use crate::input::{
13 InlineToken, InlineTokenPresentation, InputContent, MoveDown, MoveUp, TextDecoration,
14 TextareaMode, TextareaState,
15};
16
17const LARGE: f32 = 24. / 14.;
18const SMALL: f32 = 9. / 14.;
19
20struct Harness(Entity<TextareaState>);
21
22impl Render for Harness {
23 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
24 div().size_full().child(self.0.clone())
25 }
26}
27
28fn scaled(range: Range<usize>, scale: f32) -> TextDecoration {
29 TextDecoration::new(range, HighlightStyle::default()).with_font_scale(scale)
30}
31
32fn raised(range: Range<usize>, scale: f32, raise: f32) -> TextDecoration {
33 scaled(range, scale).with_baseline_shift(raise)
34}
35
36fn near(left: Pixels, right: Pixels) -> bool {
37 (left - right).abs() < px(0.05)
38}
39
40fn draw(visual: &mut VisualTestContext) {
41 visual.update(|window, cx| window.draw(cx).clear(cx));
42 visual.update(|window, cx| window.draw(cx).clear(cx));
43}
44
45fn view(
46 text: &str,
47 width: f32,
48 height: f32,
49 decorations: Vec<TextDecoration>,
50) -> (Entity<TextareaState>, VisualTestContext) {
51 build(text, width, height, decorations, |state| state.rows(8))
52}
53
54fn build(
55 text: &str,
56 width: f32,
57 height: f32,
58 decorations: Vec<TextDecoration>,
59 configure: impl FnOnce(TextareaState) -> TextareaState,
60) -> (Entity<TextareaState>, VisualTestContext) {
61 let platform = gpui_platform::current_platform(true);
62 let mut cx = TestAppContext::build_with_text_system(
63 gpui::TestDispatcher::new(0),
64 None,
65 platform.text_system(),
66 );
67 cx.update(crate::init);
68 let mut textarea = None;
69 let window = cx.open_window(size(px(width), px(height)), |window, cx| {
70 let state =
71 cx.new(|cx| configure(TextareaState::new(window, cx)).default_value(text.to_owned()));
72 textarea = Some(state.clone());
73 Harness(state)
74 });
75 let textarea = textarea.unwrap();
76 let mut visual = VisualTestContext::from_window(window.into(), &cx);
77 visual.update(|window, cx| {
78 textarea.update(cx, |state, cx| {
79 state.create_decorations_collection(decorations, cx);
80 });
81 window.draw(cx).clear(cx);
82 });
83 draw(&mut visual);
84 (textarea, visual)
85}
86
87fn base_size(visual: &mut VisualTestContext) -> Pixels {
88 visual.update(|window, _| window.text_style().font_size.to_pixels(window.rem_size()))
89}
90
91fn shaped_width(visual: &mut VisualTestContext, text: &str, font_size: Pixels) -> Pixels {
92 visual.update(|window, _| {
93 window
94 .text_system()
95 .shape_line(
96 text.to_owned().into(),
97 font_size,
98 &[TextRun {
99 len: text.len(),
100 font: window.text_style().font(),
101 color: gpui::black(),
102 background_color: None,
103 underline: None,
104 strikethrough: None,
105 }],
106 None,
107 )
108 .width
109 })
110}
111
112fn line_height(textarea: &Entity<TextareaState>, visual: &VisualTestContext) -> Pixels {
113 textarea.read_with(visual, |state, _| state.line_height().unwrap())
114}
115
116#[test]
117fn scaled_ranges_become_baseline_aligned_fragments_of_their_own_size() {
118 let (textarea, mut visual) = view("abc DEF ghi", 400., 200., vec![scaled(4..7, LARGE)]);
119 let font_size = base_size(&mut visual);
120 let large_width = shaped_width(&mut visual, "DEF", font_size * LARGE);
121 let large_first = shaped_width(&mut visual, "D", font_size * LARGE);
122 let plain_width = shaped_width(&mut visual, "abc ", font_size);
123 let lh = line_height(&textarea, &visual);
124 textarea.read_with(&visual, |state, _| {
125 let layout = state.last_layout.as_ref().unwrap();
126 let row = &layout.lines[0].wrapped_lines[0];
127 let fragments = row.fragments().expect("scaled row is fragmented");
128 assert_eq!(fragments.len(), 3);
129 assert_eq!(fragments[0].range, 0..4);
130 assert_eq!(fragments[1].range, 4..7);
131 assert!(near(fragments[1].x, plain_width));
132 assert!(near(fragments[1].width, large_width));
133 assert!(near(row.x_for_index(4), fragments[1].x));
134 assert!(near(row.x_for_index(7), fragments[2].x));
135 assert!(near(row.x_for_index(5), fragments[1].x + large_first));
136 let height = row.height.expect("Large grows the row");
137 assert!(height > lh * 1.5, "{height:?} vs {lh:?}");
138 let baselines: Vec<_> = fragments
139 .iter()
140 .map(|fragment| {
141 let (y, paint_height) = fragment.placement.unwrap();
142 let shaped = fragment.text.as_ref().unwrap();
143 assert!(near(paint_height, shaped.ascent + shaped.descent));
144 y + shaped.ascent
145 })
146 .collect();
147 assert!(near(baselines[0], baselines[1]) && near(baselines[1], baselines[2]));
148 assert_eq!(state.display_map.row_height(0, layout.line_height), height);
149 });
150}
151
152#[test]
153fn small_text_never_shrinks_the_row() {
154 let (textarea, mut visual) = view("abc DEF ghi", 400., 200., vec![scaled(4..7, SMALL)]);
155 let font_size = base_size(&mut visual);
156 let small_width = shaped_width(&mut visual, "DEF", font_size * SMALL);
157 let lh = line_height(&textarea, &visual);
158 textarea.read_with(&visual, |state, _| {
159 let layout = state.last_layout.as_ref().unwrap();
160 let row = &layout.lines[0].wrapped_lines[0];
161 assert!(near(row.fragments().unwrap()[1].width, small_width));
162 assert_eq!(row.height, None);
163 assert_eq!(state.display_map.row_height(0, lh), lh);
164 assert_eq!(state.display_map.content_height(lh), lh);
165 });
166}
167
168#[test]
169fn superscript_and_subscript_shift_the_baseline_and_grow_the_row() {
170 let (textarea, mut visual) = view(
171 "H2O x2",
172 400.,
173 200.,
174 vec![raised(1..2, 0.75, -0.2), raised(5..6, 0.75, 0.35)],
175 );
176 let font_size = base_size(&mut visual);
177 let lh = line_height(&textarea, &visual);
178 textarea.read_with(&visual, |state, _| {
179 let layout = state.last_layout.as_ref().unwrap();
180 let row = &layout.lines[0].wrapped_lines[0];
181 let fragments = row.fragments().unwrap();
182 let baseline = |index: usize| {
183 let fragment = &fragments[index];
184 fragment.placement.unwrap().0 + fragment.text.as_ref().unwrap().ascent
185 };
186 assert_eq!(fragments.len(), 4);
187 assert!(near(baseline(1) - baseline(0), font_size * 0.2));
188 assert!(near(baseline(0) - baseline(3), font_size * 0.35));
189 assert!(row.height.unwrap() > lh);
190 assert_eq!(state.display_map.row_height(0, lh), row.height.unwrap());
191 });
192}
193
194#[test]
195fn plain_lines_keep_the_shaped_line_path_and_row_heights_agree_with_the_wrapper() {
196 let text = "plain\nabc DEF\n\nplain";
197 let (textarea, visual) = view(text, 400., 300., vec![scaled(10..13, LARGE)]);
198 let lh = line_height(&textarea, &visual);
199 textarea.read_with(&visual, |state, _| {
200 let layout = state.last_layout.as_ref().unwrap();
201 for (index, plain) in [(0, true), (1, false), (2, true), (3, true)] {
202 let row = &layout.lines[index].wrapped_lines[0];
203 assert_eq!(row.fragments().is_none(), plain, "line {index}");
204 assert_eq!(row.height.is_none(), plain, "line {index}");
205 }
206 let large = layout.lines[1].wrapped_lines[0].height.unwrap();
207 assert_eq!(state.display_map.row_height(1, lh), large);
208 assert_eq!(state.display_map.row_top(2, lh), lh + large);
209 assert_eq!(state.display_map.content_height(lh), lh * 3. + large);
210 assert_eq!(layout.lines[1].size(lh).height, large);
211 });
212}
213
214#[test]
215fn removing_the_scale_restores_plain_rows() {
216 let (textarea, mut visual) = view("abc DEF", 400., 200., vec![]);
217 let lh = line_height(&textarea, &visual);
218 let collection = visual.update(|_, cx| {
219 textarea.update(cx, |state, cx| {
220 state.create_decorations_collection(vec![scaled(4..7, LARGE)], cx)
221 })
222 });
223 draw(&mut visual);
224 textarea.read_with(&visual, |state, _| {
225 assert!(state.display_map.row_height(0, lh) > lh);
226 });
227 visual.update(|_, cx| collection.clear(cx));
228 draw(&mut visual);
229 textarea.read_with(&visual, |state, _| {
230 assert_eq!(state.display_map.row_height(0, lh), lh);
231 let layout = state.last_layout.as_ref().unwrap();
232 assert!(layout.lines[0].wrapped_lines[0].fragments().is_none());
233 });
234}
235
236#[test]
237fn mixed_sizes_wrap_by_their_real_widths() {
238 let text = "aaaa bbbb cccc dddd eeee ffff gggg hhhh";
239 let (plain, plain_visual) = view(text, 200., 300., vec![]);
240 let (mixed, mixed_visual) = view(text, 200., 300., vec![scaled(10..24, LARGE)]);
241 let plain_rows = plain.read_with(&plain_visual, |state, _| {
242 state.last_layout.as_ref().unwrap().lines[0]
243 .wrapped_lines
244 .len()
245 });
246 mixed.read_with(&mixed_visual, |state, _| {
247 let layout = state.last_layout.as_ref().unwrap();
248 let line = &layout.lines[0];
249 assert!(line.wrapped_lines.len() > plain_rows);
250 for row in &line.wrapped_lines {
251 assert!(row.width <= layout.wrap_width.unwrap(), "{:?}", row.width);
252 }
253 let wrapper_rows = state.display_map.line(0).unwrap().wrapped_lines.clone();
254 assert_eq!(wrapper_rows.len(), line.wrapped_lines.len());
255 for (index, range) in wrapper_rows.iter().enumerate() {
256 assert_eq!(line.wrapped_lines[index].len, range.len());
257 assert_eq!(
258 state.display_map.row_height(index, layout.line_height),
259 line.row_height(index, layout.line_height)
260 );
261 }
262 assert!(line.size(layout.line_height).height > layout.line_height * plain_rows as f32);
263 });
264}
265
266#[test]
267fn offsets_map_to_pixels_and_back_across_a_size_change() {
268 let text = "ab cd EF gh";
269 let (textarea, visual) = view(text, 600., 200., vec![scaled(6..8, LARGE)]);
270 textarea.read_with(&visual, |state, _| {
271 let layout = state.last_layout.as_ref().unwrap();
272 let line = &layout.lines[0];
273 let mut previous = px(-1.);
274 for offset in 0..=text.len() {
275 let position = line.position_for_index(offset, layout, false).unwrap();
276 assert!(position.x > previous, "offset {offset}");
277 previous = position.x;
278 let (hit, _) = line.closest_index_for_position(position, layout).unwrap();
279 assert_eq!(hit, offset);
280 assert_eq!(line.index_for_position(position, layout), Some(offset));
281 }
282 let before = line.position_for_index(6, layout, false).unwrap();
283 let after = line.position_for_index(8, layout, false).unwrap();
284 let (middle, _) = line
285 .closest_index_for_position(point((before.x + after.x) / 2. + px(1.), before.y), layout)
286 .unwrap();
287 assert_eq!(middle, 8);
288 });
289}
290
291#[test]
292fn the_caret_on_a_large_line_spans_its_row() {
293 let (textarea, mut visual) = view(
294 "one\ntwo BIG\nthree",
295 400.,
296 300.,
297 vec![scaled(8..11, LARGE)],
298 );
299 let lh = line_height(&textarea, &visual);
300 let mut carets = Vec::new();
301 for offset in [8, 9] {
302 visual.update(|_, cx| {
303 textarea.update(cx, |state, cx| state.set_selected_range(offset..offset, cx))
304 });
305 draw(&mut visual);
306 carets.push(textarea.read_with(&visual, |state, _| state.cursor_layout().unwrap().0));
307 }
308 textarea.read_with(&visual, |state, _| {
309 let layout = state.last_layout.as_ref().unwrap();
310 let row_height = layout.lines[1].wrapped_lines[0].height.unwrap();
311 assert!(near(carets[0].size.height, row_height), "{:?}", carets[0]);
312 assert!(carets[0].size.height > lh * 1.4);
313 let row_top = layout.visible_top + layout.lines[0].size(lh).height;
314 let origin = state.text_bounds().unwrap().origin;
315 assert!(near(carets[0].origin.y - origin.y, row_top));
316 assert!(near(carets[0].origin.y, carets[1].origin.y));
317 let line = &layout.lines[1];
318 let step = line.position_for_index(5, layout, false).unwrap().x
319 - line.position_for_index(4, layout, false).unwrap().x;
320 assert!(near(carets[1].origin.x - carets[0].origin.x, step));
321 });
322}
323
324#[test]
325fn vertical_movement_keeps_the_pixel_column_between_a_large_and_a_normal_line() {
326 let text = "iiiiiiii\nBBBBBBBB\niiiiiiii";
327 let (textarea, mut visual) = view(text, 400., 300., vec![scaled(9..17, LARGE)]);
328 visual.update(|_, cx| textarea.update(cx, |state, cx| state.set_selected_range(4..4, cx)));
329 draw(&mut visual);
330 let expected = |direction_row: usize, source_row: usize, source_offset: usize| {
331 textarea.read_with(&visual, |state, _| {
332 let layout = state.last_layout.as_ref().unwrap();
333 let x = layout.lines[source_row]
334 .position_for_index(source_offset - 9 * source_row, layout, false)
335 .unwrap()
336 .x;
337 let (index, _) = layout.lines[direction_row]
338 .closest_index_for_position(point(x, px(0.)), layout)
339 .unwrap();
340 9 * direction_row + index
341 })
342 };
343 let down_target = expected(1, 0, 4);
344 visual.update(|window, cx| textarea.update(cx, |state, cx| state.down(&MoveDown, window, cx)));
345 let landed = textarea.read_with(&visual, |state, _| state.cursor());
346 assert_eq!(landed, down_target);
347 assert!((9..=17).contains(&landed));
348 draw(&mut visual);
349 visual.update(|window, cx| textarea.update(cx, |state, cx| state.down(&MoveDown, window, cx)));
350 let landed_below = textarea.read_with(&visual, |state, _| state.cursor());
351 assert!(landed_below >= 18);
352 visual.update(|window, cx| textarea.update(cx, |state, cx| state.up(&MoveUp, window, cx)));
353 visual.update(|window, cx| textarea.update(cx, |state, cx| state.up(&MoveUp, window, cx)));
354 let landed_top = textarea.read_with(&visual, |state, _| state.cursor());
355 assert!(landed_top < 9);
356}
357
358#[test]
359fn selection_boxes_follow_each_rows_height_across_sizes() {
360 let text = "ab CD ef\ngh ij";
361 let (textarea, visual) = view(text, 400., 300., vec![scaled(3..5, LARGE)]);
362 textarea.read_with(&visual, |state, _| {
363 let layout = state.last_layout.as_ref().unwrap();
364 let corners = TextElement::<TextareaMode>::layout_range_corners(&(1..12), layout).unwrap();
365 assert_eq!(corners.len(), 2);
366 let first_height = layout.lines[0].wrapped_lines[0].height.unwrap();
367 assert!(near(
368 corners[0].bottom_left.y - corners[0].top_left.y,
369 first_height
370 ));
371 assert!(near(
372 corners[1].bottom_left.y - corners[1].top_left.y,
373 layout.line_height
374 ));
375 assert!(near(corners[1].top_left.y, first_height));
376 let row = &layout.lines[0].wrapped_lines[0];
377 assert!(near(corners[0].top_left.x, row.x_for_index(1)));
378 assert!(near(
379 corners[0].top_right.x,
380 row.x_for_index(8) + layout.space_width
381 ));
382
383 let inside = TextElement::<TextareaMode>::layout_range_corners(&(1..7), layout).unwrap();
384 assert_eq!(inside.len(), 1);
385 assert!(near(inside[0].top_right.x, row.x_for_index(7)));
386 assert!(near(
387 inside[0].bottom_right.y - inside[0].top_right.y,
388 first_height
389 ));
390 });
391}
392
393#[test]
394fn ime_bounds_and_hit_testing_use_the_fragment_geometry() {
395 let (textarea, mut visual) = view("ab CD ef", 400., 300., vec![scaled(3..5, LARGE)]);
396 let bounds = textarea.read_with(&visual, |state, _| state.text_bounds().unwrap());
397 let (row_height, x_start, x_end, line_number_width) =
398 textarea.read_with(&visual, |state, _| {
399 let layout = state.last_layout.as_ref().unwrap();
400 let row = &layout.lines[0].wrapped_lines[0];
401 (
402 row.height.unwrap(),
403 row.x_for_index(3),
404 row.x_for_index(5),
405 layout.line_number_width,
406 )
407 });
408 let range = visual.update(|window, cx| {
409 textarea.update(cx, |state, cx| {
410 state.bounds_for_range(3..5, bounds, window, cx).unwrap()
411 })
412 });
413 assert!(near(
414 range.origin.x - bounds.origin.x - line_number_width,
415 x_start
416 ));
417 assert!(near(range.size.height, row_height));
418 assert!(near(range.right() - range.left(), x_end - x_start));
419 let probe = bounds.origin
420 + point(
421 line_number_width + x_start + (x_end - x_start) * 0.9,
422 row_height / 2.,
423 );
424 let index = visual.update(|window, cx| {
425 textarea.update(cx, |state, cx| {
426 state.character_index_for_point(probe, window, cx)
427 })
428 });
429 assert_eq!(index, Some(5));
430}
431
432#[test]
433fn inline_tokens_in_a_scaled_row_share_the_baseline() {
434 let (textarea, mut visual) = view("", 400., 300., vec![]);
435 visual.update(|window, cx| {
436 textarea.update(cx, |state, cx| {
437 state.set_token_presentation(
438 InlineTokenPresentation::default().token(|_, _, _| div().w(px(30.)).h(px(18.))),
439 );
440 let content = InputContent::new("ab[x]cd")
441 .with_token(2..5, InlineToken::new("x", "[x]"))
442 .unwrap();
443 state.set_value(content, window, cx);
444 state.create_decorations_collection(vec![scaled(0..7, LARGE)], cx);
445 });
446 });
447 draw(&mut visual);
448 let lh = line_height(&textarea, &visual);
449 textarea.read_with(&visual, |state, _| {
450 let layout = state.last_layout.as_ref().unwrap();
451 let row = &layout.lines[0].wrapped_lines[0];
452 let fragments = row.fragments().unwrap();
453 assert_eq!(fragments.len(), 3);
454 assert!(fragments[1].text.is_none());
455 assert!(near(fragments[1].width, px(30.)));
456 assert!(near(fragments[2].x, fragments[1].x + px(30.)));
457 assert!(row.height.unwrap() > lh);
458 assert!(row.inline_offset > px(0.));
459 assert!(near(row.x_for_index(5), fragments[2].x));
460 assert_eq!(state.display_map.row_height(0, lh), row.height.unwrap());
461 let (token_bounds, _) = state
462 .token_bounds
463 .iter()
464 .next()
465 .map(|(_, bounds)| (*bounds, ()))
466 .unwrap();
467 let top = state.text_bounds().unwrap().origin.y + layout.visible_top;
468 assert!(near(token_bounds.origin.y - top, row.inline_offset));
469 });
470}
471
472#[test]
473fn the_caret_stays_in_view_when_large_lines_fill_the_viewport() {
474 let text = "WWW\n".repeat(10) + "end";
475 let (textarea, mut visual) = view(&text, 300., 120., vec![scaled(0..text.len(), LARGE)]);
476 visual.update(|_, cx| {
477 textarea.update(cx, |state, cx| {
478 state.set_selected_range(text.len()..text.len(), cx)
479 })
480 });
481 draw(&mut visual);
482 textarea.read_with(&visual, |state, _| {
483 let (caret, _) = state.cursor_layout().unwrap();
484 let bounds = state.input_bounds();
485 let scroll = state.scroll_handle.offset().y;
486 assert!(
487 caret.bottom() + scroll <= bounds.bottom() + px(1.),
488 "{caret:?} {bounds:?} {scroll:?}"
489 );
490 assert!(
491 caret.top() + scroll >= bounds.top() - px(1.),
492 "{caret:?} {bounds:?} {scroll:?}"
493 );
494 });
495}
496
497#[test]
498fn an_empty_composer_with_a_scale_decoration_still_shows_its_placeholder() {
499 let (textarea, mut visual) = view("", 300., 120., vec![scaled(0..0, LARGE)]);
500 let lh = line_height(&textarea, &visual);
501 draw(&mut visual);
502 textarea.read_with(&visual, |state, _| {
503 assert_eq!(state.display_map.content_height(lh), lh);
504 });
505}
506
507#[test]
508fn auto_grow_follows_scaled_rows_by_their_exact_extra() {
509 for (decoration, taller_than_a_row) in [
510 (raised(1..2, 0.75, -0.2), false),
511 (scaled(1..2, LARGE), true),
512 ] {
513 let (textarea, visual) = build("a2b", 300., 400., vec![decoration], |state| {
514 state.auto_grow(1, 5)
515 });
516 let lh = line_height(&textarea, &visual);
517 textarea.read_with(&visual, |state, _| {
518 let layout = state.last_layout.as_ref().unwrap();
519 let row_height = layout.lines[0].wrapped_lines[0].height.unwrap();
520 assert_eq!(state.mode.rows(), 1);
521 assert!(near(state.mode.grow_extra(), row_height - lh));
522 assert_eq!(row_height > lh * 1.5, taller_than_a_row);
523 assert!(row_height < lh * 2.);
524 });
525 }
526}
vendor/gpui-base/src/input/base/mode.rs +19 −1
@@ -2,7 +2,7 @@ use crate::input::InputModeKind;
2 2 use std::rc::Rc;
3 3 use std::{cell::RefCell, ops::Range};
4 4
5 use gpui::{Context, Pixels, Window};
5 use gpui::{Context, Pixels, Window, px};
6 6 use ropey::Rope;
7 7
8 8 use super::DisplayMap;
@@ -36,6 +36,7 @@ pub(crate) enum LayoutMode {
36 36 rows: usize,
37 37 min_rows: usize,
38 38 max_rows: usize,
39 extra: Pixels,
39 40 },
40 41 /// A code editor input mode.
41 42 CodeEditor {
@@ -98,6 +99,7 @@ impl LayoutMode {
98 99 rows: min_rows,
99 100 min_rows,
100 101 max_rows,
102 extra: px(0.),
101 103 }
102 104 }
103 105
@@ -215,6 +217,7 @@ impl LayoutMode {
215 217 rows,
216 218 min_rows,
217 219 max_rows,
220 ..
218 221 } => {
219 222 *rows = new_rows.clamp(*min_rows, *max_rows);
220 223 }
@@ -237,10 +240,25 @@ impl LayoutMode {
237 240 rows,
238 241 min_rows,
239 242 max_rows,
243 extra,
240 244 } = self
241 245 {
242 246 let cap = (*max_rows + block_rows).min(*max_rows * BLOCK_GROWTH_FACTOR);
243 247 *rows = content_rows.clamp(*min_rows, cap.max(*max_rows));
248 *extra = if content_rows > *rows {
249 px(0.)
250 } else {
251 (line_height * content_rows as f32 + display_map.scaled_extra()
252 - line_height * *rows as f32)
253 .max(px(0.))
254 };
255 }
256 }
257
258 pub(super) fn grow_extra(&self) -> Pixels {
259 match self {
260 LayoutMode::AutoGrow { extra, .. } => *extra,
261 _ => px(0.),
244 262 }
245 263 }
246 264
@@ -2,7 +2,7 @@ use crate::input::InputModeKind;
2use std::rc::Rc;
2use std::rc::Rc;
3use std::{cell::RefCell, ops::Range};
3use std::{cell::RefCell, ops::Range};
4
4
5use gpui::{Context, Pixels, Window};
5use gpui::{Context, Pixels, Window, px};
6use ropey::Rope;
6use ropey::Rope;
7
7
8use super::DisplayMap;
8use super::DisplayMap;
@@ -36,6 +36,7 @@ pub(crate) enum LayoutMode {
36 rows: usize,
36 rows: usize,
37 min_rows: usize,
37 min_rows: usize,
38 max_rows: usize,
38 max_rows: usize,
39 extra: Pixels,
39 },
40 },
40 /// A code editor input mode.
41 /// A code editor input mode.
41 CodeEditor {
42 CodeEditor {
@@ -98,6 +99,7 @@ impl LayoutMode {
98 rows: min_rows,
99 rows: min_rows,
99 min_rows,
100 min_rows,
100 max_rows,
101 max_rows,
102 extra: px(0.),
101 }
103 }
102 }
104 }
103
105
@@ -215,6 +217,7 @@ impl LayoutMode {
215 rows,
217 rows,
216 min_rows,
218 min_rows,
217 max_rows,
219 max_rows,
220 ..
218 } => {
221 } => {
219 *rows = new_rows.clamp(*min_rows, *max_rows);
222 *rows = new_rows.clamp(*min_rows, *max_rows);
220 }
223 }
@@ -237,10 +240,25 @@ impl LayoutMode {
237 rows,
240 rows,
238 min_rows,
241 min_rows,
239 max_rows,
242 max_rows,
243 extra,
240 } = self
244 } = self
241 {
245 {
242 let cap = (*max_rows + block_rows).min(*max_rows * BLOCK_GROWTH_FACTOR);
246 let cap = (*max_rows + block_rows).min(*max_rows * BLOCK_GROWTH_FACTOR);
243 *rows = content_rows.clamp(*min_rows, cap.max(*max_rows));
247 *rows = content_rows.clamp(*min_rows, cap.max(*max_rows));
248 *extra = if content_rows > *rows {
249 px(0.)
250 } else {
251 (line_height * content_rows as f32 + display_map.scaled_extra()
252 - line_height * *rows as f32)
253 .max(px(0.))
254 };
255 }
256 }
257
258 pub(super) fn grow_extra(&self) -> Pixels {
259 match self {
260 LayoutMode::AutoGrow { extra, .. } => *extra,
261 _ => px(0.),
244 }
262 }
245 }
263 }
246
264
vendor/gpui-base/src/input/editor/decorations.rs +90 −1
@@ -108,6 +108,10 @@ pub struct TextDecoration {
108 108 pub style: HighlightStyle,
109 109 /// Font family override. It, `style.font_weight` and `style.font_style` change soft wrapping.
110 110 pub font_family: Option<SharedString>,
111 /// Font size as a multiple of the editor font size. Overlapping scales multiply.
112 pub font_scale: Option<f32>,
113 /// Baseline shift in editor font sizes, positive is up. The first decoration covering a byte wins.
114 pub baseline_shift: Option<f32>,
111 115 }
112 116
113 117 impl TextDecoration {
@@ -117,6 +121,8 @@ impl TextDecoration {
117 121 range,
118 122 style,
119 123 font_family: None,
124 font_scale: None,
125 baseline_shift: None,
120 126 }
121 127 }
122 128
@@ -125,6 +131,18 @@ impl TextDecoration {
125 131 self.font_family = Some(font_family.into());
126 132 self
127 133 }
134
135 /// Render this range at `font_scale` times the editor font size, e.g. 0.75 for a subscript.
136 pub fn with_font_scale(mut self, font_scale: f32) -> Self {
137 self.font_scale = Some(font_scale);
138 self
139 }
140
141 /// Shift this range's baseline by `baseline_shift` editor font sizes, positive is up.
142 pub fn with_baseline_shift(mut self, baseline_shift: f32) -> Self {
143 self.baseline_shift = Some(baseline_shift);
144 self
145 }
128 146 }
129 147
130 148 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
@@ -582,6 +600,8 @@ pub(crate) struct FontOverride {
582 600 pub(crate) family: Option<SharedString>,
583 601 pub(crate) weight: Option<FontWeight>,
584 602 pub(crate) style: Option<FontStyle>,
603 pub(crate) scale: Option<f32>,
604 pub(crate) raise: Option<f32>,
585 605 }
586 606
587 607 impl FontOverride {
@@ -624,7 +644,35 @@ where
624 644 spans
625 645 }
626 646
627 /// Font overrides per byte span; earlier layers and items win per property.
647 fn product_spans(items: Vec<(Range<usize>, f32)>) -> Vec<(Range<usize>, f32)> {
648 let mut edges: Vec<usize> = items
649 .iter()
650 .flat_map(|(range, _)| [range.start, range.end])
651 .collect();
652 edges.sort_unstable();
653 edges.dedup();
654 let mut spans: Vec<(Range<usize>, f32)> = Vec::new();
655 for segment in edges.windows(2) {
656 let mut covering = items
657 .iter()
658 .filter(|(range, _)| range.start <= segment[0] && segment[1] <= range.end)
659 .map(|(_, scale)| *scale)
660 .peekable();
661 if covering.peek().is_none() {
662 continue;
663 }
664 let scale: f32 = covering.product();
665 match spans.last_mut() {
666 Some((range, last)) if range.end == segment[0] && *last == scale => {
667 range.end = segment[1];
668 }
669 _ => spans.push((segment[0]..segment[1], scale)),
670 }
671 }
672 spans
673 }
674
675 /// Font overrides per byte span; earlier layers and items win per property, except scale.
628 676 pub(crate) fn font_override_spans(
629 677 layers: &[&[TextDecoration]],
630 678 ) -> Vec<(Range<usize>, FontOverride)> {
@@ -640,11 +688,22 @@ pub(crate) fn font_override_spans(
640 688 first_wins_spans(decorations().filter_map(|decoration| {
641 689 Some((decoration.range.clone(), decoration.style.font_style?))
642 690 }));
691 let scales = product_spans(
692 decorations()
693 .filter_map(|decoration| Some((decoration.range.clone(), decoration.font_scale?)))
694 .collect(),
695 );
696 let raises = first_wins_spans(
697 decorations()
698 .filter_map(|decoration| Some((decoration.range.clone(), decoration.baseline_shift?))),
699 );
643 700 let mut edges: Vec<usize> = families
644 701 .iter()
645 702 .map(|(range, _)| range)
646 703 .chain(weights.iter().map(|(range, _)| range))
647 704 .chain(styles.iter().map(|(range, _)| range))
705 .chain(scales.iter().map(|(range, _)| range))
706 .chain(raises.iter().map(|(range, _)| range))
648 707 .flat_map(|range| [range.start, range.end])
649 708 .collect();
650 709 edges.sort_unstable();
@@ -662,6 +721,8 @@ pub(crate) fn font_override_spans(
662 721 family: value_at(&families, segment[0]),
663 722 weight: value_at(&weights, segment[0]),
664 723 style: value_at(&styles, segment[0]),
724 scale: value_at(&scales, segment[0]),
725 raise: value_at(&raises, segment[0]),
665 726 };
666 727 if font_override == FontOverride::default() {
667 728 continue;
@@ -986,6 +1047,7 @@ mod tests {
986 1047 family: Some("Mono".into()),
987 1048 weight: Some(FontWeight::BOLD),
988 1049 style: None,
1050 ..Default::default()
989 1051 }
990 1052 ),
991 1053 (
@@ -994,6 +1056,7 @@ mod tests {
994 1056 family: Some("Mono".into()),
995 1057 weight: Some(FontWeight::BOLD),
996 1058 style: Some(FontStyle::Italic),
1059 ..Default::default()
997 1060 }
998 1061 ),
999 1062 (
@@ -1002,12 +1065,38 @@ mod tests {
1002 1065 family: None,
1003 1066 weight: Some(FontWeight::LIGHT),
1004 1067 style: Some(FontStyle::Italic),
1068 ..Default::default()
1005 1069 }
1006 1070 ),
1007 1071 ]
1008 1072 );
1009 1073 }
1010 1074
1075 #[test]
1076 fn font_override_spans_multiply_scales_and_first_raise_wins() {
1077 let style = HighlightStyle::default();
1078 let layer = [
1079 TextDecoration::new(0..8, style).with_font_scale(2.),
1080 TextDecoration::new(4..12, style)
1081 .with_font_scale(0.5)
1082 .with_baseline_shift(0.35),
1083 TextDecoration::new(6..10, style).with_baseline_shift(-0.2),
1084 ];
1085 let scaled = |scale: f32, raise: Option<f32>| FontOverride {
1086 scale: Some(scale),
1087 raise,
1088 ..Default::default()
1089 };
1090 assert_eq!(
1091 font_override_spans(&[&layer[..]]),
1092 vec![
1093 (0..4, scaled(2., None)),
1094 (4..8, scaled(1., Some(0.35))),
1095 (8..12, scaled(0.5, Some(0.35))),
1096 ]
1097 );
1098 }
1099
1011 1100 #[test]
1012 1101 fn decoration_ranges_follow_text_edits() {
1013 1102 let style = HighlightStyle::default();
@@ -108,6 +108,10 @@ pub struct TextDecoration {
108 pub style: HighlightStyle,
108 pub style: HighlightStyle,
109 /// Font family override. It, `style.font_weight` and `style.font_style` change soft wrapping.
109 /// Font family override. It, `style.font_weight` and `style.font_style` change soft wrapping.
110 pub font_family: Option<SharedString>,
110 pub font_family: Option<SharedString>,
111 /// Font size as a multiple of the editor font size. Overlapping scales multiply.
112 pub font_scale: Option<f32>,
113 /// Baseline shift in editor font sizes, positive is up. The first decoration covering a byte wins.
114 pub baseline_shift: Option<f32>,
111}
115}
112
116
113impl TextDecoration {
117impl TextDecoration {
@@ -117,6 +121,8 @@ impl TextDecoration {
117 range,
121 range,
118 style,
122 style,
119 font_family: None,
123 font_family: None,
124 font_scale: None,
125 baseline_shift: None,
120 }
126 }
121 }
127 }
122
128
@@ -125,6 +131,18 @@ impl TextDecoration {
125 self.font_family = Some(font_family.into());
131 self.font_family = Some(font_family.into());
126 self
132 self
127 }
133 }
134
135 /// Render this range at `font_scale` times the editor font size, e.g. 0.75 for a subscript.
136 pub fn with_font_scale(mut self, font_scale: f32) -> Self {
137 self.font_scale = Some(font_scale);
138 self
139 }
140
141 /// Shift this range's baseline by `baseline_shift` editor font sizes, positive is up.
142 pub fn with_baseline_shift(mut self, baseline_shift: f32) -> Self {
143 self.baseline_shift = Some(baseline_shift);
144 self
145 }
128}
146}
129
147
130#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
148#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
@@ -582,6 +600,8 @@ pub(crate) struct FontOverride {
582 pub(crate) family: Option<SharedString>,
600 pub(crate) family: Option<SharedString>,
583 pub(crate) weight: Option<FontWeight>,
601 pub(crate) weight: Option<FontWeight>,
584 pub(crate) style: Option<FontStyle>,
602 pub(crate) style: Option<FontStyle>,
603 pub(crate) scale: Option<f32>,
604 pub(crate) raise: Option<f32>,
585}
605}
586
606
587impl FontOverride {
607impl FontOverride {
@@ -624,7 +644,35 @@ where
624 spans
644 spans
625}
645}
626
646
627/// Font overrides per byte span; earlier layers and items win per property.
647fn product_spans(items: Vec<(Range<usize>, f32)>) -> Vec<(Range<usize>, f32)> {
648 let mut edges: Vec<usize> = items
649 .iter()
650 .flat_map(|(range, _)| [range.start, range.end])
651 .collect();
652 edges.sort_unstable();
653 edges.dedup();
654 let mut spans: Vec<(Range<usize>, f32)> = Vec::new();
655 for segment in edges.windows(2) {
656 let mut covering = items
657 .iter()
658 .filter(|(range, _)| range.start <= segment[0] && segment[1] <= range.end)
659 .map(|(_, scale)| *scale)
660 .peekable();
661 if covering.peek().is_none() {
662 continue;
663 }
664 let scale: f32 = covering.product();
665 match spans.last_mut() {
666 Some((range, last)) if range.end == segment[0] && *last == scale => {
667 range.end = segment[1];
668 }
669 _ => spans.push((segment[0]..segment[1], scale)),
670 }
671 }
672 spans
673}
674
675/// Font overrides per byte span; earlier layers and items win per property, except scale.
628pub(crate) fn font_override_spans(
676pub(crate) fn font_override_spans(
629 layers: &[&[TextDecoration]],
677 layers: &[&[TextDecoration]],
630) -> Vec<(Range<usize>, FontOverride)> {
678) -> Vec<(Range<usize>, FontOverride)> {
@@ -640,11 +688,22 @@ pub(crate) fn font_override_spans(
640 first_wins_spans(decorations().filter_map(|decoration| {
688 first_wins_spans(decorations().filter_map(|decoration| {
641 Some((decoration.range.clone(), decoration.style.font_style?))
689 Some((decoration.range.clone(), decoration.style.font_style?))
642 }));
690 }));
691 let scales = product_spans(
692 decorations()
693 .filter_map(|decoration| Some((decoration.range.clone(), decoration.font_scale?)))
694 .collect(),
695 );
696 let raises = first_wins_spans(
697 decorations()
698 .filter_map(|decoration| Some((decoration.range.clone(), decoration.baseline_shift?))),
699 );
643 let mut edges: Vec<usize> = families
700 let mut edges: Vec<usize> = families
644 .iter()
701 .iter()
645 .map(|(range, _)| range)
702 .map(|(range, _)| range)
646 .chain(weights.iter().map(|(range, _)| range))
703 .chain(weights.iter().map(|(range, _)| range))
647 .chain(styles.iter().map(|(range, _)| range))
704 .chain(styles.iter().map(|(range, _)| range))
705 .chain(scales.iter().map(|(range, _)| range))
706 .chain(raises.iter().map(|(range, _)| range))
648 .flat_map(|range| [range.start, range.end])
707 .flat_map(|range| [range.start, range.end])
649 .collect();
708 .collect();
650 edges.sort_unstable();
709 edges.sort_unstable();
@@ -662,6 +721,8 @@ pub(crate) fn font_override_spans(
662 family: value_at(&families, segment[0]),
721 family: value_at(&families, segment[0]),
663 weight: value_at(&weights, segment[0]),
722 weight: value_at(&weights, segment[0]),
664 style: value_at(&styles, segment[0]),
723 style: value_at(&styles, segment[0]),
724 scale: value_at(&scales, segment[0]),
725 raise: value_at(&raises, segment[0]),
665 };
726 };
666 if font_override == FontOverride::default() {
727 if font_override == FontOverride::default() {
667 continue;
728 continue;
@@ -986,6 +1047,7 @@ mod tests {
986 family: Some("Mono".into()),
1047 family: Some("Mono".into()),
987 weight: Some(FontWeight::BOLD),
1048 weight: Some(FontWeight::BOLD),
988 style: None,
1049 style: None,
1050 ..Default::default()
989 }
1051 }
990 ),
1052 ),
991 (
1053 (
@@ -994,6 +1056,7 @@ mod tests {
994 family: Some("Mono".into()),
1056 family: Some("Mono".into()),
995 weight: Some(FontWeight::BOLD),
1057 weight: Some(FontWeight::BOLD),
996 style: Some(FontStyle::Italic),
1058 style: Some(FontStyle::Italic),
1059 ..Default::default()
997 }
1060 }
998 ),
1061 ),
999 (
1062 (
@@ -1002,12 +1065,38 @@ mod tests {
1002 family: None,
1065 family: None,
1003 weight: Some(FontWeight::LIGHT),
1066 weight: Some(FontWeight::LIGHT),
1004 style: Some(FontStyle::Italic),
1067 style: Some(FontStyle::Italic),
1068 ..Default::default()
1005 }
1069 }
1006 ),
1070 ),
1007 ]
1071 ]
1008 );
1072 );
1009 }
1073 }
1010
1074
1075 #[test]
1076 fn font_override_spans_multiply_scales_and_first_raise_wins() {
1077 let style = HighlightStyle::default();
1078 let layer = [
1079 TextDecoration::new(0..8, style).with_font_scale(2.),
1080 TextDecoration::new(4..12, style)
1081 .with_font_scale(0.5)
1082 .with_baseline_shift(0.35),
1083 TextDecoration::new(6..10, style).with_baseline_shift(-0.2),
1084 ];
1085 let scaled = |scale: f32, raise: Option<f32>| FontOverride {
1086 scale: Some(scale),
1087 raise,
1088 ..Default::default()
1089 };
1090 assert_eq!(
1091 font_override_spans(&[&layer[..]]),
1092 vec![
1093 (0..4, scaled(2., None)),
1094 (4..8, scaled(1., Some(0.35))),
1095 (8..12, scaled(0.5, Some(0.35))),
1096 ]
1097 );
1098 }
1099
1011 #[test]
1100 #[test]
1012 fn decoration_ranges_follow_text_edits() {
1101 fn decoration_ranges_follow_text_edits() {
1013 let style = HighlightStyle::default();
1102 let style = HighlightStyle::default();
vendor/gpui-base/src/input/editor/display_map/display_map.rs +11 −1
@@ -245,6 +245,11 @@ impl DisplayMap {
245 245 self.rebuild_fold_projection();
246 246 }
247 247
248 pub(crate) fn set_line_height(&mut self, line_height: Pixels, cx: &mut App) {
249 self.wrap_map.set_line_height(line_height, cx);
250 self.rebuild_fold_projection();
251 }
252
248 253 /// Hang continuation rows of each marker's line under the marker's end.
249 254 pub(crate) fn set_hanging_indents(
250 255 &mut self,
@@ -395,10 +400,15 @@ impl DisplayMap {
395 400
396 401 pub(crate) fn content_rows(&self, line_height: Pixels) -> usize {
397 402 let rows = self.wrap_row_count();
398 let extra = self.content_height(line_height) - line_height * rows as f32;
403 let extra =
404 self.content_height(line_height) - self.scaled_extra() - line_height * rows as f32;
399 405 rows + (extra / line_height).ceil().max(0.) as usize
400 406 }
401 407
408 pub(crate) fn scaled_extra(&self) -> Pixels {
409 self.wrap_map.wrapper().scaled_extra()
410 }
411
402 412 /// Get the longest row index (by byte length).
403 413 #[inline]
404 414 pub(crate) fn longest_row(&self) -> usize {
@@ -245,6 +245,11 @@ impl DisplayMap {
245 self.rebuild_fold_projection();
245 self.rebuild_fold_projection();
246 }
246 }
247
247
248 pub(crate) fn set_line_height(&mut self, line_height: Pixels, cx: &mut App) {
249 self.wrap_map.set_line_height(line_height, cx);
250 self.rebuild_fold_projection();
251 }
252
248 /// Hang continuation rows of each marker's line under the marker's end.
253 /// Hang continuation rows of each marker's line under the marker's end.
249 pub(crate) fn set_hanging_indents(
254 pub(crate) fn set_hanging_indents(
250 &mut self,
255 &mut self,
@@ -395,10 +400,15 @@ impl DisplayMap {
395
400
396 pub(crate) fn content_rows(&self, line_height: Pixels) -> usize {
401 pub(crate) fn content_rows(&self, line_height: Pixels) -> usize {
397 let rows = self.wrap_row_count();
402 let rows = self.wrap_row_count();
398 let extra = self.content_height(line_height) - line_height * rows as f32;
403 let extra =
404 self.content_height(line_height) - self.scaled_extra() - line_height * rows as f32;
399 rows + (extra / line_height).ceil().max(0.) as usize
405 rows + (extra / line_height).ceil().max(0.) as usize
400 }
406 }
401
407
408 pub(crate) fn scaled_extra(&self) -> Pixels {
409 self.wrap_map.wrapper().scaled_extra()
410 }
411
402 /// Get the longest row index (by byte length).
412 /// Get the longest row index (by byte length).
403 #[inline]
413 #[inline]
404 pub(crate) fn longest_row(&self) -> usize {
414 pub(crate) fn longest_row(&self) -> usize {
vendor/gpui-base/src/input/editor/display_map/inline_line.rs +27 −9
@@ -7,6 +7,7 @@ pub(crate) struct InlineFragment {
7 7 pub(crate) x: Pixels,
8 8 pub(crate) width: Pixels,
9 9 pub(crate) text: Option<ShapedLine>,
10 pub(crate) placement: Option<(Pixels, Pixels)>,
10 11 }
11 12
12 13 pub(crate) struct InputLine {
@@ -14,6 +15,7 @@ pub(crate) struct InputLine {
14 15 pub(crate) width: Pixels,
15 16 pub(crate) text: SharedString,
16 17 pub(crate) height: Option<Pixels>,
18 pub(crate) inline_offset: Pixels,
17 19 content: Content,
18 20 }
19 21 // Keep the ordinary shaped row inline: boxing it would add an allocation to
@@ -30,6 +32,7 @@ impl From<ShapedLine> for InputLine {
30 32 width: line.width,
31 33 text: line.text.clone(),
32 34 height: None,
35 inline_offset: px(0.),
33 36 content: Content::Text(line),
34 37 }
35 38 }
@@ -42,6 +45,7 @@ impl InputLine {
42 45 text,
43 46 width,
44 47 height: None,
48 inline_offset: px(0.),
45 49 content: Content::Inline(fragments),
46 50 }
47 51 }
@@ -49,6 +53,17 @@ impl InputLine {
49 53 self.height = height;
50 54 self
51 55 }
56 #[cfg(test)]
57 pub(crate) fn fragments(&self) -> Option<&[InlineFragment]> {
58 match &self.content {
59 Content::Inline(fragments) => Some(fragments),
60 Content::Text(_) => None,
61 }
62 }
63 pub(crate) fn with_inline_offset(mut self, inline_offset: Pixels) -> Self {
64 self.inline_offset = inline_offset;
65 self
66 }
52 67 pub(crate) fn x_for_index(&self, ix: usize) -> Pixels {
53 68 match &self.content {
54 69 Content::Text(line) => line.x_for_index(ix),
@@ -129,15 +144,16 @@ impl InputLine {
129 144 window: &mut Window,
130 145 cx: &mut App,
131 146 ) {
132 let paint = |line: &ShapedLine, pos, align, width, window: &mut Window, cx: &mut App| {
133 if background {
134 let _ = line.paint_background(pos, height, align, width, window, cx);
135 } else {
136 let _ = line.paint(pos, height, align, width, window, cx);
137 }
138 };
147 let paint =
148 |line: &ShapedLine, pos, height, align, width, window: &mut Window, cx: &mut App| {
149 if background {
150 let _ = line.paint_background(pos, height, align, width, window, cx);
151 } else {
152 let _ = line.paint(pos, height, align, width, window, cx);
153 }
154 };
139 155 match &self.content {
140 Content::Text(line) => paint(line, pos, align, width, window, cx),
156 Content::Text(line) => paint(line, pos, height, align, width, window, cx),
141 157 Content::Inline(fragments) => {
142 158 let remaining = (width.unwrap_or(self.width) - self.width).max(px(0.));
143 159 let offset = match align {
@@ -147,9 +163,11 @@ impl InputLine {
147 163 };
148 164 for f in fragments {
149 165 if let Some(line) = &f.text {
166 let (y, height) = f.placement.unwrap_or((px(0.), height));
150 167 paint(
151 168 line,
152 pos + point(offset + f.x, px(0.)),
169 pos + point(offset + f.x, y),
170 height,
153 171 TextAlign::Left,
154 172 None,
155 173 window,
@@ -7,6 +7,7 @@ pub(crate) struct InlineFragment {
7 pub(crate) x: Pixels,
7 pub(crate) x: Pixels,
8 pub(crate) width: Pixels,
8 pub(crate) width: Pixels,
9 pub(crate) text: Option<ShapedLine>,
9 pub(crate) text: Option<ShapedLine>,
10 pub(crate) placement: Option<(Pixels, Pixels)>,
10}
11}
11
12
12pub(crate) struct InputLine {
13pub(crate) struct InputLine {
@@ -14,6 +15,7 @@ pub(crate) struct InputLine {
14 pub(crate) width: Pixels,
15 pub(crate) width: Pixels,
15 pub(crate) text: SharedString,
16 pub(crate) text: SharedString,
16 pub(crate) height: Option<Pixels>,
17 pub(crate) height: Option<Pixels>,
18 pub(crate) inline_offset: Pixels,
17 content: Content,
19 content: Content,
18}
20}
19// Keep the ordinary shaped row inline: boxing it would add an allocation to
21// Keep the ordinary shaped row inline: boxing it would add an allocation to
@@ -30,6 +32,7 @@ impl From<ShapedLine> for InputLine {
30 width: line.width,
32 width: line.width,
31 text: line.text.clone(),
33 text: line.text.clone(),
32 height: None,
34 height: None,
35 inline_offset: px(0.),
33 content: Content::Text(line),
36 content: Content::Text(line),
34 }
37 }
35 }
38 }
@@ -42,6 +45,7 @@ impl InputLine {
42 text,
45 text,
43 width,
46 width,
44 height: None,
47 height: None,
48 inline_offset: px(0.),
45 content: Content::Inline(fragments),
49 content: Content::Inline(fragments),
46 }
50 }
47 }
51 }
@@ -49,6 +53,17 @@ impl InputLine {
49 self.height = height;
53 self.height = height;
50 self
54 self
51 }
55 }
56 #[cfg(test)]
57 pub(crate) fn fragments(&self) -> Option<&[InlineFragment]> {
58 match &self.content {
59 Content::Inline(fragments) => Some(fragments),
60 Content::Text(_) => None,
61 }
62 }
63 pub(crate) fn with_inline_offset(mut self, inline_offset: Pixels) -> Self {
64 self.inline_offset = inline_offset;
65 self
66 }
52 pub(crate) fn x_for_index(&self, ix: usize) -> Pixels {
67 pub(crate) fn x_for_index(&self, ix: usize) -> Pixels {
53 match &self.content {
68 match &self.content {
54 Content::Text(line) => line.x_for_index(ix),
69 Content::Text(line) => line.x_for_index(ix),
@@ -129,15 +144,16 @@ impl InputLine {
129 window: &mut Window,
144 window: &mut Window,
130 cx: &mut App,
145 cx: &mut App,
131 ) {
146 ) {
132 let paint = |line: &ShapedLine, pos, align, width, window: &mut Window, cx: &mut App| {
147 let paint =
133 if background {
148 |line: &ShapedLine, pos, height, align, width, window: &mut Window, cx: &mut App| {
134 let _ = line.paint_background(pos, height, align, width, window, cx);
149 if background {
135 } else {
150 let _ = line.paint_background(pos, height, align, width, window, cx);
136 let _ = line.paint(pos, height, align, width, window, cx);
151 } else {
137 }
152 let _ = line.paint(pos, height, align, width, window, cx);
138 };
153 }
154 };
139 match &self.content {
155 match &self.content {
140 Content::Text(line) => paint(line, pos, align, width, window, cx),
156 Content::Text(line) => paint(line, pos, height, align, width, window, cx),
141 Content::Inline(fragments) => {
157 Content::Inline(fragments) => {
142 let remaining = (width.unwrap_or(self.width) - self.width).max(px(0.));
158 let remaining = (width.unwrap_or(self.width) - self.width).max(px(0.));
143 let offset = match align {
159 let offset = match align {
@@ -147,9 +163,11 @@ impl InputLine {
147 };
163 };
148 for f in fragments {
164 for f in fragments {
149 if let Some(line) = &f.text {
165 if let Some(line) = &f.text {
166 let (y, height) = f.placement.unwrap_or((px(0.), height));
150 paint(
167 paint(
151 line,
168 line,
152 pos + point(offset + f.x, px(0.)),
169 pos + point(offset + f.x, y),
170 height,
153 TextAlign::Left,
171 TextAlign::Left,
154 None,
172 None,
155 window,
173 window,
vendor/gpui-base/src/input/editor/display_map/mod.rs +2 −0
@@ -12,11 +12,13 @@ mod inline_line;
12 12 pub(crate) use inline_line::{InlineFragment, InputLine};
13 13 mod fold_map;
14 14 mod folding;
15 mod scaled_text;
15 16 mod text_wrapper;
16 17 mod wrap_map;
17 18
18 19 // Re-export public API
19 20 pub use self::display_map::{DisplayMap, WrappingIndent};
21 pub(crate) use self::scaled_text::{ScaledRow, scaled_row};
20 22 pub(crate) use self::text_wrapper::{InlineMetric, LineLayout, split_run_by_font_overrides};
21 23
22 24 // Re-export FoldRange and extract_fold_ranges
@@ -12,11 +12,13 @@ mod inline_line;
12pub(crate) use inline_line::{InlineFragment, InputLine};
12pub(crate) use inline_line::{InlineFragment, InputLine};
13mod fold_map;
13mod fold_map;
14mod folding;
14mod folding;
15mod scaled_text;
15mod text_wrapper;
16mod text_wrapper;
16mod wrap_map;
17mod wrap_map;
17
18
18// Re-export public API
19// Re-export public API
19pub use self::display_map::{DisplayMap, WrappingIndent};
20pub use self::display_map::{DisplayMap, WrappingIndent};
21pub(crate) use self::scaled_text::{ScaledRow, scaled_row};
20pub(crate) use self::text_wrapper::{InlineMetric, LineLayout, split_run_by_font_overrides};
22pub(crate) use self::text_wrapper::{InlineMetric, LineLayout, split_run_by_font_overrides};
21
23
22// Re-export FoldRange and extract_fold_ranges
24// Re-export FoldRange and extract_fold_ranges
vendor/gpui-base/src/input/editor/display_map/scaled_text.rs added +285 −0
@@ -0,0 +1,285 @@
1 use std::ops::Range;
2
3 use gpui::{Font, Pixels, TextRun, TextSystem, px};
4 use smallvec::SmallVec;
5
6 use super::text_wrapper::split_run_by_font_overrides;
7 use crate::input::decorations::FontOverride;
8
9 const HEIGHT_EPSILON: Pixels = px(0.01);
10
11 #[derive(Clone, Debug, PartialEq)]
12 pub(crate) struct ScalePiece {
13 pub(crate) range: Range<usize>,
14 pub(crate) scale: f32,
15 pub(crate) raise: f32,
16 }
17
18 #[derive(Clone, Copy, Debug, PartialEq)]
19 pub(crate) struct FontMetrics {
20 pub(crate) ascent: Pixels,
21 pub(crate) descent: Pixels,
22 }
23
24 #[derive(Clone, Debug, PartialEq)]
25 pub(crate) struct RowPiece {
26 pub(crate) piece: ScalePiece,
27 pub(crate) metrics: FontMetrics,
28 }
29
30 #[derive(Clone, Copy, Debug, PartialEq)]
31 pub(crate) struct RowBox {
32 pub(crate) baseline: Pixels,
33 pub(crate) height: Pixels,
34 pub(crate) base_baseline: Pixels,
35 }
36
37 #[derive(Clone, Debug, PartialEq)]
38 pub(crate) struct ScaledRow {
39 pub(crate) row_box: RowBox,
40 pub(crate) pieces: SmallVec<[RowPiece; 4]>,
41 pub(crate) font_size: Pixels,
42 }
43
44 impl RowBox {
45 pub(crate) fn custom_height(&self, line_height: Pixels) -> Option<Pixels> {
46 ((self.height - line_height).abs() > HEIGHT_EPSILON).then_some(self.height)
47 }
48 }
49
50 impl ScaledRow {
51 pub(crate) fn pieces_in<'a>(
52 &'a self,
53 range: Range<usize>,
54 ) -> impl Iterator<Item = (Range<usize>, &'a RowPiece)> + 'a {
55 self.pieces.iter().filter_map(move |row_piece| {
56 let start = row_piece.piece.range.start.max(range.start);
57 let end = row_piece.piece.range.end.min(range.end);
58 (start < end).then_some((start..end, row_piece))
59 })
60 }
61
62 pub(crate) fn raise_pixels(&self, row_piece: &RowPiece) -> Pixels {
63 self.font_size * row_piece.piece.raise
64 }
65 }
66
67 pub(crate) fn scale_pieces(
68 range: Range<usize>,
69 font_overrides: &[(Range<usize>, FontOverride)],
70 ) -> Option<SmallVec<[ScalePiece; 4]>> {
71 let first = font_overrides.partition_point(|(span, _)| span.end <= range.start);
72 let mut pieces: SmallVec<[ScalePiece; 4]> = SmallVec::new();
73 let mut offset = range.start;
74 let mut scaled = false;
75 let mut push = |range: Range<usize>, scale: f32, raise: f32| match pieces.last_mut() {
76 Some(last)
77 if last.scale == scale && last.raise == raise && last.range.end == range.start =>
78 {
79 last.range.end = range.end;
80 }
81 _ => pieces.push(ScalePiece {
82 range,
83 scale,
84 raise,
85 }),
86 };
87 for (span, font_override) in &font_overrides[first..] {
88 if span.start >= range.end {
89 break;
90 }
91 let start = span.start.max(range.start);
92 let end = span.end.min(range.end);
93 if offset < start {
94 push(offset..start, 1., 0.);
95 }
96 let scale = font_override.scale.unwrap_or(1.);
97 let raise = font_override.raise.unwrap_or(0.);
98 scaled |= scale != 1. || raise != 0.;
99 push(start..end, scale, raise);
100 offset = end;
101 }
102 if offset < range.end {
103 push(offset..range.end, 1., 0.);
104 }
105 scaled.then_some(pieces)
106 }
107
108 fn runs_metrics(text_system: &TextSystem, runs: &[TextRun], font_size: Pixels) -> FontMetrics {
109 runs.iter().fold(
110 FontMetrics {
111 ascent: px(0.),
112 descent: px(0.),
113 },
114 |metrics, run| {
115 let font_id = text_system.resolve_font(&run.font);
116 FontMetrics {
117 ascent: metrics.ascent.max(text_system.ascent(font_id, font_size)),
118 descent: metrics.descent.max(text_system.descent(font_id, font_size)),
119 }
120 },
121 )
122 }
123
124 fn centered_baseline(box_height: Pixels, metrics: FontMetrics) -> Pixels {
125 (box_height - metrics.ascent - metrics.descent) / 2. + metrics.ascent
126 }
127
128 pub(crate) fn scaled_row(
129 text_system: &TextSystem,
130 font: &Font,
131 font_size: Pixels,
132 line_height: Pixels,
133 range: Range<usize>,
134 font_overrides: &[(Range<usize>, FontOverride)],
135 ) -> Option<ScaledRow> {
136 let pieces = scale_pieces(range, font_overrides)?;
137 let run = |len: usize| TextRun {
138 len,
139 font: font.clone(),
140 color: gpui::black(),
141 background_color: None,
142 underline: None,
143 strikethrough: None,
144 };
145 let base_metrics = runs_metrics(text_system, &[run(0)], font_size);
146 let pieces: SmallVec<[RowPiece; 4]> = pieces
147 .into_iter()
148 .map(|piece| {
149 let runs = split_run_by_font_overrides(
150 run(piece.range.len()),
151 piece.range.clone(),
152 font_overrides,
153 );
154 let metrics = runs_metrics(text_system, &runs, font_size * piece.scale);
155 RowPiece { piece, metrics }
156 })
157 .collect();
158 Some(ScaledRow {
159 row_box: row_box(line_height, font_size, base_metrics, &pieces),
160 pieces,
161 font_size,
162 })
163 }
164
165 fn row_box(
166 line_height: Pixels,
167 font_size: Pixels,
168 base_metrics: FontMetrics,
169 pieces: &[RowPiece],
170 ) -> RowBox {
171 let base_baseline = centered_baseline(line_height, base_metrics);
172 let mut above = base_baseline;
173 let mut below = line_height - base_baseline;
174 for row_piece in pieces {
175 let height = line_height * row_piece.piece.scale;
176 let baseline = centered_baseline(height, row_piece.metrics);
177 let raise = font_size * row_piece.piece.raise;
178 above = above.max(baseline + raise);
179 below = below.max(height - baseline - raise);
180 }
181 RowBox {
182 baseline: above,
183 height: above + below,
184 base_baseline,
185 }
186 }
187
188 #[cfg(test)]
189 mod tests {
190 use super::*;
191
192 fn scaled(scale: f32, raise: f32) -> FontOverride {
193 FontOverride {
194 scale: Some(scale),
195 raise: Some(raise),
196 ..Default::default()
197 }
198 }
199
200 #[test]
201 fn plain_ranges_have_no_pieces() {
202 assert_eq!(scale_pieces(0..10, &[]), None);
203 let overrides = [(
204 2..4,
205 FontOverride {
206 family: Some("Mono".into()),
207 ..Default::default()
208 },
209 )];
210 assert_eq!(scale_pieces(0..10, &overrides), None);
211 assert_eq!(scale_pieces(5..10, &[(0..4, scaled(2., 0.))]), None);
212 }
213
214 #[test]
215 fn pieces_fill_gaps_clip_to_the_range_and_merge_equal_neighbours() {
216 let overrides = [
217 (2..4, scaled(2., 0.)),
218 (4..6, scaled(2., 0.)),
219 (8..12, scaled(0.5, 0.35)),
220 ];
221 let piece = |range, scale, raise| ScalePiece {
222 range,
223 scale,
224 raise,
225 };
226 assert_eq!(
227 scale_pieces(1..10, &overrides).unwrap().as_slice(),
228 [
229 piece(1..2, 1., 0.),
230 piece(2..6, 2., 0.),
231 piece(6..8, 1., 0.),
232 piece(8..10, 0.5, 0.35),
233 ]
234 );
235 }
236
237 fn row_piece(scale: f32, raise: f32) -> RowPiece {
238 RowPiece {
239 piece: ScalePiece {
240 range: 0..1,
241 scale,
242 raise,
243 },
244 metrics: FontMetrics {
245 ascent: px(10.) * scale,
246 descent: px(4.) * scale,
247 },
248 }
249 }
250
251 #[test]
252 fn row_box_grows_for_large_and_raised_pieces_but_never_shrinks_for_small() {
253 let base = FontMetrics {
254 ascent: px(10.),
255 descent: px(4.),
256 };
257 let line_height = px(20.);
258 let box_for = |scale: f32, raise: f32| {
259 row_box(line_height, px(14.), base, &[row_piece(scale, raise)])
260 };
261 assert_eq!(box_for(1., 0.).custom_height(line_height), None);
262 assert_eq!(box_for(9. / 14., 0.).custom_height(line_height), None);
263 let large = box_for(24. / 14., 0.);
264 assert!((large.height - px(20.) * 24. / 14.).abs() < px(0.01));
265 assert!(large.baseline > large.base_baseline);
266 assert!(box_for(0.75, 0.35).height > line_height);
267 assert!(box_for(0.75, -0.2).height > line_height);
268 }
269
270 #[test]
271 fn mixed_sizes_share_one_baseline() {
272 let base = FontMetrics {
273 ascent: px(10.),
274 descent: px(4.),
275 };
276 let mixed = row_box(
277 px(20.),
278 px(14.),
279 base,
280 &[row_piece(1., 0.), row_piece(2., 0.), row_piece(0.5, 0.)],
281 );
282 let large_only = row_box(px(20.), px(14.), base, &[row_piece(2., 0.)]);
283 assert_eq!(mixed, large_only);
284 }
285 }
@@ -0,0 +1,285 @@
1use std::ops::Range;
2
3use gpui::{Font, Pixels, TextRun, TextSystem, px};
4use smallvec::SmallVec;
5
6use super::text_wrapper::split_run_by_font_overrides;
7use crate::input::decorations::FontOverride;
8
9const HEIGHT_EPSILON: Pixels = px(0.01);
10
11#[derive(Clone, Debug, PartialEq)]
12pub(crate) struct ScalePiece {
13 pub(crate) range: Range<usize>,
14 pub(crate) scale: f32,
15 pub(crate) raise: f32,
16}
17
18#[derive(Clone, Copy, Debug, PartialEq)]
19pub(crate) struct FontMetrics {
20 pub(crate) ascent: Pixels,
21 pub(crate) descent: Pixels,
22}
23
24#[derive(Clone, Debug, PartialEq)]
25pub(crate) struct RowPiece {
26 pub(crate) piece: ScalePiece,
27 pub(crate) metrics: FontMetrics,
28}
29
30#[derive(Clone, Copy, Debug, PartialEq)]
31pub(crate) struct RowBox {
32 pub(crate) baseline: Pixels,
33 pub(crate) height: Pixels,
34 pub(crate) base_baseline: Pixels,
35}
36
37#[derive(Clone, Debug, PartialEq)]
38pub(crate) struct ScaledRow {
39 pub(crate) row_box: RowBox,
40 pub(crate) pieces: SmallVec<[RowPiece; 4]>,
41 pub(crate) font_size: Pixels,
42}
43
44impl RowBox {
45 pub(crate) fn custom_height(&self, line_height: Pixels) -> Option<Pixels> {
46 ((self.height - line_height).abs() > HEIGHT_EPSILON).then_some(self.height)
47 }
48}
49
50impl ScaledRow {
51 pub(crate) fn pieces_in<'a>(
52 &'a self,
53 range: Range<usize>,
54 ) -> impl Iterator<Item = (Range<usize>, &'a RowPiece)> + 'a {
55 self.pieces.iter().filter_map(move |row_piece| {
56 let start = row_piece.piece.range.start.max(range.start);
57 let end = row_piece.piece.range.end.min(range.end);
58 (start < end).then_some((start..end, row_piece))
59 })
60 }
61
62 pub(crate) fn raise_pixels(&self, row_piece: &RowPiece) -> Pixels {
63 self.font_size * row_piece.piece.raise
64 }
65}
66
67pub(crate) fn scale_pieces(
68 range: Range<usize>,
69 font_overrides: &[(Range<usize>, FontOverride)],
70) -> Option<SmallVec<[ScalePiece; 4]>> {
71 let first = font_overrides.partition_point(|(span, _)| span.end <= range.start);
72 let mut pieces: SmallVec<[ScalePiece; 4]> = SmallVec::new();
73 let mut offset = range.start;
74 let mut scaled = false;
75 let mut push = |range: Range<usize>, scale: f32, raise: f32| match pieces.last_mut() {
76 Some(last)
77 if last.scale == scale && last.raise == raise && last.range.end == range.start =>
78 {
79 last.range.end = range.end;
80 }
81 _ => pieces.push(ScalePiece {
82 range,
83 scale,
84 raise,
85 }),
86 };
87 for (span, font_override) in &font_overrides[first..] {
88 if span.start >= range.end {
89 break;
90 }
91 let start = span.start.max(range.start);
92 let end = span.end.min(range.end);
93 if offset < start {
94 push(offset..start, 1., 0.);
95 }
96 let scale = font_override.scale.unwrap_or(1.);
97 let raise = font_override.raise.unwrap_or(0.);
98 scaled |= scale != 1. || raise != 0.;
99 push(start..end, scale, raise);
100 offset = end;
101 }
102 if offset < range.end {
103 push(offset..range.end, 1., 0.);
104 }
105 scaled.then_some(pieces)
106}
107
108fn runs_metrics(text_system: &TextSystem, runs: &[TextRun], font_size: Pixels) -> FontMetrics {
109 runs.iter().fold(
110 FontMetrics {
111 ascent: px(0.),
112 descent: px(0.),
113 },
114 |metrics, run| {
115 let font_id = text_system.resolve_font(&run.font);
116 FontMetrics {
117 ascent: metrics.ascent.max(text_system.ascent(font_id, font_size)),
118 descent: metrics.descent.max(text_system.descent(font_id, font_size)),
119 }
120 },
121 )
122}
123
124fn centered_baseline(box_height: Pixels, metrics: FontMetrics) -> Pixels {
125 (box_height - metrics.ascent - metrics.descent) / 2. + metrics.ascent
126}
127
128pub(crate) fn scaled_row(
129 text_system: &TextSystem,
130 font: &Font,
131 font_size: Pixels,
132 line_height: Pixels,
133 range: Range<usize>,
134 font_overrides: &[(Range<usize>, FontOverride)],
135) -> Option<ScaledRow> {
136 let pieces = scale_pieces(range, font_overrides)?;
137 let run = |len: usize| TextRun {
138 len,
139 font: font.clone(),
140 color: gpui::black(),
141 background_color: None,
142 underline: None,
143 strikethrough: None,
144 };
145 let base_metrics = runs_metrics(text_system, &[run(0)], font_size);
146 let pieces: SmallVec<[RowPiece; 4]> = pieces
147 .into_iter()
148 .map(|piece| {
149 let runs = split_run_by_font_overrides(
150 run(piece.range.len()),
151 piece.range.clone(),
152 font_overrides,
153 );
154 let metrics = runs_metrics(text_system, &runs, font_size * piece.scale);
155 RowPiece { piece, metrics }
156 })
157 .collect();
158 Some(ScaledRow {
159 row_box: row_box(line_height, font_size, base_metrics, &pieces),
160 pieces,
161 font_size,
162 })
163}
164
165fn row_box(
166 line_height: Pixels,
167 font_size: Pixels,
168 base_metrics: FontMetrics,
169 pieces: &[RowPiece],
170) -> RowBox {
171 let base_baseline = centered_baseline(line_height, base_metrics);
172 let mut above = base_baseline;
173 let mut below = line_height - base_baseline;
174 for row_piece in pieces {
175 let height = line_height * row_piece.piece.scale;
176 let baseline = centered_baseline(height, row_piece.metrics);
177 let raise = font_size * row_piece.piece.raise;
178 above = above.max(baseline + raise);
179 below = below.max(height - baseline - raise);
180 }
181 RowBox {
182 baseline: above,
183 height: above + below,
184 base_baseline,
185 }
186}
187
188#[cfg(test)]
189mod tests {
190 use super::*;
191
192 fn scaled(scale: f32, raise: f32) -> FontOverride {
193 FontOverride {
194 scale: Some(scale),
195 raise: Some(raise),
196 ..Default::default()
197 }
198 }
199
200 #[test]
201 fn plain_ranges_have_no_pieces() {
202 assert_eq!(scale_pieces(0..10, &[]), None);
203 let overrides = [(
204 2..4,
205 FontOverride {
206 family: Some("Mono".into()),
207 ..Default::default()
208 },
209 )];
210 assert_eq!(scale_pieces(0..10, &overrides), None);
211 assert_eq!(scale_pieces(5..10, &[(0..4, scaled(2., 0.))]), None);
212 }
213
214 #[test]
215 fn pieces_fill_gaps_clip_to_the_range_and_merge_equal_neighbours() {
216 let overrides = [
217 (2..4, scaled(2., 0.)),
218 (4..6, scaled(2., 0.)),
219 (8..12, scaled(0.5, 0.35)),
220 ];
221 let piece = |range, scale, raise| ScalePiece {
222 range,
223 scale,
224 raise,
225 };
226 assert_eq!(
227 scale_pieces(1..10, &overrides).unwrap().as_slice(),
228 [
229 piece(1..2, 1., 0.),
230 piece(2..6, 2., 0.),
231 piece(6..8, 1., 0.),
232 piece(8..10, 0.5, 0.35),
233 ]
234 );
235 }
236
237 fn row_piece(scale: f32, raise: f32) -> RowPiece {
238 RowPiece {
239 piece: ScalePiece {
240 range: 0..1,
241 scale,
242 raise,
243 },
244 metrics: FontMetrics {
245 ascent: px(10.) * scale,
246 descent: px(4.) * scale,
247 },
248 }
249 }
250
251 #[test]
252 fn row_box_grows_for_large_and_raised_pieces_but_never_shrinks_for_small() {
253 let base = FontMetrics {
254 ascent: px(10.),
255 descent: px(4.),
256 };
257 let line_height = px(20.);
258 let box_for = |scale: f32, raise: f32| {
259 row_box(line_height, px(14.), base, &[row_piece(scale, raise)])
260 };
261 assert_eq!(box_for(1., 0.).custom_height(line_height), None);
262 assert_eq!(box_for(9. / 14., 0.).custom_height(line_height), None);
263 let large = box_for(24. / 14., 0.);
264 assert!((large.height - px(20.) * 24. / 14.).abs() < px(0.01));
265 assert!(large.baseline > large.base_baseline);
266 assert!(box_for(0.75, 0.35).height > line_height);
267 assert!(box_for(0.75, -0.2).height > line_height);
268 }
269
270 #[test]
271 fn mixed_sizes_share_one_baseline() {
272 let base = FontMetrics {
273 ascent: px(10.),
274 descent: px(4.),
275 };
276 let mixed = row_box(
277 px(20.),
278 px(14.),
279 base,
280 &[row_piece(1., 0.), row_piece(2., 0.), row_piece(0.5, 0.)],
281 );
282 let large_only = row_box(px(20.), px(14.), base, &[row_piece(2., 0.)]);
283 assert_eq!(mixed, large_only);
284 }
285}
vendor/gpui-base/src/input/editor/display_map/text_wrapper.rs +246 −35
@@ -1,4 +1,5 @@
1 1 use super::inline_line::InputLine;
2 use super::scaled_text::{scale_pieces, scaled_row};
2 3 use gpui::Half;
3 4 use std::borrow::Cow;
4 5 use std::ops::Range;
@@ -274,6 +275,7 @@ pub(crate) struct LineItem {
274 275 /// Not contains the line end `\n`.
275 276 pub(crate) wrapped_lines: SmallVec<[Range<usize>; 1]>,
276 277 pub(crate) blocks: Vec<(usize, Pixels)>,
278 pub(crate) scaled_extra: Pixels,
277 279 }
278 280
279 281 impl LineItem {
@@ -305,6 +307,7 @@ pub(crate) struct LineSummary {
305 307 longest_row: usize,
306 308 block_rows: usize,
307 309 block_height: Pixels,
310 scaled_extra: Pixels,
308 311 }
309 312
310 313 impl sum_tree::Summary for LineSummary {
@@ -319,6 +322,7 @@ impl sum_tree::Summary for LineSummary {
319 322 longest_row: 0,
320 323 block_rows: 0,
321 324 block_height: px(0.),
325 scaled_extra: px(0.),
322 326 }
323 327 }
324 328
@@ -333,6 +337,7 @@ impl sum_tree::Summary for LineSummary {
333 337 self.bytes += other.bytes;
334 338 self.block_rows += other.block_rows;
335 339 self.block_height += other.block_height;
340 self.scaled_extra += other.scaled_extra;
336 341 }
337 342 }
338 343
@@ -351,6 +356,7 @@ impl sum_tree::Item for LineItem {
351 356 .blocks
352 357 .iter()
353 358 .fold(px(0.), |height, (_, block_height)| height + *block_height),
359 scaled_extra: self.scaled_extra,
354 360 }
355 361 }
356 362 }
@@ -413,6 +419,7 @@ pub(crate) struct TextWrapper {
413 419 text: Rope,
414 420 font: Font,
415 421 font_size: Pixels,
422 line_height: Pixels,
416 423 /// If is none, it means the text is not wrapped
417 424 wrap_width: Option<Pixels>,
418 425 wrapping_indent: WrappingIndent,
@@ -436,6 +443,7 @@ impl TextWrapper {
436 443 text: Rope::new(),
437 444 font,
438 445 font_size,
446 line_height: px(0.),
439 447 wrap_width,
440 448 wrapping_indent: WrappingIndent::default(),
441 449 lines: SumTree::new(&()),
@@ -560,6 +568,10 @@ impl TextWrapper {
560 568 low
561 569 }
562 570
571 pub(crate) fn scaled_extra(&self) -> Pixels {
572 self.lines.summary().scaled_extra
573 }
574
563 575 pub(crate) fn content_height(&self, line_height: Pixels) -> Pixels {
564 576 let summary = self.lines.summary();
565 577 line_height * summary.wrap_rows as f32
@@ -594,6 +606,22 @@ impl TextWrapper {
594 606 self.update_all(&self.text.clone(), cx);
595 607 }
596 608
609 pub(crate) fn set_line_height(&mut self, line_height: Pixels, cx: &mut App) {
610 if self.line_height == line_height {
611 return;
612 }
613 self.line_height = line_height;
614 let affected: Vec<Range<usize>> = self
615 .font_overrides
616 .iter()
617 .filter(|(_, font_override)| {
618 font_override.scale.is_some() || font_override.raise.is_some()
619 })
620 .map(|(span, _)| span.clone())
621 .collect();
622 self.rewrap_rows_of(&affected, cx);
623 }
624
597 625 pub(crate) fn prepare_if_need(&mut self, text: &Rope, cx: &mut App) -> bool {
598 626 if self._initialized {
599 627 return false;
@@ -626,7 +654,11 @@ impl TextWrapper {
626 654 let text_system = gpui::WindowTextSystem::new(cx.text_system().clone());
627 655 let font = self.font.clone();
628 656 let font_size = self.font_size;
657 let line_height = self.line_height;
629 658 let wrapping_indent = self.wrapping_indent;
659 let has_scaled = font_overrides.iter().any(|(_, font_override)| {
660 font_override.scale.is_some() || font_override.raise.is_some()
661 });
630 662 self._update(
631 663 changed_text,
632 664 range,
@@ -657,21 +689,43 @@ impl TextWrapper {
657 689 if range.is_empty() {
658 690 return px(0.);
659 691 }
660 let runs = split_run_by_font_overrides(
661 TextRun {
662 len: range.len(),
663 font: font.clone(),
664 color: gpui::black(),
665 background_color: None,
666 underline: None,
667 strikethrough: None,
668 },
669 line_start + range.start..line_start + range.end,
670 &font_overrides,
671 );
672 text_system
673 .layout_line(&line_str[range], font_size, &runs, None)
674 .width
692 let measure = |range: Range<usize>, font_size: Pixels| {
693 let runs = split_run_by_font_overrides(
694 TextRun {
695 len: range.len(),
696 font: font.clone(),
697 color: gpui::black(),
698 background_color: None,
699 underline: None,
700 strikethrough: None,
701 },
702 line_start + range.start..line_start + range.end,
703 &font_overrides,
704 );
705 text_system
706 .layout_line(&line_str[range], font_size, &runs, None)
707 .width
708 };
709 let pieces = has_scaled
710 .then(|| {
711 scale_pieces(
712 line_start + range.start..line_start + range.end,
713 &font_overrides,
714 )
715 })
716 .flatten();
717 match pieces {
718 None => measure(range, font_size),
719 Some(pieces) => pieces
720 .iter()
721 .map(|piece| {
722 measure(
723 piece.range.start - line_start..piece.range.end - line_start,
724 font_size * piece.scale,
725 )
726 })
727 .fold(px(0.), |width, piece_width| width + piece_width),
728 }
675 729 };
676 730 let token_ranges: Vec<_> = tokens.iter().map(|token| token.range.clone()).collect();
677 731 let mut forced: Vec<usize> = tokens
@@ -704,6 +758,25 @@ impl TextWrapper {
704 758 },
705 759 )
706 760 },
761 &mut |line_start, rows| {
762 if !has_scaled {
763 return Vec::new();
764 }
765 rows.iter()
766 .enumerate()
767 .filter_map(|(row, range)| {
768 let scaled = scaled_row(
769 &text_system,
770 &font,
771 font_size,
772 line_height,
773 line_start + range.start..line_start + range.end,
774 &font_overrides,
775 )?;
776 Some((row, scaled.row_box.custom_height(line_height)?))
777 })
778 .collect()
779 },
707 780 );
708 781 }
709 782
@@ -859,14 +932,16 @@ impl TextWrapper {
859 932 }
860 933 }
861 934
862 fn _update<F>(
935 fn _update<F, H>(
863 936 &mut self,
864 937 changed_text: &Rope,
865 938 range: &Range<usize>,
866 939 new_text: &Rope,
867 940 wrap_line: &mut F,
941 row_heights: &mut H,
868 942 ) where
869 943 F: FnMut(&str, Pixels, usize) -> Vec<gpui::Boundary>,
944 H: FnMut(usize, &[Range<usize>]) -> Vec<(usize, Pixels)>,
870 945 {
871 946 // Remove the old changed lines.
872 947 let buffer_line_count = self.lines_count();
@@ -944,13 +1019,27 @@ impl TextWrapper {
944 1019 wrapped_lines.push(prev_boundary_ix..line.len());
945 1020 }
946 1021
947 let blocks =
1022 let mut blocks =
948 1023 block_rows_of(&self.inline_metrics, line_start, line.len(), &wrapped_lines);
1024 let mut scaled_extra = px(0.);
1025 let scaled_rows = row_heights(line_start, &wrapped_lines);
1026 if !scaled_rows.is_empty() {
1027 let scaled_rows: Vec<_> = scaled_rows
1028 .into_iter()
1029 .filter(|(row, _)| blocks.iter().all(|(block_row, _)| block_row != row))
1030 .collect();
1031 scaled_extra = scaled_rows.iter().fold(px(0.), |extra, (_, height)| {
1032 extra + (*height - self.line_height)
1033 });
1034 blocks.extend(scaled_rows);
1035 blocks.sort_by_key(|(row, _)| *row);
1036 }
949 1037 new_lines.push(LineItem {
950 1038 len: line.len(),
951 1039 indent: indent_chars,
952 1040 wrapped_lines,
953 1041 blocks,
1042 scaled_extra,
954 1043 });
955 1044 }
956 1045
@@ -1176,6 +1265,12 @@ impl LineLayout {
1176 1265 None
1177 1266 }
1178 1267
1268 pub(crate) fn inline_offset_at(&self, y: Pixels, line_height: Pixels) -> Pixels {
1269 self.row_at_y(y, line_height)
1270 .and_then(|ix| self.wrapped_lines.get(ix))
1271 .map_or(px(0.), |line| line.inline_offset)
1272 }
1273
1179 1274 pub(crate) fn lines(mut self, wrapped_lines: SmallVec<[ShapedLine; 1]>) -> Self {
1180 1275 self.set_wrapped_lines(wrapped_lines);
1181 1276 self
@@ -1679,6 +1774,7 @@ mod tests {
1679 1774 family: Some("Mono".into()),
1680 1775 weight: Some(FontWeight::BOLD),
1681 1776 style: None,
1777 ..Default::default()
1682 1778 };
1683 1779 let font_overrides = [(2..4, mono.clone()), (8..20, mono.clone())];
1684 1780 let runs = split_run_by_font_overrides(run.clone(), 0..10, &font_overrides);
@@ -1737,6 +1833,7 @@ mod tests {
1737 1833 |range| measure(&line[range]),
1738 1834 )
1739 1835 },
1836 &mut |_, _| Vec::new(),
1740 1837 );
1741 1838 let expected = if value.ends_with('s') {
1742 1839 vec![0..7, 7..value.len()]
@@ -1802,6 +1899,7 @@ mod tests {
1802 1899 indent: 0,
1803 1900 wrapped_lines,
1804 1901 blocks,
1902 scaled_extra: px(0.),
1805 1903 };
1806 1904 wrapper.lines = SumTree::from_iter(
1807 1905 [
@@ -1953,7 +2051,13 @@ mod tests {
1953 2051 assert_eq!(actual_lines, expected_lines);
1954 2052 }
1955 2053
1956 wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
2054 wrapper._update(
2055 &text,
2056 &(0..text.len()),
2057 &text,
2058 &mut fake_wrap_line,
2059 &mut |_, _| Vec::new(),
2060 );
1957 2061 assert_eq!(wrapper.lines_count(), 4);
1958 2062 assert_wrapper_lines(
1959 2063 &text,
@@ -1970,7 +2074,13 @@ mod tests {
1970 2074 let range = text.len()..text.len();
1971 2075 let new_text = "New text";
1972 2076 text.replace(range.clone(), new_text);
1973 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2077 wrapper._update(
2078 &text,
2079 &range,
2080 &Rope::from(new_text),
2081 &mut fake_wrap_line,
2082 &mut |_, _| Vec::new(),
2083 );
1974 2084 assert_eq!(
1975 2085 text.to_string(),
1976 2086 "Hello, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。New text"
@@ -1992,7 +2102,13 @@ mod tests {
1992 2102 let range = 0..5;
1993 2103 let new_text = "AAA";
1994 2104 text.replace(range.clone(), new_text);
1995 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2105 wrapper._update(
2106 &text,
2107 &range,
2108 &Rope::from(new_text),
2109 &mut fake_wrap_line,
2110 &mut |_, _| Vec::new(),
2111 );
1996 2112 assert_eq!(
1997 2113 text.to_string(),
1998 2114 "AAA, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。New text"
@@ -2014,7 +2130,13 @@ mod tests {
2014 2130 let end_offset = text.line_end_offset(1);
2015 2131 let range = start_offset..end_offset + 1;
2016 2132 text.replace(range.clone(), "");
2017 wrapper._update(&text, &range, &Rope::from(""), &mut fake_wrap_line);
2133 wrapper._update(
2134 &text,
2135 &range,
2136 &Rope::from(""),
2137 &mut fake_wrap_line,
2138 &mut |_, _| Vec::new(),
2139 );
2018 2140 assert_eq!(
2019 2141 text.to_string(),
2020 2142 "AAA, 世界!\r\nThis is third line.\n这里是第 4 行。New text"
@@ -2034,7 +2156,13 @@ mod tests {
2034 2156 let range = text.line_start_offset(0)..text.line_end_offset(1) + 1;
2035 2157 let new_text = "This is a new line.\nThis is new line 2.\n";
2036 2158 text.replace(range.clone(), new_text);
2037 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2159 wrapper._update(
2160 &text,
2161 &range,
2162 &Rope::from(new_text),
2163 &mut fake_wrap_line,
2164 &mut |_, _| Vec::new(),
2165 );
2038 2166 assert_eq!(
2039 2167 text.to_string(),
2040 2168 "This is a new line.\nThis is new line 2.\n这里是第 4 行。New text"
@@ -2054,7 +2182,13 @@ mod tests {
2054 2182 let range = text.len()..text.len();
2055 2183 let new_text = "\nThis is a new line at the end.";
2056 2184 text.replace(range.clone(), new_text);
2057 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2185 wrapper._update(
2186 &text,
2187 &range,
2188 &Rope::from(new_text),
2189 &mut fake_wrap_line,
2190 &mut |_, _| Vec::new(),
2191 );
2058 2192 assert_eq!(
2059 2193 text.to_string(),
2060 2194 "This is a new line.\nThis is new line 2.\n这里是第 4 行。New text\nThis is a new line at the end."
@@ -2075,7 +2209,13 @@ mod tests {
2075 2209 let range = 0..0;
2076 2210 let new_text = "This is a new line at the beginning.\n";
2077 2211 text.replace(range.clone(), new_text);
2078 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2212 wrapper._update(
2213 &text,
2214 &range,
2215 &Rope::from(new_text),
2216 &mut fake_wrap_line,
2217 &mut |_, _| Vec::new(),
2218 );
2079 2219 assert_eq!(
2080 2220 text.to_string(),
2081 2221 "This is a new line at the beginning.\nThis is a new line.\nThis is new line 2.\n这里是第 4 行。New text\nThis is a new line at the end."
@@ -2097,7 +2237,13 @@ mod tests {
2097 2237 let range = 0..text.len();
2098 2238 let new_text = "";
2099 2239 text.replace(range.clone(), new_text);
2100 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2240 wrapper._update(
2241 &text,
2242 &range,
2243 &Rope::from(new_text),
2244 &mut fake_wrap_line,
2245 &mut |_, _| Vec::new(),
2246 );
2101 2247 assert_eq!(text.to_string(), "");
2102 2248 assert_eq!(wrapper.lines_count(), 1);
2103 2249 assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), [0..0]);
@@ -2106,7 +2252,9 @@ mod tests {
2106 2252 let range = 0..text.len();
2107 2253 let new_text = "This is a full text.\nThis is a second line.";
2108 2254 text.replace(range.clone(), new_text);
2109 wrapper._update(&text, &range, &text, &mut fake_wrap_line);
2255 wrapper._update(&text, &range, &text, &mut fake_wrap_line, &mut |_, _| {
2256 Vec::new()
2257 });
2110 2258 assert_eq!(
2111 2259 text.to_string(),
2112 2260 "This is a full text.\nThis is a second line."
@@ -2129,7 +2277,13 @@ mod tests {
2129 2277 fn test_longest_row_after_shrink() {
2130 2278 let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
2131 2279 let mut text = Rope::from("aa\nthis is the longest line\nbb");
2132 wrapper._update(&text, &(0..text.len()), &text, &mut |_, _, _| vec![]);
2280 wrapper._update(
2281 &text,
2282 &(0..text.len()),
2283 &text,
2284 &mut |_, _, _| vec![],
2285 &mut |_, _| Vec::new(),
2286 );
2133 2287 assert_eq!(wrapper.longest_row(), 1);
2134 2288
2135 2289 // Shrink line 1 so line 2-equivalent isn't longest.
@@ -2139,7 +2293,13 @@ mod tests {
2139 2293 let range = start..end;
2140 2294 let new_text = "a very very long first line now";
2141 2295 text.replace(range.clone(), new_text);
2142 wrapper._update(&text, &range, &Rope::from(new_text), &mut |_, _, _| vec![]);
2296 wrapper._update(
2297 &text,
2298 &range,
2299 &Rope::from(new_text),
2300 &mut |_, _, _| vec![],
2301 &mut |_, _| Vec::new(),
2302 );
2143 2303 assert_eq!(wrapper.longest_row(), 0);
2144 2304 }
2145 2305
@@ -2148,7 +2308,13 @@ mod tests {
2148 2308 fn test_edit_last_line_and_full_delete() {
2149 2309 let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
2150 2310 let mut text = Rope::from("one\ntwo\nthree");
2151 wrapper._update(&text, &(0..text.len()), &text, &mut |_, _, _| vec![]);
2311 wrapper._update(
2312 &text,
2313 &(0..text.len()),
2314 &text,
2315 &mut |_, _, _| vec![],
2316 &mut |_, _| Vec::new(),
2317 );
2152 2318 assert_eq!(wrapper.lines_count(), 3);
2153 2319
2154 2320 // Replace the last line only.
@@ -2156,14 +2322,26 @@ mod tests {
2156 2322 let range = start..text.len();
2157 2323 let new_text = "THREE EDITED";
2158 2324 text.replace(range.clone(), new_text);
2159 wrapper._update(&text, &range, &Rope::from(new_text), &mut |_, _, _| vec![]);
2325 wrapper._update(
2326 &text,
2327 &range,
2328 &Rope::from(new_text),
2329 &mut |_, _, _| vec![],
2330 &mut |_, _| Vec::new(),
2331 );
2160 2332 assert_eq!(wrapper.lines_count(), 3);
2161 2333 assert_eq!(wrapper.line(2).unwrap().len(), "THREE EDITED".len());
2162 2334
2163 2335 // Delete everything.
2164 2336 let range = 0..text.len();
2165 2337 text.replace(range.clone(), "");
2166 wrapper._update(&text, &range, &Rope::from(""), &mut |_, _, _| vec![]);
2338 wrapper._update(
2339 &text,
2340 &range,
2341 &Rope::from(""),
2342 &mut |_, _, _| vec![],
2343 &mut |_, _| Vec::new(),
2344 );
2167 2345 assert_eq!(wrapper.lines_count(), 1);
2168 2346 assert_eq!(wrapper.len(), 1);
2169 2347 assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), [0..0]);
@@ -2180,18 +2358,21 @@ mod tests {
2180 2358 indent: 0,
2181 2359 wrapped_lines: smallvec::smallvec![0..2],
2182 2360 blocks: Vec::new(),
2361 scaled_extra: px(0.),
2183 2362 },
2184 2363 LineItem {
2185 2364 len: 4,
2186 2365 indent: 0,
2187 2366 wrapped_lines: smallvec::smallvec![0..2, 2..4],
2188 2367 blocks: Vec::new(),
2368 scaled_extra: px(0.),
2189 2369 },
2190 2370 LineItem {
2191 2371 len: 1,
2192 2372 indent: 0,
2193 2373 wrapped_lines: smallvec::smallvec![0..1],
2194 2374 blocks: Vec::new(),
2375 scaled_extra: px(0.),
2195 2376 },
2196 2377 ],
2197 2378 &(),
@@ -2232,7 +2413,13 @@ mod tests {
2232 2413 }
2233 2414 };
2234 2415
2235 wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
2416 wrapper._update(
2417 &text,
2418 &(0..text.len()),
2419 &text,
2420 &mut fake_wrap_line,
2421 &mut |_, _| Vec::new(),
2422 );
2236 2423 assert_eq!(wrapper.buffer_line_to_wrap_row_range(0), 0..1);
2237 2424 assert_eq!(wrapper.buffer_line_to_wrap_row_range(1), 1..3);
2238 2425 assert_eq!(wrapper.buffer_line_to_wrap_row_range(2), 3..4);
@@ -2240,7 +2427,13 @@ mod tests {
2240 2427 let range = text.line_start_offset(1)..text.line_end_offset(1);
2241 2428 let new_text = "dd\neeee";
2242 2429 text.replace(range.clone(), new_text);
2243 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2430 wrapper._update(
2431 &text,
2432 &range,
2433 &Rope::from(new_text),
2434 &mut fake_wrap_line,
2435 &mut |_, _| Vec::new(),
2436 );
2244 2437
2245 2438 assert_eq!(wrapper.lines_count(), 4);
2246 2439 assert_eq!(wrapper.len(), 5);
@@ -2354,12 +2547,14 @@ mod tests {
2354 2547 indent: 0,
2355 2548 wrapped_lines: smallvec::smallvec![0..10],
2356 2549 blocks: Vec::new(),
2550 scaled_extra: px(0.),
2357 2551 },
2358 2552 LineItem {
2359 2553 len: Rope::from("this one wraps").len(),
2360 2554 indent: 0,
2361 2555 wrapped_lines: smallvec::smallvec![0..9, 9..14],
2362 2556 blocks: Vec::new(),
2557 scaled_extra: px(0.),
2363 2558 },
2364 2559 ],
2365 2560 &(),
@@ -2412,6 +2607,7 @@ mod tests {
2412 2607 indent: 0,
2413 2608 wrapped_lines: smallvec::smallvec![0..15],
2414 2609 blocks: Vec::new(),
2610 scaled_extra: px(0.),
2415 2611 },
2416 2612 // range: 16..36
2417 2613 LineItem {
@@ -2419,6 +2615,7 @@ mod tests {
2419 2615 indent: 0,
2420 2616 wrapped_lines: smallvec::smallvec![0..10, 10..20],
2421 2617 blocks: Vec::new(),
2618 scaled_extra: px(0.),
2422 2619 },
2423 2620 // range: 37..56
2424 2621 LineItem {
@@ -2426,6 +2623,7 @@ mod tests {
2426 2623 indent: 0,
2427 2624 wrapped_lines: smallvec::smallvec![0..9, 9..15, 15..20],
2428 2625 blocks: Vec::new(),
2626 scaled_extra: px(0.),
2429 2627 },
2430 2628 // range: 57..79
2431 2629 LineItem {
@@ -2433,6 +2631,7 @@ mod tests {
2433 2631 indent: 0,
2434 2632 wrapped_lines: smallvec::smallvec![0..22],
2435 2633 blocks: Vec::new(),
2634 scaled_extra: px(0.),
2436 2635 },
2437 2636 ],
2438 2637 &(),
@@ -2527,7 +2726,13 @@ mod tests {
2527 2726 }
2528 2727 };
2529 2728
2530 wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
2729 wrapper._update(
2730 &text,
2731 &(0..text.len()),
2732 &text,
2733 &mut fake_wrap_line,
2734 &mut |_, _| Vec::new(),
2735 );
2531 2736
2532 2737 let line = wrapper.line(0).unwrap();
2533 2738 assert_eq!(line.indent, 2);
@@ -2559,7 +2764,13 @@ mod tests {
2559 2764 }
2560 2765 };
2561 2766
2562 wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
2767 wrapper._update(
2768 &text,
2769 &(0..text.len()),
2770 &text,
2771 &mut fake_wrap_line,
2772 &mut |_, _| Vec::new(),
2773 );
2563 2774
2564 2775 let line = wrapper.line(0).unwrap();
2565 2776 assert_eq!(line.indent, 0);
@@ -1,4 +1,5 @@
1use super::inline_line::InputLine;
1use super::inline_line::InputLine;
2use super::scaled_text::{scale_pieces, scaled_row};
2use gpui::Half;
3use gpui::Half;
3use std::borrow::Cow;
4use std::borrow::Cow;
4use std::ops::Range;
5use std::ops::Range;
@@ -274,6 +275,7 @@ pub(crate) struct LineItem {
274 /// Not contains the line end `\n`.
275 /// Not contains the line end `\n`.
275 pub(crate) wrapped_lines: SmallVec<[Range<usize>; 1]>,
276 pub(crate) wrapped_lines: SmallVec<[Range<usize>; 1]>,
276 pub(crate) blocks: Vec<(usize, Pixels)>,
277 pub(crate) blocks: Vec<(usize, Pixels)>,
278 pub(crate) scaled_extra: Pixels,
277}
279}
278
280
279impl LineItem {
281impl LineItem {
@@ -305,6 +307,7 @@ pub(crate) struct LineSummary {
305 longest_row: usize,
307 longest_row: usize,
306 block_rows: usize,
308 block_rows: usize,
307 block_height: Pixels,
309 block_height: Pixels,
310 scaled_extra: Pixels,
308}
311}
309
312
310impl sum_tree::Summary for LineSummary {
313impl sum_tree::Summary for LineSummary {
@@ -319,6 +322,7 @@ impl sum_tree::Summary for LineSummary {
319 longest_row: 0,
322 longest_row: 0,
320 block_rows: 0,
323 block_rows: 0,
321 block_height: px(0.),
324 block_height: px(0.),
325 scaled_extra: px(0.),
322 }
326 }
323 }
327 }
324
328
@@ -333,6 +337,7 @@ impl sum_tree::Summary for LineSummary {
333 self.bytes += other.bytes;
337 self.bytes += other.bytes;
334 self.block_rows += other.block_rows;
338 self.block_rows += other.block_rows;
335 self.block_height += other.block_height;
339 self.block_height += other.block_height;
340 self.scaled_extra += other.scaled_extra;
336 }
341 }
337}
342}
338
343
@@ -351,6 +356,7 @@ impl sum_tree::Item for LineItem {
351 .blocks
356 .blocks
352 .iter()
357 .iter()
353 .fold(px(0.), |height, (_, block_height)| height + *block_height),
358 .fold(px(0.), |height, (_, block_height)| height + *block_height),
359 scaled_extra: self.scaled_extra,
354 }
360 }
355 }
361 }
356}
362}
@@ -413,6 +419,7 @@ pub(crate) struct TextWrapper {
413 text: Rope,
419 text: Rope,
414 font: Font,
420 font: Font,
415 font_size: Pixels,
421 font_size: Pixels,
422 line_height: Pixels,
416 /// If is none, it means the text is not wrapped
423 /// If is none, it means the text is not wrapped
417 wrap_width: Option<Pixels>,
424 wrap_width: Option<Pixels>,
418 wrapping_indent: WrappingIndent,
425 wrapping_indent: WrappingIndent,
@@ -436,6 +443,7 @@ impl TextWrapper {
436 text: Rope::new(),
443 text: Rope::new(),
437 font,
444 font,
438 font_size,
445 font_size,
446 line_height: px(0.),
439 wrap_width,
447 wrap_width,
440 wrapping_indent: WrappingIndent::default(),
448 wrapping_indent: WrappingIndent::default(),
441 lines: SumTree::new(&()),
449 lines: SumTree::new(&()),
@@ -560,6 +568,10 @@ impl TextWrapper {
560 low
568 low
561 }
569 }
562
570
571 pub(crate) fn scaled_extra(&self) -> Pixels {
572 self.lines.summary().scaled_extra
573 }
574
563 pub(crate) fn content_height(&self, line_height: Pixels) -> Pixels {
575 pub(crate) fn content_height(&self, line_height: Pixels) -> Pixels {
564 let summary = self.lines.summary();
576 let summary = self.lines.summary();
565 line_height * summary.wrap_rows as f32
577 line_height * summary.wrap_rows as f32
@@ -594,6 +606,22 @@ impl TextWrapper {
594 self.update_all(&self.text.clone(), cx);
606 self.update_all(&self.text.clone(), cx);
595 }
607 }
596
608
609 pub(crate) fn set_line_height(&mut self, line_height: Pixels, cx: &mut App) {
610 if self.line_height == line_height {
611 return;
612 }
613 self.line_height = line_height;
614 let affected: Vec<Range<usize>> = self
615 .font_overrides
616 .iter()
617 .filter(|(_, font_override)| {
618 font_override.scale.is_some() || font_override.raise.is_some()
619 })
620 .map(|(span, _)| span.clone())
621 .collect();
622 self.rewrap_rows_of(&affected, cx);
623 }
624
597 pub(crate) fn prepare_if_need(&mut self, text: &Rope, cx: &mut App) -> bool {
625 pub(crate) fn prepare_if_need(&mut self, text: &Rope, cx: &mut App) -> bool {
598 if self._initialized {
626 if self._initialized {
599 return false;
627 return false;
@@ -626,7 +654,11 @@ impl TextWrapper {
626 let text_system = gpui::WindowTextSystem::new(cx.text_system().clone());
654 let text_system = gpui::WindowTextSystem::new(cx.text_system().clone());
627 let font = self.font.clone();
655 let font = self.font.clone();
628 let font_size = self.font_size;
656 let font_size = self.font_size;
657 let line_height = self.line_height;
629 let wrapping_indent = self.wrapping_indent;
658 let wrapping_indent = self.wrapping_indent;
659 let has_scaled = font_overrides.iter().any(|(_, font_override)| {
660 font_override.scale.is_some() || font_override.raise.is_some()
661 });
630 self._update(
662 self._update(
631 changed_text,
663 changed_text,
632 range,
664 range,
@@ -657,21 +689,43 @@ impl TextWrapper {
657 if range.is_empty() {
689 if range.is_empty() {
658 return px(0.);
690 return px(0.);
659 }
691 }
660 let runs = split_run_by_font_overrides(
692 let measure = |range: Range<usize>, font_size: Pixels| {
661 TextRun {
693 let runs = split_run_by_font_overrides(
662 len: range.len(),
694 TextRun {
663 font: font.clone(),
695 len: range.len(),
664 color: gpui::black(),
696 font: font.clone(),
665 background_color: None,
697 color: gpui::black(),
666 underline: None,
698 background_color: None,
667 strikethrough: None,
699 underline: None,
668 },
700 strikethrough: None,
669 line_start + range.start..line_start + range.end,
701 },
670 &font_overrides,
702 line_start + range.start..line_start + range.end,
671 );
703 &font_overrides,
672 text_system
704 );
673 .layout_line(&line_str[range], font_size, &runs, None)
705 text_system
674 .width
706 .layout_line(&line_str[range], font_size, &runs, None)
707 .width
708 };
709 let pieces = has_scaled
710 .then(|| {
711 scale_pieces(
712 line_start + range.start..line_start + range.end,
713 &font_overrides,
714 )
715 })
716 .flatten();
717 match pieces {
718 None => measure(range, font_size),
719 Some(pieces) => pieces
720 .iter()
721 .map(|piece| {
722 measure(
723 piece.range.start - line_start..piece.range.end - line_start,
724 font_size * piece.scale,
725 )
726 })
727 .fold(px(0.), |width, piece_width| width + piece_width),
728 }
675 };
729 };
676 let token_ranges: Vec<_> = tokens.iter().map(|token| token.range.clone()).collect();
730 let token_ranges: Vec<_> = tokens.iter().map(|token| token.range.clone()).collect();
677 let mut forced: Vec<usize> = tokens
731 let mut forced: Vec<usize> = tokens
@@ -704,6 +758,25 @@ impl TextWrapper {
704 },
758 },
705 )
759 )
706 },
760 },
761 &mut |line_start, rows| {
762 if !has_scaled {
763 return Vec::new();
764 }
765 rows.iter()
766 .enumerate()
767 .filter_map(|(row, range)| {
768 let scaled = scaled_row(
769 &text_system,
770 &font,
771 font_size,
772 line_height,
773 line_start + range.start..line_start + range.end,
774 &font_overrides,
775 )?;
776 Some((row, scaled.row_box.custom_height(line_height)?))
777 })
778 .collect()
779 },
707 );
780 );
708 }
781 }
709
782
@@ -859,14 +932,16 @@ impl TextWrapper {
859 }
932 }
860 }
933 }
861
934
862 fn _update<F>(
935 fn _update<F, H>(
863 &mut self,
936 &mut self,
864 changed_text: &Rope,
937 changed_text: &Rope,
865 range: &Range<usize>,
938 range: &Range<usize>,
866 new_text: &Rope,
939 new_text: &Rope,
867 wrap_line: &mut F,
940 wrap_line: &mut F,
941 row_heights: &mut H,
868 ) where
942 ) where
869 F: FnMut(&str, Pixels, usize) -> Vec<gpui::Boundary>,
943 F: FnMut(&str, Pixels, usize) -> Vec<gpui::Boundary>,
944 H: FnMut(usize, &[Range<usize>]) -> Vec<(usize, Pixels)>,
870 {
945 {
871 // Remove the old changed lines.
946 // Remove the old changed lines.
872 let buffer_line_count = self.lines_count();
947 let buffer_line_count = self.lines_count();
@@ -944,13 +1019,27 @@ impl TextWrapper {
944 wrapped_lines.push(prev_boundary_ix..line.len());
1019 wrapped_lines.push(prev_boundary_ix..line.len());
945 }
1020 }
946
1021
947 let blocks =
1022 let mut blocks =
948 block_rows_of(&self.inline_metrics, line_start, line.len(), &wrapped_lines);
1023 block_rows_of(&self.inline_metrics, line_start, line.len(), &wrapped_lines);
1024 let mut scaled_extra = px(0.);
1025 let scaled_rows = row_heights(line_start, &wrapped_lines);
1026 if !scaled_rows.is_empty() {
1027 let scaled_rows: Vec<_> = scaled_rows
1028 .into_iter()
1029 .filter(|(row, _)| blocks.iter().all(|(block_row, _)| block_row != row))
1030 .collect();
1031 scaled_extra = scaled_rows.iter().fold(px(0.), |extra, (_, height)| {
1032 extra + (*height - self.line_height)
1033 });
1034 blocks.extend(scaled_rows);
1035 blocks.sort_by_key(|(row, _)| *row);
1036 }
949 new_lines.push(LineItem {
1037 new_lines.push(LineItem {
950 len: line.len(),
1038 len: line.len(),
951 indent: indent_chars,
1039 indent: indent_chars,
952 wrapped_lines,
1040 wrapped_lines,
953 blocks,
1041 blocks,
1042 scaled_extra,
954 });
1043 });
955 }
1044 }
956
1045
@@ -1176,6 +1265,12 @@ impl LineLayout {
1176 None
1265 None
1177 }
1266 }
1178
1267
1268 pub(crate) fn inline_offset_at(&self, y: Pixels, line_height: Pixels) -> Pixels {
1269 self.row_at_y(y, line_height)
1270 .and_then(|ix| self.wrapped_lines.get(ix))
1271 .map_or(px(0.), |line| line.inline_offset)
1272 }
1273
1179 pub(crate) fn lines(mut self, wrapped_lines: SmallVec<[ShapedLine; 1]>) -> Self {
1274 pub(crate) fn lines(mut self, wrapped_lines: SmallVec<[ShapedLine; 1]>) -> Self {
1180 self.set_wrapped_lines(wrapped_lines);
1275 self.set_wrapped_lines(wrapped_lines);
1181 self
1276 self
@@ -1679,6 +1774,7 @@ mod tests {
1679 family: Some("Mono".into()),
1774 family: Some("Mono".into()),
1680 weight: Some(FontWeight::BOLD),
1775 weight: Some(FontWeight::BOLD),
1681 style: None,
1776 style: None,
1777 ..Default::default()
1682 };
1778 };
1683 let font_overrides = [(2..4, mono.clone()), (8..20, mono.clone())];
1779 let font_overrides = [(2..4, mono.clone()), (8..20, mono.clone())];
1684 let runs = split_run_by_font_overrides(run.clone(), 0..10, &font_overrides);
1780 let runs = split_run_by_font_overrides(run.clone(), 0..10, &font_overrides);
@@ -1737,6 +1833,7 @@ mod tests {
1737 |range| measure(&line[range]),
1833 |range| measure(&line[range]),
1738 )
1834 )
1739 },
1835 },
1836 &mut |_, _| Vec::new(),
1740 );
1837 );
1741 let expected = if value.ends_with('s') {
1838 let expected = if value.ends_with('s') {
1742 vec![0..7, 7..value.len()]
1839 vec![0..7, 7..value.len()]
@@ -1802,6 +1899,7 @@ mod tests {
1802 indent: 0,
1899 indent: 0,
1803 wrapped_lines,
1900 wrapped_lines,
1804 blocks,
1901 blocks,
1902 scaled_extra: px(0.),
1805 };
1903 };
1806 wrapper.lines = SumTree::from_iter(
1904 wrapper.lines = SumTree::from_iter(
1807 [
1905 [
@@ -1953,7 +2051,13 @@ mod tests {
1953 assert_eq!(actual_lines, expected_lines);
2051 assert_eq!(actual_lines, expected_lines);
1954 }
2052 }
1955
2053
1956 wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
2054 wrapper._update(
2055 &text,
2056 &(0..text.len()),
2057 &text,
2058 &mut fake_wrap_line,
2059 &mut |_, _| Vec::new(),
2060 );
1957 assert_eq!(wrapper.lines_count(), 4);
2061 assert_eq!(wrapper.lines_count(), 4);
1958 assert_wrapper_lines(
2062 assert_wrapper_lines(
1959 &text,
2063 &text,
@@ -1970,7 +2074,13 @@ mod tests {
1970 let range = text.len()..text.len();
2074 let range = text.len()..text.len();
1971 let new_text = "New text";
2075 let new_text = "New text";
1972 text.replace(range.clone(), new_text);
2076 text.replace(range.clone(), new_text);
1973 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2077 wrapper._update(
2078 &text,
2079 &range,
2080 &Rope::from(new_text),
2081 &mut fake_wrap_line,
2082 &mut |_, _| Vec::new(),
2083 );
1974 assert_eq!(
2084 assert_eq!(
1975 text.to_string(),
2085 text.to_string(),
1976 "Hello, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。New text"
2086 "Hello, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。New text"
@@ -1992,7 +2102,13 @@ mod tests {
1992 let range = 0..5;
2102 let range = 0..5;
1993 let new_text = "AAA";
2103 let new_text = "AAA";
1994 text.replace(range.clone(), new_text);
2104 text.replace(range.clone(), new_text);
1995 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2105 wrapper._update(
2106 &text,
2107 &range,
2108 &Rope::from(new_text),
2109 &mut fake_wrap_line,
2110 &mut |_, _| Vec::new(),
2111 );
1996 assert_eq!(
2112 assert_eq!(
1997 text.to_string(),
2113 text.to_string(),
1998 "AAA, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。New text"
2114 "AAA, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。New text"
@@ -2014,7 +2130,13 @@ mod tests {
2014 let end_offset = text.line_end_offset(1);
2130 let end_offset = text.line_end_offset(1);
2015 let range = start_offset..end_offset + 1;
2131 let range = start_offset..end_offset + 1;
2016 text.replace(range.clone(), "");
2132 text.replace(range.clone(), "");
2017 wrapper._update(&text, &range, &Rope::from(""), &mut fake_wrap_line);
2133 wrapper._update(
2134 &text,
2135 &range,
2136 &Rope::from(""),
2137 &mut fake_wrap_line,
2138 &mut |_, _| Vec::new(),
2139 );
2018 assert_eq!(
2140 assert_eq!(
2019 text.to_string(),
2141 text.to_string(),
2020 "AAA, 世界!\r\nThis is third line.\n这里是第 4 行。New text"
2142 "AAA, 世界!\r\nThis is third line.\n这里是第 4 行。New text"
@@ -2034,7 +2156,13 @@ mod tests {
2034 let range = text.line_start_offset(0)..text.line_end_offset(1) + 1;
2156 let range = text.line_start_offset(0)..text.line_end_offset(1) + 1;
2035 let new_text = "This is a new line.\nThis is new line 2.\n";
2157 let new_text = "This is a new line.\nThis is new line 2.\n";
2036 text.replace(range.clone(), new_text);
2158 text.replace(range.clone(), new_text);
2037 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2159 wrapper._update(
2160 &text,
2161 &range,
2162 &Rope::from(new_text),
2163 &mut fake_wrap_line,
2164 &mut |_, _| Vec::new(),
2165 );
2038 assert_eq!(
2166 assert_eq!(
2039 text.to_string(),
2167 text.to_string(),
2040 "This is a new line.\nThis is new line 2.\n这里是第 4 行。New text"
2168 "This is a new line.\nThis is new line 2.\n这里是第 4 行。New text"
@@ -2054,7 +2182,13 @@ mod tests {
2054 let range = text.len()..text.len();
2182 let range = text.len()..text.len();
2055 let new_text = "\nThis is a new line at the end.";
2183 let new_text = "\nThis is a new line at the end.";
2056 text.replace(range.clone(), new_text);
2184 text.replace(range.clone(), new_text);
2057 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2185 wrapper._update(
2186 &text,
2187 &range,
2188 &Rope::from(new_text),
2189 &mut fake_wrap_line,
2190 &mut |_, _| Vec::new(),
2191 );
2058 assert_eq!(
2192 assert_eq!(
2059 text.to_string(),
2193 text.to_string(),
2060 "This is a new line.\nThis is new line 2.\n这里是第 4 行。New text\nThis is a new line at the end."
2194 "This is a new line.\nThis is new line 2.\n这里是第 4 行。New text\nThis is a new line at the end."
@@ -2075,7 +2209,13 @@ mod tests {
2075 let range = 0..0;
2209 let range = 0..0;
2076 let new_text = "This is a new line at the beginning.\n";
2210 let new_text = "This is a new line at the beginning.\n";
2077 text.replace(range.clone(), new_text);
2211 text.replace(range.clone(), new_text);
2078 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2212 wrapper._update(
2213 &text,
2214 &range,
2215 &Rope::from(new_text),
2216 &mut fake_wrap_line,
2217 &mut |_, _| Vec::new(),
2218 );
2079 assert_eq!(
2219 assert_eq!(
2080 text.to_string(),
2220 text.to_string(),
2081 "This is a new line at the beginning.\nThis is a new line.\nThis is new line 2.\n这里是第 4 行。New text\nThis is a new line at the end."
2221 "This is a new line at the beginning.\nThis is a new line.\nThis is new line 2.\n这里是第 4 行。New text\nThis is a new line at the end."
@@ -2097,7 +2237,13 @@ mod tests {
2097 let range = 0..text.len();
2237 let range = 0..text.len();
2098 let new_text = "";
2238 let new_text = "";
2099 text.replace(range.clone(), new_text);
2239 text.replace(range.clone(), new_text);
2100 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2240 wrapper._update(
2241 &text,
2242 &range,
2243 &Rope::from(new_text),
2244 &mut fake_wrap_line,
2245 &mut |_, _| Vec::new(),
2246 );
2101 assert_eq!(text.to_string(), "");
2247 assert_eq!(text.to_string(), "");
2102 assert_eq!(wrapper.lines_count(), 1);
2248 assert_eq!(wrapper.lines_count(), 1);
2103 assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), [0..0]);
2249 assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), [0..0]);
@@ -2106,7 +2252,9 @@ mod tests {
2106 let range = 0..text.len();
2252 let range = 0..text.len();
2107 let new_text = "This is a full text.\nThis is a second line.";
2253 let new_text = "This is a full text.\nThis is a second line.";
2108 text.replace(range.clone(), new_text);
2254 text.replace(range.clone(), new_text);
2109 wrapper._update(&text, &range, &text, &mut fake_wrap_line);
2255 wrapper._update(&text, &range, &text, &mut fake_wrap_line, &mut |_, _| {
2256 Vec::new()
2257 });
2110 assert_eq!(
2258 assert_eq!(
2111 text.to_string(),
2259 text.to_string(),
2112 "This is a full text.\nThis is a second line."
2260 "This is a full text.\nThis is a second line."
@@ -2129,7 +2277,13 @@ mod tests {
2129 fn test_longest_row_after_shrink() {
2277 fn test_longest_row_after_shrink() {
2130 let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
2278 let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
2131 let mut text = Rope::from("aa\nthis is the longest line\nbb");
2279 let mut text = Rope::from("aa\nthis is the longest line\nbb");
2132 wrapper._update(&text, &(0..text.len()), &text, &mut |_, _, _| vec![]);
2280 wrapper._update(
2281 &text,
2282 &(0..text.len()),
2283 &text,
2284 &mut |_, _, _| vec![],
2285 &mut |_, _| Vec::new(),
2286 );
2133 assert_eq!(wrapper.longest_row(), 1);
2287 assert_eq!(wrapper.longest_row(), 1);
2134
2288
2135 // Shrink line 1 so line 2-equivalent isn't longest.
2289 // Shrink line 1 so line 2-equivalent isn't longest.
@@ -2139,7 +2293,13 @@ mod tests {
2139 let range = start..end;
2293 let range = start..end;
2140 let new_text = "a very very long first line now";
2294 let new_text = "a very very long first line now";
2141 text.replace(range.clone(), new_text);
2295 text.replace(range.clone(), new_text);
2142 wrapper._update(&text, &range, &Rope::from(new_text), &mut |_, _, _| vec![]);
2296 wrapper._update(
2297 &text,
2298 &range,
2299 &Rope::from(new_text),
2300 &mut |_, _, _| vec![],
2301 &mut |_, _| Vec::new(),
2302 );
2143 assert_eq!(wrapper.longest_row(), 0);
2303 assert_eq!(wrapper.longest_row(), 0);
2144 }
2304 }
2145
2305
@@ -2148,7 +2308,13 @@ mod tests {
2148 fn test_edit_last_line_and_full_delete() {
2308 fn test_edit_last_line_and_full_delete() {
2149 let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
2309 let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
2150 let mut text = Rope::from("one\ntwo\nthree");
2310 let mut text = Rope::from("one\ntwo\nthree");
2151 wrapper._update(&text, &(0..text.len()), &text, &mut |_, _, _| vec![]);
2311 wrapper._update(
2312 &text,
2313 &(0..text.len()),
2314 &text,
2315 &mut |_, _, _| vec![],
2316 &mut |_, _| Vec::new(),
2317 );
2152 assert_eq!(wrapper.lines_count(), 3);
2318 assert_eq!(wrapper.lines_count(), 3);
2153
2319
2154 // Replace the last line only.
2320 // Replace the last line only.
@@ -2156,14 +2322,26 @@ mod tests {
2156 let range = start..text.len();
2322 let range = start..text.len();
2157 let new_text = "THREE EDITED";
2323 let new_text = "THREE EDITED";
2158 text.replace(range.clone(), new_text);
2324 text.replace(range.clone(), new_text);
2159 wrapper._update(&text, &range, &Rope::from(new_text), &mut |_, _, _| vec![]);
2325 wrapper._update(
2326 &text,
2327 &range,
2328 &Rope::from(new_text),
2329 &mut |_, _, _| vec![],
2330 &mut |_, _| Vec::new(),
2331 );
2160 assert_eq!(wrapper.lines_count(), 3);
2332 assert_eq!(wrapper.lines_count(), 3);
2161 assert_eq!(wrapper.line(2).unwrap().len(), "THREE EDITED".len());
2333 assert_eq!(wrapper.line(2).unwrap().len(), "THREE EDITED".len());
2162
2334
2163 // Delete everything.
2335 // Delete everything.
2164 let range = 0..text.len();
2336 let range = 0..text.len();
2165 text.replace(range.clone(), "");
2337 text.replace(range.clone(), "");
2166 wrapper._update(&text, &range, &Rope::from(""), &mut |_, _, _| vec![]);
2338 wrapper._update(
2339 &text,
2340 &range,
2341 &Rope::from(""),
2342 &mut |_, _, _| vec![],
2343 &mut |_, _| Vec::new(),
2344 );
2167 assert_eq!(wrapper.lines_count(), 1);
2345 assert_eq!(wrapper.lines_count(), 1);
2168 assert_eq!(wrapper.len(), 1);
2346 assert_eq!(wrapper.len(), 1);
2169 assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), [0..0]);
2347 assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), [0..0]);
@@ -2180,18 +2358,21 @@ mod tests {
2180 indent: 0,
2358 indent: 0,
2181 wrapped_lines: smallvec::smallvec![0..2],
2359 wrapped_lines: smallvec::smallvec![0..2],
2182 blocks: Vec::new(),
2360 blocks: Vec::new(),
2361 scaled_extra: px(0.),
2183 },
2362 },
2184 LineItem {
2363 LineItem {
2185 len: 4,
2364 len: 4,
2186 indent: 0,
2365 indent: 0,
2187 wrapped_lines: smallvec::smallvec![0..2, 2..4],
2366 wrapped_lines: smallvec::smallvec![0..2, 2..4],
2188 blocks: Vec::new(),
2367 blocks: Vec::new(),
2368 scaled_extra: px(0.),
2189 },
2369 },
2190 LineItem {
2370 LineItem {
2191 len: 1,
2371 len: 1,
2192 indent: 0,
2372 indent: 0,
2193 wrapped_lines: smallvec::smallvec![0..1],
2373 wrapped_lines: smallvec::smallvec![0..1],
2194 blocks: Vec::new(),
2374 blocks: Vec::new(),
2375 scaled_extra: px(0.),
2195 },
2376 },
2196 ],
2377 ],
2197 &(),
2378 &(),
@@ -2232,7 +2413,13 @@ mod tests {
2232 }
2413 }
2233 };
2414 };
2234
2415
2235 wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
2416 wrapper._update(
2417 &text,
2418 &(0..text.len()),
2419 &text,
2420 &mut fake_wrap_line,
2421 &mut |_, _| Vec::new(),
2422 );
2236 assert_eq!(wrapper.buffer_line_to_wrap_row_range(0), 0..1);
2423 assert_eq!(wrapper.buffer_line_to_wrap_row_range(0), 0..1);
2237 assert_eq!(wrapper.buffer_line_to_wrap_row_range(1), 1..3);
2424 assert_eq!(wrapper.buffer_line_to_wrap_row_range(1), 1..3);
2238 assert_eq!(wrapper.buffer_line_to_wrap_row_range(2), 3..4);
2425 assert_eq!(wrapper.buffer_line_to_wrap_row_range(2), 3..4);
@@ -2240,7 +2427,13 @@ mod tests {
2240 let range = text.line_start_offset(1)..text.line_end_offset(1);
2427 let range = text.line_start_offset(1)..text.line_end_offset(1);
2241 let new_text = "dd\neeee";
2428 let new_text = "dd\neeee";
2242 text.replace(range.clone(), new_text);
2429 text.replace(range.clone(), new_text);
2243 wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
2430 wrapper._update(
2431 &text,
2432 &range,
2433 &Rope::from(new_text),
2434 &mut fake_wrap_line,
2435 &mut |_, _| Vec::new(),
2436 );
2244
2437
2245 assert_eq!(wrapper.lines_count(), 4);
2438 assert_eq!(wrapper.lines_count(), 4);
2246 assert_eq!(wrapper.len(), 5);
2439 assert_eq!(wrapper.len(), 5);
@@ -2354,12 +2547,14 @@ mod tests {
2354 indent: 0,
2547 indent: 0,
2355 wrapped_lines: smallvec::smallvec![0..10],
2548 wrapped_lines: smallvec::smallvec![0..10],
2356 blocks: Vec::new(),
2549 blocks: Vec::new(),
2550 scaled_extra: px(0.),
2357 },
2551 },
2358 LineItem {
2552 LineItem {
2359 len: Rope::from("this one wraps").len(),
2553 len: Rope::from("this one wraps").len(),
2360 indent: 0,
2554 indent: 0,
2361 wrapped_lines: smallvec::smallvec![0..9, 9..14],
2555 wrapped_lines: smallvec::smallvec![0..9, 9..14],
2362 blocks: Vec::new(),
2556 blocks: Vec::new(),
2557 scaled_extra: px(0.),
2363 },
2558 },
2364 ],
2559 ],
2365 &(),
2560 &(),
@@ -2412,6 +2607,7 @@ mod tests {
2412 indent: 0,
2607 indent: 0,
2413 wrapped_lines: smallvec::smallvec![0..15],
2608 wrapped_lines: smallvec::smallvec![0..15],
2414 blocks: Vec::new(),
2609 blocks: Vec::new(),
2610 scaled_extra: px(0.),
2415 },
2611 },
2416 // range: 16..36
2612 // range: 16..36
2417 LineItem {
2613 LineItem {
@@ -2419,6 +2615,7 @@ mod tests {
2419 indent: 0,
2615 indent: 0,
2420 wrapped_lines: smallvec::smallvec![0..10, 10..20],
2616 wrapped_lines: smallvec::smallvec![0..10, 10..20],
2421 blocks: Vec::new(),
2617 blocks: Vec::new(),
2618 scaled_extra: px(0.),
2422 },
2619 },
2423 // range: 37..56
2620 // range: 37..56
2424 LineItem {
2621 LineItem {
@@ -2426,6 +2623,7 @@ mod tests {
2426 indent: 0,
2623 indent: 0,
2427 wrapped_lines: smallvec::smallvec![0..9, 9..15, 15..20],
2624 wrapped_lines: smallvec::smallvec![0..9, 9..15, 15..20],
2428 blocks: Vec::new(),
2625 blocks: Vec::new(),
2626 scaled_extra: px(0.),
2429 },
2627 },
2430 // range: 57..79
2628 // range: 57..79
2431 LineItem {
2629 LineItem {
@@ -2433,6 +2631,7 @@ mod tests {
2433 indent: 0,
2631 indent: 0,
2434 wrapped_lines: smallvec::smallvec![0..22],
2632 wrapped_lines: smallvec::smallvec![0..22],
2435 blocks: Vec::new(),
2633 blocks: Vec::new(),
2634 scaled_extra: px(0.),
2436 },
2635 },
2437 ],
2636 ],
2438 &(),
2637 &(),
@@ -2527,7 +2726,13 @@ mod tests {
2527 }
2726 }
2528 };
2727 };
2529
2728
2530 wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
2729 wrapper._update(
2730 &text,
2731 &(0..text.len()),
2732 &text,
2733 &mut fake_wrap_line,
2734 &mut |_, _| Vec::new(),
2735 );
2531
2736
2532 let line = wrapper.line(0).unwrap();
2737 let line = wrapper.line(0).unwrap();
2533 assert_eq!(line.indent, 2);
2738 assert_eq!(line.indent, 2);
@@ -2559,7 +2764,13 @@ mod tests {
2559 }
2764 }
2560 };
2765 };
2561
2766
2562 wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
2767 wrapper._update(
2768 &text,
2769 &(0..text.len()),
2770 &text,
2771 &mut fake_wrap_line,
2772 &mut |_, _| Vec::new(),
2773 );
2563
2774
2564 let line = wrapper.line(0).unwrap();
2775 let line = wrapper.line(0).unwrap();
2565 assert_eq!(line.indent, 0);
2776 assert_eq!(line.indent, 0);
vendor/gpui-base/src/input/editor/display_map/wrap_map.rs +4 −0
@@ -131,6 +131,10 @@ impl WrapMap {
131 131 self.wrapper.set_font_overrides(font_overrides, cx);
132 132 }
133 133
134 pub(super) fn set_line_height(&mut self, line_height: Pixels, cx: &mut App) {
135 self.wrapper.set_line_height(line_height, cx);
136 }
137
134 138 pub(super) fn set_hanging_indents(
135 139 &mut self,
136 140 hanging_indents: std::rc::Rc<[Range<usize>]>,
@@ -131,6 +131,10 @@ impl WrapMap {
131 self.wrapper.set_font_overrides(font_overrides, cx);
131 self.wrapper.set_font_overrides(font_overrides, cx);
132 }
132 }
133
133
134 pub(super) fn set_line_height(&mut self, line_height: Pixels, cx: &mut App) {
135 self.wrapper.set_line_height(line_height, cx);
136 }
137
134 pub(super) fn set_hanging_indents(
138 pub(super) fn set_hanging_indents(
135 &mut self,
139 &mut self,
136 hanging_indents: std::rc::Rc<[Range<usize>]>,
140 hanging_indents: std::rc::Rc<[Range<usize>]>,