feat(composer): images sit in the text as a large preview and send at that spot
Patches gpui-base with block tokens: an inline token on its own, taller row. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -96,7 +96,7 @@ Feature parity with the Microsoft Teams desktop client.
96
96
| React to a message | Done | Hover bar, emoji picker, click a chip to toggle |
97
97
| Emoji picker | Partial | For reactions; composer still uses colon codes |
98
98
| 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 |
99
| Attach a file, paste or drag an image | Done | Images inline, files via OneDrive or the channel's Files |
99
| 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 |
100
100
| GIFs and stickers | Missing | |
101
101
| Schedule send | Missing | |
102
102
| Unsent messages survive a restart | Missing | Pending sends live in memory only |
@@ -96,7 +96,7 @@ Feature parity with the Microsoft Teams desktop client.96
| React to a message | Done | Hover bar, emoji picker, click a chip to toggle |96
| React to a message | Done | Hover bar, emoji picker, click a chip to toggle |97
| Emoji picker | Partial | For reactions; composer still uses colon codes |97
| Emoji picker | Partial | For reactions; composer still uses colon codes |98
| 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 |98
| 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 |99
| Attach a file, paste or drag an image | Done | Images inline, files via OneDrive or the channel's Files |99
| 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 |100
| GIFs and stickers | Missing | |100
| GIFs and stickers | Missing | |101
| Schedule send | Missing | |101
| Schedule send | Missing | |102
| Unsent messages survive a restart | Missing | Pending sends live in memory only |102
| Unsent messages survive a restart | Missing | Pending sends live in memory only |@@ -1,5 +1,6 @@
1
1
use std::io::Cursor;
2
2
use std::path::{Path, PathBuf};
3
use std::rc::Rc;
3
4
use std::sync::Arc;
4
5
5
6
use gpui_kit::assets::IconName;
@@ -19,7 +20,9 @@ pub const INLINE_TOTAL_MAX_BYTES: u64 = 5 * 512 * 1024;
19
20
pub const MAX_FILE_BYTES: u64 = 250 * 1024 * 1024;
20
21
pub const FILES_LATER_NOTICE: &str = "Files can be added once the chat exists.";
21
22
const PASTED_IMAGE_STEM: &str = "pasted-image";
22
const THUMB_SIZE: f32 = 72.;
23
const PREVIEW_HEIGHT: f32 = 120.;
24
const PREVIEW_GAP: f32 = 4.;
25
const PREVIEW_RADIUS: f32 = 10.;
23
26
const CHIP_WIDTH: f32 = 220.;
24
27
const CHIP_HEIGHT: f32 = 48.;
25
28
const CHIP_BADGE_SIZE: f32 = 30.;
@@ -193,6 +196,14 @@ impl TrayItem {
193
196
}
194
197
}
195
198
199
#[derive(Debug, Clone)]
200
pub struct PreviewImage {
201
pub image: Arc<Image>,
202
pub dimensions: Option<(u32, u32)>,
203
}
204
205
pub type RemoveImage = Rc<dyn Fn(&mut Window, &mut App)>;
206
196
207
#[derive(Debug, Clone, PartialEq, Eq)]
197
208
pub struct OutgoingImage {
198
209
pub name: String,
@@ -254,8 +265,20 @@ impl AttachmentTray {
254
265
&self.items
255
266
}
256
267
257
pub fn is_empty(&self) -> bool {
258
self.items.is_empty()
268
pub fn has_chips(&self) -> bool {
269
self.items
270
.iter()
271
.any(|item| !matches!(item.kind, ItemKind::Image { .. }))
272
}
273
274
pub fn image(&self, id: u64) -> Option<PreviewImage> {
275
self.items.iter().find_map(|item| match &item.kind {
276
ItemKind::Image { image, dimensions } if item.id == id => Some(PreviewImage {
277
image: image.clone(),
278
dimensions: *dimensions,
279
}),
280
_ => None,
281
})
259
282
}
260
283
261
284
pub fn notice(&self) -> Option<&str> {
@@ -465,18 +488,21 @@ impl AttachmentTray {
465
488
.sum()
466
489
}
467
490
468
pub fn restore(&mut self, images: &[OutgoingImage], files: &[OutgoingFile]) {
491
pub fn restore(&mut self, images: &[OutgoingImage], files: &[OutgoingFile]) -> Vec<u64> {
469
492
self.clear();
470
for image in images {
471
self.push(
472
image.name.clone(),
473
image.image.bytes.len() as u64,
474
ItemKind::Image {
475
image: image.image.clone(),
476
dimensions: image.dimensions,
477
},
478
);
479
}
493
let image_ids = images
494
.iter()
495
.map(|image| {
496
self.push(
497
image.name.clone(),
498
image.image.bytes.len() as u64,
499
ItemKind::Image {
500
image: image.image.clone(),
501
dimensions: image.dimensions,
502
},
503
)
504
})
505
.collect();
480
506
for file in files {
481
507
self.push(
482
508
file.name.clone(),
@@ -491,20 +517,28 @@ impl AttachmentTray {
491
517
},
492
518
);
493
519
}
520
image_ids
521
}
522
523
pub fn images_in(&self, ids: &[u64]) -> Vec<OutgoingImage> {
524
ids.iter()
525
.filter_map(|id| {
526
let item = self.items.iter().find(|item| item.id == *id)?;
527
match &item.kind {
528
ItemKind::Image { image, dimensions } => Some(OutgoingImage {
529
name: item.name.clone(),
530
image: image.clone(),
531
dimensions: *dimensions,
532
}),
533
_ => None,
534
}
535
})
536
.collect()
494
537
}
495
538
496
pub fn outgoing_images(&self) -> Vec<OutgoingImage> {
539
pub fn discard_images_except(&mut self, kept: &[u64]) {
497
540
self.items
498
.iter()
499
.filter_map(|item| match &item.kind {
500
ItemKind::Image { image, dimensions } => Some(OutgoingImage {
501
name: item.name.clone(),
502
image: image.clone(),
503
dimensions: *dimensions,
504
}),
505
_ => None,
506
})
507
.collect()
541
.retain(|item| !matches!(item.kind, ItemKind::Image { .. }) || kept.contains(&item.id));
508
542
}
509
543
510
544
pub fn outgoing_files(&self) -> Vec<OutgoingFile> {
@@ -695,13 +729,8 @@ pub fn chip_state(item: &TrayItem) -> ChipState {
695
729
696
730
type ItemAction<T> = fn(&mut T, u64, &mut Window, &mut Context<T>);
697
731
698
fn remove_button<T: 'static>(
699
id: u64,
700
over_image: bool,
701
remove: ItemAction<T>,
702
cx: &mut Context<T>,
703
) -> Stateful<Div> {
704
let button = div()
732
fn remove_button<T: 'static>(id: u64, remove: ItemAction<T>, cx: &mut Context<T>) -> Stateful<Div> {
733
div()
705
734
.id(ElementId::Name(format!("attachment-remove-{id}").into()))
706
735
.size(px(REMOVE_SIZE))
707
736
.flex_none()
@@ -709,42 +738,98 @@ fn remove_button<T: 'static>(
709
738
.items_center()
710
739
.justify_center()
711
740
.rounded_full()
712
.cursor_pointer();
713
let button = if over_image {
714
button
715
.bg(black().opacity(0.6))
716
.hover(|button| button.bg(black().opacity(0.85)))
717
.child(icon(IconName::Close, 10., white()))
718
} else {
719
button
720
.hover(|button| button.bg(theme::row_hover()))
721
.child(icon(IconName::Close, 10., theme::text_muted()))
722
};
723
button.on_click(cx.listener(move |this, _, window, cx| remove(this, id, window, cx)))
741
.cursor_pointer()
742
.hover(|button| button.bg(theme::row_hover()))
743
.child(icon(IconName::Close, 10., theme::text_muted()))
744
.on_click(cx.listener(move |this, _, window, cx| remove(this, id, window, cx)))
724
745
}
725
746
726
fn thumbnail<T: 'static>(
727
item: &TrayItem,
728
image: &Arc<Image>,
729
remove: ItemAction<T>,
730
cx: &mut Context<T>,
747
pub fn preview_size(dimensions: Option<(u32, u32)>, available_width: f32) -> (f32, f32) {
748
let (width, height) = dimensions
749
.filter(|(width, height)| *width > 0 && *height > 0)
750
.map_or((PREVIEW_HEIGHT, PREVIEW_HEIGHT), |(width, height)| {
751
(width as f32, height as f32)
752
});
753
let scale = (PREVIEW_HEIGHT / height)
754
.min(available_width / width)
755
.clamp(0., 1.);
756
(
757
(width * scale).round().max(1.),
758
(height * scale).round().max(1.),
759
)
760
}
761
762
pub fn preview_row_height(height: f32) -> f32 {
763
height + 2. * PREVIEW_GAP
764
}
765
766
pub fn inline_preview(
767
id: u64,
768
preview: Option<PreviewImage>,
769
available_width: Pixels,
770
selected: bool,
771
remove: RemoveImage,
731
772
) -> AnyElement {
732
div()
733
.id(ElementId::Name(format!("attachment-{}", item.id).into()))
773
let dimensions = preview.as_ref().and_then(|preview| preview.dimensions);
774
let (width, height) = preview_size(dimensions, f32::from(available_width));
775
let group = SharedString::from(format!("image-preview-{id}"));
776
let frame = div()
734
777
.relative()
735
.size(px(THUMB_SIZE))
736
.flex_none()
737
.rounded(px(8.))
778
.size_full()
779
.rounded(px(PREVIEW_RADIUS))
738
780
.overflow_hidden()
739
781
.border_1()
740
782
.border_color(theme::border_strong())
741
.child(img(image.clone()).size_full().object_fit(ObjectFit::Cover))
783
.bg(theme::surface_raised());
784
let frame = match preview {
785
Some(preview) => frame.child(
786
img(preview.image)
787
.size_full()
788
.rounded(px(PREVIEW_RADIUS))
789
.object_fit(ObjectFit::Cover),
790
),
791
None => frame,
792
};
793
div()
794
.group(group.clone())
795
.w(px(width))
796
.h(px(preview_row_height(height)))
797
.py(px(PREVIEW_GAP))
742
798
.child(
743
div()
744
.absolute()
745
.top(px(4.))
746
.right(px(4.))
747
.child(remove_button(item.id, true, remove, cx)),
799
frame
800
.when(selected, |frame| {
801
frame.child(
802
div()
803
.absolute()
804
.inset_0()
805
.rounded(px(PREVIEW_RADIUS))
806
.border_2()
807
.border_color(theme::accent()),
808
)
809
})
810
.child(
811
div()
812
.id(ElementId::Name(format!("image-remove-{id}").into()))
813
.absolute()
814
.top(px(6.))
815
.right(px(6.))
816
.size(px(REMOVE_SIZE))
817
.flex()
818
.items_center()
819
.justify_center()
820
.rounded_full()
821
.cursor_pointer()
822
.bg(black().opacity(0.6))
823
.opacity(0.)
824
.group_hover(group, |button| button.opacity(1.))
825
.hover(|button| button.bg(black().opacity(0.85)))
826
.child(icon(IconName::Close, 10., white()))
827
.on_mouse_down(MouseButton::Left, |_, window, cx| {
828
window.prevent_default();
829
cx.stop_propagation();
830
})
831
.on_click(move |_, window, cx| remove(window, cx)),
832
),
748
833
)
749
834
.into_any_element()
750
835
}
@@ -813,7 +898,7 @@ fn chip<T: 'static>(
813
898
.on_click(cx.listener(move |this, _, window, cx| retry(this, id, window, cx))),
814
899
)
815
900
})
816
.child(remove_button(id, false, remove, cx))
901
.child(remove_button(id, remove, cx))
817
902
.when_some(state.progress, |chip, percent| {
818
903
chip.child(
819
904
div()
@@ -834,16 +919,14 @@ pub fn render_tray<T: 'static>(
834
919
retry: ItemAction<T>,
835
920
cx: &mut Context<T>,
836
921
) -> Option<Div> {
837
if tray.is_empty() {
922
if !tray.has_chips() {
838
923
return None;
839
924
}
840
925
let elements: Vec<AnyElement> = tray
841
926
.items()
842
927
.iter()
843
.map(|item| match &item.kind {
844
ItemKind::Image { image, .. } => thumbnail(item, image, remove, cx),
845
_ => chip(item, remove, retry, cx),
846
})
928
.filter(|item| !matches!(item.kind, ItemKind::Image { .. }))
929
.map(|item| chip(item, remove, retry, cx))
847
930
.collect();
848
931
Some(
849
932
h_flex()
@@ -870,7 +953,7 @@ mod tests {
870
953
AttachmentTray, Classification, DoneFile, FILES_LATER_NOTICE, INLINE_IMAGE_MAX_BYTES,
871
954
INLINE_TOTAL_MAX_BYTES, InlineFormat, ItemKind, LoadedFile, MAX_ATTACHMENTS, PasteAction,
872
955
Tone, UploadResult, chip_state, classify, limit_notice, paste_action, pasted_image_name,
873
prepare_pasted_image, read_attachment, sniff_inline_format,
956
prepare_pasted_image, preview_size, read_attachment, sniff_inline_format,
874
957
};
875
958
876
959
const PNG_HEADER: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
@@ -1242,7 +1325,7 @@ mod tests {
1242
1325
let (mut tray, id) = tray_with_file();
1243
1326
tray.remove(id);
1244
1327
tray.finish_upload(id, done("plan.pdf"));
1245
assert!(tray.is_empty());
1328
assert!(tray.items().is_empty());
1246
1329
}
1247
1330
1248
1331
#[test]
@@ -1264,15 +1347,42 @@ mod tests {
1264
1347
source.finish_reading(ids[0], LoadedFile::new(png(4, 2)), true);
1265
1348
source.finish_reading(ids[1], LoadedFile::new(b"%PDF".to_vec()), true);
1266
1349
source.finish_upload(ids[1], done("b.pdf"));
1267
let (images, files) = (source.outgoing_images(), source.outgoing_files());
1350
let (images, files) = (source.images_in(&ids[..1]), source.outgoing_files());
1268
1351
1269
1352
let mut restored = AttachmentTray::default();
1270
restored.restore(&images, &files);
1271
assert_eq!(restored.outgoing_images(), images);
1353
let image_ids = restored.restore(&images, &files);
1354
assert_eq!(image_ids.len(), 1);
1355
assert_eq!(restored.images_in(&image_ids), images);
1272
1356
assert_eq!(restored.outgoing_files(), files);
1273
1357
assert!(!restored.blocks_send());
1274
1358
}
1275
1359
1360
#[test]
1361
fn images_come_back_in_the_order_asked_for_and_only_when_known() {
1362
let mut tray = AttachmentTray::default();
1363
let ids = tray.add_pending(&["a.png".to_owned(), "b.png".to_owned()]);
1364
tray.finish_reading(ids[0], LoadedFile::new(png(2, 2)), true);
1365
tray.finish_reading(ids[1], LoadedFile::new(png(4, 4)), true);
1366
let images = tray.images_in(&[ids[1], 99, ids[0]]);
1367
assert_eq!(images.len(), 2);
1368
assert_eq!(images[0].dimensions, Some((4, 4)));
1369
assert_eq!(images[1].dimensions, Some((2, 2)));
1370
assert!(!tray.has_chips());
1371
tray.discard_images_except(&[ids[1]]);
1372
assert_eq!(tray.items().len(), 1);
1373
assert!(tray.image(ids[1]).is_some());
1374
assert!(tray.image(ids[0]).is_none());
1375
}
1376
1377
#[test]
1378
fn previews_are_at_most_120_high_and_fit_the_row() {
1379
assert_eq!(preview_size(Some((400, 300)), 800.), (160., 120.));
1380
assert_eq!(preview_size(Some((40, 30)), 800.), (40., 30.));
1381
assert_eq!(preview_size(Some((1000, 100)), 250.), (250., 25.));
1382
assert_eq!(preview_size(None, 800.), (120., 120.));
1383
assert_eq!(preview_size(Some((400, 300)), 0.), (1., 1.));
1384
}
1385
1276
1386
#[test]
1277
1387
fn switching_chats_for_a_draft_keeps_only_images() {
1278
1388
let mut tray = AttachmentTray::default();
@@ -1289,7 +1399,7 @@ mod tests {
1289
1399
let mut tray = AttachmentTray::default();
1290
1400
let id = tray.add_pending(&["gone.txt".to_owned()])[0];
1291
1401
tray.fail_reading(id, "Could not read gone.txt.".to_owned());
1292
assert!(tray.is_empty());
1402
assert!(tray.items().is_empty());
1293
1403
assert_eq!(tray.notice(), Some("Could not read gone.txt."));
1294
1404
}
1295
1405
@@ -1,5 +1,6 @@1
use std::io::Cursor;1
use std::io::Cursor;2
use std::path::{Path, PathBuf};2
use std::path::{Path, PathBuf};3
use std::rc::Rc;3
use std::sync::Arc;4
use std::sync::Arc;4
5
5
use gpui_kit::assets::IconName;6
use gpui_kit::assets::IconName;@@ -19,7 +20,9 @@ pub const INLINE_TOTAL_MAX_BYTES: u64 = 5 * 512 * 1024;19
pub const MAX_FILE_BYTES: u64 = 250 * 1024 * 1024;20
pub const MAX_FILE_BYTES: u64 = 250 * 1024 * 1024;20
pub const FILES_LATER_NOTICE: &str = "Files can be added once the chat exists.";21
pub const FILES_LATER_NOTICE: &str = "Files can be added once the chat exists.";21
const PASTED_IMAGE_STEM: &str = "pasted-image";22
const PASTED_IMAGE_STEM: &str = "pasted-image";22
const THUMB_SIZE: f32 = 72.;23
const PREVIEW_HEIGHT: f32 = 120.;24
const PREVIEW_GAP: f32 = 4.;25
const PREVIEW_RADIUS: f32 = 10.;23
const CHIP_WIDTH: f32 = 220.;26
const CHIP_WIDTH: f32 = 220.;24
const CHIP_HEIGHT: f32 = 48.;27
const CHIP_HEIGHT: f32 = 48.;25
const CHIP_BADGE_SIZE: f32 = 30.;28
const CHIP_BADGE_SIZE: f32 = 30.;@@ -193,6 +196,14 @@ impl TrayItem {193
}196
}194
}197
}195
198
199
#[derive(Debug, Clone)]200
pub struct PreviewImage {201
pub image: Arc<Image>,202
pub dimensions: Option<(u32, u32)>,203
}204
205
pub type RemoveImage = Rc<dyn Fn(&mut Window, &mut App)>;206
196
#[derive(Debug, Clone, PartialEq, Eq)]207
#[derive(Debug, Clone, PartialEq, Eq)]197
pub struct OutgoingImage {208
pub struct OutgoingImage {198
pub name: String,209
pub name: String,@@ -254,8 +265,20 @@ impl AttachmentTray {254
&self.items265
&self.items255
}266
}256
267
257
pub fn is_empty(&self) -> bool {268
pub fn has_chips(&self) -> bool {258
self.items.is_empty()269
self.items270
.iter()271
.any(|item| !matches!(item.kind, ItemKind::Image { .. }))272
}273
274
pub fn image(&self, id: u64) -> Option<PreviewImage> {275
self.items.iter().find_map(|item| match &item.kind {276
ItemKind::Image { image, dimensions } if item.id == id => Some(PreviewImage {277
image: image.clone(),278
dimensions: *dimensions,279
}),280
_ => None,281
})259
}282
}260
283
261
pub fn notice(&self) -> Option<&str> {284
pub fn notice(&self) -> Option<&str> {@@ -465,18 +488,21 @@ impl AttachmentTray {465
.sum()488
.sum()466
}489
}467
490
468
pub fn restore(&mut self, images: &[OutgoingImage], files: &[OutgoingFile]) {491
pub fn restore(&mut self, images: &[OutgoingImage], files: &[OutgoingFile]) -> Vec<u64> {469
self.clear();492
self.clear();470
for image in images {493
let image_ids = images471
self.push(494
.iter()472
image.name.clone(),495
.map(|image| {473
image.image.bytes.len() as u64,496
self.push(474
ItemKind::Image {497
image.name.clone(),475
image: image.image.clone(),498
image.image.bytes.len() as u64,476
dimensions: image.dimensions,499
ItemKind::Image {477
},500
image: image.image.clone(),478
);501
dimensions: image.dimensions,479
}502
},503
)504
})505
.collect();480
for file in files {506
for file in files {481
self.push(507
self.push(482
file.name.clone(),508
file.name.clone(),@@ -491,20 +517,28 @@ impl AttachmentTray {491
},517
},492
);518
);493
}519
}520
image_ids521
}522
523
pub fn images_in(&self, ids: &[u64]) -> Vec<OutgoingImage> {524
ids.iter()525
.filter_map(|id| {526
let item = self.items.iter().find(|item| item.id == *id)?;527
match &item.kind {528
ItemKind::Image { image, dimensions } => Some(OutgoingImage {529
name: item.name.clone(),530
image: image.clone(),531
dimensions: *dimensions,532
}),533
_ => None,534
}535
})536
.collect()494
}537
}495
538
496
pub fn outgoing_images(&self) -> Vec<OutgoingImage> {539
pub fn discard_images_except(&mut self, kept: &[u64]) {497
self.items540
self.items498
.iter()541
.retain(|item| !matches!(item.kind, ItemKind::Image { .. }) || kept.contains(&item.id));499
.filter_map(|item| match &item.kind {500
ItemKind::Image { image, dimensions } => Some(OutgoingImage {501
name: item.name.clone(),502
image: image.clone(),503
dimensions: *dimensions,504
}),505
_ => None,506
})507
.collect()508
}542
}509
543
510
pub fn outgoing_files(&self) -> Vec<OutgoingFile> {544
pub fn outgoing_files(&self) -> Vec<OutgoingFile> {@@ -695,13 +729,8 @@ pub fn chip_state(item: &TrayItem) -> ChipState {695
729
696
type ItemAction<T> = fn(&mut T, u64, &mut Window, &mut Context<T>);730
type ItemAction<T> = fn(&mut T, u64, &mut Window, &mut Context<T>);697
731
698
fn remove_button<T: 'static>(732
fn remove_button<T: 'static>(id: u64, remove: ItemAction<T>, cx: &mut Context<T>) -> Stateful<Div> {699
id: u64,733
div()700
over_image: bool,701
remove: ItemAction<T>,702
cx: &mut Context<T>,703
) -> Stateful<Div> {704
let button = div()705
.id(ElementId::Name(format!("attachment-remove-{id}").into()))734
.id(ElementId::Name(format!("attachment-remove-{id}").into()))706
.size(px(REMOVE_SIZE))735
.size(px(REMOVE_SIZE))707
.flex_none()736
.flex_none()@@ -709,42 +738,98 @@ fn remove_button<T: 'static>(709
.items_center()738
.items_center()710
.justify_center()739
.justify_center()711
.rounded_full()740
.rounded_full()712
.cursor_pointer();741
.cursor_pointer()713
let button = if over_image {742
.hover(|button| button.bg(theme::row_hover()))714
button743
.child(icon(IconName::Close, 10., theme::text_muted()))715
.bg(black().opacity(0.6))744
.on_click(cx.listener(move |this, _, window, cx| remove(this, id, window, cx)))716
.hover(|button| button.bg(black().opacity(0.85)))717
.child(icon(IconName::Close, 10., white()))718
} else {719
button720
.hover(|button| button.bg(theme::row_hover()))721
.child(icon(IconName::Close, 10., theme::text_muted()))722
};723
button.on_click(cx.listener(move |this, _, window, cx| remove(this, id, window, cx)))724
}745
}725
746
726
fn thumbnail<T: 'static>(747
pub fn preview_size(dimensions: Option<(u32, u32)>, available_width: f32) -> (f32, f32) {727
item: &TrayItem,748
let (width, height) = dimensions728
image: &Arc<Image>,749
.filter(|(width, height)| *width > 0 && *height > 0)729
remove: ItemAction<T>,750
.map_or((PREVIEW_HEIGHT, PREVIEW_HEIGHT), |(width, height)| {730
cx: &mut Context<T>,751
(width as f32, height as f32)752
});753
let scale = (PREVIEW_HEIGHT / height)754
.min(available_width / width)755
.clamp(0., 1.);756
(757
(width * scale).round().max(1.),758
(height * scale).round().max(1.),759
)760
}761
762
pub fn preview_row_height(height: f32) -> f32 {763
height + 2. * PREVIEW_GAP764
}765
766
pub fn inline_preview(767
id: u64,768
preview: Option<PreviewImage>,769
available_width: Pixels,770
selected: bool,771
remove: RemoveImage,731
) -> AnyElement {772
) -> AnyElement {732
div()773
let dimensions = preview.as_ref().and_then(|preview| preview.dimensions);733
.id(ElementId::Name(format!("attachment-{}", item.id).into()))774
let (width, height) = preview_size(dimensions, f32::from(available_width));775
let group = SharedString::from(format!("image-preview-{id}"));776
let frame = div()734
.relative()777
.relative()735
.size(px(THUMB_SIZE))778
.size_full()736
.flex_none()779
.rounded(px(PREVIEW_RADIUS))737
.rounded(px(8.))738
.overflow_hidden()780
.overflow_hidden()739
.border_1()781
.border_1()740
.border_color(theme::border_strong())782
.border_color(theme::border_strong())741
.child(img(image.clone()).size_full().object_fit(ObjectFit::Cover))783
.bg(theme::surface_raised());784
let frame = match preview {785
Some(preview) => frame.child(786
img(preview.image)787
.size_full()788
.rounded(px(PREVIEW_RADIUS))789
.object_fit(ObjectFit::Cover),790
),791
None => frame,792
};793
div()794
.group(group.clone())795
.w(px(width))796
.h(px(preview_row_height(height)))797
.py(px(PREVIEW_GAP))742
.child(798
.child(743
div()799
frame744
.absolute()800
.when(selected, |frame| {745
.top(px(4.))801
frame.child(746
.right(px(4.))802
div()747
.child(remove_button(item.id, true, remove, cx)),803
.absolute()804
.inset_0()805
.rounded(px(PREVIEW_RADIUS))806
.border_2()807
.border_color(theme::accent()),808
)809
})810
.child(811
div()812
.id(ElementId::Name(format!("image-remove-{id}").into()))813
.absolute()814
.top(px(6.))815
.right(px(6.))816
.size(px(REMOVE_SIZE))817
.flex()818
.items_center()819
.justify_center()820
.rounded_full()821
.cursor_pointer()822
.bg(black().opacity(0.6))823
.opacity(0.)824
.group_hover(group, |button| button.opacity(1.))825
.hover(|button| button.bg(black().opacity(0.85)))826
.child(icon(IconName::Close, 10., white()))827
.on_mouse_down(MouseButton::Left, |_, window, cx| {828
window.prevent_default();829
cx.stop_propagation();830
})831
.on_click(move |_, window, cx| remove(window, cx)),832
),748
)833
)749
.into_any_element()834
.into_any_element()750
}835
}@@ -813,7 +898,7 @@ fn chip<T: 'static>(813
.on_click(cx.listener(move |this, _, window, cx| retry(this, id, window, cx))),898
.on_click(cx.listener(move |this, _, window, cx| retry(this, id, window, cx))),814
)899
)815
})900
})816
.child(remove_button(id, false, remove, cx))901
.child(remove_button(id, remove, cx))817
.when_some(state.progress, |chip, percent| {902
.when_some(state.progress, |chip, percent| {818
chip.child(903
chip.child(819
div()904
div()@@ -834,16 +919,14 @@ pub fn render_tray<T: 'static>(834
retry: ItemAction<T>,919
retry: ItemAction<T>,835
cx: &mut Context<T>,920
cx: &mut Context<T>,836
) -> Option<Div> {921
) -> Option<Div> {837
if tray.is_empty() {922
if !tray.has_chips() {838
return None;923
return None;839
}924
}840
let elements: Vec<AnyElement> = tray925
let elements: Vec<AnyElement> = tray841
.items()926
.items()842
.iter()927
.iter()843
.map(|item| match &item.kind {928
.filter(|item| !matches!(item.kind, ItemKind::Image { .. }))844
ItemKind::Image { image, .. } => thumbnail(item, image, remove, cx),929
.map(|item| chip(item, remove, retry, cx))845
_ => chip(item, remove, retry, cx),846
})847
.collect();930
.collect();848
Some(931
Some(849
h_flex()932
h_flex()@@ -870,7 +953,7 @@ mod tests {870
AttachmentTray, Classification, DoneFile, FILES_LATER_NOTICE, INLINE_IMAGE_MAX_BYTES,953
AttachmentTray, Classification, DoneFile, FILES_LATER_NOTICE, INLINE_IMAGE_MAX_BYTES,871
INLINE_TOTAL_MAX_BYTES, InlineFormat, ItemKind, LoadedFile, MAX_ATTACHMENTS, PasteAction,954
INLINE_TOTAL_MAX_BYTES, InlineFormat, ItemKind, LoadedFile, MAX_ATTACHMENTS, PasteAction,872
Tone, UploadResult, chip_state, classify, limit_notice, paste_action, pasted_image_name,955
Tone, UploadResult, chip_state, classify, limit_notice, paste_action, pasted_image_name,873
prepare_pasted_image, read_attachment, sniff_inline_format,956
prepare_pasted_image, preview_size, read_attachment, sniff_inline_format,874
};957
};875
958
876
const PNG_HEADER: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];959
const PNG_HEADER: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];@@ -1242,7 +1325,7 @@ mod tests {1242
let (mut tray, id) = tray_with_file();1325
let (mut tray, id) = tray_with_file();1243
tray.remove(id);1326
tray.remove(id);1244
tray.finish_upload(id, done("plan.pdf"));1327
tray.finish_upload(id, done("plan.pdf"));1245
assert!(tray.is_empty());1328
assert!(tray.items().is_empty());1246
}1329
}1247
1330
1248
#[test]1331
#[test]@@ -1264,15 +1347,42 @@ mod tests {1264
source.finish_reading(ids[0], LoadedFile::new(png(4, 2)), true);1347
source.finish_reading(ids[0], LoadedFile::new(png(4, 2)), true);1265
source.finish_reading(ids[1], LoadedFile::new(b"%PDF".to_vec()), true);1348
source.finish_reading(ids[1], LoadedFile::new(b"%PDF".to_vec()), true);1266
source.finish_upload(ids[1], done("b.pdf"));1349
source.finish_upload(ids[1], done("b.pdf"));1267
let (images, files) = (source.outgoing_images(), source.outgoing_files());1350
let (images, files) = (source.images_in(&ids[..1]), source.outgoing_files());1268
1351
1269
let mut restored = AttachmentTray::default();1352
let mut restored = AttachmentTray::default();1270
restored.restore(&images, &files);1353
let image_ids = restored.restore(&images, &files);1271
assert_eq!(restored.outgoing_images(), images);1354
assert_eq!(image_ids.len(), 1);1355
assert_eq!(restored.images_in(&image_ids), images);1272
assert_eq!(restored.outgoing_files(), files);1356
assert_eq!(restored.outgoing_files(), files);1273
assert!(!restored.blocks_send());1357
assert!(!restored.blocks_send());1274
}1358
}1275
1359
1360
#[test]1361
fn images_come_back_in_the_order_asked_for_and_only_when_known() {1362
let mut tray = AttachmentTray::default();1363
let ids = tray.add_pending(&["a.png".to_owned(), "b.png".to_owned()]);1364
tray.finish_reading(ids[0], LoadedFile::new(png(2, 2)), true);1365
tray.finish_reading(ids[1], LoadedFile::new(png(4, 4)), true);1366
let images = tray.images_in(&[ids[1], 99, ids[0]]);1367
assert_eq!(images.len(), 2);1368
assert_eq!(images[0].dimensions, Some((4, 4)));1369
assert_eq!(images[1].dimensions, Some((2, 2)));1370
assert!(!tray.has_chips());1371
tray.discard_images_except(&[ids[1]]);1372
assert_eq!(tray.items().len(), 1);1373
assert!(tray.image(ids[1]).is_some());1374
assert!(tray.image(ids[0]).is_none());1375
}1376
1377
#[test]1378
fn previews_are_at_most_120_high_and_fit_the_row() {1379
assert_eq!(preview_size(Some((400, 300)), 800.), (160., 120.));1380
assert_eq!(preview_size(Some((40, 30)), 800.), (40., 30.));1381
assert_eq!(preview_size(Some((1000, 100)), 250.), (250., 25.));1382
assert_eq!(preview_size(None, 800.), (120., 120.));1383
assert_eq!(preview_size(Some((400, 300)), 0.), (1., 1.));1384
}1385
1276
#[test]1386
#[test]1277
fn switching_chats_for_a_draft_keeps_only_images() {1387
fn switching_chats_for_a_draft_keeps_only_images() {1278
let mut tray = AttachmentTray::default();1388
let mut tray = AttachmentTray::default();@@ -1289,7 +1399,7 @@ mod tests {1289
let mut tray = AttachmentTray::default();1399
let mut tray = AttachmentTray::default();1290
let id = tray.add_pending(&["gone.txt".to_owned()])[0];1400
let id = tray.add_pending(&["gone.txt".to_owned()])[0];1291
tray.fail_reading(id, "Could not read gone.txt.".to_owned());1401
tray.fail_reading(id, "Could not read gone.txt.".to_owned());1292
assert!(tray.is_empty());1402
assert!(tray.items().is_empty());1293
assert_eq!(tray.notice(), Some("Could not read gone.txt."));1403
assert_eq!(tray.notice(), Some("Could not read gone.txt."));1294
}1404
}1295
1405
@@ -21,14 +21,14 @@ use gpui_kit::prelude::FluentBuilder as _;
21
21
use gpui_kit::*;
22
22
use teams_core::{
23
23
Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,
24
MentionCandidate, MentionInput, MessageExtras, TypingStyle, UploadedFile, changed_span,
25
has_markdown, link_url, map_offset, reverse_edits,
24
MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, TypingStyle, UploadedFile,
25
changed_span, has_markdown, link_url, map_offset, reverse_edits,
26
26
};
27
27
28
28
use super::attachment_tray::{
29
AttachmentTray, DoneFile, JobKind, LoadedFile, OutgoingFile, OutgoingImage, PasteAction,
30
UploadJob, UploadResult, discard_uploaded, names_of, paste_action, pasted_image_name,
31
prepare_pasted_image, read_attachment, render_tray,
29
AttachmentTray, DoneFile, JobKind, LoadedFile, MAX_ATTACHMENTS, OutgoingFile, OutgoingImage,
30
PasteAction, UploadJob, UploadResult, discard_uploaded, inline_preview, names_of, paste_action,
31
pasted_image_name, prepare_pasted_image, read_attachment, render_tray,
32
32
};
33
33
use super::avatar::{person_avatar, square_avatar};
34
34
use super::draft_style::draft_style;
@@ -54,6 +54,7 @@ const DEMO_FAILURE_STEP: u8 = 6;
54
54
const HISTORY_LIMIT: usize = 200;
55
55
const PASTE_HINT_DURATION: Duration = Duration::from_secs(4);
56
56
const KEY_CONTEXT: &str = "Composer";
57
const IMAGE_TOKEN_PREFIX: &str = "image-";
57
58
58
59
actions!(
59
60
composer,
@@ -117,7 +118,19 @@ impl Outgoing {
117
118
118
119
/// The body before mentions become `<at>` tags.
119
120
pub fn html(&self) -> String {
120
self.draft.to_html()
121
let mut html = String::new();
122
let mut placed = 0;
123
for character in self.draft.to_html().chars() {
124
if character != OBJECT_MARK {
125
html.push(character);
126
continue;
127
}
128
placed += 1;
129
if placed <= self.images.len() {
130
html.push_str(&format!("<img src=\"../hostedContents/{placed}/$value\">"));
131
}
132
}
133
html
121
134
}
122
135
123
136
pub fn has_attachments(&self) -> bool {
@@ -243,6 +256,7 @@ pub struct Composer {
243
256
uploads: HashMap<u64, UploadHandle>,
244
257
demo_failed: HashSet<u64>,
245
258
carry_images_into: Option<String>,
259
pending_anchors: HashMap<u64, usize>,
246
260
_subscriptions: [Subscription; 2],
247
261
}
248
262
@@ -354,6 +368,14 @@ fn looks_like_url(text: &str) -> bool {
354
368
&& !text.contains(char::is_whitespace)
355
369
}
356
370
371
fn image_token(id: u64) -> InlineToken {
372
InlineToken::new(format!("{IMAGE_TOKEN_PREFIX}{id}"), OBJECT_MARK.to_string()).block()
373
}
374
375
fn image_id(token: &InlineToken) -> Option<u64> {
376
token.id().strip_prefix(IMAGE_TOKEN_PREFIX)?.parse().ok()
377
}
378
357
379
fn candidate_key(candidate: &MentionCandidate) -> &str {
358
380
match candidate {
359
381
MentionCandidate::Person(person) => &person.user_id,
@@ -416,6 +438,7 @@ impl Composer {
416
438
uploads: HashMap::new(),
417
439
demo_failed: HashSet::new(),
418
440
carry_images_into: None,
441
pending_anchors: HashMap::new(),
419
442
_subscriptions: [subscription, observer],
420
443
}
421
444
}
@@ -435,7 +458,7 @@ impl Composer {
435
458
}
436
459
let value = input.read(cx).value();
437
460
if submitted_text(event, &value).is_some()
438
|| (is_plain_enter(event) && !self.tray.is_empty())
461
|| (is_plain_enter(event) && self.has_attachments(cx))
439
462
{
440
463
self.submit_current(window, cx);
441
464
}
@@ -480,6 +503,10 @@ impl Composer {
480
503
let state = self.input.read(cx);
481
504
let (value, input_cursor) = (state.value().to_string(), state.cursor());
482
505
let previous = std::mem::replace(&mut self.previous_value, value.clone());
506
if previous != value {
507
let (start, old_end, new_end) = changed_span(&previous, &value);
508
self.shift_anchors(start, old_end, new_end);
509
}
483
510
if value == self.draft.text() {
484
511
self.refresh_style(cx);
485
512
return;
@@ -636,6 +663,9 @@ impl Composer {
636
663
state.set_selected_range(selection.clone(), cx);
637
664
}
638
665
});
666
for anchor in self.pending_anchors.values_mut() {
667
*anchor = map_offset(&edits, *anchor);
668
}
639
669
let value = self.input.read(cx).value().to_string();
640
670
if value != self.draft.text() {
641
671
self.draft.apply_edit(&value, selection.end, None);
@@ -645,6 +675,18 @@ impl Composer {
645
675
self.refresh_style(cx);
646
676
}
647
677
678
fn shift_anchors(&mut self, start: usize, old_end: usize, new_end: usize) {
679
for anchor in self.pending_anchors.values_mut() {
680
*anchor = if *anchor <= start {
681
*anchor
682
} else if *anchor >= old_end {
683
*anchor - old_end + new_end
684
} else {
685
new_end
686
};
687
}
688
}
689
648
690
/// Adds the current state as an undo step. Typing and deleting runs merge into one step;
649
691
/// a typed space ends a typing step.
650
692
fn record(&mut self, kind: StepKind, cx: &App) {
@@ -700,6 +742,9 @@ impl Composer {
700
742
(true, true) => source_selection,
701
743
(true, false) => step.selection.clone(),
702
744
};
745
if start != old_end || start != new_end {
746
self.shift_anchors(start, old_end, new_end);
747
}
703
748
self.draft = draft.clone();
704
749
self.previous_value = draft.text().to_owned();
705
750
self.input.update(cx, |state, cx| {
@@ -761,6 +806,7 @@ impl Composer {
761
806
self.paste_hint = None;
762
807
self.link_editor = None;
763
808
self.toolbar_dismissed = None;
809
self.pending_anchors.clear();
764
810
self.history.clear();
765
811
self.history_index = 0;
766
812
self.record(StepKind::Other, cx);
@@ -1018,8 +1064,16 @@ impl Composer {
1018
1064
if selection.is_empty() || self.draft.text().get(selection.clone()).is_none() {
1019
1065
return false;
1020
1066
}
1021
let text = self.draft.text()[selection.clone()].to_owned();
1022
let lines = self.draft.slice(selection);
1067
let selected = &self.draft.text()[selection.clone()];
1068
let text = selected.replace(OBJECT_MARK, "");
1069
let lines = if selected.contains(OBJECT_MARK) {
1070
self.draft.slice_without_objects(selection)
1071
} else {
1072
self.draft.slice(selection)
1073
};
1074
if text.is_empty() {
1075
return true;
1076
}
1023
1077
cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1024
1078
text.clone(),
1025
1079
lines.clone(),
@@ -1221,6 +1275,7 @@ impl Composer {
1221
1275
self.tray.clear()
1222
1276
};
1223
1277
self.discard_uploaded(dropped, cx);
1278
self.remove_orphan_image_tokens(window, cx);
1224
1279
self.reply = None;
1225
1280
if self.editing.take().is_some() {
1226
1281
self.load_draft(Draft::default(), InputContent::new(""), window, cx);
@@ -1263,7 +1318,26 @@ impl Composer {
1263
1318
if !self.can_send(cx) {
1264
1319
return None;
1265
1320
}
1266
let mut draft = self.current_draft(cx).trimmed();
1321
let mut draft = self.current_draft(cx);
1322
let image_spans: Vec<(Range<usize>, u64)> = state
1323
.tokens()
1324
.iter()
1325
.filter_map(|span| Some((span.range(), image_id(span.token())?)))
1326
.collect();
1327
let image_ids: Vec<u64> = image_spans
1328
.iter()
1329
.filter(|(_, id)| self.tray.image(*id).is_some())
1330
.map(|(_, id)| *id)
1331
.collect();
1332
for (range, _) in image_spans
1333
.iter()
1334
.rev()
1335
.filter(|(_, id)| self.tray.image(*id).is_none())
1336
{
1337
draft.replace(range.clone(), "");
1338
}
1339
draft.take_edits();
1340
let mut draft = draft.trimmed();
1267
1341
let attachments_apply = self.editing.is_none();
1268
1342
if self.undone_value.as_deref() != Some(state.value().as_ref())
1269
1343
&& let Some((range, glyph)) = emoji::trailing_smiley(draft.text())
@@ -1284,7 +1358,7 @@ impl Composer {
1284
1358
reply: self.reply.clone(),
1285
1359
edit: self.editing.clone(),
1286
1360
images: if attachments_apply {
1287
self.tray.outgoing_images()
1361
self.tray.images_in(&image_ids)
1288
1362
} else {
1289
1363
Vec::new()
1290
1364
},
@@ -1311,7 +1385,101 @@ impl Composer {
1311
1385
if self.editing.is_some() {
1312
1386
return has_text;
1313
1387
}
1314
(has_text || !self.tray.is_empty()) && !self.tray.blocks_send()
1388
(has_text || self.has_attachments(cx)) && !self.tray.blocks_send()
1389
}
1390
1391
fn has_attachments(&self, cx: &App) -> bool {
1392
self.tray.has_chips()
1393
|| self
1394
.input
1395
.read(cx)
1396
.tokens()
1397
.iter()
1398
.any(|span| image_id(span.token()).is_some_and(|id| self.tray.image(id).is_some()))
1399
}
1400
1401
fn image_token_range(&self, id: u64, cx: &App) -> Option<Range<usize>> {
1402
self.input
1403
.read(cx)
1404
.tokens()
1405
.iter()
1406
.find(|span| image_id(span.token()) == Some(id))
1407
.map(|span| span.range())
1408
}
1409
1410
fn remove_orphan_image_tokens(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1411
let edits: Vec<Edit> = self
1412
.input
1413
.read(cx)
1414
.tokens()
1415
.iter()
1416
.filter(|span| image_id(span.token()).is_some_and(|id| self.tray.image(id).is_none()))
1417
.map(|span| (span.range(), String::new()))
1418
.collect();
1419
if !edits.is_empty() {
1420
self.input
1421
.update(cx, |state, cx| state.apply_edits(&edits, window, cx));
1422
}
1423
}
1424
1425
fn remove_image_token(&mut self, id: u64, window: &mut Window, cx: &mut Context<Self>) {
1426
let Some(range) = self.image_token_range(id, cx) else {
1427
return;
1428
};
1429
self.input.update(cx, |state, cx| {
1430
state.set_selected_range(range, cx);
1431
state.replace("", window, cx);
1432
});
1433
}
1434
1435
fn insert_image_token(&mut self, id: u64, window: &mut Window, cx: &mut Context<Self>) {
1436
let state = self.input.read(cx);
1437
let value = state.value().to_string();
1438
let selection = state.selected_range();
1439
let mut offset = self
1440
.pending_anchors
1441
.remove(&id)
1442
.unwrap_or(selection.end)
1443
.min(value.len());
1444
while !value.is_char_boundary(offset) {
1445
offset -= 1;
1446
}
1447
if value == self.draft.text() && self.draft.in_code(offset) {
1448
offset = value.len();
1449
}
1450
if let Some(span) = state
1451
.tokens()
1452
.iter()
1453
.find(|span| span.range().start < offset && offset < span.range().end)
1454
{
1455
offset = span.range().end;
1456
}
1457
let length = OBJECT_MARK.len_utf8();
1458
let after = |position: usize| {
1459
if position >= offset {
1460
position + length
1461
} else {
1462
position
1463
}
1464
};
1465
let inserted = self.input.update(cx, |state, cx| {
1466
let inserted = state
1467
.replace_range_with_token(offset..offset, image_token(id), window, cx)
1468
.is_ok();
1469
if inserted {
1470
state.set_selected_range(after(selection.start)..after(selection.end), cx);
1471
}
1472
inserted
1473
});
1474
if !inserted {
1475
return;
1476
}
1477
for (other, anchor) in self.pending_anchors.iter_mut() {
1478
if *anchor > offset || (*anchor == offset && *other > id) {
1479
*anchor += length;
1480
}
1481
}
1482
self.previous_value = self.input.read(cx).value().to_string();
1315
1483
}
1316
1484
1317
1485
pub fn is_editing(&self) -> bool {
@@ -1330,7 +1498,7 @@ impl Composer {
1330
1498
}
1331
1499
}
1332
1500
1333
pub fn open_picker(&mut self, cx: &mut Context<Self>) {
1501
pub fn open_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1334
1502
if self.editing.is_some() {
1335
1503
return;
1336
1504
}
@@ -1340,46 +1508,69 @@ impl Composer {
1340
1508
multiple: true,
1341
1509
prompt: None,
1342
1510
});
1343
cx.spawn(async move |this, cx| {
1511
cx.spawn_in(window, async move |this, cx| {
1344
1512
if let Ok(Ok(Some(paths))) = receiver.await {
1345
this.update(cx, |this, cx| this.add_paths(paths, cx)).ok();
1513
this.update_in(cx, |this, window, cx| this.add_paths(paths, window, cx))
1514
.ok();
1346
1515
}
1347
1516
})
1348
1517
.detach();
1349
1518
}
1350
1519
1351
pub fn add_paths(&mut self, paths: Vec<PathBuf>, cx: &mut Context<Self>) {
1520
pub fn add_paths(&mut self, paths: Vec<PathBuf>, window: &mut Window, cx: &mut Context<Self>) {
1352
1521
if self.editing.is_some() || paths.is_empty() {
1353
1522
return;
1354
1523
}
1355
let ids = self.tray.add_pending(&names_of(&paths));
1524
let ids = self.add_pending(&names_of(&paths), cx);
1356
1525
for (id, path) in ids.into_iter().zip(paths) {
1357
cx.spawn(async move |this, cx| {
1526
cx.spawn_in(window, async move |this, cx| {
1358
1527
let loaded = cx
1359
1528
.background_executor()
1360
1529
.spawn(async move { read_attachment(&path) })
1361
1530
.await;
1362
this.update(cx, |this, cx| this.finish_reading(id, loaded, cx))
1363
.ok();
1531
this.update_in(cx, |this, window, cx| {
1532
this.finish_reading(id, loaded, window, cx)
1533
})
1534
.ok();
1364
1535
})
1365
1536
.detach();
1366
1537
}
1367
1538
cx.notify();
1368
1539
}
1369
1540
1370
fn add_pasted_image(&mut self, pasted: Image, cx: &mut Context<Self>) {
1371
let ids = self.tray.add_pending(&[pasted_image_name()]);
1541
fn add_pending(&mut self, names: &[String], cx: &App) -> Vec<u64> {
1542
if self.tray.items().len() + names.len() > MAX_ATTACHMENTS {
1543
let referenced: Vec<u64> = self
1544
.input
1545
.read(cx)
1546
.tokens()
1547
.iter()
1548
.filter_map(|span| image_id(span.token()))
1549
.collect();
1550
self.tray.discard_images_except(&referenced);
1551
}
1552
let ids = self.tray.add_pending(names);
1553
let anchor = self.selection(cx).end;
1554
self.pending_anchors
1555
.extend(ids.iter().map(|id| (*id, anchor)));
1556
ids
1557
}
1558
1559
fn add_pasted_image(&mut self, pasted: Image, window: &mut Window, cx: &mut Context<Self>) {
1560
let ids = self.add_pending(&[pasted_image_name()], cx);
1372
1561
cx.notify();
1373
1562
let Some(&id) = ids.first() else {
1374
1563
return;
1375
1564
};
1376
cx.spawn(async move |this, cx| {
1565
cx.spawn_in(window, async move |this, cx| {
1377
1566
let loaded = cx
1378
1567
.background_executor()
1379
1568
.spawn(async move { prepare_pasted_image(pasted) })
1380
1569
.await;
1381
this.update(cx, |this, cx| this.finish_reading(id, loaded, cx))
1382
.ok();
1570
this.update_in(cx, |this, window, cx| {
1571
this.finish_reading(id, loaded, window, cx)
1572
})
1573
.ok();
1383
1574
})
1384
1575
.detach();
1385
1576
}
@@ -1389,11 +1580,11 @@ impl Composer {
1389
1580
match paste_action(item) {
1390
1581
PasteAction::Text => {}
1391
1582
PasteAction::Files(paths) => {
1392
self.add_paths(paths, cx);
1583
self.add_paths(paths, window, cx);
1393
1584
return true;
1394
1585
}
1395
1586
PasteAction::Image(pasted) => {
1396
self.add_pasted_image(pasted, cx);
1587
self.add_pasted_image(pasted, window, cx);
1397
1588
return true;
1398
1589
}
1399
1590
}
@@ -1401,6 +1592,12 @@ impl Composer {
1401
1592
let Some(text) = item.text() else {
1402
1593
return false;
1403
1594
};
1595
if text.contains(OBJECT_MARK) {
1596
let cleaned = text.replace(OBJECT_MARK, "");
1597
self.input
1598
.update(cx, |state, cx| state.replace(cleaned, window, cx));
1599
return true;
1600
}
1404
1601
if self.draft.in_code(self.selection(cx).start) {
1405
1602
return false;
1406
1603
}
@@ -1417,16 +1614,26 @@ impl Composer {
1417
1614
&mut self,
1418
1615
id: u64,
1419
1616
loaded: Result<LoadedFile, String>,
1617
window: &mut Window,
1420
1618
cx: &mut Context<Self>,
1421
1619
) {
1422
1620
match loaded {
1423
1621
Ok(loaded) => {
1424
1622
let files_allowed = self.files_allowed();
1425
if let Some(job) = self.tray.finish_reading(id, loaded, files_allowed) {
1623
let job = self.tray.finish_reading(id, loaded, files_allowed);
1624
if self.tray.image(id).is_some() {
1625
self.insert_image_token(id, window, cx);
1626
} else {
1627
self.pending_anchors.remove(&id);
1628
}
1629
if let Some(job) = job {
1426
1630
self.start_upload(job, cx);
1427
1631
}
1428
1632
}
1429
Err(message) => self.tray.fail_reading(id, message),
1633
Err(message) => {
1634
self.pending_anchors.remove(&id);
1635
self.tray.fail_reading(id, message);
1636
}
1430
1637
}
1431
1638
cx.notify();
1432
1639
}
@@ -1595,8 +1802,20 @@ impl Composer {
1595
1802
1596
1803
pub fn restore(&mut self, outgoing: &Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1597
1804
self.mention_inputs.clear();
1805
let image_ids = if outgoing.edit.is_none() {
1806
self.cancel_uploads();
1807
self.tray.restore(&outgoing.images, &outgoing.files)
1808
} else {
1809
Vec::new()
1810
};
1598
1811
let text = outgoing.draft.text();
1599
1812
let mut content = InputContent::new(text.to_owned());
1813
for ((offset, _), id) in text.match_indices(OBJECT_MARK).zip(image_ids) {
1814
let range = offset..offset + OBJECT_MARK.len_utf8();
1815
if let Ok(next) = content.clone().with_token(range, image_token(id)) {
1816
content = next;
1817
}
1818
}
1600
1819
let mut cursor = 0;
1601
1820
for mention in &outgoing.mentions {
1602
1821
let needle = format!("@{}", mention.text);
@@ -1616,10 +1835,6 @@ impl Composer {
1616
1835
self.load_draft(outgoing.draft.clone(), content, window, cx);
1617
1836
self.reply = outgoing.reply.clone();
1618
1837
self.editing = outgoing.edit.clone();
1619
if outgoing.edit.is_none() {
1620
self.cancel_uploads();
1621
self.tray.restore(&outgoing.images, &outgoing.files);
1622
}
1623
1838
self.close_popup();
1624
1839
cx.notify();
1625
1840
}
@@ -1635,8 +1850,8 @@ impl Composer {
1635
1850
cx.notify();
1636
1851
}
1637
1852
1638
pub fn is_empty(&self, _: &App) -> bool {
1639
self.draft.is_blank() && self.tray.is_empty()
1853
pub fn is_empty(&self, cx: &App) -> bool {
1854
self.draft.is_blank() && !self.has_attachments(cx)
1640
1855
}
1641
1856
1642
1857
pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
@@ -1981,9 +2196,10 @@ impl Render for Composer {
1981
2196
.hover(|button| button.bg(theme::row_hover()))
1982
2197
.tooltip(|window, cx| Tooltip::new("Attach file").build(window, cx))
1983
2198
.child(symbol("attach_file", 20., theme::text_muted()))
1984
.on_click(cx.listener(|this, _, _, cx| this.open_picker(cx)))
2199
.on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
1985
2200
});
1986
2201
let composer = cx.weak_entity();
2202
let tokens_composer = composer.clone();
1987
2203
let input = Textarea::new(&self.input)
1988
2204
.appearance(false)
1989
2205
.bordered(false)
@@ -1992,7 +2208,29 @@ impl Render for Composer {
1992
2208
.update(cx, |this, cx| this.paste(item, window, cx))
1993
2209
.unwrap_or(false)
1994
2210
})
1995
.token(|context, _, _| {
2211
.token(move |context, _, cx| {
2212
if let Some(id) = context
2213
.is_block()
2214
.then(|| image_id(context.token()))
2215
.flatten()
2216
{
2217
let preview = tokens_composer
2218
.read_with(cx, |this, _| this.tray.image(id))
2219
.ok()
2220
.flatten();
2221
let remove_composer = tokens_composer.clone();
2222
return inline_preview(
2223
id,
2224
preview,
2225
context.available_width(),
2226
context.is_selected(),
2227
Rc::new(move |window, cx| {
2228
remove_composer
2229
.update(cx, |this, cx| this.remove_image_token(id, window, cx))
2230
.ok();
2231
}),
2232
);
2233
}
1996
2234
div()
1997
2235
.h(context.line_height())
1998
2236
.px(px(5.))
@@ -2005,6 +2243,7 @@ impl Render for Composer {
2005
2243
.text_color(theme::mention_text())
2006
2244
.font_weight(FontWeight::SEMIBOLD)
2007
2245
.child(context.token().label().clone())
2246
.into_any_element()
2008
2247
});
2009
2248
let tray = can_attach
2010
2249
.then(|| {
@@ -2341,6 +2580,53 @@ mod tests {
2341
2580
assert!(outgoing.has_attachments());
2342
2581
}
2343
2582
2583
fn placed_image(width: u32) -> super::OutgoingImage {
2584
use std::sync::Arc;
2585
2586
use gpui_kit::{Image, ImageFormat};
2587
2588
super::OutgoingImage {
2589
name: "pasted-image.png".into(),
2590
image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![width as u8])),
2591
dimensions: Some((width, width)),
2592
}
2593
}
2594
2595
fn outgoing_with(text: &str, images: Vec<super::OutgoingImage>) -> super::Outgoing {
2596
super::Outgoing {
2597
draft: teams_core::Draft::plain(text),
2598
mentions: Vec::new(),
2599
reply: None,
2600
edit: None,
2601
images,
2602
files: Vec::new(),
2603
}
2604
}
2605
2606
#[test]
2607
fn an_image_is_placed_in_the_html_where_its_mark_sits() {
2608
let outgoing = outgoing_with("a \u{FFFC} b", vec![placed_image(2)]);
2609
assert_eq!(
2610
outgoing.html(),
2611
"a <img src=\"../hostedContents/1/$value\"> b"
2612
);
2613
assert_eq!(outgoing.text(), "a b");
2614
}
2615
2616
#[test]
2617
fn images_keep_the_order_of_their_marks() {
2618
let outgoing = outgoing_with("\u{FFFC}x\u{FFFC}", vec![placed_image(2), placed_image(4)]);
2619
assert_eq!(
2620
outgoing.html(),
2621
"<img src=\"../hostedContents/1/$value\">x<img src=\"../hostedContents/2/$value\">"
2622
);
2623
}
2624
2625
#[test]
2626
fn a_mark_without_an_image_leaves_no_trace() {
2627
assert_eq!(outgoing_with("a\u{FFFC}b", Vec::new()).html(), "ab");
2628
}
2629
2344
2630
#[test]
2345
2631
fn enter_sends_attachments_even_without_text() {
2346
2632
assert!(super::is_plain_enter(&press(false)));
@@ -2449,6 +2735,201 @@ mod tests {
2449
2735
typist
2450
2736
}
2451
2737
2738
fn png_bytes(side: u32) -> Vec<u8> {
2739
let mut bytes = Vec::new();
2740
image::RgbaImage::new(side, side)
2741
.write_to(
2742
&mut std::io::Cursor::new(&mut bytes),
2743
image::ImageFormat::Png,
2744
)
2745
.unwrap();
2746
bytes
2747
}
2748
2749
fn paste_image(typist: &mut Typist<'_>, side: u32) {
2750
typist.cx.write_to_clipboard(gpui_kit::ClipboardItem {
2751
entries: vec![gpui_kit::ClipboardEntry::Image(
2752
gpui_kit::Image::from_bytes(gpui_kit::ImageFormat::Png, png_bytes(side)),
2753
)],
2754
});
2755
typist.press("ctrl-v");
2756
}
2757
2758
fn image_tokens(typist: &mut Typist<'_>) -> Vec<(std::ops::Range<usize>, bool)> {
2759
let composer = typist.composer.clone();
2760
typist.cx.update(|cx| {
2761
composer
2762
.read(cx)
2763
.input
2764
.read(cx)
2765
.tokens()
2766
.iter()
2767
.map(|span| (span.range(), span.token().is_block()))
2768
.collect()
2769
})
2770
}
2771
2772
#[gpui_kit::test]
2773
fn a_pasted_image_sits_at_the_cursor_and_is_sent_there(cx: &mut TestAppContext) {
2774
let mut typist = typist(cx);
2775
typist.type_text("ab");
2776
typist.press("left");
2777
paste_image(&mut typist, 2);
2778
assert_eq!(typist.value(), "a\u{FFFC}b");
2779
assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
2780
let outgoing = typist.outgoing();
2781
assert_eq!(outgoing.images.len(), 1);
2782
assert_eq!(
2783
outgoing.html(),
2784
"a<img src=\"../hostedContents/1/$value\">b"
2785
);
2786
let composer = typist.composer.clone();
2787
assert!(!typist.cx.update(|cx| composer.read(cx).tray.has_chips()));
2788
}
2789
2790
fn wide_png_bytes() -> Vec<u8> {
2791
let mut bytes = Vec::new();
2792
image::RgbaImage::new(600, 300)
2793
.write_to(
2794
&mut std::io::Cursor::new(&mut bytes),
2795
image::ImageFormat::Png,
2796
)
2797
.unwrap();
2798
bytes
2799
}
2800
2801
fn caret_is_visible(typist: &mut Typist<'_>) -> bool {
2802
let composer = typist.composer.clone();
2803
typist.cx.update(|cx| {
2804
let state = composer.read(cx).input.read(cx);
2805
let cursor = state.cursor();
2806
let caret = state.range_to_bounds(&(cursor..cursor)).unwrap();
2807
let viewport = state.input_bounds();
2808
caret.origin.y >= viewport.origin.y && caret.bottom() <= viewport.bottom()
2809
})
2810
}
2811
2812
#[gpui_kit::test]
2813
fn typing_after_a_tall_image_keeps_the_caret_in_view(cx: &mut TestAppContext) {
2814
let mut typist = typist(cx);
2815
typist.type_text("look at this ");
2816
typist.cx.write_to_clipboard(gpui_kit::ClipboardItem {
2817
entries: vec![gpui_kit::ClipboardEntry::Image(
2818
gpui_kit::Image::from_bytes(gpui_kit::ImageFormat::Png, wide_png_bytes()),
2819
)],
2820
});
2821
typist.press("ctrl-v");
2822
typist.act(|window, _| window.refresh());
2823
typist.type_text("and then more text");
2824
typist.act(|window, _| window.refresh());
2825
assert!(caret_is_visible(&mut typist));
2826
}
2827
2828
#[gpui_kit::test]
2829
fn deleting_the_token_drops_the_image_and_undo_brings_it_back(cx: &mut TestAppContext) {
2830
let mut typist = typist(cx);
2831
typist.type_text("ab");
2832
typist.press("left");
2833
paste_image(&mut typist, 2);
2834
typist.press("backspace");
2835
assert_eq!(typist.value(), "ab");
2836
assert!(image_tokens(&mut typist).is_empty());
2837
let outgoing = typist.outgoing();
2838
assert!(outgoing.images.is_empty());
2839
assert_eq!(outgoing.html(), "ab");
2840
typist.press("ctrl-z");
2841
assert_eq!(typist.value(), "a\u{FFFC}b");
2842
assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
2843
assert_eq!(typist.outgoing().images.len(), 1);
2844
}
2845
2846
#[gpui_kit::test]
2847
fn the_remove_button_drops_the_image_and_one_undo_brings_it_back(cx: &mut TestAppContext) {
2848
let mut typist = typist(cx);
2849
typist.type_text("ab");
2850
paste_image(&mut typist, 2);
2851
typist.type_text("cd");
2852
let composer = typist.composer.clone();
2853
let id = typist.cx.update(|cx| {
2854
let state = composer.read(cx).input.read(cx);
2855
super::super::image_id(state.tokens()[0].token()).unwrap()
2856
});
2857
typist.act(|window, cx| {
2858
composer.update(cx, |composer, cx| {
2859
composer.remove_image_token(id, window, cx)
2860
});
2861
});
2862
assert_eq!(typist.value(), "abcd");
2863
assert!(image_tokens(&mut typist).is_empty());
2864
assert!(typist.outgoing().images.is_empty());
2865
typist.press("ctrl-z");
2866
assert_eq!(typist.value(), "ab\u{FFFC}cd");
2867
assert_eq!(image_tokens(&mut typist), vec![(2..5, true)]);
2868
assert_eq!(typist.outgoing().images.len(), 1);
2869
}
2870
2871
#[gpui_kit::test]
2872
fn images_are_sent_in_the_order_they_appear_in_the_text(cx: &mut TestAppContext) {
2873
let mut typist = typist(cx);
2874
typist.type_text("x");
2875
paste_image(&mut typist, 2);
2876
typist.type_text("y");
2877
typist.press("ctrl-home");
2878
paste_image(&mut typist, 4);
2879
assert_eq!(typist.value(), "\u{FFFC}x\u{FFFC}y");
2880
let outgoing = typist.outgoing();
2881
let dimensions: Vec<_> = outgoing
2882
.images
2883
.iter()
2884
.map(|image| image.dimensions)
2885
.collect();
2886
assert_eq!(dimensions, [Some((4, 4)), Some((2, 2))]);
2887
assert_eq!(
2888
outgoing.html(),
2889
"<img src=\"../hostedContents/1/$value\">x<img src=\"../hostedContents/2/$value\">y"
2890
);
2891
}
2892
2893
#[gpui_kit::test]
2894
fn an_image_alone_can_be_sent_and_never_leaks_into_copied_text(cx: &mut TestAppContext) {
2895
let mut typist = typist(cx);
2896
paste_image(&mut typist, 2);
2897
let composer = typist.composer.clone();
2898
assert!(typist.cx.update(|cx| composer.read(cx).can_send(cx)));
2899
let outgoing = typist.outgoing();
2900
assert_eq!(outgoing.text(), "");
2901
assert_eq!(outgoing.images.len(), 1);
2902
typist.type_text("hi");
2903
typist.press("ctrl-a ctrl-c");
2904
let copied = typist.cx.read_from_clipboard().and_then(|item| item.text());
2905
assert_eq!(copied.as_deref(), Some("hi"));
2906
}
2907
2908
#[gpui_kit::test]
2909
fn pasted_text_loses_object_marks(cx: &mut TestAppContext) {
2910
let mut typist = typist(cx);
2911
typist
2912
.cx
2913
.write_to_clipboard(gpui_kit::ClipboardItem::new_string("a\u{FFFC}b".to_owned()));
2914
typist.press("ctrl-v");
2915
assert_eq!(typist.value(), "ab");
2916
}
2917
2918
#[gpui_kit::test]
2919
fn a_restored_outgoing_gets_its_image_tokens_back(cx: &mut TestAppContext) {
2920
let mut typist = typist(cx);
2921
let outgoing = super::outgoing_with("x\u{FFFC}y", vec![super::placed_image(3)]);
2922
let composer = typist.composer.clone();
2923
typist.act(|window, cx| {
2924
composer.update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
2925
});
2926
assert_eq!(typist.value(), "x\u{FFFC}y");
2927
assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);
2928
let again = typist.outgoing();
2929
assert_eq!(again.images, outgoing.images);
2930
assert_eq!(again.html(), "x<img src=\"../hostedContents/1/$value\">y");
2931
}
2932
2452
2933
#[gpui_kit::test]
2453
2934
fn typed_markdown_is_formatted_and_backspace_brings_it_back(cx: &mut TestAppContext) {
2454
2935
use teams_core::{FormatState, MarkKind};
@@ -2936,7 +3417,7 @@ mod tests {
2936
3417
cx.update_window(handle, |_, window, cx| {
2937
3418
composer.update(cx, |composer, cx| {
2938
3419
composer.set_conversation("demo-chat", "Demo", window, cx);
2939
composer.add_paths(vec![path], cx);
3420
composer.add_paths(vec![path], window, cx);
2940
3421
});
2941
3422
})
2942
3423
.unwrap();
@@ -2983,7 +3464,7 @@ mod tests {
2983
3464
cx.update_window(handle, |_, window, cx| {
2984
3465
composer.update(cx, |composer, cx| {
2985
3466
composer.set_conversation("demo-chat", "Demo", window, cx);
2986
composer.add_paths(vec![path], cx);
3467
composer.add_paths(vec![path], window, cx);
2987
3468
});
2988
3469
})
2989
3470
.unwrap();
@@ -2994,7 +3475,7 @@ mod tests {
2994
3475
});
2995
3476
})
2996
3477
.unwrap();
2997
cx.update(|cx| assert!(composer.read(cx).tray.is_empty()));
3478
cx.update(|cx| assert!(composer.read(cx).tray.items().is_empty()));
2998
3479
}
2999
3480
3000
3481
fn demo_composer(
@@ -3034,7 +3515,7 @@ mod tests {
3034
3515
cx.update_window(handle, |_, window, cx| {
3035
3516
composer.update(cx, |composer, cx| {
3036
3517
composer.set_conversation("demo-chat", "Demo", window, cx);
3037
composer.add_paths(vec![path], cx);
3518
composer.add_paths(vec![path], window, cx);
3038
3519
});
3039
3520
})
3040
3521
.unwrap();
@@ -3090,7 +3571,7 @@ mod tests {
3090
3571
cx.update_window(handle, |_, window, cx| {
3091
3572
composer.update(cx, |composer, cx| {
3092
3573
composer.set_conversation("", "", window, cx);
3093
composer.add_paths(vec![path.clone()], cx);
3574
composer.add_paths(vec![path.clone()], window, cx);
3094
3575
});
3095
3576
})
3096
3577
.unwrap();
@@ -3120,7 +3601,7 @@ mod tests {
3120
3601
cx.update_window(handle, |_, window, cx| {
3121
3602
composer.update(cx, |composer, cx| {
3122
3603
composer.set_conversation("bob-chat", "Bob", window, cx);
3123
composer.add_paths(vec![png, pdf], cx);
3604
composer.add_paths(vec![png, pdf], window, cx);
3124
3605
});
3125
3606
})
3126
3607
.unwrap();
@@ -21,14 +21,14 @@ use gpui_kit::prelude::FluentBuilder as _;21
use gpui_kit::*;21
use gpui_kit::*;22
use teams_core::{22
use teams_core::{23
Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,23
Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,24
MentionCandidate, MentionInput, MessageExtras, TypingStyle, UploadedFile, changed_span,24
MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, TypingStyle, UploadedFile,25
has_markdown, link_url, map_offset, reverse_edits,25
changed_span, has_markdown, link_url, map_offset, reverse_edits,26
};26
};27
27
28
use super::attachment_tray::{28
use super::attachment_tray::{29
AttachmentTray, DoneFile, JobKind, LoadedFile, OutgoingFile, OutgoingImage, PasteAction,29
AttachmentTray, DoneFile, JobKind, LoadedFile, MAX_ATTACHMENTS, OutgoingFile, OutgoingImage,30
UploadJob, UploadResult, discard_uploaded, names_of, paste_action, pasted_image_name,30
PasteAction, UploadJob, UploadResult, discard_uploaded, inline_preview, names_of, paste_action,31
prepare_pasted_image, read_attachment, render_tray,31
pasted_image_name, prepare_pasted_image, read_attachment, render_tray,32
};32
};33
use super::avatar::{person_avatar, square_avatar};33
use super::avatar::{person_avatar, square_avatar};34
use super::draft_style::draft_style;34
use super::draft_style::draft_style;@@ -54,6 +54,7 @@ const DEMO_FAILURE_STEP: u8 = 6;54
const HISTORY_LIMIT: usize = 200;54
const HISTORY_LIMIT: usize = 200;55
const PASTE_HINT_DURATION: Duration = Duration::from_secs(4);55
const PASTE_HINT_DURATION: Duration = Duration::from_secs(4);56
const KEY_CONTEXT: &str = "Composer";56
const KEY_CONTEXT: &str = "Composer";57
const IMAGE_TOKEN_PREFIX: &str = "image-";57
58
58
actions!(59
actions!(59
composer,60
composer,@@ -117,7 +118,19 @@ impl Outgoing {117
118
118
/// The body before mentions become `<at>` tags.119
/// The body before mentions become `<at>` tags.119
pub fn html(&self) -> String {120
pub fn html(&self) -> String {120
self.draft.to_html()121
let mut html = String::new();122
let mut placed = 0;123
for character in self.draft.to_html().chars() {124
if character != OBJECT_MARK {125
html.push(character);126
continue;127
}128
placed += 1;129
if placed <= self.images.len() {130
html.push_str(&format!("<img src=\"../hostedContents/{placed}/$value\">"));131
}132
}133
html121
}134
}122
135
123
pub fn has_attachments(&self) -> bool {136
pub fn has_attachments(&self) -> bool {@@ -243,6 +256,7 @@ pub struct Composer {243
uploads: HashMap<u64, UploadHandle>,256
uploads: HashMap<u64, UploadHandle>,244
demo_failed: HashSet<u64>,257
demo_failed: HashSet<u64>,245
carry_images_into: Option<String>,258
carry_images_into: Option<String>,259
pending_anchors: HashMap<u64, usize>,246
_subscriptions: [Subscription; 2],260
_subscriptions: [Subscription; 2],247
}261
}248
262
@@ -354,6 +368,14 @@ fn looks_like_url(text: &str) -> bool {354
&& !text.contains(char::is_whitespace)368
&& !text.contains(char::is_whitespace)355
}369
}356
370
371
fn image_token(id: u64) -> InlineToken {372
InlineToken::new(format!("{IMAGE_TOKEN_PREFIX}{id}"), OBJECT_MARK.to_string()).block()373
}374
375
fn image_id(token: &InlineToken) -> Option<u64> {376
token.id().strip_prefix(IMAGE_TOKEN_PREFIX)?.parse().ok()377
}378
357
fn candidate_key(candidate: &MentionCandidate) -> &str {379
fn candidate_key(candidate: &MentionCandidate) -> &str {358
match candidate {380
match candidate {359
MentionCandidate::Person(person) => &person.user_id,381
MentionCandidate::Person(person) => &person.user_id,@@ -416,6 +438,7 @@ impl Composer {416
uploads: HashMap::new(),438
uploads: HashMap::new(),417
demo_failed: HashSet::new(),439
demo_failed: HashSet::new(),418
carry_images_into: None,440
carry_images_into: None,441
pending_anchors: HashMap::new(),419
_subscriptions: [subscription, observer],442
_subscriptions: [subscription, observer],420
}443
}421
}444
}@@ -435,7 +458,7 @@ impl Composer {435
}458
}436
let value = input.read(cx).value();459
let value = input.read(cx).value();437
if submitted_text(event, &value).is_some()460
if submitted_text(event, &value).is_some()438
|| (is_plain_enter(event) && !self.tray.is_empty())461
|| (is_plain_enter(event) && self.has_attachments(cx))439
{462
{440
self.submit_current(window, cx);463
self.submit_current(window, cx);441
}464
}@@ -480,6 +503,10 @@ impl Composer {480
let state = self.input.read(cx);503
let state = self.input.read(cx);481
let (value, input_cursor) = (state.value().to_string(), state.cursor());504
let (value, input_cursor) = (state.value().to_string(), state.cursor());482
let previous = std::mem::replace(&mut self.previous_value, value.clone());505
let previous = std::mem::replace(&mut self.previous_value, value.clone());506
if previous != value {507
let (start, old_end, new_end) = changed_span(&previous, &value);508
self.shift_anchors(start, old_end, new_end);509
}483
if value == self.draft.text() {510
if value == self.draft.text() {484
self.refresh_style(cx);511
self.refresh_style(cx);485
return;512
return;@@ -636,6 +663,9 @@ impl Composer {636
state.set_selected_range(selection.clone(), cx);663
state.set_selected_range(selection.clone(), cx);637
}664
}638
});665
});666
for anchor in self.pending_anchors.values_mut() {667
*anchor = map_offset(&edits, *anchor);668
}639
let value = self.input.read(cx).value().to_string();669
let value = self.input.read(cx).value().to_string();640
if value != self.draft.text() {670
if value != self.draft.text() {641
self.draft.apply_edit(&value, selection.end, None);671
self.draft.apply_edit(&value, selection.end, None);@@ -645,6 +675,18 @@ impl Composer {645
self.refresh_style(cx);675
self.refresh_style(cx);646
}676
}647
677
678
fn shift_anchors(&mut self, start: usize, old_end: usize, new_end: usize) {679
for anchor in self.pending_anchors.values_mut() {680
*anchor = if *anchor <= start {681
*anchor682
} else if *anchor >= old_end {683
*anchor - old_end + new_end684
} else {685
new_end686
};687
}688
}689
648
/// Adds the current state as an undo step. Typing and deleting runs merge into one step;690
/// Adds the current state as an undo step. Typing and deleting runs merge into one step;649
/// a typed space ends a typing step.691
/// a typed space ends a typing step.650
fn record(&mut self, kind: StepKind, cx: &App) {692
fn record(&mut self, kind: StepKind, cx: &App) {@@ -700,6 +742,9 @@ impl Composer {700
(true, true) => source_selection,742
(true, true) => source_selection,701
(true, false) => step.selection.clone(),743
(true, false) => step.selection.clone(),702
};744
};745
if start != old_end || start != new_end {746
self.shift_anchors(start, old_end, new_end);747
}703
self.draft = draft.clone();748
self.draft = draft.clone();704
self.previous_value = draft.text().to_owned();749
self.previous_value = draft.text().to_owned();705
self.input.update(cx, |state, cx| {750
self.input.update(cx, |state, cx| {@@ -761,6 +806,7 @@ impl Composer {761
self.paste_hint = None;806
self.paste_hint = None;762
self.link_editor = None;807
self.link_editor = None;763
self.toolbar_dismissed = None;808
self.toolbar_dismissed = None;809
self.pending_anchors.clear();764
self.history.clear();810
self.history.clear();765
self.history_index = 0;811
self.history_index = 0;766
self.record(StepKind::Other, cx);812
self.record(StepKind::Other, cx);@@ -1018,8 +1064,16 @@ impl Composer {1018
if selection.is_empty() || self.draft.text().get(selection.clone()).is_none() {1064
if selection.is_empty() || self.draft.text().get(selection.clone()).is_none() {1019
return false;1065
return false;1020
}1066
}1021
let text = self.draft.text()[selection.clone()].to_owned();1067
let selected = &self.draft.text()[selection.clone()];1022
let lines = self.draft.slice(selection);1068
let text = selected.replace(OBJECT_MARK, "");1069
let lines = if selected.contains(OBJECT_MARK) {1070
self.draft.slice_without_objects(selection)1071
} else {1072
self.draft.slice(selection)1073
};1074
if text.is_empty() {1075
return true;1076
}1023
cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(1077
cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(1024
text.clone(),1078
text.clone(),1025
lines.clone(),1079
lines.clone(),@@ -1221,6 +1275,7 @@ impl Composer {1221
self.tray.clear()1275
self.tray.clear()1222
};1276
};1223
self.discard_uploaded(dropped, cx);1277
self.discard_uploaded(dropped, cx);1278
self.remove_orphan_image_tokens(window, cx);1224
self.reply = None;1279
self.reply = None;1225
if self.editing.take().is_some() {1280
if self.editing.take().is_some() {1226
self.load_draft(Draft::default(), InputContent::new(""), window, cx);1281
self.load_draft(Draft::default(), InputContent::new(""), window, cx);@@ -1263,7 +1318,26 @@ impl Composer {1263
if !self.can_send(cx) {1318
if !self.can_send(cx) {1264
return None;1319
return None;1265
}1320
}1266
let mut draft = self.current_draft(cx).trimmed();1321
let mut draft = self.current_draft(cx);1322
let image_spans: Vec<(Range<usize>, u64)> = state1323
.tokens()1324
.iter()1325
.filter_map(|span| Some((span.range(), image_id(span.token())?)))1326
.collect();1327
let image_ids: Vec<u64> = image_spans1328
.iter()1329
.filter(|(_, id)| self.tray.image(*id).is_some())1330
.map(|(_, id)| *id)1331
.collect();1332
for (range, _) in image_spans1333
.iter()1334
.rev()1335
.filter(|(_, id)| self.tray.image(*id).is_none())1336
{1337
draft.replace(range.clone(), "");1338
}1339
draft.take_edits();1340
let mut draft = draft.trimmed();1267
let attachments_apply = self.editing.is_none();1341
let attachments_apply = self.editing.is_none();1268
if self.undone_value.as_deref() != Some(state.value().as_ref())1342
if self.undone_value.as_deref() != Some(state.value().as_ref())1269
&& let Some((range, glyph)) = emoji::trailing_smiley(draft.text())1343
&& let Some((range, glyph)) = emoji::trailing_smiley(draft.text())@@ -1284,7 +1358,7 @@ impl Composer {1284
reply: self.reply.clone(),1358
reply: self.reply.clone(),1285
edit: self.editing.clone(),1359
edit: self.editing.clone(),1286
images: if attachments_apply {1360
images: if attachments_apply {1287
self.tray.outgoing_images()1361
self.tray.images_in(&image_ids)1288
} else {1362
} else {1289
Vec::new()1363
Vec::new()1290
},1364
},@@ -1311,7 +1385,101 @@ impl Composer {1311
if self.editing.is_some() {1385
if self.editing.is_some() {1312
return has_text;1386
return has_text;1313
}1387
}1314
(has_text || !self.tray.is_empty()) && !self.tray.blocks_send()1388
(has_text || self.has_attachments(cx)) && !self.tray.blocks_send()1389
}1390
1391
fn has_attachments(&self, cx: &App) -> bool {1392
self.tray.has_chips()1393
|| self1394
.input1395
.read(cx)1396
.tokens()1397
.iter()1398
.any(|span| image_id(span.token()).is_some_and(|id| self.tray.image(id).is_some()))1399
}1400
1401
fn image_token_range(&self, id: u64, cx: &App) -> Option<Range<usize>> {1402
self.input1403
.read(cx)1404
.tokens()1405
.iter()1406
.find(|span| image_id(span.token()) == Some(id))1407
.map(|span| span.range())1408
}1409
1410
fn remove_orphan_image_tokens(&mut self, window: &mut Window, cx: &mut Context<Self>) {1411
let edits: Vec<Edit> = self1412
.input1413
.read(cx)1414
.tokens()1415
.iter()1416
.filter(|span| image_id(span.token()).is_some_and(|id| self.tray.image(id).is_none()))1417
.map(|span| (span.range(), String::new()))1418
.collect();1419
if !edits.is_empty() {1420
self.input1421
.update(cx, |state, cx| state.apply_edits(&edits, window, cx));1422
}1423
}1424
1425
fn remove_image_token(&mut self, id: u64, window: &mut Window, cx: &mut Context<Self>) {1426
let Some(range) = self.image_token_range(id, cx) else {1427
return;1428
};1429
self.input.update(cx, |state, cx| {1430
state.set_selected_range(range, cx);1431
state.replace("", window, cx);1432
});1433
}1434
1435
fn insert_image_token(&mut self, id: u64, window: &mut Window, cx: &mut Context<Self>) {1436
let state = self.input.read(cx);1437
let value = state.value().to_string();1438
let selection = state.selected_range();1439
let mut offset = self1440
.pending_anchors1441
.remove(&id)1442
.unwrap_or(selection.end)1443
.min(value.len());1444
while !value.is_char_boundary(offset) {1445
offset -= 1;1446
}1447
if value == self.draft.text() && self.draft.in_code(offset) {1448
offset = value.len();1449
}1450
if let Some(span) = state1451
.tokens()1452
.iter()1453
.find(|span| span.range().start < offset && offset < span.range().end)1454
{1455
offset = span.range().end;1456
}1457
let length = OBJECT_MARK.len_utf8();1458
let after = |position: usize| {1459
if position >= offset {1460
position + length1461
} else {1462
position1463
}1464
};1465
let inserted = self.input.update(cx, |state, cx| {1466
let inserted = state1467
.replace_range_with_token(offset..offset, image_token(id), window, cx)1468
.is_ok();1469
if inserted {1470
state.set_selected_range(after(selection.start)..after(selection.end), cx);1471
}1472
inserted1473
});1474
if !inserted {1475
return;1476
}1477
for (other, anchor) in self.pending_anchors.iter_mut() {1478
if *anchor > offset || (*anchor == offset && *other > id) {1479
*anchor += length;1480
}1481
}1482
self.previous_value = self.input.read(cx).value().to_string();1315
}1483
}1316
1484
1317
pub fn is_editing(&self) -> bool {1485
pub fn is_editing(&self) -> bool {@@ -1330,7 +1498,7 @@ impl Composer {1330
}1498
}1331
}1499
}1332
1500
1333
pub fn open_picker(&mut self, cx: &mut Context<Self>) {1501
pub fn open_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {1334
if self.editing.is_some() {1502
if self.editing.is_some() {1335
return;1503
return;1336
}1504
}@@ -1340,46 +1508,69 @@ impl Composer {1340
multiple: true,1508
multiple: true,1341
prompt: None,1509
prompt: None,1342
});1510
});1343
cx.spawn(async move |this, cx| {1511
cx.spawn_in(window, async move |this, cx| {1344
if let Ok(Ok(Some(paths))) = receiver.await {1512
if let Ok(Ok(Some(paths))) = receiver.await {1345
this.update(cx, |this, cx| this.add_paths(paths, cx)).ok();1513
this.update_in(cx, |this, window, cx| this.add_paths(paths, window, cx))1514
.ok();1346
}1515
}1347
})1516
})1348
.detach();1517
.detach();1349
}1518
}1350
1519
1351
pub fn add_paths(&mut self, paths: Vec<PathBuf>, cx: &mut Context<Self>) {1520
pub fn add_paths(&mut self, paths: Vec<PathBuf>, window: &mut Window, cx: &mut Context<Self>) {1352
if self.editing.is_some() || paths.is_empty() {1521
if self.editing.is_some() || paths.is_empty() {1353
return;1522
return;1354
}1523
}1355
let ids = self.tray.add_pending(&names_of(&paths));1524
let ids = self.add_pending(&names_of(&paths), cx);1356
for (id, path) in ids.into_iter().zip(paths) {1525
for (id, path) in ids.into_iter().zip(paths) {1357
cx.spawn(async move |this, cx| {1526
cx.spawn_in(window, async move |this, cx| {1358
let loaded = cx1527
let loaded = cx1359
.background_executor()1528
.background_executor()1360
.spawn(async move { read_attachment(&path) })1529
.spawn(async move { read_attachment(&path) })1361
.await;1530
.await;1362
this.update(cx, |this, cx| this.finish_reading(id, loaded, cx))1531
this.update_in(cx, |this, window, cx| {1363
.ok();1532
this.finish_reading(id, loaded, window, cx)1533
})1534
.ok();1364
})1535
})1365
.detach();1536
.detach();1366
}1537
}1367
cx.notify();1538
cx.notify();1368
}1539
}1369
1540
1370
fn add_pasted_image(&mut self, pasted: Image, cx: &mut Context<Self>) {1541
fn add_pending(&mut self, names: &[String], cx: &App) -> Vec<u64> {1371
let ids = self.tray.add_pending(&[pasted_image_name()]);1542
if self.tray.items().len() + names.len() > MAX_ATTACHMENTS {1543
let referenced: Vec<u64> = self1544
.input1545
.read(cx)1546
.tokens()1547
.iter()1548
.filter_map(|span| image_id(span.token()))1549
.collect();1550
self.tray.discard_images_except(&referenced);1551
}1552
let ids = self.tray.add_pending(names);1553
let anchor = self.selection(cx).end;1554
self.pending_anchors1555
.extend(ids.iter().map(|id| (*id, anchor)));1556
ids1557
}1558
1559
fn add_pasted_image(&mut self, pasted: Image, window: &mut Window, cx: &mut Context<Self>) {1560
let ids = self.add_pending(&[pasted_image_name()], cx);1372
cx.notify();1561
cx.notify();1373
let Some(&id) = ids.first() else {1562
let Some(&id) = ids.first() else {1374
return;1563
return;1375
};1564
};1376
cx.spawn(async move |this, cx| {1565
cx.spawn_in(window, async move |this, cx| {1377
let loaded = cx1566
let loaded = cx1378
.background_executor()1567
.background_executor()1379
.spawn(async move { prepare_pasted_image(pasted) })1568
.spawn(async move { prepare_pasted_image(pasted) })1380
.await;1569
.await;1381
this.update(cx, |this, cx| this.finish_reading(id, loaded, cx))1570
this.update_in(cx, |this, window, cx| {1382
.ok();1571
this.finish_reading(id, loaded, window, cx)1572
})1573
.ok();1383
})1574
})1384
.detach();1575
.detach();1385
}1576
}@@ -1389,11 +1580,11 @@ impl Composer {1389
match paste_action(item) {1580
match paste_action(item) {1390
PasteAction::Text => {}1581
PasteAction::Text => {}1391
PasteAction::Files(paths) => {1582
PasteAction::Files(paths) => {1392
self.add_paths(paths, cx);1583
self.add_paths(paths, window, cx);1393
return true;1584
return true;1394
}1585
}1395
PasteAction::Image(pasted) => {1586
PasteAction::Image(pasted) => {1396
self.add_pasted_image(pasted, cx);1587
self.add_pasted_image(pasted, window, cx);1397
return true;1588
return true;1398
}1589
}1399
}1590
}@@ -1401,6 +1592,12 @@ impl Composer {1401
let Some(text) = item.text() else {1592
let Some(text) = item.text() else {1402
return false;1593
return false;1403
};1594
};1595
if text.contains(OBJECT_MARK) {1596
let cleaned = text.replace(OBJECT_MARK, "");1597
self.input1598
.update(cx, |state, cx| state.replace(cleaned, window, cx));1599
return true;1600
}1404
if self.draft.in_code(self.selection(cx).start) {1601
if self.draft.in_code(self.selection(cx).start) {1405
return false;1602
return false;1406
}1603
}@@ -1417,16 +1614,26 @@ impl Composer {1417
&mut self,1614
&mut self,1418
id: u64,1615
id: u64,1419
loaded: Result<LoadedFile, String>,1616
loaded: Result<LoadedFile, String>,1617
window: &mut Window,1420
cx: &mut Context<Self>,1618
cx: &mut Context<Self>,1421
) {1619
) {1422
match loaded {1620
match loaded {1423
Ok(loaded) => {1621
Ok(loaded) => {1424
let files_allowed = self.files_allowed();1622
let files_allowed = self.files_allowed();1425
if let Some(job) = self.tray.finish_reading(id, loaded, files_allowed) {1623
let job = self.tray.finish_reading(id, loaded, files_allowed);1624
if self.tray.image(id).is_some() {1625
self.insert_image_token(id, window, cx);1626
} else {1627
self.pending_anchors.remove(&id);1628
}1629
if let Some(job) = job {1426
self.start_upload(job, cx);1630
self.start_upload(job, cx);1427
}1631
}1428
}1632
}1429
Err(message) => self.tray.fail_reading(id, message),1633
Err(message) => {1634
self.pending_anchors.remove(&id);1635
self.tray.fail_reading(id, message);1636
}1430
}1637
}1431
cx.notify();1638
cx.notify();1432
}1639
}@@ -1595,8 +1802,20 @@ impl Composer {1595
1802
1596
pub fn restore(&mut self, outgoing: &Outgoing, window: &mut Window, cx: &mut Context<Self>) {1803
pub fn restore(&mut self, outgoing: &Outgoing, window: &mut Window, cx: &mut Context<Self>) {1597
self.mention_inputs.clear();1804
self.mention_inputs.clear();1805
let image_ids = if outgoing.edit.is_none() {1806
self.cancel_uploads();1807
self.tray.restore(&outgoing.images, &outgoing.files)1808
} else {1809
Vec::new()1810
};1598
let text = outgoing.draft.text();1811
let text = outgoing.draft.text();1599
let mut content = InputContent::new(text.to_owned());1812
let mut content = InputContent::new(text.to_owned());1813
for ((offset, _), id) in text.match_indices(OBJECT_MARK).zip(image_ids) {1814
let range = offset..offset + OBJECT_MARK.len_utf8();1815
if let Ok(next) = content.clone().with_token(range, image_token(id)) {1816
content = next;1817
}1818
}1600
let mut cursor = 0;1819
let mut cursor = 0;1601
for mention in &outgoing.mentions {1820
for mention in &outgoing.mentions {1602
let needle = format!("@{}", mention.text);1821
let needle = format!("@{}", mention.text);@@ -1616,10 +1835,6 @@ impl Composer {1616
self.load_draft(outgoing.draft.clone(), content, window, cx);1835
self.load_draft(outgoing.draft.clone(), content, window, cx);1617
self.reply = outgoing.reply.clone();1836
self.reply = outgoing.reply.clone();1618
self.editing = outgoing.edit.clone();1837
self.editing = outgoing.edit.clone();1619
if outgoing.edit.is_none() {1620
self.cancel_uploads();1621
self.tray.restore(&outgoing.images, &outgoing.files);1622
}1623
self.close_popup();1838
self.close_popup();1624
cx.notify();1839
cx.notify();1625
}1840
}@@ -1635,8 +1850,8 @@ impl Composer {1635
cx.notify();1850
cx.notify();1636
}1851
}1637
1852
1638
pub fn is_empty(&self, _: &App) -> bool {1853
pub fn is_empty(&self, cx: &App) -> bool {1639
self.draft.is_blank() && self.tray.is_empty()1854
self.draft.is_blank() && !self.has_attachments(cx)1640
}1855
}1641
1856
1642
pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {1857
pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {@@ -1981,9 +2196,10 @@ impl Render for Composer {1981
.hover(|button| button.bg(theme::row_hover()))2196
.hover(|button| button.bg(theme::row_hover()))1982
.tooltip(|window, cx| Tooltip::new("Attach file").build(window, cx))2197
.tooltip(|window, cx| Tooltip::new("Attach file").build(window, cx))1983
.child(symbol("attach_file", 20., theme::text_muted()))2198
.child(symbol("attach_file", 20., theme::text_muted()))1984
.on_click(cx.listener(|this, _, _, cx| this.open_picker(cx)))2199
.on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))1985
});2200
});1986
let composer = cx.weak_entity();2201
let composer = cx.weak_entity();2202
let tokens_composer = composer.clone();1987
let input = Textarea::new(&self.input)2203
let input = Textarea::new(&self.input)1988
.appearance(false)2204
.appearance(false)1989
.bordered(false)2205
.bordered(false)@@ -1992,7 +2208,29 @@ impl Render for Composer {1992
.update(cx, |this, cx| this.paste(item, window, cx))2208
.update(cx, |this, cx| this.paste(item, window, cx))1993
.unwrap_or(false)2209
.unwrap_or(false)1994
})2210
})1995
.token(|context, _, _| {2211
.token(move |context, _, cx| {2212
if let Some(id) = context2213
.is_block()2214
.then(|| image_id(context.token()))2215
.flatten()2216
{2217
let preview = tokens_composer2218
.read_with(cx, |this, _| this.tray.image(id))2219
.ok()2220
.flatten();2221
let remove_composer = tokens_composer.clone();2222
return inline_preview(2223
id,2224
preview,2225
context.available_width(),2226
context.is_selected(),2227
Rc::new(move |window, cx| {2228
remove_composer2229
.update(cx, |this, cx| this.remove_image_token(id, window, cx))2230
.ok();2231
}),2232
);2233
}1996
div()2234
div()1997
.h(context.line_height())2235
.h(context.line_height())1998
.px(px(5.))2236
.px(px(5.))@@ -2005,6 +2243,7 @@ impl Render for Composer {2005
.text_color(theme::mention_text())2243
.text_color(theme::mention_text())2006
.font_weight(FontWeight::SEMIBOLD)2244
.font_weight(FontWeight::SEMIBOLD)2007
.child(context.token().label().clone())2245
.child(context.token().label().clone())2246
.into_any_element()2008
});2247
});2009
let tray = can_attach2248
let tray = can_attach2010
.then(|| {2249
.then(|| {@@ -2341,6 +2580,53 @@ mod tests {2341
assert!(outgoing.has_attachments());2580
assert!(outgoing.has_attachments());2342
}2581
}2343
2582
2583
fn placed_image(width: u32) -> super::OutgoingImage {2584
use std::sync::Arc;2585
2586
use gpui_kit::{Image, ImageFormat};2587
2588
super::OutgoingImage {2589
name: "pasted-image.png".into(),2590
image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![width as u8])),2591
dimensions: Some((width, width)),2592
}2593
}2594
2595
fn outgoing_with(text: &str, images: Vec<super::OutgoingImage>) -> super::Outgoing {2596
super::Outgoing {2597
draft: teams_core::Draft::plain(text),2598
mentions: Vec::new(),2599
reply: None,2600
edit: None,2601
images,2602
files: Vec::new(),2603
}2604
}2605
2606
#[test]2607
fn an_image_is_placed_in_the_html_where_its_mark_sits() {2608
let outgoing = outgoing_with("a \u{FFFC} b", vec![placed_image(2)]);2609
assert_eq!(2610
outgoing.html(),2611
"a <img src=\"../hostedContents/1/$value\"> b"2612
);2613
assert_eq!(outgoing.text(), "a b");2614
}2615
2616
#[test]2617
fn images_keep_the_order_of_their_marks() {2618
let outgoing = outgoing_with("\u{FFFC}x\u{FFFC}", vec![placed_image(2), placed_image(4)]);2619
assert_eq!(2620
outgoing.html(),2621
"<img src=\"../hostedContents/1/$value\">x<img src=\"../hostedContents/2/$value\">"2622
);2623
}2624
2625
#[test]2626
fn a_mark_without_an_image_leaves_no_trace() {2627
assert_eq!(outgoing_with("a\u{FFFC}b", Vec::new()).html(), "ab");2628
}2629
2344
#[test]2630
#[test]2345
fn enter_sends_attachments_even_without_text() {2631
fn enter_sends_attachments_even_without_text() {2346
assert!(super::is_plain_enter(&press(false)));2632
assert!(super::is_plain_enter(&press(false)));@@ -2449,6 +2735,201 @@ mod tests {2449
typist2735
typist2450
}2736
}2451
2737
2738
fn png_bytes(side: u32) -> Vec<u8> {2739
let mut bytes = Vec::new();2740
image::RgbaImage::new(side, side)2741
.write_to(2742
&mut std::io::Cursor::new(&mut bytes),2743
image::ImageFormat::Png,2744
)2745
.unwrap();2746
bytes2747
}2748
2749
fn paste_image(typist: &mut Typist<'_>, side: u32) {2750
typist.cx.write_to_clipboard(gpui_kit::ClipboardItem {2751
entries: vec![gpui_kit::ClipboardEntry::Image(2752
gpui_kit::Image::from_bytes(gpui_kit::ImageFormat::Png, png_bytes(side)),2753
)],2754
});2755
typist.press("ctrl-v");2756
}2757
2758
fn image_tokens(typist: &mut Typist<'_>) -> Vec<(std::ops::Range<usize>, bool)> {2759
let composer = typist.composer.clone();2760
typist.cx.update(|cx| {2761
composer2762
.read(cx)2763
.input2764
.read(cx)2765
.tokens()2766
.iter()2767
.map(|span| (span.range(), span.token().is_block()))2768
.collect()2769
})2770
}2771
2772
#[gpui_kit::test]2773
fn a_pasted_image_sits_at_the_cursor_and_is_sent_there(cx: &mut TestAppContext) {2774
let mut typist = typist(cx);2775
typist.type_text("ab");2776
typist.press("left");2777
paste_image(&mut typist, 2);2778
assert_eq!(typist.value(), "a\u{FFFC}b");2779
assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);2780
let outgoing = typist.outgoing();2781
assert_eq!(outgoing.images.len(), 1);2782
assert_eq!(2783
outgoing.html(),2784
"a<img src=\"../hostedContents/1/$value\">b"2785
);2786
let composer = typist.composer.clone();2787
assert!(!typist.cx.update(|cx| composer.read(cx).tray.has_chips()));2788
}2789
2790
fn wide_png_bytes() -> Vec<u8> {2791
let mut bytes = Vec::new();2792
image::RgbaImage::new(600, 300)2793
.write_to(2794
&mut std::io::Cursor::new(&mut bytes),2795
image::ImageFormat::Png,2796
)2797
.unwrap();2798
bytes2799
}2800
2801
fn caret_is_visible(typist: &mut Typist<'_>) -> bool {2802
let composer = typist.composer.clone();2803
typist.cx.update(|cx| {2804
let state = composer.read(cx).input.read(cx);2805
let cursor = state.cursor();2806
let caret = state.range_to_bounds(&(cursor..cursor)).unwrap();2807
let viewport = state.input_bounds();2808
caret.origin.y >= viewport.origin.y && caret.bottom() <= viewport.bottom()2809
})2810
}2811
2812
#[gpui_kit::test]2813
fn typing_after_a_tall_image_keeps_the_caret_in_view(cx: &mut TestAppContext) {2814
let mut typist = typist(cx);2815
typist.type_text("look at this ");2816
typist.cx.write_to_clipboard(gpui_kit::ClipboardItem {2817
entries: vec![gpui_kit::ClipboardEntry::Image(2818
gpui_kit::Image::from_bytes(gpui_kit::ImageFormat::Png, wide_png_bytes()),2819
)],2820
});2821
typist.press("ctrl-v");2822
typist.act(|window, _| window.refresh());2823
typist.type_text("and then more text");2824
typist.act(|window, _| window.refresh());2825
assert!(caret_is_visible(&mut typist));2826
}2827
2828
#[gpui_kit::test]2829
fn deleting_the_token_drops_the_image_and_undo_brings_it_back(cx: &mut TestAppContext) {2830
let mut typist = typist(cx);2831
typist.type_text("ab");2832
typist.press("left");2833
paste_image(&mut typist, 2);2834
typist.press("backspace");2835
assert_eq!(typist.value(), "ab");2836
assert!(image_tokens(&mut typist).is_empty());2837
let outgoing = typist.outgoing();2838
assert!(outgoing.images.is_empty());2839
assert_eq!(outgoing.html(), "ab");2840
typist.press("ctrl-z");2841
assert_eq!(typist.value(), "a\u{FFFC}b");2842
assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);2843
assert_eq!(typist.outgoing().images.len(), 1);2844
}2845
2846
#[gpui_kit::test]2847
fn the_remove_button_drops_the_image_and_one_undo_brings_it_back(cx: &mut TestAppContext) {2848
let mut typist = typist(cx);2849
typist.type_text("ab");2850
paste_image(&mut typist, 2);2851
typist.type_text("cd");2852
let composer = typist.composer.clone();2853
let id = typist.cx.update(|cx| {2854
let state = composer.read(cx).input.read(cx);2855
super::super::image_id(state.tokens()[0].token()).unwrap()2856
});2857
typist.act(|window, cx| {2858
composer.update(cx, |composer, cx| {2859
composer.remove_image_token(id, window, cx)2860
});2861
});2862
assert_eq!(typist.value(), "abcd");2863
assert!(image_tokens(&mut typist).is_empty());2864
assert!(typist.outgoing().images.is_empty());2865
typist.press("ctrl-z");2866
assert_eq!(typist.value(), "ab\u{FFFC}cd");2867
assert_eq!(image_tokens(&mut typist), vec![(2..5, true)]);2868
assert_eq!(typist.outgoing().images.len(), 1);2869
}2870
2871
#[gpui_kit::test]2872
fn images_are_sent_in_the_order_they_appear_in_the_text(cx: &mut TestAppContext) {2873
let mut typist = typist(cx);2874
typist.type_text("x");2875
paste_image(&mut typist, 2);2876
typist.type_text("y");2877
typist.press("ctrl-home");2878
paste_image(&mut typist, 4);2879
assert_eq!(typist.value(), "\u{FFFC}x\u{FFFC}y");2880
let outgoing = typist.outgoing();2881
let dimensions: Vec<_> = outgoing2882
.images2883
.iter()2884
.map(|image| image.dimensions)2885
.collect();2886
assert_eq!(dimensions, [Some((4, 4)), Some((2, 2))]);2887
assert_eq!(2888
outgoing.html(),2889
"<img src=\"../hostedContents/1/$value\">x<img src=\"../hostedContents/2/$value\">y"2890
);2891
}2892
2893
#[gpui_kit::test]2894
fn an_image_alone_can_be_sent_and_never_leaks_into_copied_text(cx: &mut TestAppContext) {2895
let mut typist = typist(cx);2896
paste_image(&mut typist, 2);2897
let composer = typist.composer.clone();2898
assert!(typist.cx.update(|cx| composer.read(cx).can_send(cx)));2899
let outgoing = typist.outgoing();2900
assert_eq!(outgoing.text(), "");2901
assert_eq!(outgoing.images.len(), 1);2902
typist.type_text("hi");2903
typist.press("ctrl-a ctrl-c");2904
let copied = typist.cx.read_from_clipboard().and_then(|item| item.text());2905
assert_eq!(copied.as_deref(), Some("hi"));2906
}2907
2908
#[gpui_kit::test]2909
fn pasted_text_loses_object_marks(cx: &mut TestAppContext) {2910
let mut typist = typist(cx);2911
typist2912
.cx2913
.write_to_clipboard(gpui_kit::ClipboardItem::new_string("a\u{FFFC}b".to_owned()));2914
typist.press("ctrl-v");2915
assert_eq!(typist.value(), "ab");2916
}2917
2918
#[gpui_kit::test]2919
fn a_restored_outgoing_gets_its_image_tokens_back(cx: &mut TestAppContext) {2920
let mut typist = typist(cx);2921
let outgoing = super::outgoing_with("x\u{FFFC}y", vec![super::placed_image(3)]);2922
let composer = typist.composer.clone();2923
typist.act(|window, cx| {2924
composer.update(cx, |composer, cx| composer.restore(&outgoing, window, cx));2925
});2926
assert_eq!(typist.value(), "x\u{FFFC}y");2927
assert_eq!(image_tokens(&mut typist), vec![(1..4, true)]);2928
let again = typist.outgoing();2929
assert_eq!(again.images, outgoing.images);2930
assert_eq!(again.html(), "x<img src=\"../hostedContents/1/$value\">y");2931
}2932
2452
#[gpui_kit::test]2933
#[gpui_kit::test]2453
fn typed_markdown_is_formatted_and_backspace_brings_it_back(cx: &mut TestAppContext) {2934
fn typed_markdown_is_formatted_and_backspace_brings_it_back(cx: &mut TestAppContext) {2454
use teams_core::{FormatState, MarkKind};2935
use teams_core::{FormatState, MarkKind};@@ -2936,7 +3417,7 @@ mod tests {2936
cx.update_window(handle, |_, window, cx| {3417
cx.update_window(handle, |_, window, cx| {2937
composer.update(cx, |composer, cx| {3418
composer.update(cx, |composer, cx| {2938
composer.set_conversation("demo-chat", "Demo", window, cx);3419
composer.set_conversation("demo-chat", "Demo", window, cx);2939
composer.add_paths(vec![path], cx);3420
composer.add_paths(vec![path], window, cx);2940
});3421
});2941
})3422
})2942
.unwrap();3423
.unwrap();@@ -2983,7 +3464,7 @@ mod tests {2983
cx.update_window(handle, |_, window, cx| {3464
cx.update_window(handle, |_, window, cx| {2984
composer.update(cx, |composer, cx| {3465
composer.update(cx, |composer, cx| {2985
composer.set_conversation("demo-chat", "Demo", window, cx);3466
composer.set_conversation("demo-chat", "Demo", window, cx);2986
composer.add_paths(vec![path], cx);3467
composer.add_paths(vec![path], window, cx);2987
});3468
});2988
})3469
})2989
.unwrap();3470
.unwrap();@@ -2994,7 +3475,7 @@ mod tests {2994
});3475
});2995
})3476
})2996
.unwrap();3477
.unwrap();2997
cx.update(|cx| assert!(composer.read(cx).tray.is_empty()));3478
cx.update(|cx| assert!(composer.read(cx).tray.items().is_empty()));2998
}3479
}2999
3480
3000
fn demo_composer(3481
fn demo_composer(@@ -3034,7 +3515,7 @@ mod tests {3034
cx.update_window(handle, |_, window, cx| {3515
cx.update_window(handle, |_, window, cx| {3035
composer.update(cx, |composer, cx| {3516
composer.update(cx, |composer, cx| {3036
composer.set_conversation("demo-chat", "Demo", window, cx);3517
composer.set_conversation("demo-chat", "Demo", window, cx);3037
composer.add_paths(vec![path], cx);3518
composer.add_paths(vec![path], window, cx);3038
});3519
});3039
})3520
})3040
.unwrap();3521
.unwrap();@@ -3090,7 +3571,7 @@ mod tests {3090
cx.update_window(handle, |_, window, cx| {3571
cx.update_window(handle, |_, window, cx| {3091
composer.update(cx, |composer, cx| {3572
composer.update(cx, |composer, cx| {3092
composer.set_conversation("", "", window, cx);3573
composer.set_conversation("", "", window, cx);3093
composer.add_paths(vec![path.clone()], cx);3574
composer.add_paths(vec![path.clone()], window, cx);3094
});3575
});3095
})3576
})3096
.unwrap();3577
.unwrap();@@ -3120,7 +3601,7 @@ mod tests {3120
cx.update_window(handle, |_, window, cx| {3601
cx.update_window(handle, |_, window, cx| {3121
composer.update(cx, |composer, cx| {3602
composer.update(cx, |composer, cx| {3122
composer.set_conversation("bob-chat", "Bob", window, cx);3603
composer.set_conversation("bob-chat", "Bob", window, cx);3123
composer.add_paths(vec![png, pdf], cx);3604
composer.add_paths(vec![png, pdf], window, cx);3124
});3605
});3125
})3606
})3126
.unwrap();3607
.unwrap();@@ -1601,7 +1601,7 @@ impl ConversationView {
1601
1601
card: false,
1602
1602
time: chrono::Local::now().format("%H:%M").to_string(),
1603
1603
day_header: None,
1604
blocks: if outgoing.draft.is_blank() {
1604
blocks: if outgoing.draft.is_blank() && outgoing.images.is_empty() {
1605
1605
Vec::new()
1606
1606
} else {
1607
1607
layout_blocks(&teams_core::html_to_spans(&outgoing.html()))
@@ -2202,10 +2202,10 @@ impl ConversationView {
2202
2202
}
2203
2203
}),
2204
2204
)
2205
.on_drop(cx.listener(|this, dropped: &ExternalPaths, _, cx| {
2205
.on_drop(cx.listener(|this, dropped: &ExternalPaths, window, cx| {
2206
2206
let paths = dropped.paths().to_vec();
2207
2207
this.composer
2208
.update(cx, |composer, cx| composer.add_paths(paths, cx));
2208
.update(cx, |composer, cx| composer.add_paths(paths, window, cx));
2209
2209
}))
2210
2210
.child(
2211
2211
div()
@@ -1601,7 +1601,7 @@ impl ConversationView {1601
card: false,1601
card: false,1602
time: chrono::Local::now().format("%H:%M").to_string(),1602
time: chrono::Local::now().format("%H:%M").to_string(),1603
day_header: None,1603
day_header: None,1604
blocks: if outgoing.draft.is_blank() {1604
blocks: if outgoing.draft.is_blank() && outgoing.images.is_empty() {1605
Vec::new()1605
Vec::new()1606
} else {1606
} else {1607
layout_blocks(&teams_core::html_to_spans(&outgoing.html()))1607
layout_blocks(&teams_core::html_to_spans(&outgoing.html()))@@ -2202,10 +2202,10 @@ impl ConversationView {2202
}2202
}2203
}),2203
}),2204
)2204
)2205
.on_drop(cx.listener(|this, dropped: &ExternalPaths, _, cx| {2205
.on_drop(cx.listener(|this, dropped: &ExternalPaths, window, cx| {2206
let paths = dropped.paths().to_vec();2206
let paths = dropped.paths().to_vec();2207
this.composer2207
this.composer2208
.update(cx, |composer, cx| composer.add_paths(paths, cx));2208
.update(cx, |composer, cx| composer.add_paths(paths, window, cx));2209
}))2209
}))2210
.child(2210
.child(2211
div()2211
div()@@ -8,6 +8,7 @@ use crate::markdown::escape_html;
8
8
use crate::spans::Span;
9
9
10
10
pub const MAX_DEPTH: u8 = 2;
11
pub const OBJECT_MARK: char = '\u{FFFC}';
11
12
const BULLETS: [&str; 3] = ["•", "◦", "▪"];
12
13
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
13
14
const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];
@@ -350,13 +351,15 @@ impl Draft {
350
351
self.plain_text().trim().is_empty()
351
352
}
352
353
353
/// The text without list and quote markers.
354
/// The text without list and quote markers and object marks.
354
355
pub fn plain_text(&self) -> String {
355
356
self.slice(0..self.text.len())
356
357
.into_iter()
357
358
.map(|line| line.content)
358
359
.collect::<Vec<_>>()
359
360
.join("\n")
361
.replace(&format!(" {OBJECT_MARK} "), " ")
362
.replace(OBJECT_MARK, "")
360
363
}
361
364
362
365
pub fn line_ranges(&self) -> Vec<Range<usize>> {
@@ -859,6 +862,19 @@ impl Draft {
859
862
lines
860
863
}
861
864
865
pub fn slice_without_objects(&self, range: Range<usize>) -> Vec<DraftLine> {
866
let mut copy = Draft::from_lines(&self.slice(range));
867
let marks: Vec<usize> = copy
868
.text
869
.match_indices(OBJECT_MARK)
870
.map(|(index, _)| index)
871
.collect();
872
for index in marks.into_iter().rev() {
873
copy.replace(index..index + OBJECT_MARK.len_utf8(), "");
874
}
875
copy.slice(0..usize::MAX)
876
}
877
862
878
/// Puts `lines` in place of `range`. Returns the offset after the inserted content.
863
879
pub fn insert_lines(&mut self, range: Range<usize>, lines: &[DraftLine]) -> usize {
864
880
self.journal = Journal::default();
@@ -1904,6 +1920,30 @@ mod tests {
1904
1920
}
1905
1921
}
1906
1922
1923
#[test]
1924
fn object_marks_stay_in_the_html_and_leave_the_plain_text() {
1925
let draft = Draft::plain("a \u{FFFC} b");
1926
assert_eq!(draft.plain_text(), "a b");
1927
assert_eq!(draft.to_html(), "a \u{FFFC} b");
1928
assert!(Draft::plain("\u{FFFC}").is_blank());
1929
}
1930
1931
#[test]
1932
fn slices_without_objects_keep_the_formatting_of_the_rest() {
1933
let mut draft = Draft::plain("ab\u{FFFC}cd");
1934
draft.toggle(0..draft.text().len(), MarkKind::Bold);
1935
let lines = draft.slice_without_objects(0..draft.text().len());
1936
assert_eq!(lines.len(), 1);
1937
assert_eq!(lines[0].content, "abcd");
1938
assert_eq!(
1939
lines[0].marks,
1940
[Mark {
1941
range: 0..4,
1942
kind: MarkKind::Bold
1943
}]
1944
);
1945
}
1946
1907
1947
fn typed_draft(text: &str) -> Draft {
1908
1948
let mut draft = Draft::default();
1909
1949
typed(&mut draft, text);
@@ -8,6 +8,7 @@ use crate::markdown::escape_html;8
use crate::spans::Span;8
use crate::spans::Span;9
9
10
pub const MAX_DEPTH: u8 = 2;10
pub const MAX_DEPTH: u8 = 2;11
pub const OBJECT_MARK: char = '\u{FFFC}';11
const BULLETS: [&str; 3] = ["•", "◦", "▪"];12
const BULLETS: [&str; 3] = ["•", "◦", "▪"];12
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];13
const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];13
const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];14
const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];@@ -350,13 +351,15 @@ impl Draft {350
self.plain_text().trim().is_empty()351
self.plain_text().trim().is_empty()351
}352
}352
353
353
/// The text without list and quote markers.354
/// The text without list and quote markers and object marks.354
pub fn plain_text(&self) -> String {355
pub fn plain_text(&self) -> String {355
self.slice(0..self.text.len())356
self.slice(0..self.text.len())356
.into_iter()357
.into_iter()357
.map(|line| line.content)358
.map(|line| line.content)358
.collect::<Vec<_>>()359
.collect::<Vec<_>>()359
.join("\n")360
.join("\n")361
.replace(&format!(" {OBJECT_MARK} "), " ")362
.replace(OBJECT_MARK, "")360
}363
}361
364
362
pub fn line_ranges(&self) -> Vec<Range<usize>> {365
pub fn line_ranges(&self) -> Vec<Range<usize>> {@@ -859,6 +862,19 @@ impl Draft {859
lines862
lines860
}863
}861
864
865
pub fn slice_without_objects(&self, range: Range<usize>) -> Vec<DraftLine> {866
let mut copy = Draft::from_lines(&self.slice(range));867
let marks: Vec<usize> = copy868
.text869
.match_indices(OBJECT_MARK)870
.map(|(index, _)| index)871
.collect();872
for index in marks.into_iter().rev() {873
copy.replace(index..index + OBJECT_MARK.len_utf8(), "");874
}875
copy.slice(0..usize::MAX)876
}877
862
/// Puts `lines` in place of `range`. Returns the offset after the inserted content.878
/// Puts `lines` in place of `range`. Returns the offset after the inserted content.863
pub fn insert_lines(&mut self, range: Range<usize>, lines: &[DraftLine]) -> usize {879
pub fn insert_lines(&mut self, range: Range<usize>, lines: &[DraftLine]) -> usize {864
self.journal = Journal::default();880
self.journal = Journal::default();@@ -1904,6 +1920,30 @@ mod tests {1904
}1920
}1905
}1921
}1906
1922
1923
#[test]1924
fn object_marks_stay_in_the_html_and_leave_the_plain_text() {1925
let draft = Draft::plain("a \u{FFFC} b");1926
assert_eq!(draft.plain_text(), "a b");1927
assert_eq!(draft.to_html(), "a \u{FFFC} b");1928
assert!(Draft::plain("\u{FFFC}").is_blank());1929
}1930
1931
#[test]1932
fn slices_without_objects_keep_the_formatting_of_the_rest() {1933
let mut draft = Draft::plain("ab\u{FFFC}cd");1934
draft.toggle(0..draft.text().len(), MarkKind::Bold);1935
let lines = draft.slice_without_objects(0..draft.text().len());1936
assert_eq!(lines.len(), 1);1937
assert_eq!(lines[0].content, "abcd");1938
assert_eq!(1939
lines[0].marks,1940
[Mark {1941
range: 0..4,1942
kind: MarkKind::Bold1943
}]1944
);1945
}1946
1907
fn typed_draft(text: &str) -> Draft {1947
fn typed_draft(text: &str) -> Draft {1908
let mut draft = Draft::default();1948
let mut draft = Draft::default();1909
typed(&mut draft, text);1949
typed(&mut draft, text);@@ -30,8 +30,8 @@ pub use adaptive_card::{
30
30
};
31
31
pub use avatars::Avatar;
32
32
pub use draft::{
33
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, TypingStyle,
34
changed_span, has_markdown, link_url, map_offset, reverse_edits,
33
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
34
TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,
35
35
};
36
36
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};
37
37
pub use error::{Error, Result};
@@ -30,8 +30,8 @@ pub use adaptive_card::{30
};30
};31
pub use avatars::Avatar;31
pub use avatars::Avatar;32
pub use draft::{32
pub use draft::{33
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, TypingStyle,33
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,34
changed_span, has_markdown, link_url, map_offset, reverse_edits,34
TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,35
};35
};36
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};36
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};37
pub use error::{Error, Result};37
pub use error::{Error, Result};@@ -91,9 +91,10 @@ fn extras_html(html: &str, extras: &MessageExtras) -> String {
91
91
let mut content = extras.kept_html();
92
92
content.push_str(html);
93
93
for index in 1..=extras.images.len() {
94
content.push_str(&format!(
95
"<p><img src=\"../hostedContents/{index}/$value\"></p>"
96
));
94
let tag = format!("<img src=\"../hostedContents/{index}/$value\">");
95
if !html.contains(&tag) {
96
content.push_str(&format!("<p>{tag}</p>"));
97
}
97
98
}
98
99
content.push_str(&extras.files_html());
99
100
content
@@ -264,6 +265,21 @@ mod tests {
264
265
assert!(body.get("attachments").is_none());
265
266
}
266
267
268
#[test]
269
fn images_already_placed_in_the_text_are_not_appended_again() {
270
let extras = MessageExtras {
271
kept: Vec::new(),
272
images: vec![image("image/png", &[1]), image("image/png", &[2])],
273
files: Vec::new(),
274
};
275
let body = message_body("a <img src=\"../hostedContents/2/$value\"> b", &[], &extras);
276
assert_eq!(
277
body["body"]["content"],
278
"a <img src=\"../hostedContents/2/$value\"> b<p><img src=\"../hostedContents/1/$value\"></p>"
279
);
280
assert_eq!(body["hostedContents"].as_array().unwrap().len(), 2);
281
}
282
267
283
#[test]
268
284
fn an_edit_keeps_the_original_files_and_image_elements() {
269
285
let extras = MessageExtras {
@@ -91,9 +91,10 @@ fn extras_html(html: &str, extras: &MessageExtras) -> String {91
let mut content = extras.kept_html();91
let mut content = extras.kept_html();92
content.push_str(html);92
content.push_str(html);93
for index in 1..=extras.images.len() {93
for index in 1..=extras.images.len() {94
content.push_str(&format!(94
let tag = format!("<img src=\"../hostedContents/{index}/$value\">");95
"<p><img src=\"../hostedContents/{index}/$value\"></p>"95
if !html.contains(&tag) {96
));96
content.push_str(&format!("<p>{tag}</p>"));97
}97
}98
}98
content.push_str(&extras.files_html());99
content.push_str(&extras.files_html());99
content100
content@@ -264,6 +265,21 @@ mod tests {264
assert!(body.get("attachments").is_none());265
assert!(body.get("attachments").is_none());265
}266
}266
267
268
#[test]269
fn images_already_placed_in_the_text_are_not_appended_again() {270
let extras = MessageExtras {271
kept: Vec::new(),272
images: vec![image("image/png", &[1]), image("image/png", &[2])],273
files: Vec::new(),274
};275
let body = message_body("a <img src=\"../hostedContents/2/$value\"> b", &[], &extras);276
assert_eq!(277
body["body"]["content"],278
"a <img src=\"../hostedContents/2/$value\"> b<p><img src=\"../hostedContents/1/$value\"></p>"279
);280
assert_eq!(body["hostedContents"].as_array().unwrap().len(), 2);281
}282
267
#[test]283
#[test]268
fn an_edit_keeps_the_original_files_and_image_elements() {284
fn an_edit_keeps_the_original_files_and_image_elements() {269
let extras = MessageExtras {285
let extras = MessageExtras {@@ -22,12 +22,20 @@ Upstream: crates.io `gpui-base 0.7.1` (git `87d10ae5`, `crates/base`). Wired in
22
22
| `src/input/editor/decorations.rs` | `RangeDecorationStyle::{Pill, Block, Bar}`, `RangeDecoration::with_border()` / `with_radius()`; Block and Bar keep empty ranges (`TrackedDecoration::keeps_empty`) and the index finds them | rounded inline code pills, full-width code block fill, quote bar; a block over one empty line |
23
23
| `src/input/base/element.rs` | `layout_range_decoration_quads()` paints pills, blocks and bars as quads below the fills | rounded corners and borders, which paths cannot draw |
24
24
| `src/input/base/state.rs` | `apply_edits(&[(Range, String)])` on all states | several edits in one undo step without touching inline tokens between them |
25
| `src/input/base/inline_tokens.rs`, `src/input/base/token_presentation.rs` | `InlineToken::block()` / `is_block()` (part of Hash and Eq), `InlineTokenContext::is_block()`, token layout cache keeps a `Size` per token (`sizes`) | a token that sits alone on its own row at its rendered height, e.g. an image preview in the composer |
26
| `src/input/editor/display_map/text_wrapper.rs` | `InlineMetric { range, width, height }` replaces `(Range, Pixels)`; `measured_wrap_boundaries(.., forced, ..)` ends a row at each block token edge; `LineItem.blocks`, `LineSummary.block_rows` / `block_height`, `BlockExtent` dimension; `TextWrapper::row_top` / `row_height` / `row_at_y` / `content_height`; `LineLayout::row_top` / `row_height` / `row_at_y`; `InputLine.height` | rows are no longer uniform: a row that is exactly one block token has the token's height, lookups stay O(log n) |
27
| `src/input/editor/display_map/display_map.rs`, `wrap_map.rs`, `mod.rs` | `DisplayMap::row_top` / `row_height` / `row_at_y` / `content_height` / `content_rows`, `InlineMetric` plumbing and export | plumbing |
28
| `src/input/base/element.rs` | block tokens measured with `MinContent` height (always, also off-screen); caret top and height, selection corners, Block / Bar decoration height, visible range, scroll size and token placement use the row helpers | caret, selection and paint follow the taller row |
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 |
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 |
25
32
26
33
## Limits
27
34
28
35
- Syntax-highlight (tree-sitter / LSP) bold or italic still wraps with the base font; only decorations feed wrapping.
29
36
- Hanging-indent markers are dropped by an edit inside them; the app sets them again on change.
30
37
- The unwrapped longest-line width (soft wrap off) ignores font overrides.
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.
31
39
32
40
## Re-apply on a gpui-kit upgrade
33
41
@@ -22,12 +22,20 @@ Upstream: crates.io `gpui-base 0.7.1` (git `87d10ae5`, `crates/base`). Wired in22
| `src/input/editor/decorations.rs` | `RangeDecorationStyle::{Pill, Block, Bar}`, `RangeDecoration::with_border()` / `with_radius()`; Block and Bar keep empty ranges (`TrackedDecoration::keeps_empty`) and the index finds them | rounded inline code pills, full-width code block fill, quote bar; a block over one empty line |22
| `src/input/editor/decorations.rs` | `RangeDecorationStyle::{Pill, Block, Bar}`, `RangeDecoration::with_border()` / `with_radius()`; Block and Bar keep empty ranges (`TrackedDecoration::keeps_empty`) and the index finds them | rounded inline code pills, full-width code block fill, quote bar; a block over one empty line |23
| `src/input/base/element.rs` | `layout_range_decoration_quads()` paints pills, blocks and bars as quads below the fills | rounded corners and borders, which paths cannot draw |23
| `src/input/base/element.rs` | `layout_range_decoration_quads()` paints pills, blocks and bars as quads below the fills | rounded corners and borders, which paths cannot draw |24
| `src/input/base/state.rs` | `apply_edits(&[(Range, String)])` on all states | several edits in one undo step without touching inline tokens between them |24
| `src/input/base/state.rs` | `apply_edits(&[(Range, String)])` on all states | several edits in one undo step without touching inline tokens between them |25
| `src/input/base/inline_tokens.rs`, `src/input/base/token_presentation.rs` | `InlineToken::block()` / `is_block()` (part of Hash and Eq), `InlineTokenContext::is_block()`, token layout cache keeps a `Size` per token (`sizes`) | a token that sits alone on its own row at its rendered height, e.g. an image preview in the composer |26
| `src/input/editor/display_map/text_wrapper.rs` | `InlineMetric { range, width, height }` replaces `(Range, Pixels)`; `measured_wrap_boundaries(.., forced, ..)` ends a row at each block token edge; `LineItem.blocks`, `LineSummary.block_rows` / `block_height`, `BlockExtent` dimension; `TextWrapper::row_top` / `row_height` / `row_at_y` / `content_height`; `LineLayout::row_top` / `row_height` / `row_at_y`; `InputLine.height` | rows are no longer uniform: a row that is exactly one block token has the token's height, lookups stay O(log n) |27
| `src/input/editor/display_map/display_map.rs`, `wrap_map.rs`, `mod.rs` | `DisplayMap::row_top` / `row_height` / `row_at_y` / `content_height` / `content_rows`, `InlineMetric` plumbing and export | plumbing |28
| `src/input/base/element.rs` | block tokens measured with `MinContent` height (always, also off-screen); caret top and height, selection corners, Block / Bar decoration height, visible range, scroll size and token placement use the row helpers | caret, selection and paint follow the taller row |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 |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 |25
32
26
## Limits33
## Limits27
34
28
- Syntax-highlight (tree-sitter / LSP) bold or italic still wraps with the base font; only decorations feed wrapping.35
- Syntax-highlight (tree-sitter / LSP) bold or italic still wraps with the base font; only decorations feed wrapping.29
- Hanging-indent markers are dropped by an edit inside them; the app sets them again on change.36
- Hanging-indent markers are dropped by an edit inside them; the app sets them again on change.30
- The unwrapped longest-line width (soft wrap off) ignores font overrides.37
- The unwrapped longest-line width (soft wrap off) ignores font overrides.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.31
39
32
## Re-apply on a gpui-kit upgrade40
## Re-apply on a gpui-kit upgrade33
41
@@ -22,7 +22,7 @@ use crate::{
22
22
RopeExt as _,
23
23
blink_cursor::CURSOR_WIDTH,
24
24
decorations::font_override_spans,
25
display_map::{LineLayout, split_run_by_font_overrides},
25
display_map::{InlineMetric, LineLayout, split_run_by_font_overrides},
26
26
},
27
27
};
28
28
@@ -562,9 +562,12 @@ impl<M: InputModeKind> TextElement<M> {
562
562
563
563
// Resolve a cursor or selection endpoint to a content-space position.
564
564
let visible_buffer_lines = &last_layout.visible_buffer_lines;
565
let caret_for = |row: usize, offset: usize, affinity: bool| -> Point<Pixels> {
565
let caret_for = |row: usize, offset: usize, affinity: bool| -> (Point<Pixels>, Pixels) {
566
566
// y of the top of buffer line `row` in content space.
567
let top = line_height * state.display_map.buffer_line_to_display_row(row);
567
let top = state.display_map.row_top(
568
state.display_map.buffer_line_to_display_row(row),
569
line_height,
570
);
568
571
let line_origin = point(px(0.), top);
569
572
570
573
if let Some(vi) = visible_buffer_lines.iter().position(|&bl| bl == row) {
@@ -572,14 +575,15 @@ impl<M: InputModeKind> TextElement<M> {
572
575
let line_start = last_layout.visible_line_byte_offsets[vi];
573
576
let local = offset.saturating_sub(line_start);
574
577
if let Some(pos) = line.position_for_index(local, last_layout, affinity) {
575
return line_origin + pos;
578
let row_height = line
579
.row_at_y(pos.y, line_height)
580
.map_or(line_height, |ix| line.row_height(ix, line_height));
581
return (line_origin + pos, row_height);
576
582
}
577
583
}
578
line_origin
584
(line_origin, line_height)
579
585
};
580
586
581
let cursor_height = 0.85 * line_height;
582
583
587
for selection in state.selections.iter() {
584
588
let is_active = selection.id == active_id;
585
589
@@ -613,16 +617,25 @@ impl<M: InputModeKind> TextElement<M> {
613
617
}
614
618
615
619
let affinity = is_active && state.cursor_line_end_affinity;
616
let cursor_pos = caret_for(cursor_row, cursor, affinity);
617
let cursor_start = caret_for(sel_start_row, selected_range.start, false);
618
let cursor_end = caret_for(sel_end_row, selected_range.end, false);
620
let (cursor_pos, row_height) = caret_for(cursor_row, cursor, affinity);
621
let (cursor_start, _) = caret_for(sel_start_row, selected_range.start, false);
622
let (cursor_end, _) = caret_for(sel_end_row, selected_range.end, false);
623
let cursor_height = if row_height == line_height {
624
0.85 * line_height
625
} else {
626
row_height
627
};
619
628
620
629
if is_active {
621
630
current_row = Some(cursor_row);
622
631
623
632
let selection_changed = state.last_selected_range != Some(selected_range);
624
633
let auto_scrolling = state.auto_scroll.is_active();
625
if selection_changed && !is_selected_all {
634
let viewport_changed = state.mode.is_auto_grow()
635
&& state
636
.last_bounds
637
.is_some_and(|last| last.size.height != bounds.size.height);
638
if (selection_changed || viewport_changed) && !is_selected_all {
626
639
// For Right alignment use 0 margin: cursor is clamped to bounds separately,
627
640
// so we never scroll the text for cursor-at-edge, avoiding a first-click jump.
628
641
let safety_margin = match last_layout.text_align {
@@ -695,7 +708,7 @@ impl<M: InputModeKind> TextElement<M> {
695
708
bounds: Bounds::new(
696
709
point(
697
710
cursor_x,
698
bounds.top() + cursor_pos.y + ((line_height - cursor_height) / 2.),
711
bounds.top() + cursor_pos.y + ((row_height - cursor_height) / 2.),
699
712
),
700
713
size(CURSOR_WIDTH, cursor_height),
701
714
),
@@ -789,15 +802,16 @@ impl<M: InputModeKind> TextElement<M> {
789
802
} else {
790
803
shaped.x_for_index(end_ix - offset)
791
804
};
805
let bottom = y + line.row_height(row, last_layout.line_height);
792
806
corners.push(Corners {
793
807
top_left: point(left, y),
794
808
top_right: point(right, y),
795
bottom_left: point(left, y + last_layout.line_height),
796
bottom_right: point(right, y + last_layout.line_height),
809
bottom_left: point(left, bottom),
810
bottom_right: point(right, bottom),
797
811
});
798
812
}
799
813
offset = end;
800
y += last_layout.line_height;
814
y += line.row_height(row, last_layout.line_height);
801
815
}
802
816
}
803
817
(!corners.is_empty()).then_some(corners)
@@ -929,8 +943,10 @@ impl<M: InputModeKind> TextElement<M> {
929
943
.iter()
930
944
.zip(last_layout.lines.iter())
931
945
{
932
let height =
933
last_layout.line_height * line.wrapped_lines.len().max(1) as f32;
946
let height = line
947
.size(last_layout.line_height)
948
.height
949
.max(last_layout.line_height);
934
950
let covered = (range.start..=range.end).contains(&line_start);
935
951
if covered {
936
952
top.get_or_insert(y);
@@ -1125,7 +1141,6 @@ impl<M: InputModeKind> TextElement<M> {
1125
1141
return (0..1, vec![0], px(0.));
1126
1142
}
1127
1143
1128
let total_lines = state.display_map.wrap_row_count();
1129
1144
let display_count = state.display_map.display_row_count();
1130
1145
let buffer_line_count = state.display_map.buffer_line_count();
1131
1146
if display_count == 0 || buffer_line_count == 0 {
@@ -1140,19 +1155,24 @@ impl<M: InputModeKind> TextElement<M> {
1140
1155
scroll_top = clamp_auto_grow_vertical_scroll_offset(
1141
1156
&state.mode,
1142
1157
scroll_top,
1143
line_height * total_lines,
1158
state.display_map.content_height(line_height),
1144
1159
input_height,
1145
1160
);
1146
1161
1147
// Display rows are uniformly `line_height` tall, so the visible window maps
1148
// directly to a display-row range.
1149
1162
let viewport_top = (-scroll_top).max(px(0.));
1150
1163
let viewport_bottom = viewport_top + input_height;
1151
let line_height_f = f32::from(line_height);
1152
let first_display =
1153
((f32::from(viewport_top) / line_height_f).floor() as usize).min(display_count - 1);
1164
let first_display = state
1165
.display_map
1166
.row_at_y(viewport_top, line_height)
1167
.min(display_count - 1);
1168
let bottom_row = state.display_map.row_at_y(viewport_bottom, line_height);
1154
1169
let last_display =
1155
((f32::from(viewport_bottom) / line_height_f).ceil() as usize).min(display_count - 1);
1170
if state.display_map.row_top(bottom_row, line_height) < viewport_bottom {
1171
bottom_row + 1
1172
} else {
1173
bottom_row
1174
}
1175
.min(display_count - 1);
1156
1176
1157
1177
let start_line = state.display_map.display_row_to_buffer_line(first_display);
1158
1178
let end_line = state.display_map.display_row_to_buffer_line(last_display);
@@ -1162,8 +1182,8 @@ impl<M: InputModeKind> TextElement<M> {
1162
1182
.display_map
1163
1183
.buffer_line_to_display_row_range(start_line)
1164
1184
{
1165
Some(range) => line_height * range.start,
1166
None => line_height * first_display,
1185
Some(range) => state.display_map.row_top(range.start, line_height),
1186
None => state.display_map.row_top(first_display, line_height),
1167
1187
};
1168
1188
1169
1189
let visible_range = start_line..(end_line + 1 + extra_rows).min(buffer_line_count);
@@ -1586,7 +1606,7 @@ impl<M: InputModeKind> TextElement<M> {
1586
1606
.id(id)
1587
1607
.flex()
1588
1608
.items_center()
1589
.h(token.line_height())
1609
.when(!token.is_block(), |this| this.h(token.line_height()))
1590
1610
.max_w(token.available_width())
1591
1611
.overflow_hidden()
1592
1612
// A token is an object, not text: the arrow, never the I-beam.
@@ -1718,6 +1738,20 @@ impl<M: InputModeKind> TextElement<M> {
1718
1738
.into_any_element()
1719
1739
}
1720
1740
1741
fn token_available_space(
1742
token: &super::InlineTokenContext,
1743
line_height: Pixels,
1744
) -> Size<gpui::AvailableSpace> {
1745
size(
1746
gpui::AvailableSpace::MaxContent,
1747
if token.is_block() {
1748
gpui::AvailableSpace::MinContent
1749
} else {
1750
gpui::AvailableSpace::Definite(line_height)
1751
},
1752
)
1753
}
1754
1721
1755
fn measure_tokens(
1722
1756
&self,
1723
1757
width: Pixels,
@@ -1766,31 +1800,18 @@ impl<M: InputModeKind> TextElement<M> {
1766
1800
}
1767
1801
let revision = state.document_revision;
1768
1802
let cache = state.token_layout_cache.as_ref();
1769
let all = cache.is_none_or(|cache| {
1770
cache.key.as_ref() != Some(&key)
1771
|| cache.revision != revision
1772
|| state
1773
.token_spans()
1774
.iter()
1775
.any(|span| !cache.widths.contains_key(span.token()))
1776
});
1777
1803
let (visible, _, _) = self.calculate_visible_range(state, line_height, viewport);
1778
1804
let start = state.text.line_start_offset(visible.start);
1779
1805
let end = state.text.line_end_offset(visible.end.saturating_sub(1));
1780
1806
let spans = state.token_spans();
1781
let first = if all {
1782
0
1783
} else {
1784
spans.partition_point(|s| s.range().end <= start)
1785
};
1786
let contexts: Vec<_> = spans[first..]
1807
let contexts: Vec<_> = spans
1787
1808
.iter()
1788
.take_while(|s| all || s.range().start <= end)
1789
1809
.filter(|span| {
1790
1810
let range = span.range();
1791
(range.start <= end && range.end >= start)
1811
span.token().is_block()
1812
|| (range.start <= end && range.end >= start)
1792
1813
|| cache.is_none_or(|cache| {
1793
cache.key.as_ref() != Some(&key) || !cache.widths.contains_key(span.token())
1814
cache.key.as_ref() != Some(&key) || !cache.sizes.contains_key(span.token())
1794
1815
})
1795
1816
})
1796
1817
.map(|span| state.token_context(span, line_height, width))
@@ -1800,39 +1821,46 @@ impl<M: InputModeKind> TextElement<M> {
1800
1821
for token in contexts {
1801
1822
let mut element = self.token_element(&token, window, cx);
1802
1823
let size = element.layout_as_root(
1803
size(
1804
gpui::AvailableSpace::MaxContent,
1805
gpui::AvailableSpace::Definite(line_height),
1806
),
1824
Self::token_available_space(&token, line_height),
1807
1825
window,
1808
1826
cx,
1809
1827
);
1810
measured.push((token.token().clone(), size.width.min(width).max(px(1.))));
1828
measured.push((
1829
token.token().clone(),
1830
gpui::Size {
1831
width: size.width.min(width).max(px(1.)),
1832
height: size.height.max(px(1.)),
1833
},
1834
));
1811
1835
elements.insert(token.range().start, (element, size));
1812
1836
}
1813
1837
self.state.update(cx, |state, cx| {
1814
1838
let mut cache = state.token_layout_cache.take().unwrap_or_default();
1815
1839
let mut changed = cache.key.as_ref() != Some(&key) || cache.revision != revision;
1816
1840
if cache.key.as_ref() != Some(&key) {
1817
cache.widths.clear();
1841
cache.sizes.clear();
1818
1842
}
1819
for (token, width) in measured {
1820
changed |= cache.widths.get(&token) != Some(&width);
1821
cache.widths.insert(token, width);
1843
for (token, token_size) in measured {
1844
changed |= cache.sizes.get(&token) != Some(&token_size);
1845
cache.sizes.insert(token, token_size);
1822
1846
}
1823
1847
cache.key = Some(key);
1824
1848
if changed {
1825
1849
let spans = state.token_spans();
1826
1850
let tokens: std::collections::HashSet<_> =
1827
1851
spans.iter().map(|s| s.token()).collect();
1828
cache.widths.retain(|token, _| tokens.contains(token));
1852
cache.sizes.retain(|token, _| tokens.contains(token));
1829
1853
cache.metrics = spans
1830
1854
.iter()
1831
1855
.filter_map(|span| {
1832
1856
cache
1833
.widths
1857
.sizes
1834
1858
.get(span.token())
1835
.map(|width| (span.range(), *width))
1859
.map(|token_size| InlineMetric {
1860
range: span.range(),
1861
width: token_size.width,
1862
height: span.token().is_block().then_some(token_size.height),
1863
})
1836
1864
})
1837
1865
.collect();
1838
1866
cache.revision = revision;
@@ -1867,8 +1895,10 @@ impl<M: InputModeKind> TextElement<M> {
1867
1895
None,
1868
1896
)
1869
1897
.width;
1870
width +=
1871
cache.widths.get(span.token()).copied().unwrap_or_default();
1898
width += cache
1899
.sizes
1900
.get(span.token())
1901
.map_or(px(0.), |token_size| token_size.width);
1872
1902
offset = local.end;
1873
1903
}
1874
1904
let part = &text[offset..];
@@ -1892,7 +1922,7 @@ impl<M: InputModeKind> TextElement<M> {
1892
1922
state.display_map.set_inline_metrics(metrics, cx);
1893
1923
if state.mode.is_auto_grow() {
1894
1924
let rows = state.mode.rows();
1895
state.mode.update_auto_grow(&state.display_map);
1925
state.mode.update_auto_grow(&state.display_map, line_height);
1896
1926
if state.mode.rows() != rows {
1897
1927
cx.notify();
1898
1928
}
@@ -1934,6 +1964,7 @@ impl<M: InputModeKind> TextElement<M> {
1934
1964
let mut lines: SmallVec<[InputLine; 1]> = SmallVec::new();
1935
1965
for range in ranges {
1936
1966
let mut fragments = Vec::new();
1967
let mut block_height = None;
1937
1968
let mut offset = range.start;
1938
1969
let mut x = px(0.);
1939
1970
let first =
@@ -1960,7 +1991,11 @@ impl<M: InputModeKind> TextElement<M> {
1960
1991
});
1961
1992
x += width;
1962
1993
}
1963
let width = cache.widths.get(span.token()).copied().unwrap_or_default();
1994
let token_size = cache.sizes.get(span.token()).copied().unwrap_or_default();
1995
let width = token_size.width;
1996
if span.token().is_block() && local == range {
1997
block_height = Some(token_size.height);
1998
}
1964
1999
fragments.push(InlineFragment {
1965
2000
range: local.start - range.start..local.end - range.start,
1966
2001
x,
@@ -1986,7 +2021,10 @@ impl<M: InputModeKind> TextElement<M> {
1986
2021
text: Some(shaped),
1987
2022
});
1988
2023
}
1989
lines.push(InputLine::inline(text[range].to_owned().into(), fragments));
2024
lines.push(
2025
InputLine::inline(text[range].to_owned().into(), fragments)
2026
.with_height(block_height),
2027
);
1990
2028
}
1991
2029
let indent = state.display_map.line(row).map_or(0, |line| line.indent);
1992
2030
let wrap_indent = if indent > 0 && lines.len() > 1 {
@@ -2061,10 +2099,7 @@ impl<M: InputModeKind> TextElement<M> {
2061
2099
None => {
2062
2100
let mut element = self.token_element(&token, window, cx);
2063
2101
let element_size = element.layout_as_root(
2064
size(
2065
gpui::AvailableSpace::MaxContent,
2066
gpui::AvailableSpace::Definite(layout.line_height),
2067
),
2102
Self::token_available_space(&token, layout.line_height),
2068
2103
window,
2069
2104
cx,
2070
2105
);
@@ -2613,8 +2648,8 @@ impl<M: InputModeKind> Element for TextElement<M> {
2613
2648
style.flex_grow = 1.0;
2614
2649
style.size.height = relative(1.).into();
2615
2650
// At least `rows` tall (auto grow: the content's rows, capped at
2616
// `max_rows`); a taller parent still fills it.
2617
let rows = state.mode.max_rows().min(state.mode.rows());
2651
// `max_rows` plus the rows of block tokens); a taller parent still fills it.
2652
let rows = state.mode.rows();
2618
2653
style.min_size.height = (rows * line_height).into();
2619
2654
} else {
2620
2655
// For single-line inputs, the minimum height should be the line height
@@ -2923,7 +2958,6 @@ impl<M: InputModeKind> Element for TextElement<M> {
2923
2958
let ghost_line_count = ghost_lines.len();
2924
2959
let ghost_lines_height = ghost_line_count as f32 * line_height;
2925
2960
2926
let total_wrapped_lines = state.display_map.wrap_row_count();
2927
2961
let empty_bottom_height = empty_bottom_height(
2928
2962
state.is_code_editor(),
2929
2963
state.scroll_beyond_last_line,
@@ -2940,7 +2974,7 @@ impl<M: InputModeKind> Element for TextElement<M> {
2940
2974
} else {
2941
2975
longest_line_width
2942
2976
},
2943
(total_wrapped_lines as f32 * line_height
2977
(state.display_map.content_height(line_height)
2944
2978
+ empty_bottom_height.max(ghost_lines_height))
2945
2979
.max(bounds.size.height),
2946
2980
);
@@ -3890,6 +3924,69 @@ mod tests {
3890
3924
});
3891
3925
}
3892
3926
3927
#[cfg(target_os = "linux")]
3928
#[test]
3929
fn block_token_selection_and_block_decoration_span_the_row_height() {
3930
use crate::input::{InlineToken, InlineTokenPresentation};
3931
let platform = gpui_platform::current_platform(true);
3932
let mut cx = TestAppContext::build_with_text_system(
3933
gpui::TestDispatcher::new(0),
3934
None,
3935
platform.text_system(),
3936
);
3937
cx.update(crate::init);
3938
let mut textarea = None;
3939
let window = cx.open_window(size(px(400.), px(300.)), |window, cx| {
3940
let state = cx.new(|cx| {
3941
crate::input::TextareaState::new(window, cx)
3942
.rows(4)
3943
.default_value("ab[img]cd")
3944
});
3945
textarea = Some(state.clone());
3946
TextareaHarness(state)
3947
});
3948
let textarea = textarea.unwrap();
3949
let mut cx = VisualTestContext::from_window(window.into(), &mut cx);
3950
cx.update(|window, cx| {
3951
textarea.update(cx, |state, cx| {
3952
state.set_token_presentation(
3953
InlineTokenPresentation::default()
3954
.token(|_, _, _| div().w(px(200.)).h(px(120.))),
3955
);
3956
state
3957
.replace_range_with_token(
3958
2..7,
3959
InlineToken::new("img", "[img]").block(),
3960
window,
3961
cx,
3962
)
3963
.unwrap();
3964
state.create_range_decorations_collection(
3965
vec![RangeDecoration::new(0..0).with_style(RangeDecorationStyle::Block)],
3966
cx,
3967
);
3968
});
3969
window.draw(cx).clear(cx);
3970
window.draw(cx).clear(cx);
3971
let state = textarea.read(cx);
3972
let layout = state.last_layout.as_ref().unwrap();
3973
let line_height = layout.line_height;
3974
let corners =
3975
TextElement::<crate::input::TextareaMode>::layout_range_corners(&(2..7), layout)
3976
.unwrap();
3977
assert_eq!(corners.len(), 1);
3978
assert_eq!(corners[0].top_left.y, layout.visible_top + line_height);
3979
assert_eq!(corners[0].bottom_left.y - corners[0].top_left.y, px(120.));
3980
assert_eq!(
3981
(corners[0].top_left.x, corners[0].top_right.x),
3982
(px(0.), px(200.))
3983
);
3984
let element = TextElement::new(textarea.clone());
3985
let quads = element.layout_range_decoration_quads(layout, &state.input_bounds, cx);
3986
assert_eq!(quads[0].bounds.size.height, line_height * 2. + px(120.));
3987
});
3988
}
3989
3893
3990
#[cfg(target_os = "linux")]
3894
3991
#[test]
3895
3992
fn textarea_decorations_render_fill_and_wrap_like_the_editor() {
@@ -22,7 +22,7 @@ use crate::{22
RopeExt as _,22
RopeExt as _,23
blink_cursor::CURSOR_WIDTH,23
blink_cursor::CURSOR_WIDTH,24
decorations::font_override_spans,24
decorations::font_override_spans,25
display_map::{LineLayout, split_run_by_font_overrides},25
display_map::{InlineMetric, LineLayout, split_run_by_font_overrides},26
},26
},27
};27
};28
28
@@ -562,9 +562,12 @@ impl<M: InputModeKind> TextElement<M> {562
562
563
// Resolve a cursor or selection endpoint to a content-space position.563
// Resolve a cursor or selection endpoint to a content-space position.564
let visible_buffer_lines = &last_layout.visible_buffer_lines;564
let visible_buffer_lines = &last_layout.visible_buffer_lines;565
let caret_for = |row: usize, offset: usize, affinity: bool| -> Point<Pixels> {565
let caret_for = |row: usize, offset: usize, affinity: bool| -> (Point<Pixels>, Pixels) {566
// y of the top of buffer line `row` in content space.566
// y of the top of buffer line `row` in content space.567
let top = line_height * state.display_map.buffer_line_to_display_row(row);567
let top = state.display_map.row_top(568
state.display_map.buffer_line_to_display_row(row),569
line_height,570
);568
let line_origin = point(px(0.), top);571
let line_origin = point(px(0.), top);569
572
570
if let Some(vi) = visible_buffer_lines.iter().position(|&bl| bl == row) {573
if let Some(vi) = visible_buffer_lines.iter().position(|&bl| bl == row) {@@ -572,14 +575,15 @@ impl<M: InputModeKind> TextElement<M> {572
let line_start = last_layout.visible_line_byte_offsets[vi];575
let line_start = last_layout.visible_line_byte_offsets[vi];573
let local = offset.saturating_sub(line_start);576
let local = offset.saturating_sub(line_start);574
if let Some(pos) = line.position_for_index(local, last_layout, affinity) {577
if let Some(pos) = line.position_for_index(local, last_layout, affinity) {575
return line_origin + pos;578
let row_height = line579
.row_at_y(pos.y, line_height)580
.map_or(line_height, |ix| line.row_height(ix, line_height));581
return (line_origin + pos, row_height);576
}582
}577
}583
}578
line_origin584
(line_origin, line_height)579
};585
};580
586
581
let cursor_height = 0.85 * line_height;582
583
for selection in state.selections.iter() {587
for selection in state.selections.iter() {584
let is_active = selection.id == active_id;588
let is_active = selection.id == active_id;585
589
@@ -613,16 +617,25 @@ impl<M: InputModeKind> TextElement<M> {613
}617
}614
618
615
let affinity = is_active && state.cursor_line_end_affinity;619
let affinity = is_active && state.cursor_line_end_affinity;616
let cursor_pos = caret_for(cursor_row, cursor, affinity);620
let (cursor_pos, row_height) = caret_for(cursor_row, cursor, affinity);617
let cursor_start = caret_for(sel_start_row, selected_range.start, false);621
let (cursor_start, _) = caret_for(sel_start_row, selected_range.start, false);618
let cursor_end = caret_for(sel_end_row, selected_range.end, false);622
let (cursor_end, _) = caret_for(sel_end_row, selected_range.end, false);623
let cursor_height = if row_height == line_height {624
0.85 * line_height625
} else {626
row_height627
};619
628
620
if is_active {629
if is_active {621
current_row = Some(cursor_row);630
current_row = Some(cursor_row);622
631
623
let selection_changed = state.last_selected_range != Some(selected_range);632
let selection_changed = state.last_selected_range != Some(selected_range);624
let auto_scrolling = state.auto_scroll.is_active();633
let auto_scrolling = state.auto_scroll.is_active();625
if selection_changed && !is_selected_all {634
let viewport_changed = state.mode.is_auto_grow()635
&& state636
.last_bounds637
.is_some_and(|last| last.size.height != bounds.size.height);638
if (selection_changed || viewport_changed) && !is_selected_all {626
// For Right alignment use 0 margin: cursor is clamped to bounds separately,639
// For Right alignment use 0 margin: cursor is clamped to bounds separately,627
// so we never scroll the text for cursor-at-edge, avoiding a first-click jump.640
// so we never scroll the text for cursor-at-edge, avoiding a first-click jump.628
let safety_margin = match last_layout.text_align {641
let safety_margin = match last_layout.text_align {@@ -695,7 +708,7 @@ impl<M: InputModeKind> TextElement<M> {695
bounds: Bounds::new(708
bounds: Bounds::new(696
point(709
point(697
cursor_x,710
cursor_x,698
bounds.top() + cursor_pos.y + ((line_height - cursor_height) / 2.),711
bounds.top() + cursor_pos.y + ((row_height - cursor_height) / 2.),699
),712
),700
size(CURSOR_WIDTH, cursor_height),713
size(CURSOR_WIDTH, cursor_height),701
),714
),@@ -789,15 +802,16 @@ impl<M: InputModeKind> TextElement<M> {789
} else {802
} else {790
shaped.x_for_index(end_ix - offset)803
shaped.x_for_index(end_ix - offset)791
};804
};805
let bottom = y + line.row_height(row, last_layout.line_height);792
corners.push(Corners {806
corners.push(Corners {793
top_left: point(left, y),807
top_left: point(left, y),794
top_right: point(right, y),808
top_right: point(right, y),795
bottom_left: point(left, y + last_layout.line_height),809
bottom_left: point(left, bottom),796
bottom_right: point(right, y + last_layout.line_height),810
bottom_right: point(right, bottom),797
});811
});798
}812
}799
offset = end;813
offset = end;800
y += last_layout.line_height;814
y += line.row_height(row, last_layout.line_height);801
}815
}802
}816
}803
(!corners.is_empty()).then_some(corners)817
(!corners.is_empty()).then_some(corners)@@ -929,8 +943,10 @@ impl<M: InputModeKind> TextElement<M> {929
.iter()943
.iter()930
.zip(last_layout.lines.iter())944
.zip(last_layout.lines.iter())931
{945
{932
let height =946
let height = line933
last_layout.line_height * line.wrapped_lines.len().max(1) as f32;947
.size(last_layout.line_height)948
.height949
.max(last_layout.line_height);934
let covered = (range.start..=range.end).contains(&line_start);950
let covered = (range.start..=range.end).contains(&line_start);935
if covered {951
if covered {936
top.get_or_insert(y);952
top.get_or_insert(y);@@ -1125,7 +1141,6 @@ impl<M: InputModeKind> TextElement<M> {1125
return (0..1, vec![0], px(0.));1141
return (0..1, vec![0], px(0.));1126
}1142
}1127
1143
1128
let total_lines = state.display_map.wrap_row_count();1129
let display_count = state.display_map.display_row_count();1144
let display_count = state.display_map.display_row_count();1130
let buffer_line_count = state.display_map.buffer_line_count();1145
let buffer_line_count = state.display_map.buffer_line_count();1131
if display_count == 0 || buffer_line_count == 0 {1146
if display_count == 0 || buffer_line_count == 0 {@@ -1140,19 +1155,24 @@ impl<M: InputModeKind> TextElement<M> {1140
scroll_top = clamp_auto_grow_vertical_scroll_offset(1155
scroll_top = clamp_auto_grow_vertical_scroll_offset(1141
&state.mode,1156
&state.mode,1142
scroll_top,1157
scroll_top,1143
line_height * total_lines,1158
state.display_map.content_height(line_height),1144
input_height,1159
input_height,1145
);1160
);1146
1161
1147
// Display rows are uniformly `line_height` tall, so the visible window maps1148
// directly to a display-row range.1149
let viewport_top = (-scroll_top).max(px(0.));1162
let viewport_top = (-scroll_top).max(px(0.));1150
let viewport_bottom = viewport_top + input_height;1163
let viewport_bottom = viewport_top + input_height;1151
let line_height_f = f32::from(line_height);1164
let first_display = state1152
let first_display =1165
.display_map1153
((f32::from(viewport_top) / line_height_f).floor() as usize).min(display_count - 1);1166
.row_at_y(viewport_top, line_height)1167
.min(display_count - 1);1168
let bottom_row = state.display_map.row_at_y(viewport_bottom, line_height);1154
let last_display =1169
let last_display =1155
((f32::from(viewport_bottom) / line_height_f).ceil() as usize).min(display_count - 1);1170
if state.display_map.row_top(bottom_row, line_height) < viewport_bottom {1171
bottom_row + 11172
} else {1173
bottom_row1174
}1175
.min(display_count - 1);1156
1176
1157
let start_line = state.display_map.display_row_to_buffer_line(first_display);1177
let start_line = state.display_map.display_row_to_buffer_line(first_display);1158
let end_line = state.display_map.display_row_to_buffer_line(last_display);1178
let end_line = state.display_map.display_row_to_buffer_line(last_display);@@ -1162,8 +1182,8 @@ impl<M: InputModeKind> TextElement<M> {1162
.display_map1182
.display_map1163
.buffer_line_to_display_row_range(start_line)1183
.buffer_line_to_display_row_range(start_line)1164
{1184
{1165
Some(range) => line_height * range.start,1185
Some(range) => state.display_map.row_top(range.start, line_height),1166
None => line_height * first_display,1186
None => state.display_map.row_top(first_display, line_height),1167
};1187
};1168
1188
1169
let visible_range = start_line..(end_line + 1 + extra_rows).min(buffer_line_count);1189
let visible_range = start_line..(end_line + 1 + extra_rows).min(buffer_line_count);@@ -1586,7 +1606,7 @@ impl<M: InputModeKind> TextElement<M> {1586
.id(id)1606
.id(id)1587
.flex()1607
.flex()1588
.items_center()1608
.items_center()1589
.h(token.line_height())1609
.when(!token.is_block(), |this| this.h(token.line_height()))1590
.max_w(token.available_width())1610
.max_w(token.available_width())1591
.overflow_hidden()1611
.overflow_hidden()1592
// A token is an object, not text: the arrow, never the I-beam.1612
// A token is an object, not text: the arrow, never the I-beam.@@ -1718,6 +1738,20 @@ impl<M: InputModeKind> TextElement<M> {1718
.into_any_element()1738
.into_any_element()1719
}1739
}1720
1740
1741
fn token_available_space(1742
token: &super::InlineTokenContext,1743
line_height: Pixels,1744
) -> Size<gpui::AvailableSpace> {1745
size(1746
gpui::AvailableSpace::MaxContent,1747
if token.is_block() {1748
gpui::AvailableSpace::MinContent1749
} else {1750
gpui::AvailableSpace::Definite(line_height)1751
},1752
)1753
}1754
1721
fn measure_tokens(1755
fn measure_tokens(1722
&self,1756
&self,1723
width: Pixels,1757
width: Pixels,@@ -1766,31 +1800,18 @@ impl<M: InputModeKind> TextElement<M> {1766
}1800
}1767
let revision = state.document_revision;1801
let revision = state.document_revision;1768
let cache = state.token_layout_cache.as_ref();1802
let cache = state.token_layout_cache.as_ref();1769
let all = cache.is_none_or(|cache| {1770
cache.key.as_ref() != Some(&key)1771
|| cache.revision != revision1772
|| state1773
.token_spans()1774
.iter()1775
.any(|span| !cache.widths.contains_key(span.token()))1776
});1777
let (visible, _, _) = self.calculate_visible_range(state, line_height, viewport);1803
let (visible, _, _) = self.calculate_visible_range(state, line_height, viewport);1778
let start = state.text.line_start_offset(visible.start);1804
let start = state.text.line_start_offset(visible.start);1779
let end = state.text.line_end_offset(visible.end.saturating_sub(1));1805
let end = state.text.line_end_offset(visible.end.saturating_sub(1));1780
let spans = state.token_spans();1806
let spans = state.token_spans();1781
let first = if all {1807
let contexts: Vec<_> = spans1782
01783
} else {1784
spans.partition_point(|s| s.range().end <= start)1785
};1786
let contexts: Vec<_> = spans[first..]1787
.iter()1808
.iter()1788
.take_while(|s| all || s.range().start <= end)1789
.filter(|span| {1809
.filter(|span| {1790
let range = span.range();1810
let range = span.range();1791
(range.start <= end && range.end >= start)1811
span.token().is_block()1812
|| (range.start <= end && range.end >= start)1792
|| cache.is_none_or(|cache| {1813
|| cache.is_none_or(|cache| {1793
cache.key.as_ref() != Some(&key) || !cache.widths.contains_key(span.token())1814
cache.key.as_ref() != Some(&key) || !cache.sizes.contains_key(span.token())1794
})1815
})1795
})1816
})1796
.map(|span| state.token_context(span, line_height, width))1817
.map(|span| state.token_context(span, line_height, width))@@ -1800,39 +1821,46 @@ impl<M: InputModeKind> TextElement<M> {1800
for token in contexts {1821
for token in contexts {1801
let mut element = self.token_element(&token, window, cx);1822
let mut element = self.token_element(&token, window, cx);1802
let size = element.layout_as_root(1823
let size = element.layout_as_root(1803
size(1824
Self::token_available_space(&token, line_height),1804
gpui::AvailableSpace::MaxContent,1805
gpui::AvailableSpace::Definite(line_height),1806
),1807
window,1825
window,1808
cx,1826
cx,1809
);1827
);1810
measured.push((token.token().clone(), size.width.min(width).max(px(1.))));1828
measured.push((1829
token.token().clone(),1830
gpui::Size {1831
width: size.width.min(width).max(px(1.)),1832
height: size.height.max(px(1.)),1833
},1834
));1811
elements.insert(token.range().start, (element, size));1835
elements.insert(token.range().start, (element, size));1812
}1836
}1813
self.state.update(cx, |state, cx| {1837
self.state.update(cx, |state, cx| {1814
let mut cache = state.token_layout_cache.take().unwrap_or_default();1838
let mut cache = state.token_layout_cache.take().unwrap_or_default();1815
let mut changed = cache.key.as_ref() != Some(&key) || cache.revision != revision;1839
let mut changed = cache.key.as_ref() != Some(&key) || cache.revision != revision;1816
if cache.key.as_ref() != Some(&key) {1840
if cache.key.as_ref() != Some(&key) {1817
cache.widths.clear();1841
cache.sizes.clear();1818
}1842
}1819
for (token, width) in measured {1843
for (token, token_size) in measured {1820
changed |= cache.widths.get(&token) != Some(&width);1844
changed |= cache.sizes.get(&token) != Some(&token_size);1821
cache.widths.insert(token, width);1845
cache.sizes.insert(token, token_size);1822
}1846
}1823
cache.key = Some(key);1847
cache.key = Some(key);1824
if changed {1848
if changed {1825
let spans = state.token_spans();1849
let spans = state.token_spans();1826
let tokens: std::collections::HashSet<_> =1850
let tokens: std::collections::HashSet<_> =1827
spans.iter().map(|s| s.token()).collect();1851
spans.iter().map(|s| s.token()).collect();1828
cache.widths.retain(|token, _| tokens.contains(token));1852
cache.sizes.retain(|token, _| tokens.contains(token));1829
cache.metrics = spans1853
cache.metrics = spans1830
.iter()1854
.iter()1831
.filter_map(|span| {1855
.filter_map(|span| {1832
cache1856
cache1833
.widths1857
.sizes1834
.get(span.token())1858
.get(span.token())1835
.map(|width| (span.range(), *width))1859
.map(|token_size| InlineMetric {1860
range: span.range(),1861
width: token_size.width,1862
height: span.token().is_block().then_some(token_size.height),1863
})1836
})1864
})1837
.collect();1865
.collect();1838
cache.revision = revision;1866
cache.revision = revision;@@ -1867,8 +1895,10 @@ impl<M: InputModeKind> TextElement<M> {1867
None,1895
None,1868
)1896
)1869
.width;1897
.width;1870
width +=1898
width += cache1871
cache.widths.get(span.token()).copied().unwrap_or_default();1899
.sizes1900
.get(span.token())1901
.map_or(px(0.), |token_size| token_size.width);1872
offset = local.end;1902
offset = local.end;1873
}1903
}1874
let part = &text[offset..];1904
let part = &text[offset..];@@ -1892,7 +1922,7 @@ impl<M: InputModeKind> TextElement<M> {1892
state.display_map.set_inline_metrics(metrics, cx);1922
state.display_map.set_inline_metrics(metrics, cx);1893
if state.mode.is_auto_grow() {1923
if state.mode.is_auto_grow() {1894
let rows = state.mode.rows();1924
let rows = state.mode.rows();1895
state.mode.update_auto_grow(&state.display_map);1925
state.mode.update_auto_grow(&state.display_map, line_height);1896
if state.mode.rows() != rows {1926
if state.mode.rows() != rows {1897
cx.notify();1927
cx.notify();1898
}1928
}@@ -1934,6 +1964,7 @@ impl<M: InputModeKind> TextElement<M> {1934
let mut lines: SmallVec<[InputLine; 1]> = SmallVec::new();1964
let mut lines: SmallVec<[InputLine; 1]> = SmallVec::new();1935
for range in ranges {1965
for range in ranges {1936
let mut fragments = Vec::new();1966
let mut fragments = Vec::new();1967
let mut block_height = None;1937
let mut offset = range.start;1968
let mut offset = range.start;1938
let mut x = px(0.);1969
let mut x = px(0.);1939
let first =1970
let first =@@ -1960,7 +1991,11 @@ impl<M: InputModeKind> TextElement<M> {1960
});1991
});1961
x += width;1992
x += width;1962
}1993
}1963
let width = cache.widths.get(span.token()).copied().unwrap_or_default();1994
let token_size = cache.sizes.get(span.token()).copied().unwrap_or_default();1995
let width = token_size.width;1996
if span.token().is_block() && local == range {1997
block_height = Some(token_size.height);1998
}1964
fragments.push(InlineFragment {1999
fragments.push(InlineFragment {1965
range: local.start - range.start..local.end - range.start,2000
range: local.start - range.start..local.end - range.start,1966
x,2001
x,@@ -1986,7 +2021,10 @@ impl<M: InputModeKind> TextElement<M> {1986
text: Some(shaped),2021
text: Some(shaped),1987
});2022
});1988
}2023
}1989
lines.push(InputLine::inline(text[range].to_owned().into(), fragments));2024
lines.push(2025
InputLine::inline(text[range].to_owned().into(), fragments)2026
.with_height(block_height),2027
);1990
}2028
}1991
let indent = state.display_map.line(row).map_or(0, |line| line.indent);2029
let indent = state.display_map.line(row).map_or(0, |line| line.indent);1992
let wrap_indent = if indent > 0 && lines.len() > 1 {2030
let wrap_indent = if indent > 0 && lines.len() > 1 {@@ -2061,10 +2099,7 @@ impl<M: InputModeKind> TextElement<M> {2061
None => {2099
None => {2062
let mut element = self.token_element(&token, window, cx);2100
let mut element = self.token_element(&token, window, cx);2063
let element_size = element.layout_as_root(2101
let element_size = element.layout_as_root(2064
size(2102
Self::token_available_space(&token, layout.line_height),2065
gpui::AvailableSpace::MaxContent,2066
gpui::AvailableSpace::Definite(layout.line_height),2067
),2068
window,2103
window,2069
cx,2104
cx,2070
);2105
);@@ -2613,8 +2648,8 @@ impl<M: InputModeKind> Element for TextElement<M> {2613
style.flex_grow = 1.0;2648
style.flex_grow = 1.0;2614
style.size.height = relative(1.).into();2649
style.size.height = relative(1.).into();2615
// At least `rows` tall (auto grow: the content's rows, capped at2650
// At least `rows` tall (auto grow: the content's rows, capped at2616
// `max_rows`); a taller parent still fills it.2651
// `max_rows` plus the rows of block tokens); a taller parent still fills it.2617
let rows = state.mode.max_rows().min(state.mode.rows());2652
let rows = state.mode.rows();2618
style.min_size.height = (rows * line_height).into();2653
style.min_size.height = (rows * line_height).into();2619
} else {2654
} else {2620
// For single-line inputs, the minimum height should be the line height2655
// For single-line inputs, the minimum height should be the line height@@ -2923,7 +2958,6 @@ impl<M: InputModeKind> Element for TextElement<M> {2923
let ghost_line_count = ghost_lines.len();2958
let ghost_line_count = ghost_lines.len();2924
let ghost_lines_height = ghost_line_count as f32 * line_height;2959
let ghost_lines_height = ghost_line_count as f32 * line_height;2925
2960
2926
let total_wrapped_lines = state.display_map.wrap_row_count();2927
let empty_bottom_height = empty_bottom_height(2961
let empty_bottom_height = empty_bottom_height(2928
state.is_code_editor(),2962
state.is_code_editor(),2929
state.scroll_beyond_last_line,2963
state.scroll_beyond_last_line,@@ -2940,7 +2974,7 @@ impl<M: InputModeKind> Element for TextElement<M> {2940
} else {2974
} else {2941
longest_line_width2975
longest_line_width2942
},2976
},2943
(total_wrapped_lines as f32 * line_height2977
(state.display_map.content_height(line_height)2944
+ empty_bottom_height.max(ghost_lines_height))2978
+ empty_bottom_height.max(ghost_lines_height))2945
.max(bounds.size.height),2979
.max(bounds.size.height),2946
);2980
);@@ -3890,6 +3924,69 @@ mod tests {3890
});3924
});3891
}3925
}3892
3926
3927
#[cfg(target_os = "linux")]3928
#[test]3929
fn block_token_selection_and_block_decoration_span_the_row_height() {3930
use crate::input::{InlineToken, InlineTokenPresentation};3931
let platform = gpui_platform::current_platform(true);3932
let mut cx = TestAppContext::build_with_text_system(3933
gpui::TestDispatcher::new(0),3934
None,3935
platform.text_system(),3936
);3937
cx.update(crate::init);3938
let mut textarea = None;3939
let window = cx.open_window(size(px(400.), px(300.)), |window, cx| {3940
let state = cx.new(|cx| {3941
crate::input::TextareaState::new(window, cx)3942
.rows(4)3943
.default_value("ab[img]cd")3944
});3945
textarea = Some(state.clone());3946
TextareaHarness(state)3947
});3948
let textarea = textarea.unwrap();3949
let mut cx = VisualTestContext::from_window(window.into(), &mut cx);3950
cx.update(|window, cx| {3951
textarea.update(cx, |state, cx| {3952
state.set_token_presentation(3953
InlineTokenPresentation::default()3954
.token(|_, _, _| div().w(px(200.)).h(px(120.))),3955
);3956
state3957
.replace_range_with_token(3958
2..7,3959
InlineToken::new("img", "[img]").block(),3960
window,3961
cx,3962
)3963
.unwrap();3964
state.create_range_decorations_collection(3965
vec![RangeDecoration::new(0..0).with_style(RangeDecorationStyle::Block)],3966
cx,3967
);3968
});3969
window.draw(cx).clear(cx);3970
window.draw(cx).clear(cx);3971
let state = textarea.read(cx);3972
let layout = state.last_layout.as_ref().unwrap();3973
let line_height = layout.line_height;3974
let corners =3975
TextElement::<crate::input::TextareaMode>::layout_range_corners(&(2..7), layout)3976
.unwrap();3977
assert_eq!(corners.len(), 1);3978
assert_eq!(corners[0].top_left.y, layout.visible_top + line_height);3979
assert_eq!(corners[0].bottom_left.y - corners[0].top_left.y, px(120.));3980
assert_eq!(3981
(corners[0].top_left.x, corners[0].top_right.x),3982
(px(0.), px(200.))3983
);3984
let element = TextElement::new(textarea.clone());3985
let quads = element.layout_range_decoration_quads(layout, &state.input_bounds, cx);3986
assert_eq!(quads[0].bounds.size.height, line_height * 2. + px(120.));3987
});3988
}3989
3893
#[cfg(target_os = "linux")]3990
#[cfg(target_os = "linux")]3894
#[test]3991
#[test]3895
fn textarea_decorations_render_fill_and_wrap_like_the_editor() {3992
fn textarea_decorations_render_fill_and_wrap_like_the_editor() {@@ -13,6 +13,7 @@ pub struct InlineToken {
13
13
id: SharedString,
14
14
text: SharedString,
15
15
label: SharedString,
16
block: bool,
16
17
}
17
18
18
19
impl InlineToken {
@@ -22,12 +23,21 @@ impl InlineToken {
22
23
id: id.into(),
23
24
label: text.clone(),
24
25
text,
26
block: false,
25
27
}
26
28
}
27
29
pub fn with_label(mut self, label: impl Into<SharedString>) -> Self {
28
30
self.label = label.into();
29
31
self
30
32
}
33
/// Show the token alone on its own row, as tall as its rendered element.
34
pub fn block(mut self) -> Self {
35
self.block = true;
36
self
37
}
38
pub fn is_block(&self) -> bool {
39
self.block
40
}
31
41
pub fn id(&self) -> &SharedString {
32
42
&self.id
33
43
}
@@ -13,6 +13,7 @@ pub struct InlineToken {13
id: SharedString,13
id: SharedString,14
text: SharedString,14
text: SharedString,15
label: SharedString,15
label: SharedString,16
block: bool,16
}17
}17
18
18
impl InlineToken {19
impl InlineToken {@@ -22,12 +23,21 @@ impl InlineToken {22
id: id.into(),23
id: id.into(),23
label: text.clone(),24
label: text.clone(),24
text,25
text,26
block: false,25
}27
}26
}28
}27
pub fn with_label(mut self, label: impl Into<SharedString>) -> Self {29
pub fn with_label(mut self, label: impl Into<SharedString>) -> Self {28
self.label = label.into();30
self.label = label.into();29
self31
self30
}32
}33
/// Show the token alone on its own row, as tall as its rendered element.34
pub fn block(mut self) -> Self {35
self.block = true;36
self37
}38
pub fn is_block(&self) -> bool {39
self.block40
}31
pub fn id(&self) -> &SharedString {41
pub fn id(&self) -> &SharedString {32
&self.id42
&self.id33
}43
}@@ -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, Window};
5
use gpui::{Context, Pixels, Window};
6
6
use ropey::Rope;
7
7
8
8
use super::DisplayMap;
@@ -11,6 +11,8 @@ use crate::input::{
11
11
LanguageConfig, RopeExt as _, TabSize,
12
12
};
13
13
14
const BLOCK_GROWTH_FACTOR: usize = 2;
15
14
16
/// What changed, handed to the syntax highlighter.
15
17
pub(crate) struct HighlighterUpdate<'a> {
16
18
pub(super) selected_range: &'a Range<usize>,
@@ -219,17 +221,27 @@ impl LayoutMode {
219
221
}
220
222
}
221
223
222
/// Grow the row count to fit the content.
224
/// Grow the row count to fit the content. Block tokens add their height on top of
225
/// `max_rows`, up to `BLOCK_GROWTH_FACTOR` times it.
223
226
///
224
227
/// Callers gate this on the input being multi-line; a single-line field
225
228
/// keeps its one row. Only auto grow follows the content: in the other
226
229
/// modes `rows` is the configured height.
227
pub(super) fn update_auto_grow(&mut self, display_map: &DisplayMap) {
230
pub(super) fn update_auto_grow(&mut self, display_map: &DisplayMap, line_height: Pixels) {
228
231
if !self.is_auto_grow() {
229
232
return;
230
233
}
231
let wrapped_lines = display_map.wrap_row_count();
232
self.set_rows(wrapped_lines);
234
let content_rows = display_map.content_rows(line_height);
235
let block_rows = content_rows.saturating_sub(display_map.wrap_row_count());
236
if let LayoutMode::AutoGrow {
237
rows,
238
min_rows,
239
max_rows,
240
} = self
241
{
242
let cap = (*max_rows + block_rows).min(*max_rows * BLOCK_GROWTH_FACTOR);
243
*rows = content_rows.clamp(*min_rows, cap.max(*max_rows));
244
}
233
245
}
234
246
235
247
/// At least 1 row be return.
@@ -2,7 +2,7 @@ use crate::input::InputModeKind;2
use std::rc::Rc;2
use std::rc::Rc;3
use std::{cell::RefCell, ops::Range};3
use std::{cell::RefCell, ops::Range};4
4
5
use gpui::{Context, Window};5
use gpui::{Context, Pixels, Window};6
use ropey::Rope;6
use ropey::Rope;7
7
8
use super::DisplayMap;8
use super::DisplayMap;@@ -11,6 +11,8 @@ use crate::input::{11
LanguageConfig, RopeExt as _, TabSize,11
LanguageConfig, RopeExt as _, TabSize,12
};12
};13
13
14
const BLOCK_GROWTH_FACTOR: usize = 2;15
14
/// What changed, handed to the syntax highlighter.16
/// What changed, handed to the syntax highlighter.15
pub(crate) struct HighlighterUpdate<'a> {17
pub(crate) struct HighlighterUpdate<'a> {16
pub(super) selected_range: &'a Range<usize>,18
pub(super) selected_range: &'a Range<usize>,@@ -219,17 +221,27 @@ impl LayoutMode {219
}221
}220
}222
}221
223
222
/// Grow the row count to fit the content.224
/// Grow the row count to fit the content. Block tokens add their height on top of225
/// `max_rows`, up to `BLOCK_GROWTH_FACTOR` times it.223
///226
///224
/// Callers gate this on the input being multi-line; a single-line field227
/// Callers gate this on the input being multi-line; a single-line field225
/// keeps its one row. Only auto grow follows the content: in the other228
/// keeps its one row. Only auto grow follows the content: in the other226
/// modes `rows` is the configured height.229
/// modes `rows` is the configured height.227
pub(super) fn update_auto_grow(&mut self, display_map: &DisplayMap) {230
pub(super) fn update_auto_grow(&mut self, display_map: &DisplayMap, line_height: Pixels) {228
if !self.is_auto_grow() {231
if !self.is_auto_grow() {229
return;232
return;230
}233
}231
let wrapped_lines = display_map.wrap_row_count();234
let content_rows = display_map.content_rows(line_height);232
self.set_rows(wrapped_lines);235
let block_rows = content_rows.saturating_sub(display_map.wrap_row_count());236
if let LayoutMode::AutoGrow {237
rows,238
min_rows,239
max_rows,240
} = self241
{242
let cap = (*max_rows + block_rows).min(*max_rows * BLOCK_GROWTH_FACTOR);243
*rows = content_rows.clamp(*min_rows, cap.max(*max_rows));244
}233
}245
}234
246
235
/// At least 1 row be return.247
/// At least 1 row be return.@@ -155,7 +155,7 @@ impl<M: InputModeKind> InputBaseState<M> {
155
155
if let Some((x, line_end_affinity)) = line.closest_index_for_position(
156
156
Point {
157
157
x: preferred_x,
158
y: next_display_point.local_row * last_layout.line_height,
158
y: line.row_top(next_display_point.local_row, last_layout.line_height),
159
159
},
160
160
last_layout,
161
161
) {
@@ -155,7 +155,7 @@ impl<M: InputModeKind> InputBaseState<M> {155
if let Some((x, line_end_affinity)) = line.closest_index_for_position(155
if let Some((x, line_end_affinity)) = line.closest_index_for_position(156
Point {156
Point {157
x: preferred_x,157
x: preferred_x,158
y: next_display_point.local_row * last_layout.line_height,158
y: line.row_top(next_display_point.local_row, last_layout.line_height),159
},159
},160
last_layout,160
last_layout,161
) {161
) {@@ -927,7 +927,7 @@ impl<M: InputModeKind> InputBaseState<M> {
927
927
let prev_lines_offset = last_layout.visible_line_byte_offsets[vi];
928
928
let local_offset = offset.saturating_sub(prev_lines_offset);
929
929
if let Some(pos) = line.position_for_index(local_offset, last_layout, false) {
930
let sub_line_index = (pos.y / line_height) as usize;
930
let sub_line_index = line.row_at_y(pos.y, line_height).unwrap_or(0);
931
931
let adjusted_pos = point(pos.x + last_layout.line_number_width, pos.y + y_offset);
932
932
return (vi, sub_line_index, Some(adjusted_pos));
933
933
}
@@ -2574,7 +2574,8 @@ impl<M: InputModeKind> InputBaseState<M> {
2574
2574
let display_pos = self
2575
2575
.display_map
2576
2576
.buffer_pos_to_display_pos(crate::input::BufferPoint::new(row, point.column));
2577
let row_offset_y = line_height * display_pos.row;
2577
let row_offset_y = self.display_map.row_top(display_pos.row, line_height);
2578
let row_extra = self.display_map.row_height(display_pos.row, line_height) - line_height;
2578
2579
2579
2580
// For Right alignment use 0 margin: the cursor indicator is clamped inside bounds
2580
2581
// in layout_cursors, so shifting the text here would cause a first-click visual jump.
@@ -2620,9 +2621,9 @@ impl<M: InputModeKind> InputBaseState<M> {
2620
2621
if row_offset_y - edge_height + line_height < -scroll_offset.y {
2621
2622
// Scroll up
2622
2623
scroll_offset.y = -row_offset_y + edge_height - line_height;
2623
} else if row_offset_y + edge_height > -scroll_offset.y + bounds.size.height {
2624
} else if row_offset_y + row_extra + edge_height > -scroll_offset.y + bounds.size.height {
2624
2625
// Scroll down
2625
scroll_offset.y = -(row_offset_y - bounds.size.height + edge_height);
2626
scroll_offset.y = -(row_offset_y + row_extra - bounds.size.height + edge_height);
2626
2627
}
2627
2628
2628
2629
// Avoid necessary scroll, when it was already in the correct position.
@@ -3162,7 +3163,10 @@ impl<M: InputModeKind> InputBaseState<M> {
3162
3163
.zip(last_line_pos)
3163
3164
.zip(last_layout.visible_line_byte_offsets.last())
3164
3165
.map(|((line_layout, pos), line_start)| {
3165
let last_row_top = (line_layout.size(line_height).height - line_height).max(px(0.));
3166
let last_row_top = line_layout.row_top(
3167
line_layout.wrapped_lines.len().saturating_sub(1),
3168
line_height,
3169
);
3166
3170
let pos = point(pos.x, last_row_top);
3167
3171
(
3168
3172
self.resolve_index(line_start + line_layout.len()),
@@ -3625,7 +3629,8 @@ impl<M: InputModeKind> InputBaseState<M> {
3625
3629
3626
3630
self.display_map.on_layout_changed(wrap_width, cx);
3627
3631
if self.is_multi_line() {
3628
self.mode.update_auto_grow(&self.display_map);
3632
self.mode
3633
.update_auto_grow(&self.display_map, self.line_height().unwrap_or(px(1.)));
3629
3634
}
3630
3635
cx.notify();
3631
3636
}
@@ -3889,7 +3894,8 @@ impl<M: InputModeKind> InputBaseState<M> {
3889
3894
self.update_preferred_column();
3890
3895
self.dismiss_touch_selection(cx);
3891
3896
if self.is_multi_line() {
3892
self.mode.update_auto_grow(&self.display_map);
3897
self.mode
3898
.update_auto_grow(&self.display_map, self.line_height().unwrap_or(px(1.)));
3893
3899
}
3894
3900
if self.emit_events {
3895
3901
cx.emit(InputEvent::Change);
@@ -4213,7 +4219,8 @@ impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> {
4213
4219
self.update_search(cx);
4214
4220
self.dismiss_touch_selection(cx);
4215
4221
if self.is_multi_line() {
4216
self.mode.update_auto_grow(&self.display_map);
4222
self.mode
4223
.update_auto_grow(&self.display_map, self.line_height().unwrap_or(px(1.)));
4217
4224
}
4218
4225
if !self.silent_replace_text {
4219
4226
M::on_text_typed(self, &range, &new_text, window, cx);
@@ -4332,7 +4339,8 @@ impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> {
4332
4339
self.set_selection(new_range.start, new_range.end);
4333
4340
}
4334
4341
if self.is_multi_line() {
4335
self.mode.update_auto_grow(&self.display_map);
4342
self.mode
4343
.update_auto_grow(&self.display_map, self.line_height().unwrap_or(px(1.)));
4336
4344
}
4337
4345
if self.push_history(
4338
4346
&old_text,
@@ -4369,6 +4377,7 @@ impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> {
4369
4377
let range = self.range_from_utf16(&range_utf16);
4370
4378
4371
4379
let mut start_origin = None;
4380
let mut start_height = line_height;
4372
4381
let mut end_origin = None;
4373
4382
let line_number_origin = point(line_number_width, px(0.));
4374
4383
let mut y_offset = last_layout.visible_top;
@@ -4387,6 +4396,9 @@ impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> {
4387
4396
false,
4388
4397
) {
4389
4398
start_origin = Some(p + point(px(0.), y_offset));
4399
start_height = line
4400
.row_at_y(p.y, line_height)
4401
.map_or(line_height, |ix| line.row_height(ix, line_height));
4390
4402
}
4391
4403
}
4392
4404
@@ -4414,8 +4426,8 @@ impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> {
4414
4426
4415
4427
Some(Bounds::from_corners(
4416
4428
bounds.origin + line_number_origin + start_origin,
4417
// + line_height for show IME panel under the cursor line.
4418
bounds.origin + line_number_origin + point(end_origin.x, end_origin.y + line_height),
4429
// + row height for show IME panel under the cursor line.
4430
bounds.origin + line_number_origin + point(end_origin.x, end_origin.y + start_height),
4419
4431
))
4420
4432
}
4421
4433
@@ -4724,6 +4736,331 @@ mod tests {
4724
4736
});
4725
4737
}
4726
4738
4739
fn build_block_view(
4740
cx: &mut TestAppContext,
4741
value: &'static str,
4742
token_range: Range<usize>,
4743
) -> (InputView<TextareaMode>, VisualTestContext) {
4744
use crate::input::{InlineToken, InlineTokenPresentation};
4745
let view =
4746
InputView::build_textarea(cx, move |state| state.auto_grow(1, 40).default_value(value));
4747
view.window_handle
4748
.update(cx, |_, window, cx| {
4749
view.input.update(cx, |state, cx| {
4750
state.set_token_presentation(
4751
InlineTokenPresentation::default()
4752
.token(|_, _, _| div().w(px(200.)).h(px(120.))),
4753
);
4754
state
4755
.replace_range_with_token(
4756
token_range,
4757
InlineToken::new("img", "[img]").block(),
4758
window,
4759
cx,
4760
)
4761
.unwrap();
4762
});
4763
})
4764
.unwrap();
4765
let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
4766
visual.update(|window, cx| window.draw(cx).clear(cx));
4767
visual.update(|window, cx| window.draw(cx).clear(cx));
4768
(view, visual)
4769
}
4770
4771
#[gpui::test]
4772
fn test_block_token_row_height_feeds_row_top_and_auto_grow(cx: &mut TestAppContext) {
4773
let (view, visual) = build_block_view(cx, "ab[img]cd", 2..7);
4774
view.input.read_with(&visual, |state, _| {
4775
let line_height = state.line_height().unwrap();
4776
assert_eq!(
4777
state.display_map.line(0).unwrap().wrapped_lines.as_slice(),
4778
[0..2, 2..7, 7..9]
4779
);
4780
assert_eq!(
4781
state.display_map.row_top(2, line_height),
4782
line_height + px(120.)
4783
);
4784
assert_eq!(
4785
state.display_map.content_height(line_height),
4786
line_height * 2. + px(120.)
4787
);
4788
assert_eq!(state.display_map.row_at_y(px(119.), line_height), 1);
4789
assert_eq!(state.display_map.row_at_y(px(1000.), line_height), 2);
4790
assert!(state.mode.rows() > state.display_map.wrap_row_count());
4791
assert_eq!(
4792
state.mode.rows(),
4793
state.display_map.content_rows(line_height)
4794
);
4795
});
4796
}
4797
4798
struct GrowingRoot(Entity<InputBaseState<TextareaMode>>);
4799
4800
impl Render for GrowingRoot {
4801
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4802
div()
4803
.flex()
4804
.items_end()
4805
.child(div().w(px(600.)).child(self.0.clone()))
4806
}
4807
}
4808
4809
fn build_growing_view(
4810
cx: &mut TestAppContext,
4811
max_rows: usize,
4812
) -> (Entity<InputBaseState<TextareaMode>>, VisualTestContext) {
4813
use crate::input::InlineTokenPresentation;
4814
let mut input = None;
4815
let window = cx.update(|cx| {
4816
cx.open_window(Default::default(), |window, cx| {
4817
cx.set_global(Theme::default());
4818
super::super::init(cx);
4819
let state = cx.new(|cx| {
4820
let mut state =
4821
crate::input::TextareaState::new(window, cx).auto_grow(1, max_rows);
4822
state.set_token_presentation(
4823
InlineTokenPresentation::default()
4824
.token(|_, _, _| div().w(px(200.)).h(px(120.))),
4825
);
4826
state
4827
});
4828
input = Some(state.clone());
4829
cx.new(|_| GrowingRoot(state))
4830
})
4831
.unwrap()
4832
});
4833
let mut visual = VisualTestContext::from_window(window.into(), cx);
4834
visual.update(|window, cx| window.draw(cx).clear(cx));
4835
(input.unwrap(), visual)
4836
}
4837
4838
fn draw_twice(visual: &mut VisualTestContext) {
4839
visual.update(|window, cx| window.draw(cx).clear(cx));
4840
visual.update(|window, cx| window.draw(cx).clear(cx));
4841
}
4842
4843
fn load_block_content(
4844
input: &Entity<InputBaseState<TextareaMode>>,
4845
visual: &mut VisualTestContext,
4846
before: &str,
4847
after: &str,
4848
) {
4849
use crate::input::InlineToken;
4850
let before = before.to_owned();
4851
let after = after.to_owned();
4852
visual.update(|window, cx| {
4853
input.update(cx, |state, cx| {
4854
let text = format!("{before}[img]{after}");
4855
let range = before.len()..before.len() + 5;
4856
let content = crate::input::InputContent::new(text.clone())
4857
.with_token(range, InlineToken::new("img", "[img]").block())
4858
.unwrap();
4859
state.set_value(content, window, cx);
4860
state.set_selected_range(text.len()..text.len(), cx);
4861
})
4862
});
4863
draw_twice(visual);
4864
}
4865
4866
fn assert_cursor_row_in_view(
4867
input: &Entity<InputBaseState<TextareaMode>>,
4868
visual: &VisualTestContext,
4869
) {
4870
input.read_with(visual, |state, _| {
4871
let line_height = state.line_height().unwrap();
4872
let content = state.display_map.content_height(line_height);
4873
let viewport = state.input_bounds.size.height;
4874
assert!(
4875
content > viewport,
4876
"content {content:?} viewport {viewport:?}"
4877
);
4878
assert_eq!(state.scroll_handle.offset().y, viewport - content);
4879
});
4880
}
4881
4882
#[gpui::test]
4883
fn test_typing_after_a_block_token_scrolls_the_cursor_row_into_view(cx: &mut TestAppContext) {
4884
let (input, mut visual) = build_growing_view(cx, 4);
4885
load_block_content(
4886
&input,
4887
&mut visual,
4888
"ab\ncd\nef\ngh\nij\nkl\nmn\nop\nqr\n",
4889
"",
4890
);
4891
for character in ["x", "y"] {
4892
visual.update(|window, cx| {
4893
input.update(cx, |state, cx| state.insert(character, window, cx))
4894
});
4895
}
4896
draw_twice(&mut visual);
4897
assert_cursor_row_in_view(&input, &visual);
4898
}
4899
4900
#[gpui::test]
4901
fn test_loading_content_with_a_block_token_scrolls_the_cursor_row_into_view(
4902
cx: &mut TestAppContext,
4903
) {
4904
let (input, mut visual) = build_growing_view(cx, 4);
4905
load_block_content(
4906
&input,
4907
&mut visual,
4908
"ab\ncd\nef\ngh\nij\nkl\nmn\nop\nqr\n",
4909
"cd",
4910
);
4911
assert_cursor_row_in_view(&input, &visual);
4912
}
4913
4914
#[gpui::test]
4915
fn test_block_tokens_add_their_rows_on_top_of_max_rows_up_to_twice_of_it(
4916
cx: &mut TestAppContext,
4917
) {
4918
let (input, mut visual) = build_growing_view(cx, 4);
4919
load_block_content(&input, &mut visual, "ab", "cd");
4920
let rows_with_one_image = input.read_with(&visual, |state, _| state.mode.rows());
4921
assert!(rows_with_one_image > 4, "{rows_with_one_image}");
4922
input.read_with(&visual, |state, _| {
4923
let line_height = state.line_height().unwrap();
4924
assert_eq!(
4925
state.input_bounds.size.height,
4926
line_height * rows_with_one_image as f32
4927
);
4928
assert!(
4929
state.display_map.content_height(line_height) <= state.input_bounds.size.height
4930
);
4931
});
4932
load_block_content(
4933
&input,
4934
&mut visual,
4935
"ab\ncd\nef\ngh\nij\nkl\nmn\nop\nqr\n",
4936
"cd",
4937
);
4938
assert_eq!(input.read_with(&visual, |state, _| state.mode.rows()), 8);
4939
}
4940
4941
#[gpui::test]
4942
fn test_block_token_caret_spans_the_row(cx: &mut TestAppContext) {
4943
let (view, mut visual) = build_block_view(cx, "ab[img]cd", 2..7);
4944
view.input.read_with(&visual, |state, _| {
4945
let line_height = state.line_height().unwrap();
4946
let layout = state.last_layout.as_ref().unwrap();
4947
let line = &layout.lines[0];
4948
let before = line.position_for_index(2, layout, false).unwrap();
4949
let after = line.position_for_index(7, layout, true).unwrap();
4950
assert_eq!((before.x, after.x), (px(0.), px(200.)));
4951
assert_eq!(before.y, line.row_top(1, line_height));
4952
assert_eq!(after.y, before.y);
4953
});
4954
view.input
4955
.update(&mut visual, |state, cx| state.set_selected_range(2..2, cx));
4956
visual.update(|window, cx| window.draw(cx).clear(cx));
4957
let before = view
4958
.input
4959
.read_with(&visual, |state, _| state.cursor_layout().unwrap().0);
4960
assert_eq!(before.size.height, px(120.));
4961
view.input.update(&mut visual, |state, cx| {
4962
state.set_selected_range(7..7, cx);
4963
state.cursor_line_end_affinity = true;
4964
});
4965
visual.update(|window, cx| window.draw(cx).clear(cx));
4966
let after = view
4967
.input
4968
.read_with(&visual, |state, _| state.cursor_layout().unwrap().0);
4969
assert_eq!(after.size.height, px(120.));
4970
assert_eq!(after.origin.y, before.origin.y);
4971
assert_eq!(after.origin.x - before.origin.x, px(200.));
4972
}
4973
4974
#[gpui::test]
4975
fn test_block_token_click_beside_the_image_lands_on_its_edge(cx: &mut TestAppContext) {
4976
let (view, visual) = build_block_view(cx, "ab[img]cd", 2..7);
4977
view.input.read_with(&visual, |state, _| {
4978
let line_height = state.line_height().unwrap();
4979
let bounds = state.last_bounds.unwrap();
4980
let layout = state.last_layout.as_ref().unwrap();
4981
let row_top = layout.visible_top + layout.lines[0].row_top(1, line_height);
4982
let at =
4983
|x: f32| bounds.origin + point(layout.line_number_width + px(x), row_top + px(60.));
4984
assert_eq!(state.resolve_mouse_position(at(500.)).0, 7);
4985
assert_eq!(state.resolve_mouse_position(at(150.)).0, 7);
4986
assert_eq!(state.resolve_mouse_position(at(10.)).0, 2);
4987
});
4988
}
4989
4990
#[gpui::test]
4991
fn test_block_token_vertical_movement_visits_its_row(cx: &mut TestAppContext) {
4992
let (view, mut visual) = build_block_view(cx, "ab[img]cd", 2..7);
4993
let row = |view: &InputView<TextareaMode>, visual: &VisualTestContext| {
4994
view.input.read_with(visual, |state, _| {
4995
state
4996
.display_map
4997
.offset_to_wrap_display_point_with_affinity(
4998
state.cursor(),
4999
state.cursor_line_end_affinity,
5000
)
5001
.row
5002
})
5003
};
5004
view.input
5005
.update(&mut visual, |state, _| state.set_cursor_to(0));
5006
for expected_row in [1, 2] {
5007
visual.update(|window, cx| {
5008
view.input
5009
.update(cx, |state, cx| state.down(&MoveDown, window, cx))
5010
});
5011
assert_eq!(row(&view, &visual), expected_row);
5012
}
5013
for expected_row in [1, 0] {
5014
visual.update(|window, cx| {
5015
view.input
5016
.update(cx, |state, cx| state.up(&MoveUp, window, cx))
5017
});
5018
assert_eq!(row(&view, &visual), expected_row);
5019
}
5020
}
5021
5022
#[gpui::test]
5023
fn test_block_token_scroll_to_brings_its_rows_into_view(cx: &mut TestAppContext) {
5024
let value: &'static str =
5025
Box::leak(format!("{}[img]cd", "x\n".repeat(60)).into_boxed_str());
5026
let token_start = 120;
5027
let (view, mut visual) = build_block_view(cx, value, token_start..token_start + 5);
5028
for (offset, row) in [(token_start, 60), (token_start + 5, 61)] {
5029
view.input.update(&mut visual, |state, cx| {
5030
state.scroll_to(offset, None, cx);
5031
let line_height = state.line_height().unwrap();
5032
let scrolled = -state.deferred_scroll_offset.unwrap().y;
5033
let top = state.display_map.row_top(row, line_height);
5034
let height = state.display_map.row_height(row, line_height);
5035
assert!(top >= scrolled, "row {row} top is above the viewport");
5036
assert!(
5037
top + height <= scrolled + state.input_bounds.size.height,
5038
"row {row} bottom is below the viewport"
5039
);
5040
});
5041
}
5042
}
5043
5044
#[gpui::test]
5045
fn test_block_token_undo_restores_uniform_rows(cx: &mut TestAppContext) {
5046
let (view, mut visual) = build_block_view(cx, "ab[img]cd", 2..7);
5047
visual.update(|window, cx| {
5048
view.input
5049
.update(cx, |state, cx| state.undo(&Undo, window, cx))
5050
});
5051
visual.update(|window, cx| window.draw(cx).clear(cx));
5052
view.input.read_with(&visual, |state, _| {
5053
let line_height = state.line_height().unwrap();
5054
assert!(state.tokens().is_empty());
5055
assert!(state.display_map.line(0).unwrap().blocks.is_empty());
5056
assert_eq!(
5057
state.display_map.content_height(line_height),
5058
line_height * state.display_map.wrap_row_count() as f32
5059
);
5060
assert_eq!(state.mode.rows(), state.display_map.wrap_row_count());
5061
});
5062
}
5063
4727
5064
#[gpui::test]
4728
5065
fn test_inline_token_geometry_and_reentrant_activation(cx: &mut TestAppContext) {
4729
5066
use crate::input::{InlineToken, InlineTokenPresentation};
@@ -8830,8 +9167,9 @@ mod tests {
8830
9167
let view = InputView::build_textarea(cx, move |state| state.rows(4).default_value(text));
8831
9168
let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
8832
9169
visual.update(|_, cx| {
8833
view.input
8834
.update(cx, |state, cx| state.set_line_indents(vec![(0, px(10.))], cx))
9170
view.input.update(cx, |state, cx| {
9171
state.set_line_indents(vec![(0, px(10.))], cx)
9172
})
8835
9173
});
8836
9174
visual.update(|window, cx| window.draw(cx).clear(cx));
8837
9175
view.input.read_with(&visual, |state, _| {
@@ -927,7 +927,7 @@ impl<M: InputModeKind> InputBaseState<M> {927
let prev_lines_offset = last_layout.visible_line_byte_offsets[vi];927
let prev_lines_offset = last_layout.visible_line_byte_offsets[vi];928
let local_offset = offset.saturating_sub(prev_lines_offset);928
let local_offset = offset.saturating_sub(prev_lines_offset);929
if let Some(pos) = line.position_for_index(local_offset, last_layout, false) {929
if let Some(pos) = line.position_for_index(local_offset, last_layout, false) {930
let sub_line_index = (pos.y / line_height) as usize;930
let sub_line_index = line.row_at_y(pos.y, line_height).unwrap_or(0);931
let adjusted_pos = point(pos.x + last_layout.line_number_width, pos.y + y_offset);931
let adjusted_pos = point(pos.x + last_layout.line_number_width, pos.y + y_offset);932
return (vi, sub_line_index, Some(adjusted_pos));932
return (vi, sub_line_index, Some(adjusted_pos));933
}933
}@@ -2574,7 +2574,8 @@ impl<M: InputModeKind> InputBaseState<M> {2574
let display_pos = self2574
let display_pos = self2575
.display_map2575
.display_map2576
.buffer_pos_to_display_pos(crate::input::BufferPoint::new(row, point.column));2576
.buffer_pos_to_display_pos(crate::input::BufferPoint::new(row, point.column));2577
let row_offset_y = line_height * display_pos.row;2577
let row_offset_y = self.display_map.row_top(display_pos.row, line_height);2578
let row_extra = self.display_map.row_height(display_pos.row, line_height) - line_height;2578
2579
2579
// For Right alignment use 0 margin: the cursor indicator is clamped inside bounds2580
// For Right alignment use 0 margin: the cursor indicator is clamped inside bounds2580
// in layout_cursors, so shifting the text here would cause a first-click visual jump.2581
// in layout_cursors, so shifting the text here would cause a first-click visual jump.@@ -2620,9 +2621,9 @@ impl<M: InputModeKind> InputBaseState<M> {2620
if row_offset_y - edge_height + line_height < -scroll_offset.y {2621
if row_offset_y - edge_height + line_height < -scroll_offset.y {2621
// Scroll up2622
// Scroll up2622
scroll_offset.y = -row_offset_y + edge_height - line_height;2623
scroll_offset.y = -row_offset_y + edge_height - line_height;2623
} else if row_offset_y + edge_height > -scroll_offset.y + bounds.size.height {2624
} else if row_offset_y + row_extra + edge_height > -scroll_offset.y + bounds.size.height {2624
// Scroll down2625
// Scroll down2625
scroll_offset.y = -(row_offset_y - bounds.size.height + edge_height);2626
scroll_offset.y = -(row_offset_y + row_extra - bounds.size.height + edge_height);2626
}2627
}2627
2628
2628
// Avoid necessary scroll, when it was already in the correct position.2629
// Avoid necessary scroll, when it was already in the correct position.@@ -3162,7 +3163,10 @@ impl<M: InputModeKind> InputBaseState<M> {3162
.zip(last_line_pos)3163
.zip(last_line_pos)3163
.zip(last_layout.visible_line_byte_offsets.last())3164
.zip(last_layout.visible_line_byte_offsets.last())3164
.map(|((line_layout, pos), line_start)| {3165
.map(|((line_layout, pos), line_start)| {3165
let last_row_top = (line_layout.size(line_height).height - line_height).max(px(0.));3166
let last_row_top = line_layout.row_top(3167
line_layout.wrapped_lines.len().saturating_sub(1),3168
line_height,3169
);3166
let pos = point(pos.x, last_row_top);3170
let pos = point(pos.x, last_row_top);3167
(3171
(3168
self.resolve_index(line_start + line_layout.len()),3172
self.resolve_index(line_start + line_layout.len()),@@ -3625,7 +3629,8 @@ impl<M: InputModeKind> InputBaseState<M> {3625
3629
3626
self.display_map.on_layout_changed(wrap_width, cx);3630
self.display_map.on_layout_changed(wrap_width, cx);3627
if self.is_multi_line() {3631
if self.is_multi_line() {3628
self.mode.update_auto_grow(&self.display_map);3632
self.mode3633
.update_auto_grow(&self.display_map, self.line_height().unwrap_or(px(1.)));3629
}3634
}3630
cx.notify();3635
cx.notify();3631
}3636
}@@ -3889,7 +3894,8 @@ impl<M: InputModeKind> InputBaseState<M> {3889
self.update_preferred_column();3894
self.update_preferred_column();3890
self.dismiss_touch_selection(cx);3895
self.dismiss_touch_selection(cx);3891
if self.is_multi_line() {3896
if self.is_multi_line() {3892
self.mode.update_auto_grow(&self.display_map);3897
self.mode3898
.update_auto_grow(&self.display_map, self.line_height().unwrap_or(px(1.)));3893
}3899
}3894
if self.emit_events {3900
if self.emit_events {3895
cx.emit(InputEvent::Change);3901
cx.emit(InputEvent::Change);@@ -4213,7 +4219,8 @@ impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> {4213
self.update_search(cx);4219
self.update_search(cx);4214
self.dismiss_touch_selection(cx);4220
self.dismiss_touch_selection(cx);4215
if self.is_multi_line() {4221
if self.is_multi_line() {4216
self.mode.update_auto_grow(&self.display_map);4222
self.mode4223
.update_auto_grow(&self.display_map, self.line_height().unwrap_or(px(1.)));4217
}4224
}4218
if !self.silent_replace_text {4225
if !self.silent_replace_text {4219
M::on_text_typed(self, &range, &new_text, window, cx);4226
M::on_text_typed(self, &range, &new_text, window, cx);@@ -4332,7 +4339,8 @@ impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> {4332
self.set_selection(new_range.start, new_range.end);4339
self.set_selection(new_range.start, new_range.end);4333
}4340
}4334
if self.is_multi_line() {4341
if self.is_multi_line() {4335
self.mode.update_auto_grow(&self.display_map);4342
self.mode4343
.update_auto_grow(&self.display_map, self.line_height().unwrap_or(px(1.)));4336
}4344
}4337
if self.push_history(4345
if self.push_history(4338
&old_text,4346
&old_text,@@ -4369,6 +4377,7 @@ impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> {4369
let range = self.range_from_utf16(&range_utf16);4377
let range = self.range_from_utf16(&range_utf16);4370
4378
4371
let mut start_origin = None;4379
let mut start_origin = None;4380
let mut start_height = line_height;4372
let mut end_origin = None;4381
let mut end_origin = None;4373
let line_number_origin = point(line_number_width, px(0.));4382
let line_number_origin = point(line_number_width, px(0.));4374
let mut y_offset = last_layout.visible_top;4383
let mut y_offset = last_layout.visible_top;@@ -4387,6 +4396,9 @@ impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> {4387
false,4396
false,4388
) {4397
) {4389
start_origin = Some(p + point(px(0.), y_offset));4398
start_origin = Some(p + point(px(0.), y_offset));4399
start_height = line4400
.row_at_y(p.y, line_height)4401
.map_or(line_height, |ix| line.row_height(ix, line_height));4390
}4402
}4391
}4403
}4392
4404
@@ -4414,8 +4426,8 @@ impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> {4414
4426
4415
Some(Bounds::from_corners(4427
Some(Bounds::from_corners(4416
bounds.origin + line_number_origin + start_origin,4428
bounds.origin + line_number_origin + start_origin,4417
// + line_height for show IME panel under the cursor line.4429
// + row height for show IME panel under the cursor line.4418
bounds.origin + line_number_origin + point(end_origin.x, end_origin.y + line_height),4430
bounds.origin + line_number_origin + point(end_origin.x, end_origin.y + start_height),4419
))4431
))4420
}4432
}4421
4433
@@ -4724,6 +4736,331 @@ mod tests {4724
});4736
});4725
}4737
}4726
4738
4739
fn build_block_view(4740
cx: &mut TestAppContext,4741
value: &'static str,4742
token_range: Range<usize>,4743
) -> (InputView<TextareaMode>, VisualTestContext) {4744
use crate::input::{InlineToken, InlineTokenPresentation};4745
let view =4746
InputView::build_textarea(cx, move |state| state.auto_grow(1, 40).default_value(value));4747
view.window_handle4748
.update(cx, |_, window, cx| {4749
view.input.update(cx, |state, cx| {4750
state.set_token_presentation(4751
InlineTokenPresentation::default()4752
.token(|_, _, _| div().w(px(200.)).h(px(120.))),4753
);4754
state4755
.replace_range_with_token(4756
token_range,4757
InlineToken::new("img", "[img]").block(),4758
window,4759
cx,4760
)4761
.unwrap();4762
});4763
})4764
.unwrap();4765
let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);4766
visual.update(|window, cx| window.draw(cx).clear(cx));4767
visual.update(|window, cx| window.draw(cx).clear(cx));4768
(view, visual)4769
}4770
4771
#[gpui::test]4772
fn test_block_token_row_height_feeds_row_top_and_auto_grow(cx: &mut TestAppContext) {4773
let (view, visual) = build_block_view(cx, "ab[img]cd", 2..7);4774
view.input.read_with(&visual, |state, _| {4775
let line_height = state.line_height().unwrap();4776
assert_eq!(4777
state.display_map.line(0).unwrap().wrapped_lines.as_slice(),4778
[0..2, 2..7, 7..9]4779
);4780
assert_eq!(4781
state.display_map.row_top(2, line_height),4782
line_height + px(120.)4783
);4784
assert_eq!(4785
state.display_map.content_height(line_height),4786
line_height * 2. + px(120.)4787
);4788
assert_eq!(state.display_map.row_at_y(px(119.), line_height), 1);4789
assert_eq!(state.display_map.row_at_y(px(1000.), line_height), 2);4790
assert!(state.mode.rows() > state.display_map.wrap_row_count());4791
assert_eq!(4792
state.mode.rows(),4793
state.display_map.content_rows(line_height)4794
);4795
});4796
}4797
4798
struct GrowingRoot(Entity<InputBaseState<TextareaMode>>);4799
4800
impl Render for GrowingRoot {4801
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {4802
div()4803
.flex()4804
.items_end()4805
.child(div().w(px(600.)).child(self.0.clone()))4806
}4807
}4808
4809
fn build_growing_view(4810
cx: &mut TestAppContext,4811
max_rows: usize,4812
) -> (Entity<InputBaseState<TextareaMode>>, VisualTestContext) {4813
use crate::input::InlineTokenPresentation;4814
let mut input = None;4815
let window = cx.update(|cx| {4816
cx.open_window(Default::default(), |window, cx| {4817
cx.set_global(Theme::default());4818
super::super::init(cx);4819
let state = cx.new(|cx| {4820
let mut state =4821
crate::input::TextareaState::new(window, cx).auto_grow(1, max_rows);4822
state.set_token_presentation(4823
InlineTokenPresentation::default()4824
.token(|_, _, _| div().w(px(200.)).h(px(120.))),4825
);4826
state4827
});4828
input = Some(state.clone());4829
cx.new(|_| GrowingRoot(state))4830
})4831
.unwrap()4832
});4833
let mut visual = VisualTestContext::from_window(window.into(), cx);4834
visual.update(|window, cx| window.draw(cx).clear(cx));4835
(input.unwrap(), visual)4836
}4837
4838
fn draw_twice(visual: &mut VisualTestContext) {4839
visual.update(|window, cx| window.draw(cx).clear(cx));4840
visual.update(|window, cx| window.draw(cx).clear(cx));4841
}4842
4843
fn load_block_content(4844
input: &Entity<InputBaseState<TextareaMode>>,4845
visual: &mut VisualTestContext,4846
before: &str,4847
after: &str,4848
) {4849
use crate::input::InlineToken;4850
let before = before.to_owned();4851
let after = after.to_owned();4852
visual.update(|window, cx| {4853
input.update(cx, |state, cx| {4854
let text = format!("{before}[img]{after}");4855
let range = before.len()..before.len() + 5;4856
let content = crate::input::InputContent::new(text.clone())4857
.with_token(range, InlineToken::new("img", "[img]").block())4858
.unwrap();4859
state.set_value(content, window, cx);4860
state.set_selected_range(text.len()..text.len(), cx);4861
})4862
});4863
draw_twice(visual);4864
}4865
4866
fn assert_cursor_row_in_view(4867
input: &Entity<InputBaseState<TextareaMode>>,4868
visual: &VisualTestContext,4869
) {4870
input.read_with(visual, |state, _| {4871
let line_height = state.line_height().unwrap();4872
let content = state.display_map.content_height(line_height);4873
let viewport = state.input_bounds.size.height;4874
assert!(4875
content > viewport,4876
"content {content:?} viewport {viewport:?}"4877
);4878
assert_eq!(state.scroll_handle.offset().y, viewport - content);4879
});4880
}4881
4882
#[gpui::test]4883
fn test_typing_after_a_block_token_scrolls_the_cursor_row_into_view(cx: &mut TestAppContext) {4884
let (input, mut visual) = build_growing_view(cx, 4);4885
load_block_content(4886
&input,4887
&mut visual,4888
"ab\ncd\nef\ngh\nij\nkl\nmn\nop\nqr\n",4889
"",4890
);4891
for character in ["x", "y"] {4892
visual.update(|window, cx| {4893
input.update(cx, |state, cx| state.insert(character, window, cx))4894
});4895
}4896
draw_twice(&mut visual);4897
assert_cursor_row_in_view(&input, &visual);4898
}4899
4900
#[gpui::test]4901
fn test_loading_content_with_a_block_token_scrolls_the_cursor_row_into_view(4902
cx: &mut TestAppContext,4903
) {4904
let (input, mut visual) = build_growing_view(cx, 4);4905
load_block_content(4906
&input,4907
&mut visual,4908
"ab\ncd\nef\ngh\nij\nkl\nmn\nop\nqr\n",4909
"cd",4910
);4911
assert_cursor_row_in_view(&input, &visual);4912
}4913
4914
#[gpui::test]4915
fn test_block_tokens_add_their_rows_on_top_of_max_rows_up_to_twice_of_it(4916
cx: &mut TestAppContext,4917
) {4918
let (input, mut visual) = build_growing_view(cx, 4);4919
load_block_content(&input, &mut visual, "ab", "cd");4920
let rows_with_one_image = input.read_with(&visual, |state, _| state.mode.rows());4921
assert!(rows_with_one_image > 4, "{rows_with_one_image}");4922
input.read_with(&visual, |state, _| {4923
let line_height = state.line_height().unwrap();4924
assert_eq!(4925
state.input_bounds.size.height,4926
line_height * rows_with_one_image as f324927
);4928
assert!(4929
state.display_map.content_height(line_height) <= state.input_bounds.size.height4930
);4931
});4932
load_block_content(4933
&input,4934
&mut visual,4935
"ab\ncd\nef\ngh\nij\nkl\nmn\nop\nqr\n",4936
"cd",4937
);4938
assert_eq!(input.read_with(&visual, |state, _| state.mode.rows()), 8);4939
}4940
4941
#[gpui::test]4942
fn test_block_token_caret_spans_the_row(cx: &mut TestAppContext) {4943
let (view, mut visual) = build_block_view(cx, "ab[img]cd", 2..7);4944
view.input.read_with(&visual, |state, _| {4945
let line_height = state.line_height().unwrap();4946
let layout = state.last_layout.as_ref().unwrap();4947
let line = &layout.lines[0];4948
let before = line.position_for_index(2, layout, false).unwrap();4949
let after = line.position_for_index(7, layout, true).unwrap();4950
assert_eq!((before.x, after.x), (px(0.), px(200.)));4951
assert_eq!(before.y, line.row_top(1, line_height));4952
assert_eq!(after.y, before.y);4953
});4954
view.input4955
.update(&mut visual, |state, cx| state.set_selected_range(2..2, cx));4956
visual.update(|window, cx| window.draw(cx).clear(cx));4957
let before = view4958
.input4959
.read_with(&visual, |state, _| state.cursor_layout().unwrap().0);4960
assert_eq!(before.size.height, px(120.));4961
view.input.update(&mut visual, |state, cx| {4962
state.set_selected_range(7..7, cx);4963
state.cursor_line_end_affinity = true;4964
});4965
visual.update(|window, cx| window.draw(cx).clear(cx));4966
let after = view4967
.input4968
.read_with(&visual, |state, _| state.cursor_layout().unwrap().0);4969
assert_eq!(after.size.height, px(120.));4970
assert_eq!(after.origin.y, before.origin.y);4971
assert_eq!(after.origin.x - before.origin.x, px(200.));4972
}4973
4974
#[gpui::test]4975
fn test_block_token_click_beside_the_image_lands_on_its_edge(cx: &mut TestAppContext) {4976
let (view, visual) = build_block_view(cx, "ab[img]cd", 2..7);4977
view.input.read_with(&visual, |state, _| {4978
let line_height = state.line_height().unwrap();4979
let bounds = state.last_bounds.unwrap();4980
let layout = state.last_layout.as_ref().unwrap();4981
let row_top = layout.visible_top + layout.lines[0].row_top(1, line_height);4982
let at =4983
|x: f32| bounds.origin + point(layout.line_number_width + px(x), row_top + px(60.));4984
assert_eq!(state.resolve_mouse_position(at(500.)).0, 7);4985
assert_eq!(state.resolve_mouse_position(at(150.)).0, 7);4986
assert_eq!(state.resolve_mouse_position(at(10.)).0, 2);4987
});4988
}4989
4990
#[gpui::test]4991
fn test_block_token_vertical_movement_visits_its_row(cx: &mut TestAppContext) {4992
let (view, mut visual) = build_block_view(cx, "ab[img]cd", 2..7);4993
let row = |view: &InputView<TextareaMode>, visual: &VisualTestContext| {4994
view.input.read_with(visual, |state, _| {4995
state4996
.display_map4997
.offset_to_wrap_display_point_with_affinity(4998
state.cursor(),4999
state.cursor_line_end_affinity,5000
)5001
.row5002
})5003
};5004
view.input5005
.update(&mut visual, |state, _| state.set_cursor_to(0));5006
for expected_row in [1, 2] {5007
visual.update(|window, cx| {5008
view.input5009
.update(cx, |state, cx| state.down(&MoveDown, window, cx))5010
});5011
assert_eq!(row(&view, &visual), expected_row);5012
}5013
for expected_row in [1, 0] {5014
visual.update(|window, cx| {5015
view.input5016
.update(cx, |state, cx| state.up(&MoveUp, window, cx))5017
});5018
assert_eq!(row(&view, &visual), expected_row);5019
}5020
}5021
5022
#[gpui::test]5023
fn test_block_token_scroll_to_brings_its_rows_into_view(cx: &mut TestAppContext) {5024
let value: &'static str =5025
Box::leak(format!("{}[img]cd", "x\n".repeat(60)).into_boxed_str());5026
let token_start = 120;5027
let (view, mut visual) = build_block_view(cx, value, token_start..token_start + 5);5028
for (offset, row) in [(token_start, 60), (token_start + 5, 61)] {5029
view.input.update(&mut visual, |state, cx| {5030
state.scroll_to(offset, None, cx);5031
let line_height = state.line_height().unwrap();5032
let scrolled = -state.deferred_scroll_offset.unwrap().y;5033
let top = state.display_map.row_top(row, line_height);5034
let height = state.display_map.row_height(row, line_height);5035
assert!(top >= scrolled, "row {row} top is above the viewport");5036
assert!(5037
top + height <= scrolled + state.input_bounds.size.height,5038
"row {row} bottom is below the viewport"5039
);5040
});5041
}5042
}5043
5044
#[gpui::test]5045
fn test_block_token_undo_restores_uniform_rows(cx: &mut TestAppContext) {5046
let (view, mut visual) = build_block_view(cx, "ab[img]cd", 2..7);5047
visual.update(|window, cx| {5048
view.input5049
.update(cx, |state, cx| state.undo(&Undo, window, cx))5050
});5051
visual.update(|window, cx| window.draw(cx).clear(cx));5052
view.input.read_with(&visual, |state, _| {5053
let line_height = state.line_height().unwrap();5054
assert!(state.tokens().is_empty());5055
assert!(state.display_map.line(0).unwrap().blocks.is_empty());5056
assert_eq!(5057
state.display_map.content_height(line_height),5058
line_height * state.display_map.wrap_row_count() as f325059
);5060
assert_eq!(state.mode.rows(), state.display_map.wrap_row_count());5061
});5062
}5063
4727
#[gpui::test]5064
#[gpui::test]4728
fn test_inline_token_geometry_and_reentrant_activation(cx: &mut TestAppContext) {5065
fn test_inline_token_geometry_and_reentrant_activation(cx: &mut TestAppContext) {4729
use crate::input::{InlineToken, InlineTokenPresentation};5066
use crate::input::{InlineToken, InlineTokenPresentation};@@ -8830,8 +9167,9 @@ mod tests {8830
let view = InputView::build_textarea(cx, move |state| state.rows(4).default_value(text));9167
let view = InputView::build_textarea(cx, move |state| state.rows(4).default_value(text));8831
let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);9168
let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);8832
visual.update(|_, cx| {9169
visual.update(|_, cx| {8833
view.input9170
view.input.update(cx, |state, cx| {8834
.update(cx, |state, cx| state.set_line_indents(vec![(0, px(10.))], cx))9171
state.set_line_indents(vec![(0, px(10.))], cx)9172
})8835
});9173
});8836
visual.update(|window, cx| window.draw(cx).clear(cx));9174
visual.update(|window, cx| window.draw(cx).clear(cx));8837
view.input.read_with(&visual, |state, _| {9175
view.input.read_with(&visual, |state, _| {@@ -1,6 +1,8 @@
1
1
//! Presentation callbacks and measured geometry. None of this enters document history.
2
2
use super::{InlineToken, InlineTokenSpan, InputBaseState, InputModeKind, rope_ext::RopeExt as _};
3
use gpui::{AnyElement, App, Bounds, ClickEvent, Font, IntoElement, Pixels, Window};
3
use gpui::{AnyElement, App, Bounds, ClickEvent, Font, IntoElement, Pixels, Size, Window};
4
5
use crate::input::display_map::InlineMetric;
4
6
use std::{collections::HashMap, ops::Range, rc::Rc};
5
7
6
8
/// Read-only context for a single inline renderer. Width is the full available row.
@@ -29,6 +31,9 @@ impl InlineTokenContext {
29
31
pub fn is_readonly(&self) -> bool {
30
32
self.readonly
31
33
}
34
pub fn is_block(&self) -> bool {
35
self.span.token().is_block()
36
}
32
37
pub fn line_height(&self) -> Pixels {
33
38
self.line_height
34
39
}
@@ -175,8 +180,8 @@ pub(super) struct TokenLayoutCache {
175
180
pub(super) key: Option<(Font, Pixels, Pixels, Pixels, bool)>,
176
181
pub(super) revision: u64,
177
182
pub(super) unwrapped_width: Pixels,
178
pub(super) metrics: Rc<[(Range<usize>, Pixels)]>,
179
pub(super) widths: HashMap<InlineToken, Pixels>,
183
pub(super) metrics: Rc<[InlineMetric]>,
184
pub(super) sizes: HashMap<InlineToken, Size<Pixels>>,
180
185
}
181
186
182
187
impl<M: InputModeKind> InputBaseState<M> {
@@ -1,6 +1,8 @@1
//! Presentation callbacks and measured geometry. None of this enters document history.1
//! Presentation callbacks and measured geometry. None of this enters document history.2
use super::{InlineToken, InlineTokenSpan, InputBaseState, InputModeKind, rope_ext::RopeExt as _};2
use super::{InlineToken, InlineTokenSpan, InputBaseState, InputModeKind, rope_ext::RopeExt as _};3
use gpui::{AnyElement, App, Bounds, ClickEvent, Font, IntoElement, Pixels, Window};3
use gpui::{AnyElement, App, Bounds, ClickEvent, Font, IntoElement, Pixels, Size, Window};4
5
use crate::input::display_map::InlineMetric;4
use std::{collections::HashMap, ops::Range, rc::Rc};6
use std::{collections::HashMap, ops::Range, rc::Rc};5
7
6
/// Read-only context for a single inline renderer. Width is the full available row.8
/// Read-only context for a single inline renderer. Width is the full available row.@@ -29,6 +31,9 @@ impl InlineTokenContext {29
pub fn is_readonly(&self) -> bool {31
pub fn is_readonly(&self) -> bool {30
self.readonly32
self.readonly31
}33
}34
pub fn is_block(&self) -> bool {35
self.span.token().is_block()36
}32
pub fn line_height(&self) -> Pixels {37
pub fn line_height(&self) -> Pixels {33
self.line_height38
self.line_height34
}39
}@@ -175,8 +180,8 @@ pub(super) struct TokenLayoutCache {175
pub(super) key: Option<(Font, Pixels, Pixels, Pixels, bool)>,180
pub(super) key: Option<(Font, Pixels, Pixels, Pixels, bool)>,176
pub(super) revision: u64,181
pub(super) revision: u64,177
pub(super) unwrapped_width: Pixels,182
pub(super) unwrapped_width: Pixels,178
pub(super) metrics: Rc<[(Range<usize>, Pixels)]>,183
pub(super) metrics: Rc<[InlineMetric]>,179
pub(super) widths: HashMap<InlineToken, Pixels>,184
pub(super) sizes: HashMap<InlineToken, Size<Pixels>>,180
}185
}181
186
182
impl<M: InputModeKind> InputBaseState<M> {187
impl<M: InputModeKind> InputBaseState<M> {@@ -12,7 +12,7 @@ use ropey::Rope;
12
12
use super::fold_map::FoldMap;
13
13
use super::folding::FoldRange;
14
14
pub use super::text_wrapper::WrappingIndent;
15
use super::text_wrapper::{LineItem, WrapDisplayPoint};
15
use super::text_wrapper::{InlineMetric, LineItem, WrapDisplayPoint};
16
16
use super::wrap_map::WrapMap;
17
17
use super::{BufferPoint, DisplayPoint};
18
18
use crate::input::Point as TreeSitterPoint;
@@ -228,7 +228,7 @@ impl DisplayMap {
228
228
/// Update layout parameters (wrap width or font)
229
229
pub(crate) fn set_inline_metrics(
230
230
&mut self,
231
metrics: std::rc::Rc<[(std::ops::Range<usize>, Pixels)]>,
231
metrics: std::rc::Rc<[InlineMetric]>,
232
232
cx: &mut App,
233
233
) {
234
234
self.wrap_map.set_inline_metrics(metrics, cx);
@@ -377,6 +377,28 @@ impl DisplayMap {
377
377
.display_point_to_offset(WrapDisplayPoint::new(wrap_row, 0, column))
378
378
}
379
379
380
pub(crate) fn row_top(&self, display_row: usize, line_height: Pixels) -> Pixels {
381
self.wrap_map.wrapper().row_top(display_row, line_height)
382
}
383
384
pub(crate) fn row_height(&self, display_row: usize, line_height: Pixels) -> Pixels {
385
self.wrap_map.wrapper().row_height(display_row, line_height)
386
}
387
388
pub(crate) fn row_at_y(&self, y: Pixels, line_height: Pixels) -> usize {
389
self.wrap_map.wrapper().row_at_y(y, line_height)
390
}
391
392
pub(crate) fn content_height(&self, line_height: Pixels) -> Pixels {
393
self.wrap_map.wrapper().content_height(line_height)
394
}
395
396
pub(crate) fn content_rows(&self, line_height: Pixels) -> usize {
397
let rows = self.wrap_row_count();
398
let extra = self.content_height(line_height) - line_height * rows as f32;
399
rows + (extra / line_height).ceil().max(0.) as usize
400
}
401
380
402
/// Get the longest row index (by byte length).
381
403
#[inline]
382
404
pub(crate) fn longest_row(&self) -> usize {
@@ -12,7 +12,7 @@ use ropey::Rope;12
use super::fold_map::FoldMap;12
use super::fold_map::FoldMap;13
use super::folding::FoldRange;13
use super::folding::FoldRange;14
pub use super::text_wrapper::WrappingIndent;14
pub use super::text_wrapper::WrappingIndent;15
use super::text_wrapper::{LineItem, WrapDisplayPoint};15
use super::text_wrapper::{InlineMetric, LineItem, WrapDisplayPoint};16
use super::wrap_map::WrapMap;16
use super::wrap_map::WrapMap;17
use super::{BufferPoint, DisplayPoint};17
use super::{BufferPoint, DisplayPoint};18
use crate::input::Point as TreeSitterPoint;18
use crate::input::Point as TreeSitterPoint;@@ -228,7 +228,7 @@ impl DisplayMap {228
/// Update layout parameters (wrap width or font)228
/// Update layout parameters (wrap width or font)229
pub(crate) fn set_inline_metrics(229
pub(crate) fn set_inline_metrics(230
&mut self,230
&mut self,231
metrics: std::rc::Rc<[(std::ops::Range<usize>, Pixels)]>,231
metrics: std::rc::Rc<[InlineMetric]>,232
cx: &mut App,232
cx: &mut App,233
) {233
) {234
self.wrap_map.set_inline_metrics(metrics, cx);234
self.wrap_map.set_inline_metrics(metrics, cx);@@ -377,6 +377,28 @@ impl DisplayMap {377
.display_point_to_offset(WrapDisplayPoint::new(wrap_row, 0, column))377
.display_point_to_offset(WrapDisplayPoint::new(wrap_row, 0, column))378
}378
}379
379
380
pub(crate) fn row_top(&self, display_row: usize, line_height: Pixels) -> Pixels {381
self.wrap_map.wrapper().row_top(display_row, line_height)382
}383
384
pub(crate) fn row_height(&self, display_row: usize, line_height: Pixels) -> Pixels {385
self.wrap_map.wrapper().row_height(display_row, line_height)386
}387
388
pub(crate) fn row_at_y(&self, y: Pixels, line_height: Pixels) -> usize {389
self.wrap_map.wrapper().row_at_y(y, line_height)390
}391
392
pub(crate) fn content_height(&self, line_height: Pixels) -> Pixels {393
self.wrap_map.wrapper().content_height(line_height)394
}395
396
pub(crate) fn content_rows(&self, line_height: Pixels) -> usize {397
let rows = self.wrap_row_count();398
let extra = self.content_height(line_height) - line_height * rows as f32;399
rows + (extra / line_height).ceil().max(0.) as usize400
}401
380
/// Get the longest row index (by byte length).402
/// Get the longest row index (by byte length).381
#[inline]403
#[inline]382
pub(crate) fn longest_row(&self) -> usize {404
pub(crate) fn longest_row(&self) -> usize {@@ -13,6 +13,7 @@ pub(crate) struct InputLine {
13
13
pub(crate) len: usize,
14
14
pub(crate) width: Pixels,
15
15
pub(crate) text: SharedString,
16
pub(crate) height: Option<Pixels>,
16
17
content: Content,
17
18
}
18
19
// Keep the ordinary shaped row inline: boxing it would add an allocation to
@@ -28,6 +29,7 @@ impl From<ShapedLine> for InputLine {
28
29
len: line.len,
29
30
width: line.width,
30
31
text: line.text.clone(),
32
height: None,
31
33
content: Content::Text(line),
32
34
}
33
35
}
@@ -39,9 +41,14 @@ impl InputLine {
39
41
len: text.len(),
40
42
text,
41
43
width,
44
height: None,
42
45
content: Content::Inline(fragments),
43
46
}
44
47
}
48
pub(crate) fn with_height(mut self, height: Option<Pixels>) -> Self {
49
self.height = height;
50
self
51
}
45
52
pub(crate) fn x_for_index(&self, ix: usize) -> Pixels {
46
53
match &self.content {
47
54
Content::Text(line) => line.x_for_index(ix),
@@ -13,6 +13,7 @@ pub(crate) struct InputLine {13
pub(crate) len: usize,13
pub(crate) len: usize,14
pub(crate) width: Pixels,14
pub(crate) width: Pixels,15
pub(crate) text: SharedString,15
pub(crate) text: SharedString,16
pub(crate) height: Option<Pixels>,16
content: Content,17
content: Content,17
}18
}18
// Keep the ordinary shaped row inline: boxing it would add an allocation to19
// Keep the ordinary shaped row inline: boxing it would add an allocation to@@ -28,6 +29,7 @@ impl From<ShapedLine> for InputLine {28
len: line.len,29
len: line.len,29
width: line.width,30
width: line.width,30
text: line.text.clone(),31
text: line.text.clone(),32
height: None,31
content: Content::Text(line),33
content: Content::Text(line),32
}34
}33
}35
}@@ -39,9 +41,14 @@ impl InputLine {39
len: text.len(),41
len: text.len(),40
text,42
text,41
width,43
width,44
height: None,42
content: Content::Inline(fragments),45
content: Content::Inline(fragments),43
}46
}44
}47
}48
pub(crate) fn with_height(mut self, height: Option<Pixels>) -> Self {49
self.height = height;50
self51
}45
pub(crate) fn x_for_index(&self, ix: usize) -> Pixels {52
pub(crate) fn x_for_index(&self, ix: usize) -> Pixels {46
match &self.content {53
match &self.content {47
Content::Text(line) => line.x_for_index(ix),54
Content::Text(line) => line.x_for_index(ix),@@ -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, split_run_by_font_overrides};
20
pub(crate) use self::text_wrapper::{InlineMetric, LineLayout, split_run_by_font_overrides};
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, split_run_by_font_overrides};20
pub(crate) use self::text_wrapper::{InlineMetric, LineLayout, split_run_by_font_overrides};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;@@ -31,13 +31,14 @@ pub enum WrappingIndent {
31
31
/// Choose Unicode line-break opportunities using the same shaped widths as
32
32
/// painting. Oversized words fall back to complete graphemes, never UTF-8 bytes.
33
33
/// `hanging_indent` is a byte offset continuation rows align under; it wins over `wrapping_indent`.
34
/// `atomic` ranges (inline tokens) are never split.
34
/// `atomic` ranges (inline tokens) are never split. `forced` offsets (sorted) always end a row.
35
35
fn measured_wrap_boundaries(
36
36
text: &str,
37
37
width: Pixels,
38
38
wrapping_indent: WrappingIndent,
39
39
hanging_indent: Option<usize>,
40
40
atomic: &[Range<usize>],
41
forced: &[usize],
41
42
mut measure: impl FnMut(Range<usize>) -> Pixels,
42
43
) -> Vec<gpui::Boundary> {
43
44
let mut indent = match hanging_indent {
@@ -76,9 +77,15 @@ fn measured_wrap_boundaries(
76
77
} else {
77
78
width - indent_width
78
79
};
80
let forced_end = forced
81
.get(forced.partition_point(|&ix| ix <= start))
82
.copied();
83
let row_ends = forced_end.map_or(ends.len(), |forced_end| {
84
ends.partition_point(|&ix| ix <= forced_end)
85
});
79
86
// Find the fitting prefix locally. Exponential probing avoids shaping
80
87
// the entire remaining logical line for every visual row of a long paste.
81
let remaining = ends.len() - first;
88
let remaining = row_ends - first;
82
89
let mut low = 0;
83
90
let mut high = 1;
84
91
while measure(start..ends[first + high - 1]) <= available {
@@ -102,11 +109,15 @@ fn measured_wrap_boundaries(
102
109
break;
103
110
}
104
111
let candidate = opportunities.partition_point(|&ix| ix <= fitting_end);
105
let end = candidate
106
.checked_sub(1)
107
.map(|ix| opportunities[ix])
108
.filter(|&ix| ix > start && (start != 0 || ix > indent))
109
.unwrap_or(fitting_end);
112
let end = if Some(fitting_end) == forced_end {
113
fitting_end
114
} else {
115
candidate
116
.checked_sub(1)
117
.map(|ix| opportunities[ix])
118
.filter(|&ix| ix > start && (start != 0 || ix > indent))
119
.unwrap_or(fitting_end)
120
};
110
121
result.push(gpui::Boundary {
111
122
ix: end,
112
123
next_indent: text[..indent].chars().count() as u32,
@@ -187,6 +198,36 @@ fn line_indent_at(line_indents: &[(usize, Pixels)], line_start: usize) -> Pixels
187
198
.map_or(px(0.), |found| line_indents[found].1)
188
199
}
189
200
201
/// An inline token's measured size. `height` is `Some` for a block token: the full height of its own row.
202
#[derive(Clone, Debug, PartialEq)]
203
pub(crate) struct InlineMetric {
204
pub(crate) range: Range<usize>,
205
pub(crate) width: Pixels,
206
pub(crate) height: Option<Pixels>,
207
}
208
209
fn block_rows_of(
210
metrics: &[InlineMetric],
211
line_start: usize,
212
line_len: usize,
213
rows: &[Range<usize>],
214
) -> Vec<(usize, Pixels)> {
215
let first = metrics.partition_point(|metric| metric.range.end <= line_start);
216
metrics[first..]
217
.iter()
218
.take_while(|metric| metric.range.start < line_start + line_len)
219
.filter_map(|metric| {
220
let height = metric.height?;
221
let range = metric.range.start.checked_sub(line_start)?
222
..metric.range.end.checked_sub(line_start)?;
223
let row = rows
224
.binary_search_by_key(&range.start, |row| row.start)
225
.ok()?;
226
(rows[row].end == range.end).then_some((row, height))
227
})
228
.collect()
229
}
230
190
231
/// Ranges whose entry differs between two sorted span lists.
191
232
fn changed_ranges<T: PartialEq>(
192
233
old: &[(Range<usize>, T)],
@@ -232,6 +273,7 @@ pub(crate) struct LineItem {
232
273
///
233
274
/// Not contains the line end `\n`.
234
275
pub(crate) wrapped_lines: SmallVec<[Range<usize>; 1]>,
276
pub(crate) blocks: Vec<(usize, Pixels)>,
235
277
}
236
278
237
279
impl LineItem {
@@ -261,6 +303,8 @@ pub(crate) struct LineSummary {
261
303
max_line_len: usize,
262
304
/// Buffer row (relative to this subtree) of the first line achieving `max_line_len`.
263
305
longest_row: usize,
306
block_rows: usize,
307
block_height: Pixels,
264
308
}
265
309
266
310
impl sum_tree::Summary for LineSummary {
@@ -273,6 +317,8 @@ impl sum_tree::Summary for LineSummary {
273
317
bytes: 0,
274
318
max_line_len: 0,
275
319
longest_row: 0,
320
block_rows: 0,
321
block_height: px(0.),
276
322
}
277
323
}
278
324
@@ -285,6 +331,8 @@ impl sum_tree::Summary for LineSummary {
285
331
self.buffer_rows += other.buffer_rows;
286
332
self.wrap_rows += other.wrap_rows;
287
333
self.bytes += other.bytes;
334
self.block_rows += other.block_rows;
335
self.block_height += other.block_height;
288
336
}
289
337
}
290
338
@@ -298,6 +346,11 @@ impl sum_tree::Item for LineItem {
298
346
bytes: self.len(),
299
347
max_line_len: self.len(),
300
348
longest_row: 0,
349
block_rows: self.blocks.len(),
350
block_height: self
351
.blocks
352
.iter()
353
.fold(px(0.), |height, (_, block_height)| height + *block_height),
301
354
}
302
355
}
303
356
}
@@ -330,6 +383,29 @@ impl<'a> sum_tree::Dimension<'a, LineSummary> for WrapRows {
330
383
}
331
384
}
332
385
386
#[derive(Clone, Copy, Default, Debug)]
387
pub(crate) struct BlockExtent {
388
rows: usize,
389
height: Pixels,
390
}
391
392
impl BlockExtent {
393
fn extra(&self, line_height: Pixels) -> Pixels {
394
self.height - line_height * self.rows as f32
395
}
396
}
397
398
impl<'a> sum_tree::Dimension<'a, LineSummary> for BlockExtent {
399
fn zero(_: &()) -> Self {
400
BlockExtent::default()
401
}
402
403
fn add_summary(&mut self, summary: &'a LineSummary, _: &()) {
404
self.rows += summary.block_rows;
405
self.height += summary.block_height;
406
}
407
}
408
333
409
/// Used to prepare the text with soft wrap to be get lines to displayed in the Editor.
334
410
///
335
411
/// After use lines to calculate the scroll size of the Editor.
@@ -343,7 +419,7 @@ pub(crate) struct TextWrapper {
343
419
/// The lines by split \n
344
420
pub(crate) lines: SumTree<LineItem>,
345
421
346
inline_metrics: Rc<[(Range<usize>, Pixels)]>,
422
inline_metrics: Rc<[InlineMetric]>,
347
423
/// Sorted, non-overlapping document byte ranges measured in another font.
348
424
font_overrides: Rc<[(Range<usize>, FontOverride)]>,
349
425
/// Sorted list marker ranges, at most one per line; continuation rows start under their end.
@@ -441,6 +517,55 @@ impl TextWrapper {
441
517
}
442
518
}
443
519
520
fn row_span(&self, wrap_row: usize, line_height: Pixels) -> (Pixels, Pixels) {
521
let mut cursor = self.lines.cursor::<Dimensions<WrapRows, BlockExtent>>(&());
522
cursor.seek(&WrapRows(wrap_row), Bias::Right);
523
let first_row = cursor.start().0.0;
524
let mut extra = cursor.start().1.extra(line_height);
525
let mut height = line_height;
526
if let Some(line) = cursor.item() {
527
for (local_row, block_height) in &line.blocks {
528
match (first_row + local_row).cmp(&wrap_row) {
529
std::cmp::Ordering::Less => extra += *block_height - line_height,
530
std::cmp::Ordering::Equal => height = *block_height,
531
std::cmp::Ordering::Greater => {}
532
}
533
}
534
}
535
(line_height * wrap_row as f32 + extra, height)
536
}
537
538
pub(crate) fn row_top(&self, wrap_row: usize, line_height: Pixels) -> Pixels {
539
self.row_span(wrap_row, line_height).0
540
}
541
542
pub(crate) fn row_height(&self, wrap_row: usize, line_height: Pixels) -> Pixels {
543
self.row_span(wrap_row, line_height).1
544
}
545
546
pub(crate) fn row_at_y(&self, y: Pixels, line_height: Pixels) -> usize {
547
let rows = self.len();
548
if self.lines.summary().block_rows == 0 {
549
return ((y / line_height).floor().max(0.) as usize).min(rows.saturating_sub(1));
550
}
551
let (mut low, mut high) = (0, rows.max(1));
552
while low + 1 < high {
553
let mid = (low + high) / 2;
554
if self.row_top(mid, line_height) <= y {
555
low = mid;
556
} else {
557
high = mid;
558
}
559
}
560
low
561
}
562
563
pub(crate) fn content_height(&self, line_height: Pixels) -> Pixels {
564
let summary = self.lines.summary();
565
line_height * summary.wrap_rows as f32
566
+ (summary.block_height - line_height * summary.block_rows as f32)
567
}
568
444
569
pub(crate) fn set_wrap_width(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {
445
570
if wrap_width == self.wrap_width {
446
571
return;
@@ -508,8 +633,9 @@ impl TextWrapper {
508
633
new_text,
509
634
&mut |line_str, wrap_width, line_start| {
510
635
let mut tokens = Vec::new();
511
let first = metrics.partition_point(|(r, _)| r.end <= line_start);
512
for (range, width) in &metrics[first..] {
636
let first = metrics.partition_point(|metric| metric.range.end <= line_start);
637
for metric in &metrics[first..] {
638
let range = &metric.range;
513
639
if range.start >= line_start + line_str.len() {
514
640
break;
515
641
}
@@ -522,7 +648,10 @@ impl TextWrapper {
522
648
{
523
649
continue;
524
650
}
525
tokens.push((range, *width));
651
tokens.push(InlineMetric {
652
range,
653
..metric.clone()
654
});
526
655
}
527
656
let shape = |range: Range<usize>| {
528
657
if range.is_empty() {
@@ -544,7 +673,13 @@ impl TextWrapper {
544
673
.layout_line(&line_str[range], font_size, &runs, None)
545
674
.width
546
675
};
547
let token_ranges: Vec<_> = tokens.iter().map(|(range, _)| range.clone()).collect();
676
let token_ranges: Vec<_> = tokens.iter().map(|token| token.range.clone()).collect();
677
let mut forced: Vec<usize> = tokens
678
.iter()
679
.filter(|token| token.height.is_some())
680
.flat_map(|token| [token.range.start, token.range.end])
681
.collect();
682
forced.dedup();
548
683
let wrap_width =
549
684
(wrap_width - line_indent_at(&line_indents, line_start)).max(px(1.));
550
685
let line_indented = line_indent_at(&line_indents, line_start) > px(0.);
@@ -555,13 +690,14 @@ impl TextWrapper {
555
690
hanging_indent_at(&hanging_indents, line_start, line_str.len())
556
691
.or(line_indented.then_some(0)),
557
692
&token_ranges,
693
&forced,
558
694
|range| {
559
695
let mut width = px(0.);
560
696
let mut offset = range.start;
561
for (token, token_width) in &tokens {
562
if token.start >= offset && token.end <= range.end {
563
width += shape(offset..token.start) + *token_width;
564
offset = token.end;
697
for token in &tokens {
698
if token.range.start >= offset && token.range.end <= range.end {
699
width += shape(offset..token.range.start) + token.width;
700
offset = token.range.end;
565
701
}
566
702
}
567
703
width + shape(offset..range.end)
@@ -605,7 +741,12 @@ impl TextWrapper {
605
741
self.inline_metrics = self
606
742
.inline_metrics
607
743
.iter()
608
.filter_map(|(token, width)| Some((shift_span(token, range, new_len)?, *width)))
744
.filter_map(|metric| {
745
Some(InlineMetric {
746
range: shift_span(&metric.range, range, new_len)?,
747
..metric.clone()
748
})
749
})
609
750
.collect();
610
751
}
611
752
@@ -678,16 +819,18 @@ impl TextWrapper {
678
819
line_indent_at(&self.line_indents, line_start)
679
820
}
680
821
681
pub(crate) fn set_inline_metrics(
682
&mut self,
683
metrics: Rc<[(Range<usize>, Pixels)]>,
684
cx: &mut App,
685
) {
822
pub(crate) fn set_inline_metrics(&mut self, metrics: Rc<[InlineMetric]>, cx: &mut App) {
686
823
if self.inline_metrics == metrics {
687
824
return;
688
825
}
826
let as_spans = |metrics: &[InlineMetric]| -> Vec<(Range<usize>, (Pixels, Option<Pixels>))> {
827
metrics
828
.iter()
829
.map(|metric| (metric.range.clone(), (metric.width, metric.height)))
830
.collect()
831
};
689
832
// Only rows whose element geometry changed need another wrap pass.
690
let affected = changed_ranges(&self.inline_metrics, &metrics);
833
let affected = changed_ranges(&as_spans(&self.inline_metrics), &as_spans(&metrics));
691
834
self.inline_metrics = metrics;
692
835
self.rewrap_rows_of(&affected, cx);
693
836
}
@@ -801,10 +944,13 @@ impl TextWrapper {
801
944
wrapped_lines.push(prev_boundary_ix..line.len());
802
945
}
803
946
947
let blocks =
948
block_rows_of(&self.inline_metrics, line_start, line.len(), &wrapped_lines);
804
949
new_lines.push(LineItem {
805
950
len: line.len(),
806
951
indent: indent_chars,
807
952
wrapped_lines,
953
blocks,
808
954
});
809
955
}
810
956
@@ -1006,6 +1152,30 @@ impl LineLayout {
1006
1152
}
1007
1153
}
1008
1154
1155
#[inline]
1156
pub(crate) fn row_height(&self, ix: usize, line_height: Pixels) -> Pixels {
1157
self.wrapped_lines
1158
.get(ix)
1159
.and_then(|line| line.height)
1160
.unwrap_or(line_height)
1161
}
1162
1163
pub(crate) fn row_top(&self, ix: usize, line_height: Pixels) -> Pixels {
1164
(0..ix).fold(px(0.), |top, row| top + self.row_height(row, line_height))
1165
}
1166
1167
pub(crate) fn row_at_y(&self, y: Pixels, line_height: Pixels) -> Option<usize> {
1168
let mut top = px(0.);
1169
for ix in 0..self.wrapped_lines.len() {
1170
let bottom = top + self.row_height(ix, line_height);
1171
if y >= top && y < bottom {
1172
return Some(ix);
1173
}
1174
top = bottom;
1175
}
1176
None
1177
}
1178
1009
1179
pub(crate) fn lines(mut self, wrapped_lines: SmallVec<[ShapedLine; 1]>) -> Self {
1010
1180
self.set_wrapped_lines(wrapped_lines);
1011
1181
self
@@ -1107,7 +1277,7 @@ impl LineLayout {
1107
1277
// Always advance by actual line length. The last line gets +1 so the
1108
1278
// cursor can be placed after the final character.
1109
1279
acc_len += if is_last { line.len + 1 } else { line.len };
1110
offset_y += last_layout.line_height;
1280
offset_y += self.row_height(i, last_layout.line_height);
1111
1281
}
1112
1282
1113
1283
None
@@ -1143,21 +1313,11 @@ impl LineLayout {
1143
1313
pos: Point<Pixels>,
1144
1314
last_layout: &LastLayout,
1145
1315
) -> Option<(usize, usize, Pixels)> {
1146
let mut offset = 0;
1147
let mut line_top = px(0.);
1148
1316
let x_offset = last_layout.alignment_offset(self.longest_width);
1317
let i = self.row_at_y(pos.y, last_layout.line_height)?;
1318
let offset = self.wrapped_lines.iter().take(i).map(|line| line.len).sum();
1149
1319
1150
for (i, line) in self.wrapped_lines.iter().enumerate() {
1151
let line_bottom = line_top + last_layout.line_height;
1152
if pos.y >= line_top && pos.y < line_bottom {
1153
return Some((i, offset, pos.x - x_offset - self.line_indent(i)));
1154
}
1155
1156
offset += line.len;
1157
line_top = line_bottom;
1158
}
1159
1160
None
1320
Some((i, offset, pos.x - x_offset - self.line_indent(i)))
1161
1321
}
1162
1322
1163
1323
/// Get the index for the given position (x, y) in this line layout.
@@ -1232,7 +1392,7 @@ impl LineLayout {
1232
1392
.map(|(ix, line)| line.width + self.line_indent(ix))
1233
1393
.max()
1234
1394
.unwrap_or(self.longest_width);
1235
size(width, self.wrapped_lines.len() * line_height)
1395
size(width, self.row_top(self.wrapped_lines.len(), line_height))
1236
1396
}
1237
1397
1238
1398
/// Paint only the glyph background quads of this line.
@@ -1254,15 +1414,17 @@ impl LineLayout {
1254
1414
return;
1255
1415
}
1256
1416
1417
let mut top = px(0.);
1257
1418
for (ix, line) in self.wrapped_lines.iter().enumerate() {
1258
1419
_ = line.paint_background(
1259
pos + point(self.line_indent(ix), ix * line_height),
1420
pos + point(self.line_indent(ix), top),
1260
1421
line_height,
1261
1422
text_align,
1262
1423
align_width,
1263
1424
window,
1264
1425
cx,
1265
1426
);
1427
top += self.row_height(ix, line_height);
1266
1428
}
1267
1429
}
1268
1430
@@ -1275,15 +1437,17 @@ impl LineLayout {
1275
1437
window: &mut Window,
1276
1438
cx: &mut App,
1277
1439
) {
1440
let mut top = px(0.);
1278
1441
for (ix, line) in self.wrapped_lines.iter().enumerate() {
1279
1442
_ = line.paint(
1280
pos + point(self.line_indent(ix), ix * line_height),
1443
pos + point(self.line_indent(ix), top),
1281
1444
line_height,
1282
1445
text_align,
1283
1446
align_width,
1284
1447
window,
1285
1448
cx,
1286
1449
);
1450
top += self.row_height(ix, line_height);
1287
1451
}
1288
1452
1289
1453
// Paint whitespace indicators
@@ -1297,7 +1461,7 @@ impl LineLayout {
1297
1461
1298
1462
let origin = point(
1299
1463
pos.x + *x_position + self.line_indent(*line_index),
1300
pos.y + *line_index as f32 * line_height,
1464
pos.y + self.row_top(*line_index, line_height),
1301
1465
);
1302
1466
1303
1467
_ = invisible.paint(origin, line_height, text_align, align_width, window, cx);
@@ -1472,7 +1636,14 @@ mod tests {
1472
1636
let mut wrapper = TextWrapper::new(font.clone(), font_size, Some(width));
1473
1637
wrapper.wrapping_indent = WrappingIndent::None;
1474
1638
wrapper.update(&text, &(0..0), &text, cx);
1475
wrapper.set_inline_metrics(Rc::from([(token.clone(), px(32.))]), cx);
1639
wrapper.set_inline_metrics(
1640
Rc::from([InlineMetric {
1641
range: token.clone(),
1642
width: px(32.),
1643
height: None,
1644
}]),
1645
cx,
1646
);
1476
1647
let rows = wrapper.line(0).unwrap().wrapped_lines.to_vec();
1477
1648
assert!(
1478
1649
rows.iter()
@@ -1562,6 +1733,7 @@ mod tests {
1562
1733
WrappingIndent::None,
1563
1734
None,
1564
1735
&[],
1736
&[],
1565
1737
|range| measure(&line[range]),
1566
1738
)
1567
1739
},
@@ -1581,7 +1753,7 @@ mod tests {
1581
1753
#[test]
1582
1754
fn measured_wrap_preserves_words_graphemes_and_indentation() {
1583
1755
let wrap = |text: &str, width, indent| {
1584
measured_wrap_boundaries(text, px(width), indent, None, &[], |range| {
1756
measured_wrap_boundaries(text, px(width), indent, None, &[], &[], |range| {
1585
1757
px(text[range].graphemes(true).count() as f32)
1586
1758
})
1587
1759
.into_iter()
@@ -1598,6 +1770,123 @@ mod tests {
1598
1770
assert_eq!(wrap("你好,世界", 2., WrappingIndent::None), vec![3, 9]);
1599
1771
}
1600
1772
1773
#[test]
1774
fn measured_wrap_gives_forced_ranges_their_own_row() {
1775
let wrap = |text: &str, atomic: &[Range<usize>], forced: &[usize]| {
1776
measured_wrap_boundaries(
1777
text,
1778
px(100.),
1779
WrappingIndent::None,
1780
None,
1781
atomic,
1782
forced,
1783
|range| px(text[range].graphemes(true).count() as f32),
1784
)
1785
.into_iter()
1786
.map(|boundary| boundary.ix)
1787
.collect::<Vec<_>>()
1788
};
1789
assert_eq!(wrap("ab[img]cd", &[2..7], &[2, 7]), vec![2, 7]);
1790
assert_eq!(wrap("[img]cd", &[0..5], &[0, 5]), vec![5]);
1791
assert_eq!(wrap("ab[img]", &[2..7], &[2, 7]), vec![2]);
1792
assert!(wrap("[img]", &[0..5], &[0, 5]).is_empty());
1793
assert_eq!(wrap("[a][b]", &[0..3, 3..6], &[0, 3, 6]), vec![3]);
1794
}
1795
1796
#[test]
1797
fn block_rows_add_their_height_over_line_height() {
1798
let line_height = px(20.);
1799
let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
1800
let line = |len, wrapped_lines: SmallVec<[Range<usize>; 1]>, blocks| LineItem {
1801
len,
1802
indent: 0,
1803
wrapped_lines,
1804
blocks,
1805
};
1806
wrapper.lines = SumTree::from_iter(
1807
[
1808
line(2, smallvec::smallvec![0..2], Vec::new()),
1809
line(
1810
9,
1811
smallvec::smallvec![0..2, 2..7, 7..9],
1812
vec![(1, px(120.))],
1813
),
1814
line(1, smallvec::smallvec![0..1], Vec::new()),
1815
line(5, smallvec::smallvec![0..5], vec![(0, px(60.))]),
1816
],
1817
&(),
1818
);
1819
1820
let tops: Vec<_> = (0..6)
1821
.map(|row| wrapper.row_top(row, line_height))
1822
.collect();
1823
assert_eq!(
1824
tops,
1825
[0., 20., 40., 160., 180., 200.].map(px).to_vec(),
1826
"block rows push every later row down"
1827
);
1828
let heights: Vec<_> = (0..6)
1829
.map(|row| wrapper.row_height(row, line_height))
1830
.collect();
1831
assert_eq!(heights, [20., 20., 120., 20., 20., 60.].map(px).to_vec());
1832
assert_eq!(wrapper.content_height(line_height), px(260.));
1833
for (y, row) in [
1834
(0., 0),
1835
(39., 1),
1836
(40., 2),
1837
(159., 2),
1838
(160., 3),
1839
(259., 5),
1840
(999., 5),
1841
] {
1842
assert_eq!(wrapper.row_at_y(px(y), line_height), row, "y {y}");
1843
}
1844
}
1845
1846
#[cfg(target_os = "linux")]
1847
#[test]
1848
fn block_token_wraps_onto_its_own_row_and_tracks_edits() {
1849
let cx = shaping_test_context();
1850
cx.update(|cx| {
1851
let line_height = px(20.);
1852
let block = |range: Range<usize>| InlineMetric {
1853
range,
1854
width: px(200.),
1855
height: Some(px(120.)),
1856
};
1857
for (value, range, rows) in [
1858
("ab[img]cd", 2..7, vec![0..2, 2..7, 7..9]),
1859
("[img]cd", 0..5, vec![0..5, 5..7]),
1860
("ab[img]", 2..7, vec![0..2, 2..7]),
1861
("[img]", 0..5, vec![0..5]),
1862
] {
1863
let text = Rope::from(value);
1864
let mut wrapper = TextWrapper::new(test_font(), px(14.), Some(px(1000.)));
1865
wrapper.update(&text, &(0..0), &text, cx);
1866
assert_eq!(wrapper.len(), 1);
1867
wrapper.set_inline_metrics(Rc::from([block(range.clone())]), cx);
1868
assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), rows);
1869
assert_eq!(wrapper.len(), rows.len());
1870
assert_eq!(
1871
wrapper.content_height(line_height),
1872
line_height * (rows.len() - 1) as f32 + px(120.)
1873
);
1874
}
1875
1876
let text = Rope::from("ab[img]cd");
1877
let mut wrapper = TextWrapper::new(test_font(), px(14.), Some(px(1000.)));
1878
wrapper.update(&text, &(0..0), &text, cx);
1879
wrapper.set_inline_metrics(Rc::from([block(2..7)]), cx);
1880
assert_eq!(wrapper.row_top(2, line_height), line_height + px(120.));
1881
let removed = Rope::from("abcd");
1882
wrapper.adjust_inline_metrics(&(2..7), 0);
1883
wrapper.update(&removed, &(2..7), &Rope::new(), cx);
1884
assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), [0..4]);
1885
assert!(wrapper.line(0).unwrap().blocks.is_empty());
1886
assert_eq!(wrapper.content_height(line_height), line_height);
1887
});
1888
}
1889
1601
1890
#[test]
1602
1891
fn measured_wrap_hangs_continuation_rows_under_the_marker() {
1603
1892
let wrap = |text: &str, hanging_indent| {
@@ -1607,6 +1896,7 @@ mod tests {
1607
1896
WrappingIndent::None,
1608
1897
hanging_indent,
1609
1898
&[],
1899
&[],
1610
1900
|range| px(text[range].graphemes(true).count() as f32),
1611
1901
)
1612
1902
.into_iter()
@@ -1889,16 +2179,19 @@ mod tests {
1889
2179
len: 2,
1890
2180
indent: 0,
1891
2181
wrapped_lines: smallvec::smallvec![0..2],
2182
blocks: Vec::new(),
1892
2183
},
1893
2184
LineItem {
1894
2185
len: 4,
1895
2186
indent: 0,
1896
2187
wrapped_lines: smallvec::smallvec![0..2, 2..4],
2188
blocks: Vec::new(),
1897
2189
},
1898
2190
LineItem {
1899
2191
len: 1,
1900
2192
indent: 0,
1901
2193
wrapped_lines: smallvec::smallvec![0..1],
2194
blocks: Vec::new(),
1902
2195
},
1903
2196
],
1904
2197
&(),
@@ -2060,11 +2353,13 @@ mod tests {
2060
2353
len: Rope::from("first line").len(),
2061
2354
indent: 0,
2062
2355
wrapped_lines: smallvec::smallvec![0..10],
2356
blocks: Vec::new(),
2063
2357
},
2064
2358
LineItem {
2065
2359
len: Rope::from("this one wraps").len(),
2066
2360
indent: 0,
2067
2361
wrapped_lines: smallvec::smallvec![0..9, 9..14],
2362
blocks: Vec::new(),
2068
2363
},
2069
2364
],
2070
2365
&(),
@@ -2116,24 +2411,28 @@ mod tests {
2116
2411
len: Rope::from("Hello, 世界!\r").len(),
2117
2412
indent: 0,
2118
2413
wrapped_lines: smallvec::smallvec![0..15],
2414
blocks: Vec::new(),
2119
2415
},
2120
2416
// range: 16..36
2121
2417
LineItem {
2122
2418
len: Rope::from("This is second line.\n").len(),
2123
2419
indent: 0,
2124
2420
wrapped_lines: smallvec::smallvec![0..10, 10..20],
2421
blocks: Vec::new(),
2125
2422
},
2126
2423
// range: 37..56
2127
2424
LineItem {
2128
2425
len: Rope::from("This is third line.\n").len(),
2129
2426
indent: 0,
2130
2427
wrapped_lines: smallvec::smallvec![0..9, 9..15, 15..20],
2428
blocks: Vec::new(),
2131
2429
},
2132
2430
// range: 57..79
2133
2431
LineItem {
2134
2432
len: Rope::from("这里是第 4 行。").len(),
2135
2433
indent: 0,
2136
2434
wrapped_lines: smallvec::smallvec![0..22],
2435
blocks: Vec::new(),
2137
2436
},
2138
2437
],
2139
2438
&(),
@@ -31,13 +31,14 @@ pub enum WrappingIndent {31
/// Choose Unicode line-break opportunities using the same shaped widths as31
/// Choose Unicode line-break opportunities using the same shaped widths as32
/// painting. Oversized words fall back to complete graphemes, never UTF-8 bytes.32
/// painting. Oversized words fall back to complete graphemes, never UTF-8 bytes.33
/// `hanging_indent` is a byte offset continuation rows align under; it wins over `wrapping_indent`.33
/// `hanging_indent` is a byte offset continuation rows align under; it wins over `wrapping_indent`.34
/// `atomic` ranges (inline tokens) are never split.34
/// `atomic` ranges (inline tokens) are never split. `forced` offsets (sorted) always end a row.35
fn measured_wrap_boundaries(35
fn measured_wrap_boundaries(36
text: &str,36
text: &str,37
width: Pixels,37
width: Pixels,38
wrapping_indent: WrappingIndent,38
wrapping_indent: WrappingIndent,39
hanging_indent: Option<usize>,39
hanging_indent: Option<usize>,40
atomic: &[Range<usize>],40
atomic: &[Range<usize>],41
forced: &[usize],41
mut measure: impl FnMut(Range<usize>) -> Pixels,42
mut measure: impl FnMut(Range<usize>) -> Pixels,42
) -> Vec<gpui::Boundary> {43
) -> Vec<gpui::Boundary> {43
let mut indent = match hanging_indent {44
let mut indent = match hanging_indent {@@ -76,9 +77,15 @@ fn measured_wrap_boundaries(76
} else {77
} else {77
width - indent_width78
width - indent_width78
};79
};80
let forced_end = forced81
.get(forced.partition_point(|&ix| ix <= start))82
.copied();83
let row_ends = forced_end.map_or(ends.len(), |forced_end| {84
ends.partition_point(|&ix| ix <= forced_end)85
});79
// Find the fitting prefix locally. Exponential probing avoids shaping86
// Find the fitting prefix locally. Exponential probing avoids shaping80
// the entire remaining logical line for every visual row of a long paste.87
// the entire remaining logical line for every visual row of a long paste.81
let remaining = ends.len() - first;88
let remaining = row_ends - first;82
let mut low = 0;89
let mut low = 0;83
let mut high = 1;90
let mut high = 1;84
while measure(start..ends[first + high - 1]) <= available {91
while measure(start..ends[first + high - 1]) <= available {@@ -102,11 +109,15 @@ fn measured_wrap_boundaries(102
break;109
break;103
}110
}104
let candidate = opportunities.partition_point(|&ix| ix <= fitting_end);111
let candidate = opportunities.partition_point(|&ix| ix <= fitting_end);105
let end = candidate112
let end = if Some(fitting_end) == forced_end {106
.checked_sub(1)113
fitting_end107
.map(|ix| opportunities[ix])114
} else {108
.filter(|&ix| ix > start && (start != 0 || ix > indent))115
candidate109
.unwrap_or(fitting_end);116
.checked_sub(1)117
.map(|ix| opportunities[ix])118
.filter(|&ix| ix > start && (start != 0 || ix > indent))119
.unwrap_or(fitting_end)120
};110
result.push(gpui::Boundary {121
result.push(gpui::Boundary {111
ix: end,122
ix: end,112
next_indent: text[..indent].chars().count() as u32,123
next_indent: text[..indent].chars().count() as u32,@@ -187,6 +198,36 @@ fn line_indent_at(line_indents: &[(usize, Pixels)], line_start: usize) -> Pixels187
.map_or(px(0.), |found| line_indents[found].1)198
.map_or(px(0.), |found| line_indents[found].1)188
}199
}189
200
201
/// An inline token's measured size. `height` is `Some` for a block token: the full height of its own row.202
#[derive(Clone, Debug, PartialEq)]203
pub(crate) struct InlineMetric {204
pub(crate) range: Range<usize>,205
pub(crate) width: Pixels,206
pub(crate) height: Option<Pixels>,207
}208
209
fn block_rows_of(210
metrics: &[InlineMetric],211
line_start: usize,212
line_len: usize,213
rows: &[Range<usize>],214
) -> Vec<(usize, Pixels)> {215
let first = metrics.partition_point(|metric| metric.range.end <= line_start);216
metrics[first..]217
.iter()218
.take_while(|metric| metric.range.start < line_start + line_len)219
.filter_map(|metric| {220
let height = metric.height?;221
let range = metric.range.start.checked_sub(line_start)?222
..metric.range.end.checked_sub(line_start)?;223
let row = rows224
.binary_search_by_key(&range.start, |row| row.start)225
.ok()?;226
(rows[row].end == range.end).then_some((row, height))227
})228
.collect()229
}230
190
/// Ranges whose entry differs between two sorted span lists.231
/// Ranges whose entry differs between two sorted span lists.191
fn changed_ranges<T: PartialEq>(232
fn changed_ranges<T: PartialEq>(192
old: &[(Range<usize>, T)],233
old: &[(Range<usize>, T)],@@ -232,6 +273,7 @@ pub(crate) struct LineItem {232
///273
///233
/// Not contains the line end `\n`.274
/// Not contains the line end `\n`.234
pub(crate) wrapped_lines: SmallVec<[Range<usize>; 1]>,275
pub(crate) wrapped_lines: SmallVec<[Range<usize>; 1]>,276
pub(crate) blocks: Vec<(usize, Pixels)>,235
}277
}236
278
237
impl LineItem {279
impl LineItem {@@ -261,6 +303,8 @@ pub(crate) struct LineSummary {261
max_line_len: usize,303
max_line_len: usize,262
/// Buffer row (relative to this subtree) of the first line achieving `max_line_len`.304
/// Buffer row (relative to this subtree) of the first line achieving `max_line_len`.263
longest_row: usize,305
longest_row: usize,306
block_rows: usize,307
block_height: Pixels,264
}308
}265
309
266
impl sum_tree::Summary for LineSummary {310
impl sum_tree::Summary for LineSummary {@@ -273,6 +317,8 @@ impl sum_tree::Summary for LineSummary {273
bytes: 0,317
bytes: 0,274
max_line_len: 0,318
max_line_len: 0,275
longest_row: 0,319
longest_row: 0,320
block_rows: 0,321
block_height: px(0.),276
}322
}277
}323
}278
324
@@ -285,6 +331,8 @@ impl sum_tree::Summary for LineSummary {285
self.buffer_rows += other.buffer_rows;331
self.buffer_rows += other.buffer_rows;286
self.wrap_rows += other.wrap_rows;332
self.wrap_rows += other.wrap_rows;287
self.bytes += other.bytes;333
self.bytes += other.bytes;334
self.block_rows += other.block_rows;335
self.block_height += other.block_height;288
}336
}289
}337
}290
338
@@ -298,6 +346,11 @@ impl sum_tree::Item for LineItem {298
bytes: self.len(),346
bytes: self.len(),299
max_line_len: self.len(),347
max_line_len: self.len(),300
longest_row: 0,348
longest_row: 0,349
block_rows: self.blocks.len(),350
block_height: self351
.blocks352
.iter()353
.fold(px(0.), |height, (_, block_height)| height + *block_height),301
}354
}302
}355
}303
}356
}@@ -330,6 +383,29 @@ impl<'a> sum_tree::Dimension<'a, LineSummary> for WrapRows {330
}383
}331
}384
}332
385
386
#[derive(Clone, Copy, Default, Debug)]387
pub(crate) struct BlockExtent {388
rows: usize,389
height: Pixels,390
}391
392
impl BlockExtent {393
fn extra(&self, line_height: Pixels) -> Pixels {394
self.height - line_height * self.rows as f32395
}396
}397
398
impl<'a> sum_tree::Dimension<'a, LineSummary> for BlockExtent {399
fn zero(_: &()) -> Self {400
BlockExtent::default()401
}402
403
fn add_summary(&mut self, summary: &'a LineSummary, _: &()) {404
self.rows += summary.block_rows;405
self.height += summary.block_height;406
}407
}408
333
/// Used to prepare the text with soft wrap to be get lines to displayed in the Editor.409
/// Used to prepare the text with soft wrap to be get lines to displayed in the Editor.334
///410
///335
/// After use lines to calculate the scroll size of the Editor.411
/// After use lines to calculate the scroll size of the Editor.@@ -343,7 +419,7 @@ pub(crate) struct TextWrapper {343
/// The lines by split \n419
/// The lines by split \n344
pub(crate) lines: SumTree<LineItem>,420
pub(crate) lines: SumTree<LineItem>,345
421
346
inline_metrics: Rc<[(Range<usize>, Pixels)]>,422
inline_metrics: Rc<[InlineMetric]>,347
/// Sorted, non-overlapping document byte ranges measured in another font.423
/// Sorted, non-overlapping document byte ranges measured in another font.348
font_overrides: Rc<[(Range<usize>, FontOverride)]>,424
font_overrides: Rc<[(Range<usize>, FontOverride)]>,349
/// Sorted list marker ranges, at most one per line; continuation rows start under their end.425
/// Sorted list marker ranges, at most one per line; continuation rows start under their end.@@ -441,6 +517,55 @@ impl TextWrapper {441
}517
}442
}518
}443
519
520
fn row_span(&self, wrap_row: usize, line_height: Pixels) -> (Pixels, Pixels) {521
let mut cursor = self.lines.cursor::<Dimensions<WrapRows, BlockExtent>>(&());522
cursor.seek(&WrapRows(wrap_row), Bias::Right);523
let first_row = cursor.start().0.0;524
let mut extra = cursor.start().1.extra(line_height);525
let mut height = line_height;526
if let Some(line) = cursor.item() {527
for (local_row, block_height) in &line.blocks {528
match (first_row + local_row).cmp(&wrap_row) {529
std::cmp::Ordering::Less => extra += *block_height - line_height,530
std::cmp::Ordering::Equal => height = *block_height,531
std::cmp::Ordering::Greater => {}532
}533
}534
}535
(line_height * wrap_row as f32 + extra, height)536
}537
538
pub(crate) fn row_top(&self, wrap_row: usize, line_height: Pixels) -> Pixels {539
self.row_span(wrap_row, line_height).0540
}541
542
pub(crate) fn row_height(&self, wrap_row: usize, line_height: Pixels) -> Pixels {543
self.row_span(wrap_row, line_height).1544
}545
546
pub(crate) fn row_at_y(&self, y: Pixels, line_height: Pixels) -> usize {547
let rows = self.len();548
if self.lines.summary().block_rows == 0 {549
return ((y / line_height).floor().max(0.) as usize).min(rows.saturating_sub(1));550
}551
let (mut low, mut high) = (0, rows.max(1));552
while low + 1 < high {553
let mid = (low + high) / 2;554
if self.row_top(mid, line_height) <= y {555
low = mid;556
} else {557
high = mid;558
}559
}560
low561
}562
563
pub(crate) fn content_height(&self, line_height: Pixels) -> Pixels {564
let summary = self.lines.summary();565
line_height * summary.wrap_rows as f32566
+ (summary.block_height - line_height * summary.block_rows as f32)567
}568
444
pub(crate) fn set_wrap_width(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {569
pub(crate) fn set_wrap_width(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {445
if wrap_width == self.wrap_width {570
if wrap_width == self.wrap_width {446
return;571
return;@@ -508,8 +633,9 @@ impl TextWrapper {508
new_text,633
new_text,509
&mut |line_str, wrap_width, line_start| {634
&mut |line_str, wrap_width, line_start| {510
let mut tokens = Vec::new();635
let mut tokens = Vec::new();511
let first = metrics.partition_point(|(r, _)| r.end <= line_start);636
let first = metrics.partition_point(|metric| metric.range.end <= line_start);512
for (range, width) in &metrics[first..] {637
for metric in &metrics[first..] {638
let range = &metric.range;513
if range.start >= line_start + line_str.len() {639
if range.start >= line_start + line_str.len() {514
break;640
break;515
}641
}@@ -522,7 +648,10 @@ impl TextWrapper {522
{648
{523
continue;649
continue;524
}650
}525
tokens.push((range, *width));651
tokens.push(InlineMetric {652
range,653
..metric.clone()654
});526
}655
}527
let shape = |range: Range<usize>| {656
let shape = |range: Range<usize>| {528
if range.is_empty() {657
if range.is_empty() {@@ -544,7 +673,13 @@ impl TextWrapper {544
.layout_line(&line_str[range], font_size, &runs, None)673
.layout_line(&line_str[range], font_size, &runs, None)545
.width674
.width546
};675
};547
let token_ranges: Vec<_> = tokens.iter().map(|(range, _)| range.clone()).collect();676
let token_ranges: Vec<_> = tokens.iter().map(|token| token.range.clone()).collect();677
let mut forced: Vec<usize> = tokens678
.iter()679
.filter(|token| token.height.is_some())680
.flat_map(|token| [token.range.start, token.range.end])681
.collect();682
forced.dedup();548
let wrap_width =683
let wrap_width =549
(wrap_width - line_indent_at(&line_indents, line_start)).max(px(1.));684
(wrap_width - line_indent_at(&line_indents, line_start)).max(px(1.));550
let line_indented = line_indent_at(&line_indents, line_start) > px(0.);685
let line_indented = line_indent_at(&line_indents, line_start) > px(0.);@@ -555,13 +690,14 @@ impl TextWrapper {555
hanging_indent_at(&hanging_indents, line_start, line_str.len())690
hanging_indent_at(&hanging_indents, line_start, line_str.len())556
.or(line_indented.then_some(0)),691
.or(line_indented.then_some(0)),557
&token_ranges,692
&token_ranges,693
&forced,558
|range| {694
|range| {559
let mut width = px(0.);695
let mut width = px(0.);560
let mut offset = range.start;696
let mut offset = range.start;561
for (token, token_width) in &tokens {697
for token in &tokens {562
if token.start >= offset && token.end <= range.end {698
if token.range.start >= offset && token.range.end <= range.end {563
width += shape(offset..token.start) + *token_width;699
width += shape(offset..token.range.start) + token.width;564
offset = token.end;700
offset = token.range.end;565
}701
}566
}702
}567
width + shape(offset..range.end)703
width + shape(offset..range.end)@@ -605,7 +741,12 @@ impl TextWrapper {605
self.inline_metrics = self741
self.inline_metrics = self606
.inline_metrics742
.inline_metrics607
.iter()743
.iter()608
.filter_map(|(token, width)| Some((shift_span(token, range, new_len)?, *width)))744
.filter_map(|metric| {745
Some(InlineMetric {746
range: shift_span(&metric.range, range, new_len)?,747
..metric.clone()748
})749
})609
.collect();750
.collect();610
}751
}611
752
@@ -678,16 +819,18 @@ impl TextWrapper {678
line_indent_at(&self.line_indents, line_start)819
line_indent_at(&self.line_indents, line_start)679
}820
}680
821
681
pub(crate) fn set_inline_metrics(822
pub(crate) fn set_inline_metrics(&mut self, metrics: Rc<[InlineMetric]>, cx: &mut App) {682
&mut self,683
metrics: Rc<[(Range<usize>, Pixels)]>,684
cx: &mut App,685
) {686
if self.inline_metrics == metrics {823
if self.inline_metrics == metrics {687
return;824
return;688
}825
}826
let as_spans = |metrics: &[InlineMetric]| -> Vec<(Range<usize>, (Pixels, Option<Pixels>))> {827
metrics828
.iter()829
.map(|metric| (metric.range.clone(), (metric.width, metric.height)))830
.collect()831
};689
// Only rows whose element geometry changed need another wrap pass.832
// Only rows whose element geometry changed need another wrap pass.690
let affected = changed_ranges(&self.inline_metrics, &metrics);833
let affected = changed_ranges(&as_spans(&self.inline_metrics), &as_spans(&metrics));691
self.inline_metrics = metrics;834
self.inline_metrics = metrics;692
self.rewrap_rows_of(&affected, cx);835
self.rewrap_rows_of(&affected, cx);693
}836
}@@ -801,10 +944,13 @@ impl TextWrapper {801
wrapped_lines.push(prev_boundary_ix..line.len());944
wrapped_lines.push(prev_boundary_ix..line.len());802
}945
}803
946
947
let blocks =948
block_rows_of(&self.inline_metrics, line_start, line.len(), &wrapped_lines);804
new_lines.push(LineItem {949
new_lines.push(LineItem {805
len: line.len(),950
len: line.len(),806
indent: indent_chars,951
indent: indent_chars,807
wrapped_lines,952
wrapped_lines,953
blocks,808
});954
});809
}955
}810
956
@@ -1006,6 +1152,30 @@ impl LineLayout {1006
}1152
}1007
}1153
}1008
1154
1155
#[inline]1156
pub(crate) fn row_height(&self, ix: usize, line_height: Pixels) -> Pixels {1157
self.wrapped_lines1158
.get(ix)1159
.and_then(|line| line.height)1160
.unwrap_or(line_height)1161
}1162
1163
pub(crate) fn row_top(&self, ix: usize, line_height: Pixels) -> Pixels {1164
(0..ix).fold(px(0.), |top, row| top + self.row_height(row, line_height))1165
}1166
1167
pub(crate) fn row_at_y(&self, y: Pixels, line_height: Pixels) -> Option<usize> {1168
let mut top = px(0.);1169
for ix in 0..self.wrapped_lines.len() {1170
let bottom = top + self.row_height(ix, line_height);1171
if y >= top && y < bottom {1172
return Some(ix);1173
}1174
top = bottom;1175
}1176
None1177
}1178
1009
pub(crate) fn lines(mut self, wrapped_lines: SmallVec<[ShapedLine; 1]>) -> Self {1179
pub(crate) fn lines(mut self, wrapped_lines: SmallVec<[ShapedLine; 1]>) -> Self {1010
self.set_wrapped_lines(wrapped_lines);1180
self.set_wrapped_lines(wrapped_lines);1011
self1181
self@@ -1107,7 +1277,7 @@ impl LineLayout {1107
// Always advance by actual line length. The last line gets +1 so the1277
// Always advance by actual line length. The last line gets +1 so the1108
// cursor can be placed after the final character.1278
// cursor can be placed after the final character.1109
acc_len += if is_last { line.len + 1 } else { line.len };1279
acc_len += if is_last { line.len + 1 } else { line.len };1110
offset_y += last_layout.line_height;1280
offset_y += self.row_height(i, last_layout.line_height);1111
}1281
}1112
1282
1113
None1283
None@@ -1143,21 +1313,11 @@ impl LineLayout {1143
pos: Point<Pixels>,1313
pos: Point<Pixels>,1144
last_layout: &LastLayout,1314
last_layout: &LastLayout,1145
) -> Option<(usize, usize, Pixels)> {1315
) -> Option<(usize, usize, Pixels)> {1146
let mut offset = 0;1147
let mut line_top = px(0.);1148
let x_offset = last_layout.alignment_offset(self.longest_width);1316
let x_offset = last_layout.alignment_offset(self.longest_width);1317
let i = self.row_at_y(pos.y, last_layout.line_height)?;1318
let offset = self.wrapped_lines.iter().take(i).map(|line| line.len).sum();1149
1319
1150
for (i, line) in self.wrapped_lines.iter().enumerate() {1320
Some((i, offset, pos.x - x_offset - self.line_indent(i)))1151
let line_bottom = line_top + last_layout.line_height;1152
if pos.y >= line_top && pos.y < line_bottom {1153
return Some((i, offset, pos.x - x_offset - self.line_indent(i)));1154
}1155
1156
offset += line.len;1157
line_top = line_bottom;1158
}1159
1160
None1161
}1321
}1162
1322
1163
/// Get the index for the given position (x, y) in this line layout.1323
/// Get the index for the given position (x, y) in this line layout.@@ -1232,7 +1392,7 @@ impl LineLayout {1232
.map(|(ix, line)| line.width + self.line_indent(ix))1392
.map(|(ix, line)| line.width + self.line_indent(ix))1233
.max()1393
.max()1234
.unwrap_or(self.longest_width);1394
.unwrap_or(self.longest_width);1235
size(width, self.wrapped_lines.len() * line_height)1395
size(width, self.row_top(self.wrapped_lines.len(), line_height))1236
}1396
}1237
1397
1238
/// Paint only the glyph background quads of this line.1398
/// Paint only the glyph background quads of this line.@@ -1254,15 +1414,17 @@ impl LineLayout {1254
return;1414
return;1255
}1415
}1256
1416
1417
let mut top = px(0.);1257
for (ix, line) in self.wrapped_lines.iter().enumerate() {1418
for (ix, line) in self.wrapped_lines.iter().enumerate() {1258
_ = line.paint_background(1419
_ = line.paint_background(1259
pos + point(self.line_indent(ix), ix * line_height),1420
pos + point(self.line_indent(ix), top),1260
line_height,1421
line_height,1261
text_align,1422
text_align,1262
align_width,1423
align_width,1263
window,1424
window,1264
cx,1425
cx,1265
);1426
);1427
top += self.row_height(ix, line_height);1266
}1428
}1267
}1429
}1268
1430
@@ -1275,15 +1437,17 @@ impl LineLayout {1275
window: &mut Window,1437
window: &mut Window,1276
cx: &mut App,1438
cx: &mut App,1277
) {1439
) {1440
let mut top = px(0.);1278
for (ix, line) in self.wrapped_lines.iter().enumerate() {1441
for (ix, line) in self.wrapped_lines.iter().enumerate() {1279
_ = line.paint(1442
_ = line.paint(1280
pos + point(self.line_indent(ix), ix * line_height),1443
pos + point(self.line_indent(ix), top),1281
line_height,1444
line_height,1282
text_align,1445
text_align,1283
align_width,1446
align_width,1284
window,1447
window,1285
cx,1448
cx,1286
);1449
);1450
top += self.row_height(ix, line_height);1287
}1451
}1288
1452
1289
// Paint whitespace indicators1453
// Paint whitespace indicators@@ -1297,7 +1461,7 @@ impl LineLayout {1297
1461
1298
let origin = point(1462
let origin = point(1299
pos.x + *x_position + self.line_indent(*line_index),1463
pos.x + *x_position + self.line_indent(*line_index),1300
pos.y + *line_index as f32 * line_height,1464
pos.y + self.row_top(*line_index, line_height),1301
);1465
);1302
1466
1303
_ = invisible.paint(origin, line_height, text_align, align_width, window, cx);1467
_ = invisible.paint(origin, line_height, text_align, align_width, window, cx);@@ -1472,7 +1636,14 @@ mod tests {1472
let mut wrapper = TextWrapper::new(font.clone(), font_size, Some(width));1636
let mut wrapper = TextWrapper::new(font.clone(), font_size, Some(width));1473
wrapper.wrapping_indent = WrappingIndent::None;1637
wrapper.wrapping_indent = WrappingIndent::None;1474
wrapper.update(&text, &(0..0), &text, cx);1638
wrapper.update(&text, &(0..0), &text, cx);1475
wrapper.set_inline_metrics(Rc::from([(token.clone(), px(32.))]), cx);1639
wrapper.set_inline_metrics(1640
Rc::from([InlineMetric {1641
range: token.clone(),1642
width: px(32.),1643
height: None,1644
}]),1645
cx,1646
);1476
let rows = wrapper.line(0).unwrap().wrapped_lines.to_vec();1647
let rows = wrapper.line(0).unwrap().wrapped_lines.to_vec();1477
assert!(1648
assert!(1478
rows.iter()1649
rows.iter()@@ -1562,6 +1733,7 @@ mod tests {1562
WrappingIndent::None,1733
WrappingIndent::None,1563
None,1734
None,1564
&[],1735
&[],1736
&[],1565
|range| measure(&line[range]),1737
|range| measure(&line[range]),1566
)1738
)1567
},1739
},@@ -1581,7 +1753,7 @@ mod tests {1581
#[test]1753
#[test]1582
fn measured_wrap_preserves_words_graphemes_and_indentation() {1754
fn measured_wrap_preserves_words_graphemes_and_indentation() {1583
let wrap = |text: &str, width, indent| {1755
let wrap = |text: &str, width, indent| {1584
measured_wrap_boundaries(text, px(width), indent, None, &[], |range| {1756
measured_wrap_boundaries(text, px(width), indent, None, &[], &[], |range| {1585
px(text[range].graphemes(true).count() as f32)1757
px(text[range].graphemes(true).count() as f32)1586
})1758
})1587
.into_iter()1759
.into_iter()@@ -1598,6 +1770,123 @@ mod tests {1598
assert_eq!(wrap("你好,世界", 2., WrappingIndent::None), vec![3, 9]);1770
assert_eq!(wrap("你好,世界", 2., WrappingIndent::None), vec![3, 9]);1599
}1771
}1600
1772
1773
#[test]1774
fn measured_wrap_gives_forced_ranges_their_own_row() {1775
let wrap = |text: &str, atomic: &[Range<usize>], forced: &[usize]| {1776
measured_wrap_boundaries(1777
text,1778
px(100.),1779
WrappingIndent::None,1780
None,1781
atomic,1782
forced,1783
|range| px(text[range].graphemes(true).count() as f32),1784
)1785
.into_iter()1786
.map(|boundary| boundary.ix)1787
.collect::<Vec<_>>()1788
};1789
assert_eq!(wrap("ab[img]cd", &[2..7], &[2, 7]), vec![2, 7]);1790
assert_eq!(wrap("[img]cd", &[0..5], &[0, 5]), vec![5]);1791
assert_eq!(wrap("ab[img]", &[2..7], &[2, 7]), vec![2]);1792
assert!(wrap("[img]", &[0..5], &[0, 5]).is_empty());1793
assert_eq!(wrap("[a][b]", &[0..3, 3..6], &[0, 3, 6]), vec![3]);1794
}1795
1796
#[test]1797
fn block_rows_add_their_height_over_line_height() {1798
let line_height = px(20.);1799
let mut wrapper = TextWrapper::new(test_font(), px(14.), None);1800
let line = |len, wrapped_lines: SmallVec<[Range<usize>; 1]>, blocks| LineItem {1801
len,1802
indent: 0,1803
wrapped_lines,1804
blocks,1805
};1806
wrapper.lines = SumTree::from_iter(1807
[1808
line(2, smallvec::smallvec![0..2], Vec::new()),1809
line(1810
9,1811
smallvec::smallvec![0..2, 2..7, 7..9],1812
vec![(1, px(120.))],1813
),1814
line(1, smallvec::smallvec![0..1], Vec::new()),1815
line(5, smallvec::smallvec![0..5], vec![(0, px(60.))]),1816
],1817
&(),1818
);1819
1820
let tops: Vec<_> = (0..6)1821
.map(|row| wrapper.row_top(row, line_height))1822
.collect();1823
assert_eq!(1824
tops,1825
[0., 20., 40., 160., 180., 200.].map(px).to_vec(),1826
"block rows push every later row down"1827
);1828
let heights: Vec<_> = (0..6)1829
.map(|row| wrapper.row_height(row, line_height))1830
.collect();1831
assert_eq!(heights, [20., 20., 120., 20., 20., 60.].map(px).to_vec());1832
assert_eq!(wrapper.content_height(line_height), px(260.));1833
for (y, row) in [1834
(0., 0),1835
(39., 1),1836
(40., 2),1837
(159., 2),1838
(160., 3),1839
(259., 5),1840
(999., 5),1841
] {1842
assert_eq!(wrapper.row_at_y(px(y), line_height), row, "y {y}");1843
}1844
}1845
1846
#[cfg(target_os = "linux")]1847
#[test]1848
fn block_token_wraps_onto_its_own_row_and_tracks_edits() {1849
let cx = shaping_test_context();1850
cx.update(|cx| {1851
let line_height = px(20.);1852
let block = |range: Range<usize>| InlineMetric {1853
range,1854
width: px(200.),1855
height: Some(px(120.)),1856
};1857
for (value, range, rows) in [1858
("ab[img]cd", 2..7, vec![0..2, 2..7, 7..9]),1859
("[img]cd", 0..5, vec![0..5, 5..7]),1860
("ab[img]", 2..7, vec![0..2, 2..7]),1861
("[img]", 0..5, vec![0..5]),1862
] {1863
let text = Rope::from(value);1864
let mut wrapper = TextWrapper::new(test_font(), px(14.), Some(px(1000.)));1865
wrapper.update(&text, &(0..0), &text, cx);1866
assert_eq!(wrapper.len(), 1);1867
wrapper.set_inline_metrics(Rc::from([block(range.clone())]), cx);1868
assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), rows);1869
assert_eq!(wrapper.len(), rows.len());1870
assert_eq!(1871
wrapper.content_height(line_height),1872
line_height * (rows.len() - 1) as f32 + px(120.)1873
);1874
}1875
1876
let text = Rope::from("ab[img]cd");1877
let mut wrapper = TextWrapper::new(test_font(), px(14.), Some(px(1000.)));1878
wrapper.update(&text, &(0..0), &text, cx);1879
wrapper.set_inline_metrics(Rc::from([block(2..7)]), cx);1880
assert_eq!(wrapper.row_top(2, line_height), line_height + px(120.));1881
let removed = Rope::from("abcd");1882
wrapper.adjust_inline_metrics(&(2..7), 0);1883
wrapper.update(&removed, &(2..7), &Rope::new(), cx);1884
assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), [0..4]);1885
assert!(wrapper.line(0).unwrap().blocks.is_empty());1886
assert_eq!(wrapper.content_height(line_height), line_height);1887
});1888
}1889
1601
#[test]1890
#[test]1602
fn measured_wrap_hangs_continuation_rows_under_the_marker() {1891
fn measured_wrap_hangs_continuation_rows_under_the_marker() {1603
let wrap = |text: &str, hanging_indent| {1892
let wrap = |text: &str, hanging_indent| {@@ -1607,6 +1896,7 @@ mod tests {1607
WrappingIndent::None,1896
WrappingIndent::None,1608
hanging_indent,1897
hanging_indent,1609
&[],1898
&[],1899
&[],1610
|range| px(text[range].graphemes(true).count() as f32),1900
|range| px(text[range].graphemes(true).count() as f32),1611
)1901
)1612
.into_iter()1902
.into_iter()@@ -1889,16 +2179,19 @@ mod tests {1889
len: 2,2179
len: 2,1890
indent: 0,2180
indent: 0,1891
wrapped_lines: smallvec::smallvec![0..2],2181
wrapped_lines: smallvec::smallvec![0..2],2182
blocks: Vec::new(),1892
},2183
},1893
LineItem {2184
LineItem {1894
len: 4,2185
len: 4,1895
indent: 0,2186
indent: 0,1896
wrapped_lines: smallvec::smallvec![0..2, 2..4],2187
wrapped_lines: smallvec::smallvec![0..2, 2..4],2188
blocks: Vec::new(),1897
},2189
},1898
LineItem {2190
LineItem {1899
len: 1,2191
len: 1,1900
indent: 0,2192
indent: 0,1901
wrapped_lines: smallvec::smallvec![0..1],2193
wrapped_lines: smallvec::smallvec![0..1],2194
blocks: Vec::new(),1902
},2195
},1903
],2196
],1904
&(),2197
&(),@@ -2060,11 +2353,13 @@ mod tests {2060
len: Rope::from("first line").len(),2353
len: Rope::from("first line").len(),2061
indent: 0,2354
indent: 0,2062
wrapped_lines: smallvec::smallvec![0..10],2355
wrapped_lines: smallvec::smallvec![0..10],2356
blocks: Vec::new(),2063
},2357
},2064
LineItem {2358
LineItem {2065
len: Rope::from("this one wraps").len(),2359
len: Rope::from("this one wraps").len(),2066
indent: 0,2360
indent: 0,2067
wrapped_lines: smallvec::smallvec![0..9, 9..14],2361
wrapped_lines: smallvec::smallvec![0..9, 9..14],2362
blocks: Vec::new(),2068
},2363
},2069
],2364
],2070
&(),2365
&(),@@ -2116,24 +2411,28 @@ mod tests {2116
len: Rope::from("Hello, 世界!\r").len(),2411
len: Rope::from("Hello, 世界!\r").len(),2117
indent: 0,2412
indent: 0,2118
wrapped_lines: smallvec::smallvec![0..15],2413
wrapped_lines: smallvec::smallvec![0..15],2414
blocks: Vec::new(),2119
},2415
},2120
// range: 16..362416
// range: 16..362121
LineItem {2417
LineItem {2122
len: Rope::from("This is second line.\n").len(),2418
len: Rope::from("This is second line.\n").len(),2123
indent: 0,2419
indent: 0,2124
wrapped_lines: smallvec::smallvec![0..10, 10..20],2420
wrapped_lines: smallvec::smallvec![0..10, 10..20],2421
blocks: Vec::new(),2125
},2422
},2126
// range: 37..562423
// range: 37..562127
LineItem {2424
LineItem {2128
len: Rope::from("This is third line.\n").len(),2425
len: Rope::from("This is third line.\n").len(),2129
indent: 0,2426
indent: 0,2130
wrapped_lines: smallvec::smallvec![0..9, 9..15, 15..20],2427
wrapped_lines: smallvec::smallvec![0..9, 9..15, 15..20],2428
blocks: Vec::new(),2131
},2429
},2132
// range: 57..792430
// range: 57..792133
LineItem {2431
LineItem {2134
len: Rope::from("这里是第 4 行。").len(),2432
len: Rope::from("这里是第 4 行。").len(),2135
indent: 0,2433
indent: 0,2136
wrapped_lines: smallvec::smallvec![0..22],2434
wrapped_lines: smallvec::smallvec![0..22],2435
blocks: Vec::new(),2137
},2436
},2138
],2437
],2139
&(),2438
&(),@@ -10,7 +10,7 @@ use gpui::{App, Font, Pixels};
10
10
use ropey::Rope;
11
11
12
12
use super::fold_map::FoldMap;
13
use super::text_wrapper::{LineItem, TextWrapper, WrapDisplayPoint, WrappingIndent};
13
use super::text_wrapper::{InlineMetric, LineItem, TextWrapper, WrapDisplayPoint, WrappingIndent};
14
14
use super::{BufferPoint, WrapPoint};
15
15
use crate::input::RopeExt;
16
16
@@ -117,7 +117,7 @@ impl WrapMap {
117
117
/// Update layout parameters (wrap width or font)
118
118
pub(super) fn set_inline_metrics(
119
119
&mut self,
120
metrics: std::rc::Rc<[(std::ops::Range<usize>, Pixels)]>,
120
metrics: std::rc::Rc<[InlineMetric]>,
121
121
cx: &mut App,
122
122
) {
123
123
self.wrapper.set_inline_metrics(metrics, cx);
@@ -10,7 +10,7 @@ use gpui::{App, Font, Pixels};10
use ropey::Rope;10
use ropey::Rope;11
11
12
use super::fold_map::FoldMap;12
use super::fold_map::FoldMap;13
use super::text_wrapper::{LineItem, TextWrapper, WrapDisplayPoint, WrappingIndent};13
use super::text_wrapper::{InlineMetric, LineItem, TextWrapper, WrapDisplayPoint, WrappingIndent};14
use super::{BufferPoint, WrapPoint};14
use super::{BufferPoint, WrapPoint};15
use crate::input::RopeExt;15
use crate::input::RopeExt;16
16
@@ -117,7 +117,7 @@ impl WrapMap {117
/// Update layout parameters (wrap width or font)117
/// Update layout parameters (wrap width or font)118
pub(super) fn set_inline_metrics(118
pub(super) fn set_inline_metrics(119
&mut self,119
&mut self,120
metrics: std::rc::Rc<[(std::ops::Range<usize>, Pixels)]>,120
metrics: std::rc::Rc<[InlineMetric]>,121
cx: &mut App,121
cx: &mut App,122
) {122
) {123
self.wrapper.set_inline_metrics(metrics, cx);123
self.wrapper.set_inline_metrics(metrics, cx);