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