feat(input): font family on text decorations
- TextDecoration::with_font_family overrides the font family of a byte range - render runs, soft wrap measurement, caret and hit testing use that font - vendor gpui-base via [patch.crates-io]; see vendor/gpui-base/PATCH.md Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -2818,8 +2818,6 @@ dependencies = [
2818
2818
[[package]]
2819
2819
name = "gpui-base"
2820
2820
version = "0.7.1"
2821
source = "registry+https://github.com/rust-lang/crates.io-index"
2822
checksum = "3cf698677b253118459f552fe15513858c669d79a25837a94e480db2ae330050"
2823
2821
dependencies = [
2824
2822
"aho-corasick",
2825
2823
"anyhow",
@@ -2818,8 +2818,6 @@ dependencies = [2818
[[package]]2818
[[package]]2819
name = "gpui-base"2819
name = "gpui-base"2820
version = "0.7.1"2820
version = "0.7.1"2821
source = "registry+https://github.com/rust-lang/crates.io-index"2822
checksum = "3cf698677b253118459f552fe15513858c669d79a25837a94e480db2ae330050"2823
dependencies = [2821
dependencies = [2824
"aho-corasick",2822
"aho-corasick",2825
"anyhow",2823
"anyhow",@@ -1,6 +1,6 @@
1
1
[workspace]
2
2
members = ["crates/*"]
3
exclude = ["spikes/*"]
3
exclude = ["spikes/*", "vendor"]
4
4
resolver = "2"
5
5
6
6
[workspace.package]
@@ -34,3 +34,6 @@ teams-core = { path = "crates/core" }
34
34
gpui-kit = "=0.7.1"
35
35
chatsvc = { path = "crates/chatsvc" }
36
36
webview = { path = "crates/webview" }
37
38
[patch.crates-io]
39
gpui-base = { path = "vendor/gpui-base" }
@@ -1,6 +1,6 @@1
[workspace]1
[workspace]2
members = ["crates/*"]2
members = ["crates/*"]3
exclude = ["spikes/*"]3
exclude = ["spikes/*", "vendor"]4
resolver = "2"4
resolver = "2"5
5
6
[workspace.package]6
[workspace.package]@@ -34,3 +34,6 @@ teams-core = { path = "crates/core" }34
gpui-kit = "=0.7.1"34
gpui-kit = "=0.7.1"35
chatsvc = { path = "crates/chatsvc" }35
chatsvc = { path = "crates/chatsvc" }36
webview = { path = "crates/webview" }36
webview = { path = "crates/webview" }37
38
[patch.crates-io]39
gpui-base = { path = "vendor/gpui-base" }@@ -247,3 +247,5 @@ useless_conversion = "allow"
247
247
[lints.clippy.style]
248
248
level = "allow"
249
249
priority = -1
250
251
[workspace]
@@ -247,3 +247,5 @@ useless_conversion = "allow"247
[lints.clippy.style]247
[lints.clippy.style]248
level = "allow"248
level = "allow"249
priority = -1249
priority = -1250
251
[workspace]@@ -0,0 +1,29 @@
1
# gpui-base 0.7.1 patches
2
3
Upstream: crates.io `gpui-base 0.7.1` (git `87d10ae5`, `crates/base`). Wired in via `[patch.crates-io]` in the root `Cargo.toml`.
4
5
## Changed files
6
7
| File | Change | Why |
8
|---|---|---|
9
| `Cargo.toml` | empty `[workspace]` table at the end | `cargo test --manifest-path vendor/gpui-base/Cargo.toml` works inside the app workspace (and nested worktrees) |
10
| `src/input/editor/decorations.rs` | `TextDecoration.font_family`, `with_font_family()`, `font_family_spans()`, `adjust_range_for_edit` made `pub(crate)`, doc on layering | font family per byte range; first collection / item wins |
11
| `src/input/editor/display_map/text_wrapper.rs` | `font_families` on `TextWrapper`, `split_run_by_font_families()`, `set_font_families()` / `adjust_font_families()`, `measured_wrap_boundaries` measures by range, shared `changed_ranges()` / `rewrap_rows_of()` | soft wrap measures font-family ranges in their own font |
12
| `src/input/editor/display_map/wrap_map.rs`, `display_map.rs`, `mod.rs` | pass-through for `set_font_families`, export `split_run_by_font_families` | plumbing |
13
| `src/input/base/element.rs` | prepaint pushes font-family spans into the display map; render runs split by font family | glyphs, caret, selection and hit testing use the same shaped runs |
14
15
## Limits
16
17
- Only the font family changes wrapping. Bold/italic `HighlightStyle` decorations still wrap with the regular-weight font.
18
- Lines containing inline tokens wrap through gpui's `LineWrapper` with the base font only.
19
- The unwrapped longest-line width (soft wrap off) ignores font families.
20
- Decorations exist on `EditorState` only, not `TextareaState`.
21
22
## Re-apply on a gpui-kit upgrade
23
24
1. Check the new `gpui-base` version pinned by `gpui-kit`.
25
2. `git diff <vendor commit> HEAD -- vendor/gpui-base > /tmp/gpui-base.patch` (vendor commit: `chore: vendor gpui-base 0.7.1 unchanged`).
26
3. Replace `vendor/gpui-base` with the new registry source (`~/.cargo/registry/src/*/gpui-base-<ver>/`, drop `.cargo-ok`), commit it alone.
27
4. `git apply -3 /tmp/gpui-base.patch`, fix conflicts.
28
5. `cargo test --manifest-path vendor/gpui-base/Cargo.toml --lib -- input` and `cargo build -p app`; `Cargo.lock` must show `gpui-base` without `source`.
29
6. Delete this folder and the `[patch]` entry once upstream ships the features.
@@ -0,0 +1,29 @@1
# gpui-base 0.7.1 patches2
3
Upstream: crates.io `gpui-base 0.7.1` (git `87d10ae5`, `crates/base`). Wired in via `[patch.crates-io]` in the root `Cargo.toml`.4
5
## Changed files6
7
| File | Change | Why |8
|---|---|---|9
| `Cargo.toml` | empty `[workspace]` table at the end | `cargo test --manifest-path vendor/gpui-base/Cargo.toml` works inside the app workspace (and nested worktrees) |10
| `src/input/editor/decorations.rs` | `TextDecoration.font_family`, `with_font_family()`, `font_family_spans()`, `adjust_range_for_edit` made `pub(crate)`, doc on layering | font family per byte range; first collection / item wins |11
| `src/input/editor/display_map/text_wrapper.rs` | `font_families` on `TextWrapper`, `split_run_by_font_families()`, `set_font_families()` / `adjust_font_families()`, `measured_wrap_boundaries` measures by range, shared `changed_ranges()` / `rewrap_rows_of()` | soft wrap measures font-family ranges in their own font |12
| `src/input/editor/display_map/wrap_map.rs`, `display_map.rs`, `mod.rs` | pass-through for `set_font_families`, export `split_run_by_font_families` | plumbing |13
| `src/input/base/element.rs` | prepaint pushes font-family spans into the display map; render runs split by font family | glyphs, caret, selection and hit testing use the same shaped runs |14
15
## Limits16
17
- Only the font family changes wrapping. Bold/italic `HighlightStyle` decorations still wrap with the regular-weight font.18
- Lines containing inline tokens wrap through gpui's `LineWrapper` with the base font only.19
- The unwrapped longest-line width (soft wrap off) ignores font families.20
- Decorations exist on `EditorState` only, not `TextareaState`.21
22
## Re-apply on a gpui-kit upgrade23
24
1. Check the new `gpui-base` version pinned by `gpui-kit`.25
2. `git diff <vendor commit> HEAD -- vendor/gpui-base > /tmp/gpui-base.patch` (vendor commit: `chore: vendor gpui-base 0.7.1 unchanged`).26
3. Replace `vendor/gpui-base` with the new registry source (`~/.cargo/registry/src/*/gpui-base-<ver>/`, drop `.cargo-ok`), commit it alone.27
4. `git apply -3 /tmp/gpui-base.patch`, fix conflicts.28
5. `cargo test --manifest-path vendor/gpui-base/Cargo.toml --lib -- input` and `cargo build -p app`; `Cargo.lock` must show `gpui-base` without `source`.29
6. Delete this folder and the `[patch]` entry once upstream ships the features.@@ -17,7 +17,12 @@ use std::{ops::Range, rc::Rc};
17
17
18
18
use crate::{
19
19
Scrollbar,
20
input::{RopeExt as _, blink_cursor::CURSOR_WIDTH, display_map::LineLayout},
20
input::{
21
RopeExt as _,
22
blink_cursor::CURSOR_WIDTH,
23
decorations::font_family_spans,
24
display_map::{LineLayout, split_run_by_font_families},
25
},
21
26
};
22
27
23
28
use super::{
@@ -2525,9 +2530,20 @@ impl<M: InputModeKind> Element for TextElement<M> {
2525
2530
window.text_system().layout_width(font_id, text_size, ' ')
2526
2531
};
2527
2532
2533
let font_families: Rc<[(Range<usize>, SharedString)]> = {
2534
let state = self.state.read(cx);
2535
if state.masked {
2536
Rc::from([])
2537
} else {
2538
font_family_spans(&state.extras.decoration_layers()).into()
2539
}
2540
};
2528
2541
self.state.update(cx, |state, cx| {
2529
2542
state.display_map.set_font(font, text_size, cx);
2530
2543
state.display_map.ensure_text_prepared(&state.text, cx);
2544
state
2545
.display_map
2546
.set_font_families(font_families.clone(), cx);
2531
2547
});
2532
2548
2533
2549
let state = self.state.read(cx);
@@ -2686,12 +2702,17 @@ impl<M: InputModeKind> Element for TextElement<M> {
2686
2702
run.color = run.color.opacity(0.5);
2687
2703
}
2688
2704
2689
runs.extend(split_run_for_ime_underline(
2690
run,
2691
range.clone(),
2692
ime_marked_range.clone(),
2693
marked_run.underline,
2694
));
2705
let mut start = range.start;
2706
for run in split_run_by_font_families(run, range.clone(), &font_families) {
2707
let run_range = start..start + run.len;
2708
start = run_range.end;
2709
runs.extend(split_run_for_ime_underline(
2710
run,
2711
run_range,
2712
ime_marked_range.clone(),
2713
marked_run.underline,
2714
));
2715
}
2695
2716
}
2696
2717
runs
2697
2718
} else {
@@ -3617,6 +3638,74 @@ mod tests {
3617
3638
(editor.unwrap(), window)
3618
3639
}
3619
3640
3641
#[cfg(target_os = "linux")]
3642
#[test]
3643
fn font_family_decorations_shape_wrap_and_hit_test_in_that_font() {
3644
let platform = gpui_platform::current_platform(true);
3645
let mut cx = TestAppContext::build_with_text_system(
3646
gpui::TestDispatcher::new(0),
3647
None,
3648
platform.text_system(),
3649
);
3650
let text = "iiiiiiii ".repeat(8);
3651
let mono_range = 9..35;
3652
let (editor, window) = decoration_editor(&mut cx, &text, true);
3653
let mut cx = VisualTestContext::from_window(window.into(), &mut cx);
3654
cx.update(|window, cx| {
3655
window.draw(cx).clear(cx);
3656
let plain_rows = editor.read(cx).last_layout.as_ref().unwrap().lines[0]
3657
.wrapped_lines
3658
.len();
3659
editor.update(cx, |state, cx| {
3660
state.create_decorations_collection(
3661
vec![
3662
TextDecoration::new(mono_range.clone(), HighlightStyle::default())
3663
.with_font_family("DejaVu Sans Mono"),
3664
],
3665
cx,
3666
);
3667
});
3668
window.draw(cx).clear(cx);
3669
let state = editor.read(cx);
3670
let layout = state.last_layout.as_ref().unwrap();
3671
let line = &layout.lines[0];
3672
assert!(line.wrapped_lines.len() > plain_rows);
3673
for row in line.wrapped_lines.iter() {
3674
assert!(row.width <= layout.wrap_width.unwrap());
3675
}
3676
3677
let mono_offset = mono_range.start + 4;
3678
let position = line.position_for_index(mono_offset, layout, false).unwrap();
3679
let next = line
3680
.position_for_index(mono_offset + 1, layout, false)
3681
.unwrap();
3682
let mono_glyph_width = window
3683
.text_system()
3684
.shape_line(
3685
"i".into(),
3686
window.text_style().font_size.to_pixels(window.rem_size()),
3687
&[TextRun {
3688
len: 1,
3689
font: gpui::font("DejaVu Sans Mono"),
3690
color: gpui::black(),
3691
background_color: None,
3692
underline: None,
3693
strikethrough: None,
3694
}],
3695
None,
3696
)
3697
.width;
3698
assert_eq!(next.x - position.x, mono_glyph_width);
3699
let (hit, _) = line
3700
.closest_index_for_position(
3701
point(position.x + mono_glyph_width / 4., position.y),
3702
layout,
3703
)
3704
.unwrap();
3705
assert_eq!(hit, mono_offset);
3706
});
3707
}
3708
3620
3709
#[gpui::test]
3621
3710
fn horizontal_scroll_is_clamped_before_text_and_caret_layout(cx: &mut TestAppContext) {
3622
3711
let (editor, window) = decoration_editor(cx, "short text", false);
@@ -17,7 +17,12 @@ use std::{ops::Range, rc::Rc};17
17
18
use crate::{18
use crate::{19
Scrollbar,19
Scrollbar,20
input::{RopeExt as _, blink_cursor::CURSOR_WIDTH, display_map::LineLayout},20
input::{21
RopeExt as _,22
blink_cursor::CURSOR_WIDTH,23
decorations::font_family_spans,24
display_map::{LineLayout, split_run_by_font_families},25
},21
};26
};22
27
23
use super::{28
use super::{@@ -2525,9 +2530,20 @@ impl<M: InputModeKind> Element for TextElement<M> {2525
window.text_system().layout_width(font_id, text_size, ' ')2530
window.text_system().layout_width(font_id, text_size, ' ')2526
};2531
};2527
2532
2533
let font_families: Rc<[(Range<usize>, SharedString)]> = {2534
let state = self.state.read(cx);2535
if state.masked {2536
Rc::from([])2537
} else {2538
font_family_spans(&state.extras.decoration_layers()).into()2539
}2540
};2528
self.state.update(cx, |state, cx| {2541
self.state.update(cx, |state, cx| {2529
state.display_map.set_font(font, text_size, cx);2542
state.display_map.set_font(font, text_size, cx);2530
state.display_map.ensure_text_prepared(&state.text, cx);2543
state.display_map.ensure_text_prepared(&state.text, cx);2544
state2545
.display_map2546
.set_font_families(font_families.clone(), cx);2531
});2547
});2532
2548
2533
let state = self.state.read(cx);2549
let state = self.state.read(cx);@@ -2686,12 +2702,17 @@ impl<M: InputModeKind> Element for TextElement<M> {2686
run.color = run.color.opacity(0.5);2702
run.color = run.color.opacity(0.5);2687
}2703
}2688
2704
2689
runs.extend(split_run_for_ime_underline(2705
let mut start = range.start;2690
run,2706
for run in split_run_by_font_families(run, range.clone(), &font_families) {2691
range.clone(),2707
let run_range = start..start + run.len;2692
ime_marked_range.clone(),2708
start = run_range.end;2693
marked_run.underline,2709
runs.extend(split_run_for_ime_underline(2694
));2710
run,2711
run_range,2712
ime_marked_range.clone(),2713
marked_run.underline,2714
));2715
}2695
}2716
}2696
runs2717
runs2697
} else {2718
} else {@@ -3617,6 +3638,74 @@ mod tests {3617
(editor.unwrap(), window)3638
(editor.unwrap(), window)3618
}3639
}3619
3640
3641
#[cfg(target_os = "linux")]3642
#[test]3643
fn font_family_decorations_shape_wrap_and_hit_test_in_that_font() {3644
let platform = gpui_platform::current_platform(true);3645
let mut cx = TestAppContext::build_with_text_system(3646
gpui::TestDispatcher::new(0),3647
None,3648
platform.text_system(),3649
);3650
let text = "iiiiiiii ".repeat(8);3651
let mono_range = 9..35;3652
let (editor, window) = decoration_editor(&mut cx, &text, true);3653
let mut cx = VisualTestContext::from_window(window.into(), &mut cx);3654
cx.update(|window, cx| {3655
window.draw(cx).clear(cx);3656
let plain_rows = editor.read(cx).last_layout.as_ref().unwrap().lines[0]3657
.wrapped_lines3658
.len();3659
editor.update(cx, |state, cx| {3660
state.create_decorations_collection(3661
vec![3662
TextDecoration::new(mono_range.clone(), HighlightStyle::default())3663
.with_font_family("DejaVu Sans Mono"),3664
],3665
cx,3666
);3667
});3668
window.draw(cx).clear(cx);3669
let state = editor.read(cx);3670
let layout = state.last_layout.as_ref().unwrap();3671
let line = &layout.lines[0];3672
assert!(line.wrapped_lines.len() > plain_rows);3673
for row in line.wrapped_lines.iter() {3674
assert!(row.width <= layout.wrap_width.unwrap());3675
}3676
3677
let mono_offset = mono_range.start + 4;3678
let position = line.position_for_index(mono_offset, layout, false).unwrap();3679
let next = line3680
.position_for_index(mono_offset + 1, layout, false)3681
.unwrap();3682
let mono_glyph_width = window3683
.text_system()3684
.shape_line(3685
"i".into(),3686
window.text_style().font_size.to_pixels(window.rem_size()),3687
&[TextRun {3688
len: 1,3689
font: gpui::font("DejaVu Sans Mono"),3690
color: gpui::black(),3691
background_color: None,3692
underline: None,3693
strikethrough: None,3694
}],3695
None,3696
)3697
.width;3698
assert_eq!(next.x - position.x, mono_glyph_width);3699
let (hit, _) = line3700
.closest_index_for_position(3701
point(position.x + mono_glyph_width / 4., position.y),3702
layout,3703
)3704
.unwrap();3705
assert_eq!(hit, mono_offset);3706
});3707
}3708
3620
#[gpui::test]3709
#[gpui::test]3621
fn horizontal_scroll_is_clamped_before_text_and_caret_layout(cx: &mut TestAppContext) {3710
fn horizontal_scroll_is_clamped_before_text_and_caret_layout(cx: &mut TestAppContext) {3622
let (editor, window) = decoration_editor(cx, "short text", false);3711
let (editor, window) = decoration_editor(cx, "short text", false);@@ -1,7 +1,7 @@
1
1
use crate::input::EditorMode;
2
2
use std::{collections::BTreeMap, ops::Range};
3
3
4
use gpui::{App, Context, HighlightStyle, Hsla, WeakEntity};
4
use gpui::{App, Context, HighlightStyle, Hsla, SharedString, WeakEntity};
5
5
use ropey::Rope;
6
6
use sum_tree::Bias;
7
7
@@ -72,12 +72,24 @@ impl RangeDecoration {
72
72
pub struct TextDecoration {
73
73
pub range: Range<usize>,
74
74
pub style: HighlightStyle,
75
/// Font family override; unlike `style`, it changes glyph widths and soft wrapping.
76
pub font_family: Option<SharedString>,
75
77
}
76
78
77
79
impl TextDecoration {
78
80
/// Create a text decoration from a UTF-8 byte range and a GPUI style.
79
81
pub fn new(range: Range<usize>, style: HighlightStyle) -> Self {
80
Self { range, style }
82
Self {
83
range,
84
style,
85
font_family: None,
86
}
87
}
88
89
/// Render this range in another font family, e.g. a monospace one for inline code.
90
pub fn with_font_family(mut self, font_family: impl Into<SharedString>) -> Self {
91
self.font_family = Some(font_family.into());
92
self
81
93
}
82
94
}
83
95
@@ -427,7 +439,7 @@ impl<T: TrackedDecoration> DecorationCollections<T> {
427
439
}
428
440
}
429
441
430
fn adjust_range_for_edit(
442
pub(crate) fn adjust_range_for_edit(
431
443
range: &Range<usize>,
432
444
edited_range: &Range<usize>,
433
445
inserted_len: usize,
@@ -473,6 +485,36 @@ fn adjust_range_for_edit(
473
485
start..end
474
486
}
475
487
488
/// Non-overlapping font family spans sorted by start; earlier layers and items win.
489
pub(crate) fn font_family_spans(layers: &[&[TextDecoration]]) -> Vec<(Range<usize>, SharedString)> {
490
let mut spans: Vec<(Range<usize>, SharedString)> = Vec::new();
491
for decoration in layers.iter().flat_map(|layer| layer.iter()) {
492
let Some(font_family) = &decoration.font_family else {
493
continue;
494
};
495
let mut uncovered = vec![decoration.range.clone()];
496
for (covered, _) in &spans {
497
uncovered = uncovered
498
.into_iter()
499
.flat_map(|range| {
500
[
501
range.start..range.end.min(covered.start),
502
range.start.max(covered.end)..range.end,
503
]
504
})
505
.filter(|range| !range.is_empty())
506
.collect();
507
}
508
spans.extend(
509
uncovered
510
.into_iter()
511
.map(|range| (range, font_family.clone())),
512
);
513
}
514
spans.sort_by_key(|(range, _)| range.start);
515
spans
516
}
517
476
518
fn normalize<T: TrackedDecoration>(text: &Rope, decorations: Vec<T>) -> Vec<T> {
477
519
decorations
478
520
.into_iter()
@@ -537,7 +579,8 @@ impl InputBaseState<EditorMode> {
537
579
/// Collections live until their [`InputBaseState`] is dropped.
538
580
///
539
581
/// Collections are layered in insertion order; the first collection wins
540
/// when overlapping decorations set the same [`HighlightStyle`] property.
582
/// when overlapping decorations set the same [`HighlightStyle`] property
583
/// or font family. Only the font family affects layout and soft wrapping.
541
584
/// Callers should avoid conflicting overlaps within one collection.
542
585
pub fn create_decorations_collection(
543
586
&mut self,
@@ -724,6 +767,27 @@ mod tests {
724
767
);
725
768
}
726
769
770
#[test]
771
fn font_family_spans_let_earlier_layers_and_items_win() {
772
let style = HighlightStyle::default();
773
let first = [
774
TextDecoration::new(4..8, style).with_font_family("Mono"),
775
TextDecoration::new(6..10, style).with_font_family("Serif"),
776
TextDecoration::new(0..20, style),
777
];
778
let second = [TextDecoration::new(2..12, style).with_font_family("Other")];
779
assert_eq!(TextDecoration::new(0..1, style).font_family, None);
780
assert_eq!(
781
font_family_spans(&[&first[..], &second[..]]),
782
vec![
783
(2..4, "Other".into()),
784
(4..8, "Mono".into()),
785
(8..10, "Serif".into()),
786
(10..12, "Other".into()),
787
]
788
);
789
}
790
727
791
#[test]
728
792
fn decoration_ranges_follow_text_edits() {
729
793
let style = HighlightStyle::default();
@@ -1,7 +1,7 @@1
use crate::input::EditorMode;1
use crate::input::EditorMode;2
use std::{collections::BTreeMap, ops::Range};2
use std::{collections::BTreeMap, ops::Range};3
3
4
use gpui::{App, Context, HighlightStyle, Hsla, WeakEntity};4
use gpui::{App, Context, HighlightStyle, Hsla, SharedString, WeakEntity};5
use ropey::Rope;5
use ropey::Rope;6
use sum_tree::Bias;6
use sum_tree::Bias;7
7
@@ -72,12 +72,24 @@ impl RangeDecoration {72
pub struct TextDecoration {72
pub struct TextDecoration {73
pub range: Range<usize>,73
pub range: Range<usize>,74
pub style: HighlightStyle,74
pub style: HighlightStyle,75
/// Font family override; unlike `style`, it changes glyph widths and soft wrapping.76
pub font_family: Option<SharedString>,75
}77
}76
78
77
impl TextDecoration {79
impl TextDecoration {78
/// Create a text decoration from a UTF-8 byte range and a GPUI style.80
/// Create a text decoration from a UTF-8 byte range and a GPUI style.79
pub fn new(range: Range<usize>, style: HighlightStyle) -> Self {81
pub fn new(range: Range<usize>, style: HighlightStyle) -> Self {80
Self { range, style }82
Self {83
range,84
style,85
font_family: None,86
}87
}88
89
/// Render this range in another font family, e.g. a monospace one for inline code.90
pub fn with_font_family(mut self, font_family: impl Into<SharedString>) -> Self {91
self.font_family = Some(font_family.into());92
self81
}93
}82
}94
}83
95
@@ -427,7 +439,7 @@ impl<T: TrackedDecoration> DecorationCollections<T> {427
}439
}428
}440
}429
441
430
fn adjust_range_for_edit(442
pub(crate) fn adjust_range_for_edit(431
range: &Range<usize>,443
range: &Range<usize>,432
edited_range: &Range<usize>,444
edited_range: &Range<usize>,433
inserted_len: usize,445
inserted_len: usize,@@ -473,6 +485,36 @@ fn adjust_range_for_edit(473
start..end485
start..end474
}486
}475
487
488
/// Non-overlapping font family spans sorted by start; earlier layers and items win.489
pub(crate) fn font_family_spans(layers: &[&[TextDecoration]]) -> Vec<(Range<usize>, SharedString)> {490
let mut spans: Vec<(Range<usize>, SharedString)> = Vec::new();491
for decoration in layers.iter().flat_map(|layer| layer.iter()) {492
let Some(font_family) = &decoration.font_family else {493
continue;494
};495
let mut uncovered = vec![decoration.range.clone()];496
for (covered, _) in &spans {497
uncovered = uncovered498
.into_iter()499
.flat_map(|range| {500
[501
range.start..range.end.min(covered.start),502
range.start.max(covered.end)..range.end,503
]504
})505
.filter(|range| !range.is_empty())506
.collect();507
}508
spans.extend(509
uncovered510
.into_iter()511
.map(|range| (range, font_family.clone())),512
);513
}514
spans.sort_by_key(|(range, _)| range.start);515
spans516
}517
476
fn normalize<T: TrackedDecoration>(text: &Rope, decorations: Vec<T>) -> Vec<T> {518
fn normalize<T: TrackedDecoration>(text: &Rope, decorations: Vec<T>) -> Vec<T> {477
decorations519
decorations478
.into_iter()520
.into_iter()@@ -537,7 +579,8 @@ impl InputBaseState<EditorMode> {537
/// Collections live until their [`InputBaseState`] is dropped.579
/// Collections live until their [`InputBaseState`] is dropped.538
///580
///539
/// Collections are layered in insertion order; the first collection wins581
/// Collections are layered in insertion order; the first collection wins540
/// when overlapping decorations set the same [`HighlightStyle`] property.582
/// when overlapping decorations set the same [`HighlightStyle`] property583
/// or font family. Only the font family affects layout and soft wrapping.541
/// Callers should avoid conflicting overlaps within one collection.584
/// Callers should avoid conflicting overlaps within one collection.542
pub fn create_decorations_collection(585
pub fn create_decorations_collection(543
&mut self,586
&mut self,@@ -724,6 +767,27 @@ mod tests {724
);767
);725
}768
}726
769
770
#[test]771
fn font_family_spans_let_earlier_layers_and_items_win() {772
let style = HighlightStyle::default();773
let first = [774
TextDecoration::new(4..8, style).with_font_family("Mono"),775
TextDecoration::new(6..10, style).with_font_family("Serif"),776
TextDecoration::new(0..20, style),777
];778
let second = [TextDecoration::new(2..12, style).with_font_family("Other")];779
assert_eq!(TextDecoration::new(0..1, style).font_family, None);780
assert_eq!(781
font_family_spans(&[&first[..], &second[..]]),782
vec![783
(2..4, "Other".into()),784
(4..8, "Mono".into()),785
(8..10, "Serif".into()),786
(10..12, "Other".into()),787
]788
);789
}790
727
#[test]791
#[test]728
fn decoration_ranges_follow_text_edits() {792
fn decoration_ranges_follow_text_edits() {729
let style = HighlightStyle::default();793
let style = HighlightStyle::default();@@ -235,6 +235,16 @@ impl DisplayMap {
235
235
self.rebuild_fold_projection();
236
236
}
237
237
238
/// Measure these document byte ranges in another font family when wrapping.
239
pub(crate) fn set_font_families(
240
&mut self,
241
font_families: std::rc::Rc<[(Range<usize>, gpui::SharedString)]>,
242
cx: &mut App,
243
) {
244
self.wrap_map.set_font_families(font_families, cx);
245
self.rebuild_fold_projection();
246
}
247
238
248
pub fn on_layout_changed(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {
239
249
self.wrap_map.on_layout_changed(wrap_width, cx);
240
250
self.rebuild_fold_projection();
@@ -235,6 +235,16 @@ impl DisplayMap {235
self.rebuild_fold_projection();235
self.rebuild_fold_projection();236
}236
}237
237
238
/// Measure these document byte ranges in another font family when wrapping.239
pub(crate) fn set_font_families(240
&mut self,241
font_families: std::rc::Rc<[(Range<usize>, gpui::SharedString)]>,242
cx: &mut App,243
) {244
self.wrap_map.set_font_families(font_families, cx);245
self.rebuild_fold_projection();246
}247
238
pub fn on_layout_changed(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {248
pub fn on_layout_changed(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {239
self.wrap_map.on_layout_changed(wrap_width, cx);249
self.wrap_map.on_layout_changed(wrap_width, cx);240
self.rebuild_fold_projection();250
self.rebuild_fold_projection();@@ -17,7 +17,7 @@ mod wrap_map;
17
17
18
18
// Re-export public API
19
19
pub use self::display_map::{DisplayMap, WrappingIndent};
20
pub(crate) use self::text_wrapper::LineLayout;
20
pub(crate) use self::text_wrapper::{LineLayout, split_run_by_font_families};
21
21
22
22
// Re-export FoldRange and extract_fold_ranges
23
23
pub use folding::FoldRange;
@@ -17,7 +17,7 @@ mod wrap_map;17
17
18
// Re-export public API18
// Re-export public API19
pub use self::display_map::{DisplayMap, WrappingIndent};19
pub use self::display_map::{DisplayMap, WrappingIndent};20
pub(crate) use self::text_wrapper::LineLayout;20
pub(crate) use self::text_wrapper::{LineLayout, split_run_by_font_families};21
21
22
// Re-export FoldRange and extract_fold_ranges22
// Re-export FoldRange and extract_fold_ranges23
pub use folding::FoldRange;23
pub use folding::FoldRange;@@ -5,7 +5,8 @@ use std::ops::Range;
5
5
use std::rc::Rc;
6
6
7
7
use gpui::{
8
App, Font, LineFragment, Pixels, Point, ShapedLine, Size, TextAlign, Window, point, px, size,
8
App, Font, LineFragment, Pixels, Point, ShapedLine, SharedString, Size, TextAlign, TextRun,
9
Window, point, px, size,
9
10
};
10
11
use ropey::Rope;
11
12
use smallvec::SmallVec;
@@ -33,7 +34,7 @@ fn measured_wrap_boundaries(
33
34
text: &str,
34
35
width: Pixels,
35
36
wrapping_indent: WrappingIndent,
36
mut measure: impl FnMut(&str) -> Pixels,
37
mut measure: impl FnMut(Range<usize>) -> Pixels,
37
38
) -> Vec<gpui::Boundary> {
38
39
let indent = if wrapping_indent == WrappingIndent::Same {
39
40
text.chars()
@@ -43,7 +44,7 @@ fn measured_wrap_boundaries(
43
44
} else {
44
45
0
45
46
};
46
let indent_width = measure(&text[..indent]);
47
let indent_width = measure(0..indent);
47
48
let ends: Vec<usize> = text
48
49
.grapheme_indices(true)
49
50
.map(|(ix, grapheme)| ix + grapheme.len())
@@ -66,7 +67,7 @@ fn measured_wrap_boundaries(
66
67
let remaining = ends.len() - first;
67
68
let mut low = 0;
68
69
let mut high = 1;
69
while measure(&text[start..ends[first + high - 1]]) <= available {
70
while measure(start..ends[first + high - 1]) <= available {
70
71
low = high;
71
72
if high == remaining {
72
73
break;
@@ -75,7 +76,7 @@ fn measured_wrap_boundaries(
75
76
}
76
77
while low + 1 < high {
77
78
let mid = (low + high) / 2;
78
if measure(&text[start..ends[first + mid - 1]]) <= available {
79
if measure(start..ends[first + mid - 1]) <= available {
79
80
low = mid;
80
81
} else {
81
82
high = mid;
@@ -102,6 +103,76 @@ fn measured_wrap_boundaries(
102
103
result
103
104
}
104
105
106
/// Split `run`, covering the document bytes `range`, where `font_families` override its family.
107
pub(crate) fn split_run_by_font_families(
108
run: TextRun,
109
range: Range<usize>,
110
font_families: &[(Range<usize>, SharedString)],
111
) -> SmallVec<[TextRun; 1]> {
112
let first = font_families.partition_point(|(span, _)| span.end <= range.start);
113
let mut runs = SmallVec::new();
114
let mut offset = range.start;
115
for (span, font_family) in &font_families[first..] {
116
if span.start >= range.end {
117
break;
118
}
119
let start = span.start.max(range.start);
120
let end = span.end.min(range.end);
121
if offset < start {
122
runs.push(TextRun {
123
len: start - offset,
124
..run.clone()
125
});
126
}
127
let mut font = run.font.clone();
128
font.family = font_family.clone();
129
runs.push(TextRun {
130
len: end - start,
131
font,
132
..run.clone()
133
});
134
offset = end;
135
}
136
if offset < range.end || runs.is_empty() {
137
runs.push(TextRun {
138
len: range.end - offset,
139
..run
140
});
141
}
142
runs
143
}
144
145
/// Ranges whose entry differs between two sorted span lists.
146
fn changed_ranges<T: PartialEq>(
147
old: &[(Range<usize>, T)],
148
new: &[(Range<usize>, T)],
149
) -> Vec<Range<usize>> {
150
let mut affected = Vec::new();
151
let (mut old, mut new) = (old.iter().peekable(), new.iter().peekable());
152
while old.peek().is_some() || new.peek().is_some() {
153
match (old.peek(), new.peek()) {
154
(Some(a), Some(b)) if a == b => {
155
old.next();
156
new.next();
157
}
158
(Some(a), Some(b)) if a.0.start <= b.0.start => {
159
affected.push(a.0.clone());
160
old.next();
161
}
162
(Some(_), Some(b)) | (None, Some(b)) => {
163
affected.push(b.0.clone());
164
new.next();
165
}
166
(Some(a), None) => {
167
affected.push(a.0.clone());
168
old.next();
169
}
170
(None, None) => break,
171
}
172
}
173
affected
174
}
175
105
176
/// A line with soft wrapped lines info.
106
177
#[derive(Debug, Clone)]
107
178
pub(crate) struct LineItem {
@@ -228,6 +299,8 @@ pub(crate) struct TextWrapper {
228
299
pub(crate) lines: SumTree<LineItem>,
229
300
230
301
inline_metrics: Rc<[(Range<usize>, Pixels)]>,
302
/// Sorted, non-overlapping document byte ranges measured in another font family.
303
font_families: Rc<[(Range<usize>, SharedString)]>,
231
304
_initialized: bool,
232
305
}
233
306
@@ -242,6 +315,7 @@ impl TextWrapper {
242
315
wrapping_indent: WrappingIndent::default(),
243
316
lines: SumTree::new(&()),
244
317
inline_metrics: Rc::from([]),
318
font_families: Rc::from([]),
245
319
_initialized: false,
246
320
}
247
321
}
@@ -373,6 +447,7 @@ impl TextWrapper {
373
447
.text_system()
374
448
.line_wrapper(self.font.clone(), self.font_size);
375
449
let metrics = self.inline_metrics.clone();
450
let font_families = self.font_families.clone();
376
451
let text_system = gpui::WindowTextSystem::new(cx.text_system().clone());
377
452
let font = self.font.clone();
378
453
let font_size = self.font_size;
@@ -409,21 +484,21 @@ impl TextWrapper {
409
484
line_str,
410
485
wrap_width,
411
486
wrapping_indent,
412
|text| {
487
|range| {
488
let runs = split_run_by_font_families(
489
TextRun {
490
len: range.len(),
491
font: font.clone(),
492
color: gpui::black(),
493
background_color: None,
494
underline: None,
495
strikethrough: None,
496
},
497
line_start + range.start..line_start + range.end,
498
&font_families,
499
);
413
500
text_system
414
.layout_line(
415
text,
416
font_size,
417
&[gpui::TextRun {
418
len: text.len(),
419
font: font.clone(),
420
color: gpui::black(),
421
background_color: None,
422
underline: None,
423
strikethrough: None,
424
}],
425
None,
426
)
501
.layout_line(&line_str[range], font_size, &runs, None)
427
502
.width
428
503
},
429
504
);
@@ -438,6 +513,33 @@ impl TextWrapper {
438
513
);
439
514
}
440
515
516
pub(crate) fn adjust_font_families(&mut self, range: &Range<usize>, new_len: usize) {
517
if self.font_families.is_empty() {
518
return;
519
}
520
self.font_families = self
521
.font_families
522
.iter()
523
.filter_map(|(span, font_family)| {
524
let span = crate::input::decorations::adjust_range_for_edit(span, range, new_len);
525
(!span.is_empty()).then(|| (span, font_family.clone()))
526
})
527
.collect();
528
}
529
530
pub(crate) fn set_font_families(
531
&mut self,
532
font_families: Rc<[(Range<usize>, SharedString)]>,
533
cx: &mut App,
534
) {
535
if self.font_families == font_families {
536
return;
537
}
538
let affected = changed_ranges(&self.font_families, &font_families);
539
self.font_families = font_families;
540
self.rewrap_rows_of(&affected, cx);
541
}
542
441
543
pub(crate) fn adjust_inline_metrics(&mut self, range: &Range<usize>, new_len: usize) {
442
544
if self.inline_metrics.is_empty() {
443
545
return;
@@ -469,37 +571,20 @@ impl TextWrapper {
469
571
return;
470
572
}
471
573
// Only rows whose element geometry changed need another wrap pass.
472
let mut affected = Vec::new();
473
let (mut old, mut new) = (
474
self.inline_metrics.iter().peekable(),
475
metrics.iter().peekable(),
476
);
477
while old.peek().is_some() || new.peek().is_some() {
478
match (old.peek(), new.peek()) {
479
(Some(a), Some(b)) if a == b => {
480
old.next();
481
new.next();
482
}
483
(Some(a), Some(b)) if a.0.start <= b.0.start => {
484
affected.push(a.0.clone());
485
old.next();
486
}
487
(Some(_), Some(b)) | (None, Some(b)) => {
488
affected.push(b.0.clone());
489
new.next();
490
}
491
(Some(a), None) => {
492
affected.push(a.0.clone());
493
old.next();
494
}
495
(None, None) => break,
496
}
497
}
574
let affected = changed_ranges(&self.inline_metrics, &metrics);
498
575
self.inline_metrics = metrics;
576
self.rewrap_rows_of(&affected, cx);
577
}
578
579
fn rewrap_rows_of(&mut self, affected: &[Range<usize>], cx: &mut App) {
499
580
let text = self.text.clone();
500
581
let mut rows: Vec<usize> = affected
501
582
.iter()
502
.map(|r| text.offset_to_point(r.start.min(text.len())).row)
583
.flat_map(|r| {
584
let start_row = text.offset_to_point(r.start.min(text.len())).row;
585
let end_row = text.offset_to_point(r.end.min(text.len())).row;
586
start_row..=end_row
587
})
503
588
.collect();
504
589
rows.sort_unstable();
505
590
rows.dedup();
@@ -1195,6 +1280,70 @@ mod tests {
1195
1280
});
1196
1281
}
1197
1282
1283
#[cfg(target_os = "linux")]
1284
#[test]
1285
fn production_wrap_measures_font_family_ranges_in_their_own_font() {
1286
let cx = shaping_test_context();
1287
cx.update(|cx| {
1288
let font = gpui::font("DejaVu Sans");
1289
let mono = gpui::font("DejaVu Sans Mono");
1290
let font_size = px(14.);
1291
let value = "iiiiiiii iiiiiiii iiiiiiii";
1292
let width = shaped_width("iiiiiiii iiiiiiii ", &font, font_size, cx) + px(1.);
1293
assert!(
1294
shaped_width("iiiiiiii", &mono, font_size, cx)
1295
> shaped_width("iiiiiiii ", &font, font_size, cx) + px(1.)
1296
);
1297
let text = Rope::from(value);
1298
let wrap = |font_families: Vec<(Range<usize>, SharedString)>, cx: &mut App| {
1299
let mut wrapper = TextWrapper::new(font.clone(), font_size, Some(width));
1300
wrapper.update(&text, &(0..0), &text, cx);
1301
wrapper.set_font_families(font_families.into(), cx);
1302
wrapper.line(0).unwrap().wrapped_lines.to_vec()
1303
};
1304
assert_eq!(wrap(vec![], cx), [0..18, 18..26]);
1305
assert_eq!(
1306
wrap(vec![(9..17, mono.family.clone())], cx),
1307
[0..9, 9..18, 18..26]
1308
);
1309
});
1310
}
1311
1312
#[test]
1313
fn font_family_runs_split_at_span_edges_and_follow_edits() {
1314
let run = TextRun {
1315
len: 10,
1316
font: gpui::font("Sans"),
1317
color: gpui::black(),
1318
background_color: None,
1319
underline: None,
1320
strikethrough: None,
1321
};
1322
let font_families = [(2..4, SharedString::from("Mono")), (8..20, "Mono".into())];
1323
let runs = split_run_by_font_families(run.clone(), 0..10, &font_families);
1324
let runs: Vec<_> = runs
1325
.iter()
1326
.map(|run| (run.len, run.font.family.to_string()))
1327
.collect();
1328
assert_eq!(
1329
runs,
1330
[(2, "Sans"), (2, "Mono"), (4, "Sans"), (2, "Mono")]
1331
.map(|(len, family)| (len, family.to_string()))
1332
);
1333
let runs = split_run_by_font_families(TextRun { len: 3, ..run }, 4..7, &font_families);
1334
assert_eq!(runs.len(), 1);
1335
assert_eq!(runs[0].font.family, "Sans");
1336
1337
let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
1338
wrapper.font_families = Rc::from(font_families);
1339
wrapper.adjust_font_families(&(0..0), 1);
1340
wrapper.adjust_font_families(&(9..21), 0);
1341
assert_eq!(
1342
&*wrapper.font_families,
1343
[(3..5, SharedString::from("Mono"))]
1344
);
1345
}
1346
1198
1347
#[test]
1199
1348
fn measured_wrap_keeps_cjk_latin_boundary_stable_during_edits() {
1200
1349
let measure = |text: &str| {
@@ -1214,7 +1363,9 @@ mod tests {
1214
1363
&(start..previous.len()),
1215
1364
&inserted,
1216
1365
&mut |line, width, _| {
1217
measured_wrap_boundaries(line, width, WrappingIndent::None, measure)
1366
measured_wrap_boundaries(line, width, WrappingIndent::None, |range| {
1367
measure(&line[range])
1368
})
1218
1369
},
1219
1370
);
1220
1371
let expected = if value.ends_with('s') {
@@ -1232,8 +1383,8 @@ mod tests {
1232
1383
#[test]
1233
1384
fn measured_wrap_preserves_words_graphemes_and_indentation() {
1234
1385
let wrap = |text: &str, width, indent| {
1235
measured_wrap_boundaries(text, px(width), indent, |s| {
1236
px(s.graphemes(true).count() as f32)
1386
measured_wrap_boundaries(text, px(width), indent, |range| {
1387
px(text[range].graphemes(true).count() as f32)
1237
1388
})
1238
1389
.into_iter()
1239
1390
.map(|b| b.ix)
@@ -5,7 +5,8 @@ use std::ops::Range;5
use std::rc::Rc;5
use std::rc::Rc;6
6
7
use gpui::{7
use gpui::{8
App, Font, LineFragment, Pixels, Point, ShapedLine, Size, TextAlign, Window, point, px, size,8
App, Font, LineFragment, Pixels, Point, ShapedLine, SharedString, Size, TextAlign, TextRun,9
Window, point, px, size,9
};10
};10
use ropey::Rope;11
use ropey::Rope;11
use smallvec::SmallVec;12
use smallvec::SmallVec;@@ -33,7 +34,7 @@ fn measured_wrap_boundaries(33
text: &str,34
text: &str,34
width: Pixels,35
width: Pixels,35
wrapping_indent: WrappingIndent,36
wrapping_indent: WrappingIndent,36
mut measure: impl FnMut(&str) -> Pixels,37
mut measure: impl FnMut(Range<usize>) -> Pixels,37
) -> Vec<gpui::Boundary> {38
) -> Vec<gpui::Boundary> {38
let indent = if wrapping_indent == WrappingIndent::Same {39
let indent = if wrapping_indent == WrappingIndent::Same {39
text.chars()40
text.chars()@@ -43,7 +44,7 @@ fn measured_wrap_boundaries(43
} else {44
} else {44
045
045
};46
};46
let indent_width = measure(&text[..indent]);47
let indent_width = measure(0..indent);47
let ends: Vec<usize> = text48
let ends: Vec<usize> = text48
.grapheme_indices(true)49
.grapheme_indices(true)49
.map(|(ix, grapheme)| ix + grapheme.len())50
.map(|(ix, grapheme)| ix + grapheme.len())@@ -66,7 +67,7 @@ fn measured_wrap_boundaries(66
let remaining = ends.len() - first;67
let remaining = ends.len() - first;67
let mut low = 0;68
let mut low = 0;68
let mut high = 1;69
let mut high = 1;69
while measure(&text[start..ends[first + high - 1]]) <= available {70
while measure(start..ends[first + high - 1]) <= available {70
low = high;71
low = high;71
if high == remaining {72
if high == remaining {72
break;73
break;@@ -75,7 +76,7 @@ fn measured_wrap_boundaries(75
}76
}76
while low + 1 < high {77
while low + 1 < high {77
let mid = (low + high) / 2;78
let mid = (low + high) / 2;78
if measure(&text[start..ends[first + mid - 1]]) <= available {79
if measure(start..ends[first + mid - 1]) <= available {79
low = mid;80
low = mid;80
} else {81
} else {81
high = mid;82
high = mid;@@ -102,6 +103,76 @@ fn measured_wrap_boundaries(102
result103
result103
}104
}104
105
106
/// Split `run`, covering the document bytes `range`, where `font_families` override its family.107
pub(crate) fn split_run_by_font_families(108
run: TextRun,109
range: Range<usize>,110
font_families: &[(Range<usize>, SharedString)],111
) -> SmallVec<[TextRun; 1]> {112
let first = font_families.partition_point(|(span, _)| span.end <= range.start);113
let mut runs = SmallVec::new();114
let mut offset = range.start;115
for (span, font_family) in &font_families[first..] {116
if span.start >= range.end {117
break;118
}119
let start = span.start.max(range.start);120
let end = span.end.min(range.end);121
if offset < start {122
runs.push(TextRun {123
len: start - offset,124
..run.clone()125
});126
}127
let mut font = run.font.clone();128
font.family = font_family.clone();129
runs.push(TextRun {130
len: end - start,131
font,132
..run.clone()133
});134
offset = end;135
}136
if offset < range.end || runs.is_empty() {137
runs.push(TextRun {138
len: range.end - offset,139
..run140
});141
}142
runs143
}144
145
/// Ranges whose entry differs between two sorted span lists.146
fn changed_ranges<T: PartialEq>(147
old: &[(Range<usize>, T)],148
new: &[(Range<usize>, T)],149
) -> Vec<Range<usize>> {150
let mut affected = Vec::new();151
let (mut old, mut new) = (old.iter().peekable(), new.iter().peekable());152
while old.peek().is_some() || new.peek().is_some() {153
match (old.peek(), new.peek()) {154
(Some(a), Some(b)) if a == b => {155
old.next();156
new.next();157
}158
(Some(a), Some(b)) if a.0.start <= b.0.start => {159
affected.push(a.0.clone());160
old.next();161
}162
(Some(_), Some(b)) | (None, Some(b)) => {163
affected.push(b.0.clone());164
new.next();165
}166
(Some(a), None) => {167
affected.push(a.0.clone());168
old.next();169
}170
(None, None) => break,171
}172
}173
affected174
}175
105
/// A line with soft wrapped lines info.176
/// A line with soft wrapped lines info.106
#[derive(Debug, Clone)]177
#[derive(Debug, Clone)]107
pub(crate) struct LineItem {178
pub(crate) struct LineItem {@@ -228,6 +299,8 @@ pub(crate) struct TextWrapper {228
pub(crate) lines: SumTree<LineItem>,299
pub(crate) lines: SumTree<LineItem>,229
300
230
inline_metrics: Rc<[(Range<usize>, Pixels)]>,301
inline_metrics: Rc<[(Range<usize>, Pixels)]>,302
/// Sorted, non-overlapping document byte ranges measured in another font family.303
font_families: Rc<[(Range<usize>, SharedString)]>,231
_initialized: bool,304
_initialized: bool,232
}305
}233
306
@@ -242,6 +315,7 @@ impl TextWrapper {242
wrapping_indent: WrappingIndent::default(),315
wrapping_indent: WrappingIndent::default(),243
lines: SumTree::new(&()),316
lines: SumTree::new(&()),244
inline_metrics: Rc::from([]),317
inline_metrics: Rc::from([]),318
font_families: Rc::from([]),245
_initialized: false,319
_initialized: false,246
}320
}247
}321
}@@ -373,6 +447,7 @@ impl TextWrapper {373
.text_system()447
.text_system()374
.line_wrapper(self.font.clone(), self.font_size);448
.line_wrapper(self.font.clone(), self.font_size);375
let metrics = self.inline_metrics.clone();449
let metrics = self.inline_metrics.clone();450
let font_families = self.font_families.clone();376
let text_system = gpui::WindowTextSystem::new(cx.text_system().clone());451
let text_system = gpui::WindowTextSystem::new(cx.text_system().clone());377
let font = self.font.clone();452
let font = self.font.clone();378
let font_size = self.font_size;453
let font_size = self.font_size;@@ -409,21 +484,21 @@ impl TextWrapper {409
line_str,484
line_str,410
wrap_width,485
wrap_width,411
wrapping_indent,486
wrapping_indent,412
|text| {487
|range| {488
let runs = split_run_by_font_families(489
TextRun {490
len: range.len(),491
font: font.clone(),492
color: gpui::black(),493
background_color: None,494
underline: None,495
strikethrough: None,496
},497
line_start + range.start..line_start + range.end,498
&font_families,499
);413
text_system500
text_system414
.layout_line(501
.layout_line(&line_str[range], font_size, &runs, None)415
text,416
font_size,417
&[gpui::TextRun {418
len: text.len(),419
font: font.clone(),420
color: gpui::black(),421
background_color: None,422
underline: None,423
strikethrough: None,424
}],425
None,426
)427
.width502
.width428
},503
},429
);504
);@@ -438,6 +513,33 @@ impl TextWrapper {438
);513
);439
}514
}440
515
516
pub(crate) fn adjust_font_families(&mut self, range: &Range<usize>, new_len: usize) {517
if self.font_families.is_empty() {518
return;519
}520
self.font_families = self521
.font_families522
.iter()523
.filter_map(|(span, font_family)| {524
let span = crate::input::decorations::adjust_range_for_edit(span, range, new_len);525
(!span.is_empty()).then(|| (span, font_family.clone()))526
})527
.collect();528
}529
530
pub(crate) fn set_font_families(531
&mut self,532
font_families: Rc<[(Range<usize>, SharedString)]>,533
cx: &mut App,534
) {535
if self.font_families == font_families {536
return;537
}538
let affected = changed_ranges(&self.font_families, &font_families);539
self.font_families = font_families;540
self.rewrap_rows_of(&affected, cx);541
}542
441
pub(crate) fn adjust_inline_metrics(&mut self, range: &Range<usize>, new_len: usize) {543
pub(crate) fn adjust_inline_metrics(&mut self, range: &Range<usize>, new_len: usize) {442
if self.inline_metrics.is_empty() {544
if self.inline_metrics.is_empty() {443
return;545
return;@@ -469,37 +571,20 @@ impl TextWrapper {469
return;571
return;470
}572
}471
// Only rows whose element geometry changed need another wrap pass.573
// Only rows whose element geometry changed need another wrap pass.472
let mut affected = Vec::new();574
let affected = changed_ranges(&self.inline_metrics, &metrics);473
let (mut old, mut new) = (474
self.inline_metrics.iter().peekable(),475
metrics.iter().peekable(),476
);477
while old.peek().is_some() || new.peek().is_some() {478
match (old.peek(), new.peek()) {479
(Some(a), Some(b)) if a == b => {480
old.next();481
new.next();482
}483
(Some(a), Some(b)) if a.0.start <= b.0.start => {484
affected.push(a.0.clone());485
old.next();486
}487
(Some(_), Some(b)) | (None, Some(b)) => {488
affected.push(b.0.clone());489
new.next();490
}491
(Some(a), None) => {492
affected.push(a.0.clone());493
old.next();494
}495
(None, None) => break,496
}497
}498
self.inline_metrics = metrics;575
self.inline_metrics = metrics;576
self.rewrap_rows_of(&affected, cx);577
}578
579
fn rewrap_rows_of(&mut self, affected: &[Range<usize>], cx: &mut App) {499
let text = self.text.clone();580
let text = self.text.clone();500
let mut rows: Vec<usize> = affected581
let mut rows: Vec<usize> = affected501
.iter()582
.iter()502
.map(|r| text.offset_to_point(r.start.min(text.len())).row)583
.flat_map(|r| {584
let start_row = text.offset_to_point(r.start.min(text.len())).row;585
let end_row = text.offset_to_point(r.end.min(text.len())).row;586
start_row..=end_row587
})503
.collect();588
.collect();504
rows.sort_unstable();589
rows.sort_unstable();505
rows.dedup();590
rows.dedup();@@ -1195,6 +1280,70 @@ mod tests {1195
});1280
});1196
}1281
}1197
1282
1283
#[cfg(target_os = "linux")]1284
#[test]1285
fn production_wrap_measures_font_family_ranges_in_their_own_font() {1286
let cx = shaping_test_context();1287
cx.update(|cx| {1288
let font = gpui::font("DejaVu Sans");1289
let mono = gpui::font("DejaVu Sans Mono");1290
let font_size = px(14.);1291
let value = "iiiiiiii iiiiiiii iiiiiiii";1292
let width = shaped_width("iiiiiiii iiiiiiii ", &font, font_size, cx) + px(1.);1293
assert!(1294
shaped_width("iiiiiiii", &mono, font_size, cx)1295
> shaped_width("iiiiiiii ", &font, font_size, cx) + px(1.)1296
);1297
let text = Rope::from(value);1298
let wrap = |font_families: Vec<(Range<usize>, SharedString)>, cx: &mut App| {1299
let mut wrapper = TextWrapper::new(font.clone(), font_size, Some(width));1300
wrapper.update(&text, &(0..0), &text, cx);1301
wrapper.set_font_families(font_families.into(), cx);1302
wrapper.line(0).unwrap().wrapped_lines.to_vec()1303
};1304
assert_eq!(wrap(vec![], cx), [0..18, 18..26]);1305
assert_eq!(1306
wrap(vec![(9..17, mono.family.clone())], cx),1307
[0..9, 9..18, 18..26]1308
);1309
});1310
}1311
1312
#[test]1313
fn font_family_runs_split_at_span_edges_and_follow_edits() {1314
let run = TextRun {1315
len: 10,1316
font: gpui::font("Sans"),1317
color: gpui::black(),1318
background_color: None,1319
underline: None,1320
strikethrough: None,1321
};1322
let font_families = [(2..4, SharedString::from("Mono")), (8..20, "Mono".into())];1323
let runs = split_run_by_font_families(run.clone(), 0..10, &font_families);1324
let runs: Vec<_> = runs1325
.iter()1326
.map(|run| (run.len, run.font.family.to_string()))1327
.collect();1328
assert_eq!(1329
runs,1330
[(2, "Sans"), (2, "Mono"), (4, "Sans"), (2, "Mono")]1331
.map(|(len, family)| (len, family.to_string()))1332
);1333
let runs = split_run_by_font_families(TextRun { len: 3, ..run }, 4..7, &font_families);1334
assert_eq!(runs.len(), 1);1335
assert_eq!(runs[0].font.family, "Sans");1336
1337
let mut wrapper = TextWrapper::new(test_font(), px(14.), None);1338
wrapper.font_families = Rc::from(font_families);1339
wrapper.adjust_font_families(&(0..0), 1);1340
wrapper.adjust_font_families(&(9..21), 0);1341
assert_eq!(1342
&*wrapper.font_families,1343
[(3..5, SharedString::from("Mono"))]1344
);1345
}1346
1198
#[test]1347
#[test]1199
fn measured_wrap_keeps_cjk_latin_boundary_stable_during_edits() {1348
fn measured_wrap_keeps_cjk_latin_boundary_stable_during_edits() {1200
let measure = |text: &str| {1349
let measure = |text: &str| {@@ -1214,7 +1363,9 @@ mod tests {1214
&(start..previous.len()),1363
&(start..previous.len()),1215
&inserted,1364
&inserted,1216
&mut |line, width, _| {1365
&mut |line, width, _| {1217
measured_wrap_boundaries(line, width, WrappingIndent::None, measure)1366
measured_wrap_boundaries(line, width, WrappingIndent::None, |range| {1367
measure(&line[range])1368
})1218
},1369
},1219
);1370
);1220
let expected = if value.ends_with('s') {1371
let expected = if value.ends_with('s') {@@ -1232,8 +1383,8 @@ mod tests {1232
#[test]1383
#[test]1233
fn measured_wrap_preserves_words_graphemes_and_indentation() {1384
fn measured_wrap_preserves_words_graphemes_and_indentation() {1234
let wrap = |text: &str, width, indent| {1385
let wrap = |text: &str, width, indent| {1235
measured_wrap_boundaries(text, px(width), indent, |s| {1386
measured_wrap_boundaries(text, px(width), indent, |range| {1236
px(s.graphemes(true).count() as f32)1387
px(text[range].graphemes(true).count() as f32)1237
})1388
})1238
.into_iter()1389
.into_iter()1239
.map(|b| b.ix)1390
.map(|b| b.ix)@@ -108,6 +108,7 @@ impl WrapMap {
108
108
cx: &mut App,
109
109
) {
110
110
self.wrapper.adjust_inline_metrics(range, new_text.len());
111
self.wrapper.adjust_font_families(range, new_text.len());
111
112
self.wrapper.update(changed_text, range, new_text, cx);
112
113
}
113
114
@@ -120,6 +121,14 @@ impl WrapMap {
120
121
self.wrapper.set_inline_metrics(metrics, cx);
121
122
}
122
123
124
pub(super) fn set_font_families(
125
&mut self,
126
font_families: std::rc::Rc<[(Range<usize>, gpui::SharedString)]>,
127
cx: &mut App,
128
) {
129
self.wrapper.set_font_families(font_families, cx);
130
}
131
123
132
pub(super) fn on_layout_changed(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {
124
133
self.wrapper.set_wrap_width(wrap_width, cx);
125
134
}
@@ -108,6 +108,7 @@ impl WrapMap {108
cx: &mut App,108
cx: &mut App,109
) {109
) {110
self.wrapper.adjust_inline_metrics(range, new_text.len());110
self.wrapper.adjust_inline_metrics(range, new_text.len());111
self.wrapper.adjust_font_families(range, new_text.len());111
self.wrapper.update(changed_text, range, new_text, cx);112
self.wrapper.update(changed_text, range, new_text, cx);112
}113
}113
114
@@ -120,6 +121,14 @@ impl WrapMap {120
self.wrapper.set_inline_metrics(metrics, cx);121
self.wrapper.set_inline_metrics(metrics, cx);121
}122
}122
123
124
pub(super) fn set_font_families(125
&mut self,126
font_families: std::rc::Rc<[(Range<usize>, gpui::SharedString)]>,127
cx: &mut App,128
) {129
self.wrapper.set_font_families(font_families, cx);130
}131
123
pub(super) fn on_layout_changed(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {132
pub(super) fn on_layout_changed(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {124
self.wrapper.set_wrap_width(wrap_width, cx);133
self.wrapper.set_wrap_width(wrap_width, cx);125
}134
}