| 1 | use std::cell::RefCell; |
| 2 | use std::ops::Range; |
| 3 | use std::rc::Rc; |
| 4 | |
| 5 | use gpui_kit::base::{TextSelection, TextSelectionRegistration, TextSelectionRun, Theme}; |
| 6 | use gpui_kit::*; |
| 7 | |
| 8 | use super::blocks::CODE_PADDING; |
| 9 | use super::hooks::open_profile_link; |
| 10 | use super::link_tooltip::LinkTooltip; |
| 11 | use super::selectable::{HIT_SLOP, PILL_INSET_Y, PILL_OUTSET, Participant, Pill, TIME_ROOM}; |
| 12 | |
| 13 | const WRAP_TOLERANCE: f32 = 0.5; |
| 14 | |
| 15 | #[derive(Clone)] |
| 16 | pub struct FlowSegment { |
| 17 | pub range: Range<usize>, |
| 18 | pub highlight: HighlightStyle, |
| 19 | pub family: Option<SharedString>, |
| 20 | pub scale: f32, |
| 21 | pub raise: f32, |
| 22 | } |
| 23 | |
| 24 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 25 | struct Measured { |
| 26 | width: Pixels, |
| 27 | baseline: Pixels, |
| 28 | } |
| 29 | |
| 30 | #[derive(Debug, Clone, PartialEq)] |
| 31 | struct Piece { |
| 32 | range: Range<usize>, |
| 33 | scale: f32, |
| 34 | raise: f32, |
| 35 | width: Pixels, |
| 36 | baseline: Pixels, |
| 37 | height: Pixels, |
| 38 | } |
| 39 | |
| 40 | #[derive(Debug, Clone, PartialEq)] |
| 41 | struct Fragment { |
| 42 | range: Range<usize>, |
| 43 | scale: f32, |
| 44 | origin: Point<Pixels>, |
| 45 | size: Size<Pixels>, |
| 46 | line: usize, |
| 47 | } |
| 48 | |
| 49 | #[derive(Debug, Clone, PartialEq)] |
| 50 | struct Line { |
| 51 | top: Pixels, |
| 52 | height: Pixels, |
| 53 | } |
| 54 | |
| 55 | #[derive(Debug, Clone, PartialEq, Default)] |
| 56 | struct FlowLayout { |
| 57 | fragments: Vec<Fragment>, |
| 58 | lines: Vec<Line>, |
| 59 | size: Size<Pixels>, |
| 60 | wrap_width: Option<Pixels>, |
| 61 | } |
| 62 | |
| 63 | #[derive(Clone)] |
| 64 | struct Typography { |
| 65 | style: TextStyle, |
| 66 | font_size: Pixels, |
| 67 | line_height: Pixels, |
| 68 | rem_size: Pixels, |
| 69 | } |
| 70 | |
| 71 | impl Typography { |
| 72 | fn capture(window: &Window) -> Typography { |
| 73 | let style = window.text_style(); |
| 74 | let rem_size = window.rem_size(); |
| 75 | Typography { |
| 76 | font_size: style.font_size.to_pixels(rem_size), |
| 77 | line_height: style.line_height.to_pixels(style.font_size, rem_size), |
| 78 | rem_size, |
| 79 | style, |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | struct Atom { |
| 85 | word: Range<usize>, |
| 86 | space: Range<usize>, |
| 87 | } |
| 88 | |
| 89 | fn hard_lines(text: &str) -> Vec<Range<usize>> { |
| 90 | let mut lines = Vec::new(); |
| 91 | let mut start = 0; |
| 92 | for (newline, _) in text.match_indices('\n') { |
| 93 | lines.push(start..newline); |
| 94 | start = newline + 1; |
| 95 | } |
| 96 | lines.push(start..text.len()); |
| 97 | lines |
| 98 | } |
| 99 | |
| 100 | fn atoms(text: &str, line: Range<usize>) -> Vec<Atom> { |
| 101 | let mut atoms = Vec::new(); |
| 102 | let mut index = line.start; |
| 103 | while index < line.end { |
| 104 | let word_end = text[index..line.end] |
| 105 | .find(' ') |
| 106 | .map_or(line.end, |offset| index + offset); |
| 107 | let space_end = word_end |
| 108 | + text[word_end..line.end] |
| 109 | .bytes() |
| 110 | .take_while(|byte| *byte == b' ') |
| 111 | .count(); |
| 112 | atoms.push(Atom { |
| 113 | word: index..word_end, |
| 114 | space: word_end..space_end, |
| 115 | }); |
| 116 | index = space_end; |
| 117 | } |
| 118 | atoms |
| 119 | } |
| 120 | |
| 121 | fn style_spans(segments: &[FlowSegment], range: &Range<usize>) -> Vec<(Range<usize>, f32, f32)> { |
| 122 | let mut spans: Vec<(Range<usize>, f32, f32)> = Vec::new(); |
| 123 | for segment in segments { |
| 124 | let start = segment.range.start.max(range.start); |
| 125 | let end = segment.range.end.min(range.end); |
| 126 | if start >= end { |
| 127 | continue; |
| 128 | } |
| 129 | match spans.last_mut() { |
| 130 | Some((last, scale, raise)) |
| 131 | if *scale == segment.scale && *raise == segment.raise && last.end == start => |
| 132 | { |
| 133 | last.end = end; |
| 134 | } |
| 135 | _ => spans.push((start..end, segment.scale, segment.raise)), |
| 136 | } |
| 137 | } |
| 138 | spans |
| 139 | } |
| 140 | |
| 141 | fn build_lines( |
| 142 | text: &str, |
| 143 | segments: &[FlowSegment], |
| 144 | wrap_width: Option<Pixels>, |
| 145 | base_line_height: Pixels, |
| 146 | measure: &mut impl FnMut(&Range<usize>, f32) -> Measured, |
| 147 | ) -> Vec<Vec<Piece>> { |
| 148 | let mut pieces_of = |range: &Range<usize>| -> Vec<Piece> { |
| 149 | style_spans(segments, range) |
| 150 | .into_iter() |
| 151 | .map(|(range, scale, raise)| { |
| 152 | let measured = measure(&range, scale); |
| 153 | Piece { |
| 154 | range, |
| 155 | scale, |
| 156 | raise, |
| 157 | width: measured.width, |
| 158 | baseline: measured.baseline, |
| 159 | height: base_line_height * scale, |
| 160 | } |
| 161 | }) |
| 162 | .collect() |
| 163 | }; |
| 164 | let mut lines = Vec::new(); |
| 165 | for hard_line in hard_lines(text) { |
| 166 | let mut line: Vec<Piece> = Vec::new(); |
| 167 | let mut width = Pixels::ZERO; |
| 168 | for atom in atoms(text, hard_line) { |
| 169 | let word = pieces_of(&atom.word); |
| 170 | let space = pieces_of(&atom.space); |
| 171 | let word_width: Pixels = word.iter().map(|piece| piece.width).sum(); |
| 172 | let space_width: Pixels = space.iter().map(|piece| piece.width).sum(); |
| 173 | let overflows = |
| 174 | wrap_width.is_some_and(|limit| width + word_width > limit + px(WRAP_TOLERANCE)); |
| 175 | if overflows && !line.is_empty() { |
| 176 | lines.push(std::mem::take(&mut line)); |
| 177 | width = Pixels::ZERO; |
| 178 | } |
| 179 | line.extend(word); |
| 180 | line.extend(space); |
| 181 | width += word_width + space_width; |
| 182 | } |
| 183 | lines.push(line); |
| 184 | } |
| 185 | lines |
| 186 | } |
| 187 | |
| 188 | fn place( |
| 189 | lines: Vec<Vec<Piece>>, |
| 190 | base: Measured, |
| 191 | base_line_height: Pixels, |
| 192 | base_font_size: Pixels, |
| 193 | wrap_width: Option<Pixels>, |
| 194 | ) -> FlowLayout { |
| 195 | let mut layout = FlowLayout { |
| 196 | wrap_width, |
| 197 | ..FlowLayout::default() |
| 198 | }; |
| 199 | let mut top = Pixels::ZERO; |
| 200 | for (line_index, pieces) in lines.into_iter().enumerate() { |
| 201 | let mut ascent = base.baseline; |
| 202 | let mut descent = base_line_height - base.baseline; |
| 203 | for piece in &pieces { |
| 204 | let raise = base_font_size * piece.raise; |
| 205 | ascent = ascent.max(piece.baseline + raise); |
| 206 | descent = descent.max(piece.height - piece.baseline - raise); |
| 207 | } |
| 208 | let mut x = Pixels::ZERO; |
| 209 | let mut fragments: Vec<(Fragment, f32)> = Vec::new(); |
| 210 | for piece in pieces { |
| 211 | let raise = base_font_size * piece.raise; |
| 212 | match fragments.last_mut() { |
| 213 | Some((fragment, last_raise)) |
| 214 | if fragment.scale == piece.scale |
| 215 | && *last_raise == piece.raise |
| 216 | && fragment.range.end == piece.range.start => |
| 217 | { |
| 218 | fragment.range.end = piece.range.end; |
| 219 | fragment.size.width += piece.width; |
| 220 | } |
| 221 | _ => fragments.push(( |
| 222 | Fragment { |
| 223 | range: piece.range.clone(), |
| 224 | scale: piece.scale, |
| 225 | origin: point(x, top + ascent - piece.baseline - raise), |
| 226 | size: size(piece.width, piece.height), |
| 227 | line: line_index, |
| 228 | }, |
| 229 | piece.raise, |
| 230 | )), |
| 231 | } |
| 232 | x += piece.width; |
| 233 | } |
| 234 | layout.size.width = layout.size.width.max(x); |
| 235 | layout.lines.push(Line { |
| 236 | top, |
| 237 | height: ascent + descent, |
| 238 | }); |
| 239 | layout |
| 240 | .fragments |
| 241 | .extend(fragments.into_iter().map(|(fragment, _)| fragment)); |
| 242 | top += ascent + descent; |
| 243 | } |
| 244 | layout.size.height = top; |
| 245 | if let Some(limit) = wrap_width { |
| 246 | layout.size.width = layout.size.width.min(limit); |
| 247 | } |
| 248 | layout |
| 249 | } |
| 250 | |
| 251 | fn text_runs(style: &TextStyle, segments: &[FlowSegment], range: &Range<usize>) -> Vec<TextRun> { |
| 252 | let mut runs = Vec::new(); |
| 253 | let mut covered = range.start; |
| 254 | for segment in segments { |
| 255 | let start = segment.range.start.max(range.start); |
| 256 | let end = segment.range.end.min(range.end); |
| 257 | if start >= end { |
| 258 | continue; |
| 259 | } |
| 260 | if covered < start { |
| 261 | runs.push(style.clone().to_run(start - covered)); |
| 262 | } |
| 263 | let mut run = style |
| 264 | .clone() |
| 265 | .highlight(segment.highlight) |
| 266 | .to_run(end - start); |
| 267 | if let Some(family) = &segment.family { |
| 268 | run.font.family = family.clone(); |
| 269 | } |
| 270 | runs.push(run); |
| 271 | covered = end; |
| 272 | } |
| 273 | if covered < range.end { |
| 274 | runs.push(style.clone().to_run(range.end - covered)); |
| 275 | } |
| 276 | runs |
| 277 | } |
| 278 | |
| 279 | fn compute_layout( |
| 280 | text: &str, |
| 281 | segments: &[FlowSegment], |
| 282 | typography: &Typography, |
| 283 | wrap_width: Option<Pixels>, |
| 284 | window: &mut Window, |
| 285 | ) -> FlowLayout { |
| 286 | let mut measure = |range: &Range<usize>, scale: f32| { |
| 287 | let runs = text_runs(&typography.style, segments, range); |
| 288 | let line = window.text_system().shape_line( |
| 289 | SharedString::from(text[range.clone()].to_owned()), |
| 290 | typography.font_size * scale, |
| 291 | &runs, |
| 292 | None, |
| 293 | ); |
| 294 | let height = typography.line_height * scale; |
| 295 | Measured { |
| 296 | width: line.width(), |
| 297 | baseline: (height - line.ascent - line.descent) / 2. + line.ascent, |
| 298 | } |
| 299 | }; |
| 300 | let strut = { |
| 301 | let runs = vec![typography.style.clone().to_run(1)]; |
| 302 | let line = window |
| 303 | .text_system() |
| 304 | .shape_line(" ".into(), typography.font_size, &runs, None); |
| 305 | Measured { |
| 306 | width: Pixels::ZERO, |
| 307 | baseline: (typography.line_height - line.ascent - line.descent) / 2. + line.ascent, |
| 308 | } |
| 309 | }; |
| 310 | let lines = build_lines( |
| 311 | text, |
| 312 | segments, |
| 313 | wrap_width, |
| 314 | typography.line_height, |
| 315 | &mut measure, |
| 316 | ); |
| 317 | place( |
| 318 | lines, |
| 319 | strut, |
| 320 | typography.line_height, |
| 321 | typography.font_size, |
| 322 | wrap_width, |
| 323 | ) |
| 324 | } |
| 325 | |
| 326 | pub struct FlowText { |
| 327 | id: ElementId, |
| 328 | text: SharedString, |
| 329 | segments: Vec<FlowSegment>, |
| 330 | links: Vec<(Range<usize>, String)>, |
| 331 | pills: Vec<Pill>, |
| 332 | } |
| 333 | |
| 334 | impl FlowText { |
| 335 | pub fn new( |
| 336 | id: impl Into<ElementId>, |
| 337 | text: impl Into<SharedString>, |
| 338 | segments: Vec<FlowSegment>, |
| 339 | ) -> Self { |
| 340 | FlowText { |
| 341 | id: id.into(), |
| 342 | text: text.into(), |
| 343 | segments, |
| 344 | links: Vec::new(), |
| 345 | pills: Vec::new(), |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | pub fn links(mut self, links: Vec<(Range<usize>, String)>) -> Self { |
| 350 | self.links = links; |
| 351 | self |
| 352 | } |
| 353 | |
| 354 | pub fn pills(mut self, pills: Vec<Pill>) -> Self { |
| 355 | self.pills = pills; |
| 356 | self |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | pub struct FlowRequest { |
| 361 | participant: Participant, |
| 362 | typography: Typography, |
| 363 | measured: Rc<RefCell<Option<Rc<FlowLayout>>>>, |
| 364 | } |
| 365 | |
| 366 | struct PaintedFragment { |
| 367 | element: AnyElement, |
| 368 | layout: TextLayout, |
| 369 | fragment: Fragment, |
| 370 | bounds: Bounds<Pixels>, |
| 371 | band: Bounds<Pixels>, |
| 372 | } |
| 373 | |
| 374 | pub struct FlowPrepaint { |
| 375 | hitbox: Hitbox, |
| 376 | fragments: Vec<PaintedFragment>, |
| 377 | lines: Vec<Line>, |
| 378 | tooltip: Option<LinkTooltip>, |
| 379 | } |
| 380 | |
| 381 | impl IntoElement for FlowText { |
| 382 | type Element = Self; |
| 383 | |
| 384 | fn into_element(self) -> Self::Element { |
| 385 | self |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | impl FlowText { |
| 390 | fn fragment_text(&self, fragment: &Fragment) -> SharedString { |
| 391 | SharedString::from(self.text[fragment.range.clone()].to_owned()) |
| 392 | } |
| 393 | |
| 394 | fn fragment_styled_text(&self, fragment: &Fragment) -> StyledText { |
| 395 | let mut highlights = Vec::new(); |
| 396 | let mut families = Vec::new(); |
| 397 | for segment in &self.segments { |
| 398 | let start = segment.range.start.max(fragment.range.start); |
| 399 | let end = segment.range.end.min(fragment.range.end); |
| 400 | if start >= end { |
| 401 | continue; |
| 402 | } |
| 403 | let local = start - fragment.range.start..end - fragment.range.start; |
| 404 | if segment.highlight != HighlightStyle::default() { |
| 405 | highlights.push((local.clone(), segment.highlight)); |
| 406 | } |
| 407 | if let Some(family) = &segment.family { |
| 408 | families.push((local, family.clone())); |
| 409 | } |
| 410 | } |
| 411 | let styled = StyledText::new(self.fragment_text(fragment)).with_highlights(highlights); |
| 412 | if families.is_empty() { |
| 413 | styled |
| 414 | } else { |
| 415 | styled.with_font_family_overrides(families) |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | fn lay_out_fragment( |
| 420 | &self, |
| 421 | fragment: &Fragment, |
| 422 | area: Bounds<Pixels>, |
| 423 | typography: &Typography, |
| 424 | window: &mut Window, |
| 425 | cx: &mut App, |
| 426 | ) -> (AnyElement, TextLayout) { |
| 427 | let styled = self.fragment_styled_text(fragment); |
| 428 | let text_layout = styled.layout().clone(); |
| 429 | let mut element = styled.into_any_element(); |
| 430 | let mut style = typography.style.clone(); |
| 431 | style.font_size = (typography.font_size * fragment.scale).into(); |
| 432 | style.line_height = area.size.height.into(); |
| 433 | style.white_space = WhiteSpace::Nowrap; |
| 434 | window.with_rem_size(Some(typography.rem_size), |window| { |
| 435 | window.with_text_style(Some(style.subtract(&Default::default())), |window| { |
| 436 | element.prepaint_as_root( |
| 437 | area.origin, |
| 438 | size( |
| 439 | AvailableSpace::Definite(area.size.width), |
| 440 | AvailableSpace::Definite(area.size.height), |
| 441 | ), |
| 442 | window, |
| 443 | cx, |
| 444 | ); |
| 445 | }); |
| 446 | }); |
| 447 | (element, text_layout) |
| 448 | } |
| 449 | |
| 450 | fn link_at( |
| 451 | prepaint: &[PaintedFragment], |
| 452 | links: &[(Range<usize>, String)], |
| 453 | position: Point<Pixels>, |
| 454 | ) -> Option<String> { |
| 455 | prepaint.iter().find_map(|painted| { |
| 456 | let index = painted.layout.index_for_position(position).ok()?; |
| 457 | let global = painted.fragment.range.start + index; |
| 458 | links |
| 459 | .iter() |
| 460 | .find(|(range, _)| range.contains(&global)) |
| 461 | .map(|(_, url)| url.clone()) |
| 462 | }) |
| 463 | } |
| 464 | |
| 465 | fn paint_pills(&self, prepaint: &[PaintedFragment], window: &mut Window) { |
| 466 | for pill in &self.pills { |
| 467 | for painted in prepaint { |
| 468 | let start = pill.range.start.max(painted.fragment.range.start); |
| 469 | let end = pill.range.end.min(painted.fragment.range.end); |
| 470 | if start >= end { |
| 471 | continue; |
| 472 | } |
| 473 | let offset = painted.fragment.range.start; |
| 474 | let (Some(from), Some(to)) = ( |
| 475 | painted.layout.position_for_index(start - offset), |
| 476 | painted.layout.position_for_index(end - offset), |
| 477 | ) else { |
| 478 | continue; |
| 479 | }; |
| 480 | let left = if start == pill.range.start { |
| 481 | from.x - px(PILL_OUTSET) |
| 482 | } else { |
| 483 | from.x |
| 484 | }; |
| 485 | let right = if end == pill.range.end { |
| 486 | to.x + px(PILL_OUTSET) |
| 487 | } else { |
| 488 | to.x |
| 489 | }; |
| 490 | let area = Bounds::from_corners( |
| 491 | point(left, painted.bounds.top() + px(PILL_INSET_Y)), |
| 492 | point(right, painted.bounds.bottom() - px(PILL_INSET_Y)), |
| 493 | ); |
| 494 | let (border_width, border_color) = match pill.border { |
| 495 | Some(color) => (px(1.), color), |
| 496 | None => (px(0.), transparent_black()), |
| 497 | }; |
| 498 | window.paint_quad(quad( |
| 499 | area, |
| 500 | pill.radius, |
| 501 | pill.fill, |
| 502 | border_width, |
| 503 | border_color, |
| 504 | BorderStyle::Solid, |
| 505 | )); |
| 506 | } |
| 507 | } |
| 508 | } |
| 509 | } |
| 510 | |
| 511 | impl Element for FlowText { |
| 512 | type RequestLayoutState = FlowRequest; |
| 513 | type PrepaintState = FlowPrepaint; |
| 514 | |
| 515 | fn id(&self) -> Option<ElementId> { |
| 516 | Some(self.id.clone()) |
| 517 | } |
| 518 | |
| 519 | fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { |
| 520 | None |
| 521 | } |
| 522 | |
| 523 | fn request_layout( |
| 524 | &mut self, |
| 525 | global_id: Option<&GlobalElementId>, |
| 526 | _inspector_id: Option<&InspectorElementId>, |
| 527 | window: &mut Window, |
| 528 | cx: &mut App, |
| 529 | ) -> (LayoutId, Self::RequestLayoutState) { |
| 530 | let participant = Participant::retained(global_id, &self.text, window, cx); |
| 531 | let typography = Typography::capture(window); |
| 532 | let measured: Rc<RefCell<Option<Rc<FlowLayout>>>> = Rc::default(); |
| 533 | let text = self.text.clone(); |
| 534 | let segments = self.segments.clone(); |
| 535 | let layout_id = window.request_measured_layout(Default::default(), { |
| 536 | let typography = typography.clone(); |
| 537 | let measured = measured.clone(); |
| 538 | move |known_dimensions, available_space, window, _| { |
| 539 | let wrap_width = known_dimensions.width.or(match available_space.width { |
| 540 | AvailableSpace::Definite(width) => Some(width), |
| 541 | _ => None, |
| 542 | }); |
| 543 | let layout = compute_layout(&text, &segments, &typography, wrap_width, window); |
| 544 | let size = layout.size; |
| 545 | *measured.borrow_mut() = Some(Rc::new(layout)); |
| 546 | size |
| 547 | } |
| 548 | }); |
| 549 | ( |
| 550 | layout_id, |
| 551 | FlowRequest { |
| 552 | participant, |
| 553 | typography, |
| 554 | measured, |
| 555 | }, |
| 556 | ) |
| 557 | } |
| 558 | |
| 559 | fn prepaint( |
| 560 | &mut self, |
| 561 | global_id: Option<&GlobalElementId>, |
| 562 | _inspector_id: Option<&InspectorElementId>, |
| 563 | bounds: Bounds<Pixels>, |
| 564 | request: &mut Self::RequestLayoutState, |
| 565 | window: &mut Window, |
| 566 | cx: &mut App, |
| 567 | ) -> Self::PrepaintState { |
| 568 | let typography = request.typography.clone(); |
| 569 | let measured = request.measured.borrow().clone(); |
| 570 | let layout = match measured { |
| 571 | Some(layout) |
| 572 | if layout.wrap_width.is_some_and(|width| { |
| 573 | (width - bounds.size.width).abs() < px(WRAP_TOLERANCE) |
| 574 | }) => |
| 575 | { |
| 576 | layout |
| 577 | } |
| 578 | _ => Rc::new(compute_layout( |
| 579 | &self.text, |
| 580 | &self.segments, |
| 581 | &typography, |
| 582 | Some(bounds.size.width), |
| 583 | window, |
| 584 | )), |
| 585 | }; |
| 586 | let mut fragments = Vec::with_capacity(layout.fragments.len()); |
| 587 | for fragment in &layout.fragments { |
| 588 | let band = Bounds::new( |
| 589 | point( |
| 590 | bounds.origin.x + fragment.origin.x, |
| 591 | bounds.origin.y + layout.lines[fragment.line].top, |
| 592 | ), |
| 593 | size(fragment.size.width, layout.lines[fragment.line].height), |
| 594 | ); |
| 595 | let origin = bounds.origin + fragment.origin; |
| 596 | let glyphs = Bounds::new(origin, fragment.size); |
| 597 | let (element, _) = self.lay_out_fragment(fragment, glyphs, &typography, window, cx); |
| 598 | let (_, layout) = self.lay_out_fragment(fragment, band, &typography, window, cx); |
| 599 | fragments.push(PaintedFragment { |
| 600 | element, |
| 601 | layout, |
| 602 | fragment: fragment.clone(), |
| 603 | bounds: glyphs, |
| 604 | band, |
| 605 | }); |
| 606 | } |
| 607 | let slop = Edges { |
| 608 | left: px(HIT_SLOP), |
| 609 | right: px(HIT_SLOP), |
| 610 | ..Default::default() |
| 611 | }; |
| 612 | let hitbox = window.insert_hitbox(bounds.extend(slop), HitboxBehavior::Normal); |
| 613 | let registration = TextSelectionRegistration::new(hitbox.clone(), bounds) |
| 614 | .with_text_bounds(fragments.iter().map(|painted| painted.band).collect()) |
| 615 | .with_rendered_element(&request.participant.handle, window, cx); |
| 616 | request |
| 617 | .participant |
| 618 | .handle |
| 619 | .register(registration, window, cx); |
| 620 | FlowPrepaint { |
| 621 | hitbox, |
| 622 | fragments, |
| 623 | lines: layout.lines.clone(), |
| 624 | tooltip: LinkTooltip::prepaint(global_id, !self.links.is_empty(), window), |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | fn paint( |
| 629 | &mut self, |
| 630 | _global_id: Option<&GlobalElementId>, |
| 631 | _inspector_id: Option<&InspectorElementId>, |
| 632 | bounds: Bounds<Pixels>, |
| 633 | request: &mut Self::RequestLayoutState, |
| 634 | prepaint: &mut Self::PrepaintState, |
| 635 | window: &mut Window, |
| 636 | cx: &mut App, |
| 637 | ) { |
| 638 | let participant = &request.participant; |
| 639 | let selected_before = TextSelection::selected_text(window, cx); |
| 640 | let runs: Vec<TextSelectionRun> = prepaint |
| 641 | .fragments |
| 642 | .iter() |
| 643 | .enumerate() |
| 644 | .map(|(order, painted)| { |
| 645 | TextSelectionRun::new( |
| 646 | self.fragment_text(&painted.fragment), |
| 647 | painted.layout.clone(), |
| 648 | painted.band, |
| 649 | ) |
| 650 | .with_document_order(order as u64) |
| 651 | }) |
| 652 | .collect(); |
| 653 | let projection = participant.handle.update_runs(&runs, cx); |
| 654 | if selected_before != TextSelection::selected_text(window, cx) { |
| 655 | window.refresh(); |
| 656 | } |
| 657 | self.paint_pills(&prepaint.fragments, window); |
| 658 | |
| 659 | let color = Theme::global(cx).tokens.colors.selection; |
| 660 | let content_end = self.text.trim_end_matches(TIME_ROOM).len(); |
| 661 | let ranges = projection.ranges(); |
| 662 | let mut copied = String::new(); |
| 663 | let mut previous_end: Option<usize> = None; |
| 664 | for (index, painted) in prepaint.fragments.iter().enumerate() { |
| 665 | let Some(Some(range)) = ranges.get(index) else { |
| 666 | continue; |
| 667 | }; |
| 668 | let offset = painted.fragment.range.start; |
| 669 | let end_index = (offset + range.end).min(content_end); |
| 670 | let start_index = offset + range.start; |
| 671 | if end_index <= start_index { |
| 672 | continue; |
| 673 | } |
| 674 | if let Some(end) = previous_end |
| 675 | && self.text[end..start_index].contains('\n') |
| 676 | { |
| 677 | copied.push('\n'); |
| 678 | } |
| 679 | previous_end = Some(end_index); |
| 680 | copied.push_str(&self.text[start_index..end_index].replace(CODE_PADDING, "")); |
| 681 | let (Some(from), Some(to)) = ( |
| 682 | painted.layout.position_for_index(range.start), |
| 683 | painted.layout.position_for_index(end_index - offset), |
| 684 | ) else { |
| 685 | continue; |
| 686 | }; |
| 687 | let line = &prepaint.lines[painted.fragment.line]; |
| 688 | let top = bounds.top() + line.top; |
| 689 | let reaches_line_end = end_index >= painted.fragment.range.end |
| 690 | && prepaint |
| 691 | .fragments |
| 692 | .get(index + 1) |
| 693 | .is_some_and(|next| next.fragment.line != painted.fragment.line) |
| 694 | && ranges.iter().skip(index + 1).any(Option::is_some); |
| 695 | let right = if reaches_line_end { |
| 696 | bounds.right() |
| 697 | } else { |
| 698 | to.x |
| 699 | }; |
| 700 | window.paint_quad(fill( |
| 701 | Bounds::from_corners(point(from.x, top), point(right, top + line.height)), |
| 702 | color, |
| 703 | )); |
| 704 | } |
| 705 | *participant.copied.borrow_mut() = copied; |
| 706 | |
| 707 | for painted in prepaint.fragments.iter_mut() { |
| 708 | painted.element.paint(window, cx); |
| 709 | } |
| 710 | |
| 711 | let hovered_link = prepaint.hitbox.is_hovered(window) |
| 712 | && Self::link_at(&prepaint.fragments, &self.links, window.mouse_position()).is_some(); |
| 713 | let cursor = if hovered_link { |
| 714 | CursorStyle::PointingHand |
| 715 | } else { |
| 716 | CursorStyle::IBeam |
| 717 | }; |
| 718 | window.set_cursor_style(cursor, &prepaint.hitbox); |
| 719 | if !self.links.is_empty() { |
| 720 | let hover_layouts: Vec<(TextLayout, usize)> = prepaint |
| 721 | .fragments |
| 722 | .iter() |
| 723 | .map(|painted| (painted.layout.clone(), painted.fragment.range.start)) |
| 724 | .collect(); |
| 725 | if let Some(tooltip) = &prepaint.tooltip { |
| 726 | let (tooltip_layouts, tooltip_links) = (hover_layouts.clone(), self.links.clone()); |
| 727 | tooltip.paint( |
| 728 | &prepaint.hitbox, |
| 729 | move |position| { |
| 730 | tooltip_layouts.iter().find_map(|(layout, start)| { |
| 731 | let index = layout.index_for_position(position).ok()?; |
| 732 | tooltip_links |
| 733 | .iter() |
| 734 | .find(|(range, _)| range.contains(&(start + index))) |
| 735 | .map(|(_, url)| url.clone()) |
| 736 | }) |
| 737 | }, |
| 738 | window, |
| 739 | ); |
| 740 | } |
| 741 | let (hover_links, hover_hitbox) = (self.links.clone(), prepaint.hitbox.clone()); |
| 742 | window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, _| { |
| 743 | let over_link = hover_hitbox.is_hovered(window) |
| 744 | && hover_layouts.iter().any(|(layout, start)| { |
| 745 | layout |
| 746 | .index_for_position(event.position) |
| 747 | .is_ok_and(|index| { |
| 748 | hover_links |
| 749 | .iter() |
| 750 | .any(|(range, _)| range.contains(&(start + index))) |
| 751 | }) |
| 752 | }); |
| 753 | if phase.bubble() && over_link != hovered_link { |
| 754 | window.refresh(); |
| 755 | } |
| 756 | }); |
| 757 | } |
| 758 | window.on_mouse_event(|event: &MouseMoveEvent, phase, window, _| { |
| 759 | if phase.bubble() && event.pressed_button == Some(MouseButton::Left) { |
| 760 | window.refresh(); |
| 761 | } |
| 762 | }); |
| 763 | if self.links.is_empty() { |
| 764 | return; |
| 765 | } |
| 766 | let links = std::mem::take(&mut self.links); |
| 767 | let hitbox = prepaint.hitbox.clone(); |
| 768 | let layouts: Vec<(TextLayout, usize)> = prepaint |
| 769 | .fragments |
| 770 | .iter() |
| 771 | .map(|painted| (painted.layout.clone(), painted.fragment.range.start)) |
| 772 | .collect(); |
| 773 | window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| { |
| 774 | if !phase.bubble() || event.button != MouseButton::Left || !hitbox.is_hovered(window) { |
| 775 | return; |
| 776 | } |
| 777 | if !TextSelection::selected_text(window, cx).is_empty() { |
| 778 | return; |
| 779 | } |
| 780 | let url = layouts.iter().find_map(|(layout, offset)| { |
| 781 | let index = layout.index_for_position(event.position).ok()?; |
| 782 | links |
| 783 | .iter() |
| 784 | .find(|(range, _)| range.contains(&(offset + index))) |
| 785 | .map(|(_, url)| url.clone()) |
| 786 | }); |
| 787 | if let Some(url) = url |
| 788 | && !open_profile_link(&url, event.position, cx) |
| 789 | { |
| 790 | super::hooks::open_link(&url, cx); |
| 791 | } |
| 792 | }); |
| 793 | } |
| 794 | } |
| 795 | |
| 796 | #[cfg(test)] |
| 797 | mod tests { |
| 798 | use std::ops::Range; |
| 799 | |
| 800 | use gpui_kit::base::TextSelection; |
| 801 | use gpui_kit::test::TestWindowExt as _; |
| 802 | use gpui_kit::{ |
| 803 | AnyWindowHandle, AppContext as _, Bounds, Context, HighlightStyle, IntoElement, Modifiers, |
| 804 | MouseButton, ParentElement as _, Pixels, Point, Render, Styled as _, TestAppContext, |
| 805 | VisualTestContext, Window, WindowBounds, WindowOptions, div, point, px, size, |
| 806 | }; |
| 807 | |
| 808 | use super::{FlowLayout, FlowSegment, FlowText, Measured, build_lines, place}; |
| 809 | |
| 810 | const BASE_HEIGHT: f32 = 20.; |
| 811 | |
| 812 | fn segment(range: Range<usize>, scale: f32, raise: f32) -> FlowSegment { |
| 813 | FlowSegment { |
| 814 | range, |
| 815 | highlight: HighlightStyle::default(), |
| 816 | family: None, |
| 817 | scale, |
| 818 | raise, |
| 819 | } |
| 820 | } |
| 821 | |
| 822 | fn measure(range: &Range<usize>, scale: f32) -> Measured { |
| 823 | Measured { |
| 824 | width: px(range.len() as f32 * 10. * scale), |
| 825 | baseline: px(BASE_HEIGHT * scale * 0.8), |
| 826 | } |
| 827 | } |
| 828 | |
| 829 | fn layout(text: &str, segments: &[FlowSegment], wrap: Option<f32>) -> FlowLayout { |
| 830 | let wrap_width = wrap.map(px); |
| 831 | let lines = build_lines(text, segments, wrap_width, px(BASE_HEIGHT), &mut measure); |
| 832 | place( |
| 833 | lines, |
| 834 | Measured { |
| 835 | width: Pixels::ZERO, |
| 836 | baseline: px(BASE_HEIGHT * 0.8), |
| 837 | }, |
| 838 | px(BASE_HEIGHT), |
| 839 | px(14.), |
| 840 | wrap_width, |
| 841 | ) |
| 842 | } |
| 843 | |
| 844 | #[test] |
| 845 | fn words_wrap_at_the_width_and_keep_their_trailing_space_on_the_line() { |
| 846 | let text = "aaa bbb ccc"; |
| 847 | let flow = layout(text, &[segment(0..11, 1., 0.)], Some(75.)); |
| 848 | let ranges: Vec<_> = flow.fragments.iter().map(|f| f.range.clone()).collect(); |
| 849 | assert_eq!(ranges, vec![0..8, 8..11]); |
| 850 | assert_eq!(flow.fragments[1].origin.y, px(BASE_HEIGHT)); |
| 851 | assert_eq!(flow.size.height, px(2. * BASE_HEIGHT)); |
| 852 | } |
| 853 | |
| 854 | #[test] |
| 855 | fn a_word_is_never_split_across_scale_changes_when_wrapping() { |
| 856 | let text = "aa H2O"; |
| 857 | let segments = [ |
| 858 | segment(0..4, 1., 0.), |
| 859 | segment(4..5, 0.75, -0.2), |
| 860 | segment(5..6, 1., 0.), |
| 861 | ]; |
| 862 | let flow = layout(text, &segments, Some(45.)); |
| 863 | let lines: Vec<_> = flow.fragments.iter().map(|f| f.line).collect(); |
| 864 | assert_eq!(lines, vec![0, 1, 1, 1]); |
| 865 | } |
| 866 | |
| 867 | #[test] |
| 868 | fn a_subscript_hangs_below_the_baseline_and_a_superscript_rises_above_it() { |
| 869 | let text = "x2"; |
| 870 | let sub = layout( |
| 871 | text, |
| 872 | &[segment(0..1, 1., 0.), segment(1..2, 0.75, -0.2)], |
| 873 | None, |
| 874 | ); |
| 875 | let sup = layout( |
| 876 | text, |
| 877 | &[segment(0..1, 1., 0.), segment(1..2, 0.75, 0.35)], |
| 878 | None, |
| 879 | ); |
| 880 | let baseline = |flow: &FlowLayout, index: usize, scale: f32| { |
| 881 | flow.fragments[index].origin.y + px(BASE_HEIGHT * scale * 0.8) |
| 882 | }; |
| 883 | assert!(baseline(&sub, 1, 0.75) > baseline(&sub, 0, 1.)); |
| 884 | assert!(baseline(&sup, 1, 0.75) < baseline(&sup, 0, 1.)); |
| 885 | assert!(sup.size.height >= px(BASE_HEIGHT)); |
| 886 | } |
| 887 | |
| 888 | #[test] |
| 889 | fn large_text_makes_its_line_taller_and_small_text_does_not_shrink_it() { |
| 890 | let text = "ab"; |
| 891 | let large = layout(text, &[segment(0..1, 1., 0.), segment(1..2, 1.5, 0.)], None); |
| 892 | let small = layout( |
| 893 | text, |
| 894 | &[segment(0..1, 1., 0.), segment(1..2, 0.75, 0.)], |
| 895 | None, |
| 896 | ); |
| 897 | assert_eq!(large.size.height, px(BASE_HEIGHT * 1.5)); |
| 898 | assert_eq!(small.size.height, px(BASE_HEIGHT)); |
| 899 | } |
| 900 | |
| 901 | #[test] |
| 902 | fn a_newline_starts_a_line_and_belongs_to_no_fragment() { |
| 903 | let flow = layout("ab\ncd", &[segment(0..5, 1., 0.)], None); |
| 904 | let ranges: Vec<_> = flow.fragments.iter().map(|f| f.range.clone()).collect(); |
| 905 | assert_eq!(ranges, vec![0..2, 3..5]); |
| 906 | assert_eq!(flow.lines.len(), 2); |
| 907 | } |
| 908 | |
| 909 | struct Message; |
| 910 | |
| 911 | const TEXT: &str = "H2O big link end"; |
| 912 | |
| 913 | impl Render for Message { |
| 914 | fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { |
| 915 | div().w(px(400.)).text_size(px(14.)).child( |
| 916 | FlowText::new( |
| 917 | "flow", |
| 918 | TEXT, |
| 919 | vec![ |
| 920 | segment(0..1, 1., 0.), |
| 921 | segment(1..2, 0.75, -0.2), |
| 922 | segment(2..4, 1., 0.), |
| 923 | segment(4..7, 1.5, 0.), |
| 924 | segment(7..16, 1., 0.), |
| 925 | ], |
| 926 | ) |
| 927 | .links(vec![(8..12, "https://example.com".to_owned())]), |
| 928 | ) |
| 929 | } |
| 930 | } |
| 931 | |
| 932 | fn mount(cx: &mut TestAppContext) -> AnyWindowHandle { |
| 933 | cx.update(gpui_kit::init); |
| 934 | cx.update(|cx| { |
| 935 | let options = WindowOptions { |
| 936 | window_bounds: Some(WindowBounds::Windowed(Bounds { |
| 937 | origin: Point::default(), |
| 938 | size: size(px(400.), px(100.)), |
| 939 | })), |
| 940 | ..Default::default() |
| 941 | }; |
| 942 | gpui_kit::open_window(options, cx, |_, cx| cx.new(|_| Message)) |
| 943 | .expect("open test window") |
| 944 | .0 |
| 945 | }) |
| 946 | } |
| 947 | |
| 948 | #[gpui_kit::test] |
| 949 | fn dragging_across_sized_fragments_selects_the_whole_text(cx: &mut TestAppContext) { |
| 950 | let handle = mount(cx); |
| 951 | let selected = cx |
| 952 | .update_window(handle, |_, window, cx| { |
| 953 | window.render_frame(cx); |
| 954 | window.drag(point(px(1.), px(8.)), point(px(399.), px(8.)), cx); |
| 955 | window.render_frame(cx); |
| 956 | TextSelection::selected_text(window, cx) |
| 957 | }) |
| 958 | .unwrap(); |
| 959 | assert_eq!(selected, TEXT); |
| 960 | assert_eq!(cx.opened_url(), None); |
| 961 | } |
| 962 | |
| 963 | #[gpui_kit::test] |
| 964 | fn a_link_after_sized_text_opens_and_plain_text_does_not(cx: &mut TestAppContext) { |
| 965 | let handle = mount(cx); |
| 966 | let click = |x: f32, cx: &mut TestAppContext| { |
| 967 | cx.update_window(handle, |_, window, cx| { |
| 968 | window.render_frame(cx); |
| 969 | window.drag(point(px(x), px(8.)), point(px(x), px(8.)), cx); |
| 970 | }) |
| 971 | .unwrap(); |
| 972 | }; |
| 973 | click(2., cx); |
| 974 | assert_eq!(cx.opened_url(), None); |
| 975 | let link_x = (40..400).map(|x| x as f32).find(|x| { |
| 976 | click(*x, cx); |
| 977 | cx.opened_url().is_some() |
| 978 | }); |
| 979 | assert!(link_x.is_some()); |
| 980 | assert_eq!(cx.opened_url().as_deref(), Some("https://example.com/")); |
| 981 | } |
| 982 | |
| 983 | struct Links { |
| 984 | text: &'static str, |
| 985 | links: Vec<(Range<usize>, String)>, |
| 986 | } |
| 987 | |
| 988 | impl Render for Links { |
| 989 | fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { |
| 990 | div().w(px(400.)).text_size(px(14.)).child( |
| 991 | FlowText::new( |
| 992 | "links", |
| 993 | self.text, |
| 994 | vec![segment(0..self.text.len(), 1., 0.)], |
| 995 | ) |
| 996 | .links(self.links.clone()), |
| 997 | ) |
| 998 | } |
| 999 | } |
| 1000 | |
| 1001 | struct Hover<'a> { |
| 1002 | window_cx: &'a mut VisualTestContext, |
| 1003 | } |
| 1004 | |
| 1005 | impl Hover<'_> { |
| 1006 | fn open<'a>( |
| 1007 | cx: &'a mut TestAppContext, |
| 1008 | text: &'static str, |
| 1009 | links: &[(Range<usize>, &str)], |
| 1010 | ) -> Hover<'a> { |
| 1011 | cx.update(gpui_kit::init); |
| 1012 | let links = links |
| 1013 | .iter() |
| 1014 | .map(|(range, url)| (range.clone(), (*url).to_owned())) |
| 1015 | .collect(); |
| 1016 | let (_, window_cx) = cx.add_window_view(move |_, _| Links { text, links }); |
| 1017 | Hover { window_cx } |
| 1018 | } |
| 1019 | |
| 1020 | /// Moves the mouse to `x` on the first line, optionally holding the left button, and |
| 1021 | /// waits out the tooltip delay. The tooltip's bounds, if one shows. |
| 1022 | fn at(&mut self, x: f32, button: Option<MouseButton>) -> Option<Bounds<Pixels>> { |
| 1023 | let position = point(px(x), px(8.)); |
| 1024 | self.window_cx |
| 1025 | .simulate_mouse_move(position, button, Modifiers::none()); |
| 1026 | self.window_cx |
| 1027 | .executor() |
| 1028 | .advance_clock(std::time::Duration::from_millis(600)); |
| 1029 | self.window_cx.run_until_parked(); |
| 1030 | self.window_cx.debug_bounds("tooltip") |
| 1031 | } |
| 1032 | |
| 1033 | fn first_tooltip_x(&mut self, from: u32) -> Option<f32> { |
| 1034 | (from..400) |
| 1035 | .map(|x| x as f32) |
| 1036 | .find(|x| self.at(*x, None).is_some()) |
| 1037 | } |
| 1038 | } |
| 1039 | |
| 1040 | #[gpui_kit::test] |
| 1041 | fn hovering_a_link_shows_its_url_in_a_tooltip(cx: &mut TestAppContext) { |
| 1042 | let mut hover = Hover::open(cx, TEXT, &[(8..12, "https://example.com")]); |
| 1043 | assert!(hover.at(2., None).is_none()); |
| 1044 | assert!(hover.first_tooltip_x(40).is_some()); |
| 1045 | assert!(hover.at(2., None).is_none()); |
| 1046 | } |
| 1047 | |
| 1048 | #[gpui_kit::test] |
| 1049 | fn a_long_url_tooltip_wraps_inside_its_maximum_width(cx: &mut TestAppContext) { |
| 1050 | let url = Box::leak(format!("https://example.com/{}", "a".repeat(600)).into_boxed_str()); |
| 1051 | let mut hover = Hover::open(cx, "link", &[(0..4, url)]); |
| 1052 | let x = hover.first_tooltip_x(0).expect("tooltip over the link"); |
| 1053 | let bounds = hover.at(x, None).expect("tooltip stays"); |
| 1054 | assert!(bounds.size.width < px(560.), "{bounds:?}"); |
| 1055 | assert!(bounds.size.height > px(40.), "{bounds:?}"); |
| 1056 | } |
| 1057 | |
| 1058 | #[gpui_kit::test] |
| 1059 | fn moving_onto_the_next_link_shows_that_links_tooltip(cx: &mut TestAppContext) { |
| 1060 | let mut hover = Hover::open( |
| 1061 | cx, |
| 1062 | "aaaaaaaaaabbbbbbbbbb", |
| 1063 | &[(0..10, "https://a.example"), (10..20, "https://b.example")], |
| 1064 | ); |
| 1065 | let first = hover.at(4., None).expect("tooltip over the first link"); |
| 1066 | let second = (40..200).map(|x| x as f32).find_map(|x| { |
| 1067 | hover |
| 1068 | .at(x, None) |
| 1069 | .filter(|bounds| bounds.origin.x > first.origin.x + px(20.)) |
| 1070 | }); |
| 1071 | assert!(second.is_some()); |
| 1072 | } |
| 1073 | |
| 1074 | #[gpui_kit::test] |
| 1075 | fn no_tooltip_while_dragging_a_selection_over_a_link(cx: &mut TestAppContext) { |
| 1076 | let mut hover = Hover::open(cx, TEXT, &[(8..12, "https://example.com")]); |
| 1077 | let link_x = hover.first_tooltip_x(40).expect("tooltip over the link"); |
| 1078 | hover.at(2., None); |
| 1079 | hover.window_cx.simulate_mouse_down( |
| 1080 | point(px(2.), px(8.)), |
| 1081 | MouseButton::Left, |
| 1082 | Modifiers::none(), |
| 1083 | ); |
| 1084 | assert!(hover.at(link_x, Some(MouseButton::Left)).is_none()); |
| 1085 | hover.window_cx.simulate_mouse_up( |
| 1086 | point(px(link_x), px(8.)), |
| 1087 | MouseButton::Left, |
| 1088 | Modifiers::none(), |
| 1089 | ); |
| 1090 | hover.at(link_x + 1., None); |
| 1091 | assert!(hover.at(link_x, None).is_some()); |
| 1092 | } |
| 1093 | |
| 1094 | #[gpui_kit::test] |
| 1095 | fn a_mention_profile_link_has_no_tooltip(cx: &mut TestAppContext) { |
| 1096 | let mut hover = Hover::open(cx, "@Ada Lovelace", &[(0..13, "teams-profile:8:orgid:x")]); |
| 1097 | assert_eq!(hover.first_tooltip_x(0), None); |
| 1098 | } |
| 1099 | } |