BlueGit

ict rusty-teams

Files

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

selectable.rs

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