BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-ui-kit / src / render / selectable.rs

selectable.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
selectable.rs 17.3 KiB Download Raw
1use std::cell::RefCell;
2use std::ops::Range;
3use std::path::PathBuf;
4use std::rc::Rc;
5
6use gpui_kit::base::{
7 TextSelection, TextSelectionHandle, TextSelectionRegistration, TextSelectionRun, Theme,
8};
9use gpui_kit::*;
10
11use super::blocks::{CODE_PADDING, EMOJI_PLACEHOLDER};
12use super::hooks::{open_link, open_profile_link};
13
14pub(super) const TIME_ROOM: char = '\u{2007}';
15pub(super) const HIT_SLOP: f32 = 12.;
16
17#[derive(Clone)]
18pub struct Participant {
19 pub(super) handle: TextSelectionHandle,
20 pub(super) copied: Rc<RefCell<String>>,
21}
22
23impl Participant {
24 pub(super) fn retained(
25 global_id: Option<&GlobalElementId>,
26 text: &SharedString,
27 window: &mut Window,
28 cx: &mut App,
29 ) -> Participant {
30 window.with_element_state(
31 global_id.expect("selectable text has an element id"),
32 |retained: Option<Participant>, _| {
33 let participant = retained.unwrap_or_else(|| {
34 let handle = TextSelectionHandle::new(text.clone(), cx);
35 let copied = Rc::new(RefCell::new(String::new()));
36 let source = copied.clone();
37 handle.copy_with(move |_| source.borrow().clone(), cx);
38 Participant { handle, copied }
39 });
40 (participant.clone(), participant)
41 },
42 )
43 }
44}
45
46pub(super) const PILL_OUTSET: f32 = 3.;
47const INLINE_IMAGE_SIZE: f32 = 20.;
48pub(super) const PILL_INSET_Y: f32 = 1.;
49
50#[derive(Clone, Debug)]
51pub struct Pill {
52 pub range: Range<usize>,
53 pub fill: Hsla,
54 pub border: Option<Hsla>,
55 pub radius: Pixels,
56}
57
58/// Styled text that takes part in the window text selection, with clickable link ranges.
59pub struct SelectableRichText {
60 id: ElementId,
61 text: SharedString,
62 styled_text: StyledText,
63 links: Vec<(Range<usize>, String)>,
64 pills: Vec<Pill>,
65 inline_images: Vec<(Range<usize>, PathBuf)>,
66}
67
68impl SelectableRichText {
69 pub fn new(
70 id: impl Into<ElementId>,
71 text: impl Into<SharedString>,
72 highlights: Vec<(Range<usize>, HighlightStyle)>,
73 ) -> Self {
74 let text = text.into();
75 SelectableRichText {
76 id: id.into(),
77 styled_text: StyledText::new(text.clone()).with_highlights(highlights),
78 text,
79 links: Vec::new(),
80 pills: Vec::new(),
81 inline_images: Vec::new(),
82 }
83 }
84
85 pub fn links(mut self, links: Vec<(Range<usize>, String)>) -> Self {
86 self.links = links;
87 self
88 }
89
90 pub fn inline_images(mut self, images: Vec<(Range<usize>, PathBuf)>) -> Self {
91 self.inline_images = images;
92 self
93 }
94
95 pub fn font_overrides(mut self, overrides: Vec<(Range<usize>, SharedString)>) -> Self {
96 if !overrides.is_empty() {
97 let styled_text = std::mem::replace(&mut self.styled_text, StyledText::new(""));
98 self.styled_text = styled_text.with_font_family_overrides(overrides);
99 }
100 self
101 }
102
103 pub fn pills(mut self, pills: Vec<Pill>) -> Self {
104 self.pills = pills;
105 self
106 }
107}
108
109fn paint_inline_images(
110 images: &[(Range<usize>, PathBuf)],
111 text: &str,
112 layout: &TextLayout,
113 window: &mut Window,
114 cx: &mut App,
115) {
116 let line_height = layout.line_height();
117 let left = layout.bounds().left();
118 for (range, path) in images {
119 let Some(line) = pill_lines(text, range.clone(), left, |index| {
120 layout.position_for_index(index)
121 })
122 .into_iter()
123 .next() else {
124 continue;
125 };
126 let Some(Ok(image)) =
127 window.use_asset::<ImgResourceLoader>(&Resource::Path(path.clone().into()), cx)
128 else {
129 continue;
130 };
131 let side = line_height.min(px(INLINE_IMAGE_SIZE));
132 let center_x = line.left + (line.right - line.left) / 2.;
133 let origin = point(center_x - side / 2., line.top + (line_height - side) / 2.);
134 let image_bounds = Bounds::new(origin, size(side, side));
135 let _ = window.paint_image(
136 image_bounds,
137 image_bounds,
138 Corners::default(),
139 image,
140 0,
141 false,
142 );
143 }
144}
145
146fn paint_pills(pills: &[Pill], text: &str, layout: &TextLayout, window: &mut Window) {
147 let line_height = layout.line_height();
148 let bounds = layout.bounds();
149 for pill in pills {
150 let lines = pill_lines(text, pill.range.clone(), bounds.left(), |index| {
151 layout.position_for_index(index)
152 });
153 for line in lines {
154 let line = Bounds::from_corners(
155 point(line.left - px(PILL_OUTSET), line.top + px(PILL_INSET_Y)),
156 point(
157 line.right + px(PILL_OUTSET),
158 line.top + line_height - px(PILL_INSET_Y),
159 ),
160 );
161 let (border_width, border_color) = match pill.border {
162 Some(color) => (px(1.), color),
163 None => (px(0.), transparent_black()),
164 };
165 window.paint_quad(quad(
166 line,
167 pill.radius,
168 pill.fill,
169 border_width,
170 border_color,
171 BorderStyle::Solid,
172 ));
173 }
174 }
175}
176
177#[derive(Debug, PartialEq)]
178struct PillLine {
179 left: Pixels,
180 right: Pixels,
181 top: Pixels,
182}
183
184fn pill_lines(
185 text: &str,
186 range: Range<usize>,
187 line_left: Pixels,
188 position: impl Fn(usize) -> Option<Point<Pixels>>,
189) -> Vec<PillLine> {
190 let mut lines: Vec<PillLine> = Vec::new();
191 let Some(slice) = text.get(range.clone()) else {
192 return lines;
193 };
194 let mut before = position(range.start);
195 for (offset, character) in slice.char_indices() {
196 let after = position(range.start + offset + character.len_utf8());
197 let (Some(start), Some(end)) = (before, after) else {
198 before = after;
199 continue;
200 };
201 before = after;
202 if character == '\n' {
203 continue;
204 }
205 // gpui places a wrap-boundary index at the end of the previous line.
206 let left = if start.y == end.y { start.x } else { line_left };
207 let right = if character.is_whitespace() {
208 left
209 } else {
210 end.x
211 };
212 match lines.last_mut() {
213 Some(line) if line.top == end.y => line.right = right.max(line.right),
214 _ => lines.push(PillLine {
215 left,
216 right,
217 top: end.y,
218 }),
219 }
220 }
221 lines
222}
223
224fn link_at(
225 layout: &TextLayout,
226 links: &[(Range<usize>, String)],
227 position: Point<Pixels>,
228) -> Option<String> {
229 let index = layout.index_for_position(position).ok()?;
230 links
231 .iter()
232 .find(|(range, _)| range.contains(&index))
233 .map(|(_, url)| url.clone())
234}
235
236fn selection_quads(
237 start: Point<Pixels>,
238 end: Point<Pixels>,
239 bounds: Bounds<Pixels>,
240 line_height: Pixels,
241) -> Vec<Bounds<Pixels>> {
242 if start.y == end.y {
243 return vec![Bounds::from_corners(
244 start,
245 point(end.x, end.y + line_height),
246 )];
247 }
248 let mut quads = vec![Bounds::from_corners(
249 start,
250 point(bounds.right(), start.y + line_height),
251 )];
252 if end.y > start.y + line_height {
253 quads.push(Bounds::from_corners(
254 point(bounds.left(), start.y + line_height),
255 point(bounds.right(), end.y),
256 ));
257 }
258 quads.push(Bounds::from_corners(
259 point(bounds.left(), end.y),
260 point(end.x, end.y + line_height),
261 ));
262 quads
263}
264
265impl IntoElement for SelectableRichText {
266 type Element = Self;
267
268 fn into_element(self) -> Self::Element {
269 self
270 }
271}
272
273impl Element for SelectableRichText {
274 type RequestLayoutState = Participant;
275 type PrepaintState = Hitbox;
276
277 fn id(&self) -> Option<ElementId> {
278 Some(self.id.clone())
279 }
280
281 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
282 None
283 }
284
285 fn request_layout(
286 &mut self,
287 global_id: Option<&GlobalElementId>,
288 inspector_id: Option<&InspectorElementId>,
289 window: &mut Window,
290 cx: &mut App,
291 ) -> (LayoutId, Self::RequestLayoutState) {
292 let participant = Participant::retained(global_id, &self.text, window, cx);
293 let (layout_id, ()) = self
294 .styled_text
295 .request_layout(global_id, inspector_id, window, cx);
296 (layout_id, participant)
297 }
298
299 fn prepaint(
300 &mut self,
301 global_id: Option<&GlobalElementId>,
302 inspector_id: Option<&InspectorElementId>,
303 bounds: Bounds<Pixels>,
304 participant: &mut Self::RequestLayoutState,
305 window: &mut Window,
306 cx: &mut App,
307 ) -> Self::PrepaintState {
308 let handle = &participant.handle;
309 self.styled_text
310 .prepaint(global_id, inspector_id, bounds, &mut (), window, cx);
311 let slop = Edges {
312 left: px(HIT_SLOP),
313 right: px(HIT_SLOP),
314 ..Default::default()
315 };
316 let hitbox = window.insert_hitbox(bounds.extend(slop), HitboxBehavior::Normal);
317 let registration = TextSelectionRegistration::new(hitbox.clone(), bounds)
318 .with_text_bounds(vec![bounds])
319 .with_rendered_element(handle, window, cx);
320 handle.register(registration, window, cx);
321 hitbox
322 }
323
324 fn paint(
325 &mut self,
326 global_id: Option<&GlobalElementId>,
327 inspector_id: Option<&InspectorElementId>,
328 bounds: Bounds<Pixels>,
329 participant: &mut Self::RequestLayoutState,
330 hitbox: &mut Self::PrepaintState,
331 window: &mut Window,
332 cx: &mut App,
333 ) {
334 let layout = self.styled_text.layout().clone();
335 let selected_before = TextSelection::selected_text(window, cx);
336 let projection = participant.handle.update_runs(
337 &[TextSelectionRun::new(
338 self.text.clone(),
339 layout.clone(),
340 bounds,
341 )],
342 cx,
343 );
344 if selected_before != TextSelection::selected_text(window, cx) {
345 window.refresh();
346 }
347 paint_pills(&self.pills, &self.text, &layout, window);
348 let color = Theme::global(cx).tokens.colors.selection;
349 let content_end = self.text.trim_end_matches(TIME_ROOM).len();
350 let mut copied = String::new();
351 for range in projection.ranges().iter().flatten() {
352 let end_index = range.end.min(content_end);
353 if end_index <= range.start {
354 continue;
355 }
356 copied.push_str(
357 &self.text[range.start..end_index]
358 .replace(CODE_PADDING, "")
359 .replace(EMOJI_PLACEHOLDER, ""),
360 );
361 let (Some(start), Some(end)) = (
362 layout.position_for_index(range.start),
363 layout.position_for_index(end_index),
364 ) else {
365 continue;
366 };
367 for quad in selection_quads(start, end, layout.bounds(), layout.line_height()) {
368 window.paint_quad(fill(quad, color));
369 }
370 }
371 *participant.copied.borrow_mut() = copied;
372 self.styled_text.paint(
373 global_id,
374 inspector_id,
375 bounds,
376 &mut (),
377 &mut (),
378 window,
379 cx,
380 );
381 paint_inline_images(&self.inline_images, &self.text, &layout, window, cx);
382
383 let hovered_link = hitbox.is_hovered(window)
384 && link_at(&layout, &self.links, window.mouse_position()).is_some();
385 let cursor = if hovered_link {
386 CursorStyle::PointingHand
387 } else {
388 CursorStyle::IBeam
389 };
390 window.set_cursor_style(cursor, hitbox);
391 if !self.links.is_empty() {
392 let (hover_layout, hover_links, hover_hitbox) =
393 (layout.clone(), self.links.clone(), hitbox.clone());
394 window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, _| {
395 let over_link = hover_hitbox.is_hovered(window)
396 && link_at(&hover_layout, &hover_links, event.position).is_some();
397 if phase.bubble() && over_link != hovered_link {
398 window.refresh();
399 }
400 });
401 }
402 // gpui-base updates the selection on drag without notifying a view, so nothing redraws.
403 window.on_mouse_event(|event: &MouseMoveEvent, phase, window, _| {
404 if phase.bubble() && event.pressed_button == Some(MouseButton::Left) {
405 window.refresh();
406 }
407 });
408 if self.links.is_empty() {
409 return;
410 }
411 let links = std::mem::take(&mut self.links);
412 let hitbox = hitbox.clone();
413 window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
414 if !phase.bubble() || event.button != MouseButton::Left || !hitbox.is_hovered(window) {
415 return;
416 }
417 if !TextSelection::selected_text(window, cx).is_empty() {
418 return;
419 }
420 if let Some(url) = link_at(&layout, &links, event.position)
421 && !open_profile_link(&url, event.position, cx)
422 {
423 open_link(&url, cx);
424 }
425 });
426 }
427}
428
429#[cfg(test)]
430mod tests {
431 use gpui_kit::base::TextSelection;
432 use gpui_kit::test::TestWindowExt as _;
433 use gpui_kit::{
434 AnyWindowHandle, AppContext as _, Bounds, Context, FontWeight, HighlightStyle, IntoElement,
435 ParentElement as _, Point, Render, Styled as _, TestAppContext, Window, WindowBounds,
436 WindowOptions, div, point, px, size,
437 };
438
439 use super::{PillLine, SelectableRichText, pill_lines};
440
441 const TEXT: &str = "plain bold link";
442
443 struct Message;
444
445 impl Render for Message {
446 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
447 let bold = HighlightStyle {
448 font_weight: Some(FontWeight::BOLD),
449 ..Default::default()
450 };
451 div().w(px(400.)).child(
452 SelectableRichText::new("message", TEXT, vec![(6..10, bold)])
453 .links(vec![(11..15, "https://example.com".to_owned())]),
454 )
455 }
456 }
457
458 fn mount(cx: &mut TestAppContext) -> AnyWindowHandle {
459 cx.update(gpui_kit::init);
460 cx.update(|cx| {
461 let options = WindowOptions {
462 window_bounds: Some(WindowBounds::Windowed(Bounds {
463 origin: Point::default(),
464 size: size(px(400.), px(100.)),
465 })),
466 ..Default::default()
467 };
468 gpui_kit::open_window(options, cx, |_, cx| cx.new(|_| Message))
469 .expect("open test window")
470 .0
471 })
472 }
473
474 #[gpui_kit::test]
475 fn drag_selects_styled_text_for_copy(cx: &mut TestAppContext) {
476 let handle = mount(cx);
477 let selected = cx
478 .update_window(handle, |_, window, cx| {
479 window.render_frame(cx);
480 window.drag(point(px(1.), px(8.)), point(px(399.), px(8.)), cx);
481 window.render_frame(cx);
482 TextSelection::selected_text(window, cx)
483 })
484 .unwrap();
485 assert_eq!(selected, TEXT);
486 assert_eq!(cx.opened_url(), None);
487 }
488
489 #[gpui_kit::test]
490 fn click_on_a_link_opens_it_but_plain_text_does_not(cx: &mut TestAppContext) {
491 let handle = mount(cx);
492 let click = |x: f32, cx: &mut TestAppContext| {
493 cx.update_window(handle, |_, window, cx| {
494 window.render_frame(cx);
495 window.drag(point(px(x), px(8.)), point(px(x), px(8.)), cx);
496 })
497 .unwrap();
498 };
499 click(2., cx);
500 assert_eq!(cx.opened_url(), None);
501 let link_x = (40..400).map(|x| x as f32).find(|x| {
502 click(*x, cx);
503 cx.opened_url().is_some()
504 });
505 assert!(link_x.is_some());
506 assert_eq!(cx.opened_url().as_deref(), Some("https://example.com"));
507 }
508
509 #[test]
510 fn pill_wrapped_whole_onto_next_line_paints_only_there() {
511 let text = "the code";
512 let position = |index: usize| {
513 Some(if index <= 4 {
514 point(px(index as f32 * 10.), px(0.))
515 } else {
516 point(px((index - 4) as f32 * 10.), px(20.))
517 })
518 };
519 assert_eq!(
520 pill_lines(text, 4..8, px(0.), position),
521 vec![PillLine {
522 left: px(0.),
523 right: px(40.),
524 top: px(20.),
525 }]
526 );
527 }
528
529 #[test]
530 fn pill_split_by_a_wrap_paints_one_piece_per_line_without_the_trailing_space() {
531 let text = "ab cd";
532 let position = |index: usize| {
533 Some(if index <= 3 {
534 point(px(index as f32 * 10.), px(0.))
535 } else {
536 point(px((index - 3) as f32 * 10.), px(20.))
537 })
538 };
539 assert_eq!(
540 pill_lines(text, 0..5, px(0.), position),
541 vec![
542 PillLine {
543 left: px(0.),
544 right: px(20.),
545 top: px(0.),
546 },
547 PillLine {
548 left: px(0.),
549 right: px(20.),
550 top: px(20.),
551 },
552 ]
553 );
554 }
555}