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