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