| 1 | use crate::input::{InputExtras as _, InputModeKind}; |
| 2 | use gpui::Corners; |
| 3 | use gpui::Half; |
| 4 | use gpui::{ |
| 5 | AnyElement, App, Bounds, Edges, Element, ElementId, ElementInputHandler, Entity, |
| 6 | GlobalElementId, |
| 7 | }; |
| 8 | use gpui::{ |
| 9 | HighlightStyle, Hitbox, HitboxBehavior, Hsla, InteractiveElement, IntoElement, LayoutId, |
| 10 | LongPressEvent, MouseButton, MouseMoveEvent, MouseUpEvent, PaintQuad, ParentElement as _, Path, |
| 11 | Pixels, Point, Position, ShapedLine, SharedString, Size, Style, Styled as _, TextAlign, |
| 12 | TextRun, TextStyle, TouchDragEvent, TouchPhase, UnderlineStyle, Window, fill, point, px, |
| 13 | relative, size, |
| 14 | }; |
| 15 | use ropey::Rope; |
| 16 | use smallvec::SmallVec; |
| 17 | use std::{ops::Range, rc::Rc}; |
| 18 | |
| 19 | use crate::{ |
| 20 | Scrollbar, |
| 21 | input::{ |
| 22 | RopeExt as _, |
| 23 | blink_cursor::CURSOR_WIDTH, |
| 24 | decorations::font_override_spans, |
| 25 | display_map::{InlineMetric, LineLayout, split_run_by_font_overrides}, |
| 26 | }, |
| 27 | }; |
| 28 | |
| 29 | use super::{ |
| 30 | InputBaseState, RangeDecorationStyle, TextDecoration, |
| 31 | layout::{LastLayout, WhitespaceIndicators}, |
| 32 | mode::LayoutMode, |
| 33 | }; |
| 34 | |
| 35 | fn diagnostic_highlight_style( |
| 36 | severity: crate::input::DiagnosticSeverity, |
| 37 | colors: crate::input::DiagnosticColors, |
| 38 | ) -> HighlightStyle { |
| 39 | let color = match severity { |
| 40 | crate::input::DiagnosticSeverity::Error => colors.error, |
| 41 | crate::input::DiagnosticSeverity::Warning => colors.warning, |
| 42 | crate::input::DiagnosticSeverity::Info => colors.info, |
| 43 | crate::input::DiagnosticSeverity::Hint => colors.hint, |
| 44 | }; |
| 45 | HighlightStyle { |
| 46 | underline: Some(UnderlineStyle { |
| 47 | color: Some(color), |
| 48 | thickness: px(1.), |
| 49 | wavy: true, |
| 50 | }), |
| 51 | ..Default::default() |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | const BOTTOM_MARGIN_ROWS: usize = 3; |
| 56 | pub(super) const RIGHT_MARGIN: Pixels = px(10.); |
| 57 | pub(super) const LINE_NUMBER_RIGHT_MARGIN: Pixels = px(6.); |
| 58 | const FOLD_ICON_WIDTH: Pixels = px(14.); |
| 59 | const FOLD_ICON_HITBOX_WIDTH: Pixels = px(18.); |
| 60 | const MAX_HIGHLIGHT_LINE_LENGTH: usize = 10_000; |
| 61 | const MIN_LINE_NUMBER_DIGITS: usize = 3; |
| 62 | const MAX_LINE_NUMBER_DIGITS: usize = 7; |
| 63 | const MAX_DISPLAYED_LINE_NUMBER: usize = 9_999_999; |
| 64 | |
| 65 | fn line_number_len(total_lines: usize) -> usize { |
| 66 | (total_lines.max(1).ilog10() as usize + 1).clamp(MIN_LINE_NUMBER_DIGITS, MAX_LINE_NUMBER_DIGITS) |
| 67 | } |
| 68 | |
| 69 | fn displayed_line_number(number: usize) -> usize { |
| 70 | number.min(MAX_DISPLAYED_LINE_NUMBER) |
| 71 | } |
| 72 | const FOLD_CHEVRON_RIGHT_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 18 6-6-6-6"/></svg>"#; |
| 73 | const FOLD_CHEVRON_DOWN_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>"#; |
| 74 | |
| 75 | fn compose_decorations( |
| 76 | mut styles: Vec<(Range<usize>, HighlightStyle)>, |
| 77 | decorations: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>, |
| 78 | visible_byte_range: Range<usize>, |
| 79 | ) -> Option<Vec<(Range<usize>, HighlightStyle)>> { |
| 80 | let mut visible_decorations = decorations |
| 81 | .into_iter() |
| 82 | .filter_map(|(range, style)| { |
| 83 | let range = |
| 84 | range.start.max(visible_byte_range.start)..range.end.min(visible_byte_range.end); |
| 85 | (!range.is_empty()).then_some((range, style)) |
| 86 | }) |
| 87 | .peekable(); |
| 88 | |
| 89 | if visible_decorations.peek().is_none() { |
| 90 | return (!styles.is_empty()).then_some(styles); |
| 91 | } |
| 92 | if styles.is_empty() { |
| 93 | styles.push((visible_byte_range.clone(), HighlightStyle::default())); |
| 94 | } |
| 95 | |
| 96 | // Decorations are application-authored overrides and must win over syntax |
| 97 | // and semantic highlighting when both set the same style property. |
| 98 | Some(gpui::combine_highlights(styles, visible_decorations).collect()) |
| 99 | } |
| 100 | |
| 101 | fn compose_decoration_collections<'a>( |
| 102 | mut styles: Vec<(Range<usize>, HighlightStyle)>, |
| 103 | collections: impl IntoIterator<Item = &'a [TextDecoration]>, |
| 104 | visible_byte_range: Range<usize>, |
| 105 | ) -> Option<Vec<(Range<usize>, HighlightStyle)>> { |
| 106 | // Apply collections in reverse creation order so the first collection is |
| 107 | // composed last and retains its documented precedence. |
| 108 | let collections = collections.into_iter().collect::<Vec<_>>(); |
| 109 | for decorations in collections.into_iter().rev() { |
| 110 | styles = compose_decorations( |
| 111 | styles, |
| 112 | decorations |
| 113 | .iter() |
| 114 | .map(|decoration| (decoration.range.clone(), decoration.style)), |
| 115 | visible_byte_range.clone(), |
| 116 | ) |
| 117 | .unwrap_or_default(); |
| 118 | } |
| 119 | |
| 120 | (!styles.is_empty()).then_some(styles) |
| 121 | } |
| 122 | |
| 123 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 124 | struct EditorScrollbarLayout { |
| 125 | bounds: Bounds<Pixels>, |
| 126 | scroll_size: Size<Pixels>, |
| 127 | } |
| 128 | |
| 129 | /// What the unwrapped width of the longest line depends on. While it holds, |
| 130 | /// prepaint reuses the stored width instead of copying the line and asking |
| 131 | /// the text system for it again on every frame. |
| 132 | #[derive(Clone, Debug, PartialEq)] |
| 133 | pub(super) struct LongestLineKey { |
| 134 | document_revision: u64, |
| 135 | row: usize, |
| 136 | len: usize, |
| 137 | font: gpui::Font, |
| 138 | text_size: Pixels, |
| 139 | wrap_width: Option<Pixels>, |
| 140 | } |
| 141 | |
| 142 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 143 | pub(super) struct EditorScrollbarSnapshot { |
| 144 | layout: EditorScrollbarLayout, |
| 145 | cursor_scroll_offset: Point<Pixels>, |
| 146 | soft_wrap: bool, |
| 147 | } |
| 148 | |
| 149 | impl EditorScrollbarSnapshot { |
| 150 | fn new<M: InputModeKind>( |
| 151 | input_bounds: Bounds<Pixels>, |
| 152 | last_layout: &LastLayout, |
| 153 | scroll_size: Size<Pixels>, |
| 154 | cursor_scroll_offset: Point<Pixels>, |
| 155 | state: &InputBaseState<M>, |
| 156 | ) -> Self { |
| 157 | Self { |
| 158 | layout: EditorScrollbarLayout::new( |
| 159 | input_bounds, |
| 160 | last_layout.line_number_width, |
| 161 | scroll_size, |
| 162 | state.editor_paddings, |
| 163 | ), |
| 164 | cursor_scroll_offset, |
| 165 | soft_wrap: state.soft_wrap, |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | impl EditorScrollbarLayout { |
| 171 | fn new( |
| 172 | input_bounds: Bounds<Pixels>, |
| 173 | line_number_width: Pixels, |
| 174 | scroll_size: Size<Pixels>, |
| 175 | paddings: Edges<Pixels>, |
| 176 | ) -> Self { |
| 177 | let left = if line_number_width == px(0.) { |
| 178 | px(0.) |
| 179 | } else { |
| 180 | paddings.left + line_number_width - LINE_NUMBER_RIGHT_MARGIN |
| 181 | }; |
| 182 | |
| 183 | Self { |
| 184 | bounds: Bounds::new( |
| 185 | point( |
| 186 | input_bounds.origin.x + left, |
| 187 | input_bounds.origin.y - paddings.top, |
| 188 | ), |
| 189 | size( |
| 190 | input_bounds.size.width - left + paddings.right, |
| 191 | input_bounds.size.height + paddings.top + paddings.bottom, |
| 192 | ), |
| 193 | ), |
| 194 | scroll_size: size( |
| 195 | scroll_size.width - left + paddings.right + RIGHT_MARGIN, |
| 196 | scroll_size.height, |
| 197 | ), |
| 198 | } |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | pub(super) struct EditorScrollbar<M: InputModeKind> { |
| 203 | state: Entity<InputBaseState<M>>, |
| 204 | } |
| 205 | |
| 206 | impl<M: InputModeKind> EditorScrollbar<M> { |
| 207 | pub(super) fn new(state: Entity<InputBaseState<M>>) -> Self { |
| 208 | Self { state } |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | impl<M: InputModeKind> IntoElement for EditorScrollbar<M> { |
| 213 | type Element = Self; |
| 214 | |
| 215 | fn into_element(self) -> Self::Element { |
| 216 | self |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | impl<M: InputModeKind> Element for EditorScrollbar<M> { |
| 221 | type RequestLayoutState = (); |
| 222 | type PrepaintState = Option<AnyElement>; |
| 223 | |
| 224 | fn id(&self) -> Option<ElementId> { |
| 225 | Some("editor-scrollbar".into()) |
| 226 | } |
| 227 | |
| 228 | fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { |
| 229 | None |
| 230 | } |
| 231 | |
| 232 | fn request_layout( |
| 233 | &mut self, |
| 234 | _: Option<&GlobalElementId>, |
| 235 | _: Option<&gpui::InspectorElementId>, |
| 236 | window: &mut Window, |
| 237 | cx: &mut App, |
| 238 | ) -> (LayoutId, Self::RequestLayoutState) { |
| 239 | let mut style = Style::default(); |
| 240 | style.position = Position::Absolute; |
| 241 | style.size.width = relative(1.).into(); |
| 242 | style.size.height = relative(1.).into(); |
| 243 | |
| 244 | (window.request_layout(style, [], cx), ()) |
| 245 | } |
| 246 | |
| 247 | fn prepaint( |
| 248 | &mut self, |
| 249 | _: Option<&GlobalElementId>, |
| 250 | _: Option<&gpui::InspectorElementId>, |
| 251 | _: Bounds<Pixels>, |
| 252 | _: &mut Self::RequestLayoutState, |
| 253 | window: &mut Window, |
| 254 | cx: &mut App, |
| 255 | ) -> Self::PrepaintState { |
| 256 | let state = self.state.read(cx); |
| 257 | let Some(snapshot) = state.editor_scrollbar_snapshot.get() else { |
| 258 | return None; |
| 259 | }; |
| 260 | let scroll_handle = state.scroll_handle.clone(); |
| 261 | |
| 262 | if scroll_handle.offset() != snapshot.cursor_scroll_offset { |
| 263 | scroll_handle.set_offset(snapshot.cursor_scroll_offset); |
| 264 | } |
| 265 | |
| 266 | let mut scrollbar = if !snapshot.soft_wrap { |
| 267 | Scrollbar::new(&scroll_handle) |
| 268 | } else { |
| 269 | Scrollbar::vertical(&scroll_handle) |
| 270 | } |
| 271 | .viewport_bounds(snapshot.layout.bounds) |
| 272 | .scroll_size(snapshot.layout.scroll_size) |
| 273 | .into_any_element(); |
| 274 | |
| 275 | scrollbar.prepaint_as_root( |
| 276 | snapshot.layout.bounds.origin, |
| 277 | snapshot.layout.bounds.size.into(), |
| 278 | window, |
| 279 | cx, |
| 280 | ); |
| 281 | Some(scrollbar) |
| 282 | } |
| 283 | |
| 284 | fn paint( |
| 285 | &mut self, |
| 286 | _: Option<&GlobalElementId>, |
| 287 | _: Option<&gpui::InspectorElementId>, |
| 288 | _: Bounds<Pixels>, |
| 289 | _: &mut Self::RequestLayoutState, |
| 290 | prepaint: &mut Self::PrepaintState, |
| 291 | window: &mut Window, |
| 292 | cx: &mut App, |
| 293 | ) { |
| 294 | if let Some(scrollbar) = prepaint.as_mut() { |
| 295 | scrollbar.paint(window, cx); |
| 296 | } |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | // Prepaint and retained state must use the same range, including after content shrinks. |
| 301 | pub(super) fn clamp_horizontal_scroll_offset( |
| 302 | offset: Pixels, |
| 303 | scroll_width: Pixels, |
| 304 | input_width: Pixels, |
| 305 | text_align: TextAlign, |
| 306 | ) -> Pixels { |
| 307 | let caret_clearance = if text_align == TextAlign::Left { |
| 308 | px(0.) |
| 309 | } else { |
| 310 | -CURSOR_WIDTH |
| 311 | }; |
| 312 | let min_offset = (input_width - scroll_width + caret_clearance).min(caret_clearance); |
| 313 | offset.clamp(min_offset, px(0.)) |
| 314 | } |
| 315 | |
| 316 | fn clamp_auto_grow_vertical_scroll_offset( |
| 317 | mode: &LayoutMode, |
| 318 | scroll_top: Pixels, |
| 319 | scroll_height: Pixels, |
| 320 | input_height: Pixels, |
| 321 | ) -> Pixels { |
| 322 | if mode.is_auto_grow() { |
| 323 | scroll_top.clamp((input_height - scroll_height).min(px(0.)), px(0.)) |
| 324 | } else { |
| 325 | scroll_top |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | fn editor_gutter_bounds( |
| 330 | input_bounds: Bounds<Pixels>, |
| 331 | line_number_width: Pixels, |
| 332 | ghost_lines_height: Pixels, |
| 333 | paddings: Edges<Pixels>, |
| 334 | ) -> Bounds<Pixels> { |
| 335 | Bounds { |
| 336 | origin: point( |
| 337 | input_bounds.origin.x - paddings.left, |
| 338 | input_bounds.origin.y - paddings.top, |
| 339 | ), |
| 340 | size: size( |
| 341 | line_number_width + paddings.left, |
| 342 | input_bounds.size.height + ghost_lines_height + paddings.top + paddings.bottom, |
| 343 | ), |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | use super::MASK_CHAR; |
| 348 | |
| 349 | /// Convert a byte offset in the original text to a byte offset in the masked display string. |
| 350 | /// |
| 351 | /// The masked string consists of `MASK_CHAR` repeated once per character in the original text. |
| 352 | /// Since `MASK_CHAR` may be multi-byte in UTF-8, the byte offset in the masked string is |
| 353 | /// `char_index * MASK_CHAR.len_utf8()`. |
| 354 | fn masked_display_offset(text: &Rope, original_offset: usize) -> usize { |
| 355 | text.offset_to_char_index(original_offset) * MASK_CHAR.len_utf8() |
| 356 | } |
| 357 | |
| 358 | /// Move the IME marked range (tracked against the original text) into the display text |
| 359 | /// coordinate space, so that a run boundary can't land inside a multi-byte `MASK_CHAR` |
| 360 | /// and panic text shaping on a non-char-boundary slice. |
| 361 | fn ime_marked_display_range( |
| 362 | text: &Rope, |
| 363 | marked_range: Option<Range<usize>>, |
| 364 | masked: bool, |
| 365 | ) -> Option<Range<usize>> { |
| 366 | let marked = marked_range?; |
| 367 | if masked { |
| 368 | Some(masked_display_offset(text, marked.start)..masked_display_offset(text, marked.end)) |
| 369 | } else { |
| 370 | Some(marked) |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | /// Viewport capacity in display rows, independent of logical buffer lines. |
| 375 | /// |
| 376 | /// Shared by both scroll-into-view paths (`layout_cursors` and |
| 377 | /// `scroll_to_with_padding`) so they agree on the visible-line count even |
| 378 | /// when soft-wrapped lines make logical and display rows diverge. |
| 379 | pub(super) fn viewport_visible_lines(viewport_height: Pixels, line_height: Pixels) -> usize { |
| 380 | (viewport_height / line_height) as usize |
| 381 | } |
| 382 | |
| 383 | /// Minimum pixel padding the cursor is kept clear of the viewport's |
| 384 | /// top/bottom edges before auto-scroll engages. Backs |
| 385 | /// [`InputBaseState::cursor_surrounding_lines`]. |
| 386 | /// |
| 387 | /// Auto-grow uses one line. Otherwise `None` falls back to the historical |
| 388 | /// heuristic ([`BOTTOM_MARGIN_ROWS`] lines, or one line on small |
| 389 | /// viewports); `Some(n)` uses `n` lines. The result is saturated against |
| 390 | /// half the viewport so an oversized override can't invert the |
| 391 | /// top/bottom thresholds into a scroll feedback loop. `visible_lines` is the |
| 392 | /// viewport capacity in display rows, independent of logical buffer lines. |
| 393 | pub(super) fn cursor_surrounding_padding( |
| 394 | is_auto_grow: bool, |
| 395 | override_lines: Option<usize>, |
| 396 | visible_lines: usize, |
| 397 | line_height: Pixels, |
| 398 | ) -> Pixels { |
| 399 | if is_auto_grow { |
| 400 | return line_height; |
| 401 | } |
| 402 | let raw = match override_lines { |
| 403 | Some(lines) => lines as f32 * line_height, |
| 404 | None => { |
| 405 | if visible_lines < BOTTOM_MARGIN_ROWS * 8 { |
| 406 | line_height |
| 407 | } else { |
| 408 | BOTTOM_MARGIN_ROWS * line_height |
| 409 | } |
| 410 | } |
| 411 | }; |
| 412 | // Saturate against half the viewport so top + bottom margins can coexist. |
| 413 | let viewport_half = (visible_lines as f32 * line_height).half(); |
| 414 | raw.min(viewport_half) |
| 415 | } |
| 416 | |
| 417 | /// Pixel height of the empty area below the last line in the editor's |
| 418 | /// scrollable region. Backs [`InputBaseState::scroll_beyond_last_line`]. |
| 419 | /// |
| 420 | /// `0` outside code-editor mode. Inside it, `None` is half the viewport |
| 421 | /// (floored at [`BOTTOM_MARGIN_ROWS`] line-heights); `Some(n)` is exactly |
| 422 | /// `n` line-heights. |
| 423 | fn empty_bottom_height( |
| 424 | is_code_editor: bool, |
| 425 | override_rows: Option<usize>, |
| 426 | viewport_height: Pixels, |
| 427 | line_height: Pixels, |
| 428 | ) -> Pixels { |
| 429 | if !is_code_editor { |
| 430 | return px(0.); |
| 431 | } |
| 432 | match override_rows { |
| 433 | Some(rows) => rows as f32 * line_height, |
| 434 | None => viewport_height.half().max(BOTTOM_MARGIN_ROWS * line_height), |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | /// Layout information for fold icons. |
| 439 | struct FoldIconLayout { |
| 440 | /// Hitbox for the line number area (used for hover detection) |
| 441 | line_number_hitbox: Hitbox, |
| 442 | /// List of (display_row, is_folded, icon_element) pairs for each fold candidate |
| 443 | icons: Vec<(usize, bool, gpui::AnyElement)>, |
| 444 | } |
| 445 | |
| 446 | pub(super) struct TextElement<M: InputModeKind> { |
| 447 | pub(crate) state: Entity<InputBaseState<M>>, |
| 448 | placeholder: SharedString, |
| 449 | } |
| 450 | |
| 451 | impl<M: InputModeKind> TextElement<M> { |
| 452 | pub(super) fn new(state: Entity<InputBaseState<M>>) -> Self { |
| 453 | Self { |
| 454 | state, |
| 455 | placeholder: SharedString::default(), |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | /// Set the placeholder text of the input field. |
| 460 | pub(super) fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self { |
| 461 | self.placeholder = placeholder.into(); |
| 462 | self |
| 463 | } |
| 464 | |
| 465 | fn paint_mouse_listeners(&mut self, hitbox: &Hitbox, window: &mut Window, _: &mut App) { |
| 466 | // Every touch is offered as a drag first; that is how a tap's mouse |
| 467 | // events are later told apart from a mouse's. |
| 468 | window.on_mouse_event(move |event: &TouchDragEvent, phase, _, cx| { |
| 469 | if phase.capture() && event.phase == TouchPhase::Started { |
| 470 | crate::GlobalState::note_touch(cx); |
| 471 | } |
| 472 | }); |
| 473 | |
| 474 | // A long press is touch's way to select: the word under the finger, |
| 475 | // then whatever the finger sweeps over. Claiming it keeps the moves |
| 476 | // out of the pan recognizer, so the input does not scroll instead. |
| 477 | window.on_mouse_event({ |
| 478 | let state = self.state.clone(); |
| 479 | let hitbox = hitbox.clone(); |
| 480 | move |event: &LongPressEvent, phase, window, cx| { |
| 481 | if !phase.bubble() { |
| 482 | return; |
| 483 | } |
| 484 | if event.phase == TouchPhase::Started { |
| 485 | if window.default_prevented() || !hitbox.is_hovered(window) { |
| 486 | return; |
| 487 | } |
| 488 | if !state.update(cx, |state, cx| state.on_long_press(event, window, cx)) { |
| 489 | return; |
| 490 | } |
| 491 | window.capture_long_press(&state); |
| 492 | } else if !window.has_long_press_capture(&state) { |
| 493 | return; |
| 494 | } else { |
| 495 | state.update(cx, |state, cx| { |
| 496 | state.on_long_press(event, window, cx); |
| 497 | }); |
| 498 | } |
| 499 | window.prevent_default(); |
| 500 | cx.stop_propagation(); |
| 501 | } |
| 502 | }); |
| 503 | |
| 504 | window.on_mouse_event({ |
| 505 | let state = self.state.clone(); |
| 506 | |
| 507 | move |event: &MouseMoveEvent, _, window, cx| { |
| 508 | if event.pressed_button == Some(MouseButton::Left) { |
| 509 | state.update(cx, |state, cx| { |
| 510 | state.on_drag_move(event, window, cx); |
| 511 | }); |
| 512 | } |
| 513 | } |
| 514 | }); |
| 515 | |
| 516 | window.on_mouse_event({ |
| 517 | let state = self.state.clone(); |
| 518 | move |_: &MouseUpEvent, phase, _, cx| { |
| 519 | if !phase.bubble() { |
| 520 | return; |
| 521 | } |
| 522 | |
| 523 | // Stop auto-scroll when mouse up, and also stop selecting. |
| 524 | state.update(cx, |state, _| { |
| 525 | state.auto_scroll.stop(); |
| 526 | state.selecting = false; |
| 527 | state.column_select_start = None; |
| 528 | }); |
| 529 | } |
| 530 | }); |
| 531 | } |
| 532 | |
| 533 | /// Lays out the carets and updates the scroll position for the active one. |
| 534 | fn layout_cursors( |
| 535 | &self, |
| 536 | last_layout: &LastLayout, |
| 537 | bounds: &mut Bounds<Pixels>, |
| 538 | scroll_size: Size<Pixels>, |
| 539 | _: &mut Window, |
| 540 | cx: &mut App, |
| 541 | ) -> (Vec<CursorRenderInfo>, Point<Pixels>, Option<usize>) { |
| 542 | let state = self.state.read(cx); |
| 543 | |
| 544 | let line_height = last_layout.line_height; |
| 545 | let visible_range = &last_layout.visible_range; |
| 546 | let lines = &last_layout.lines; |
| 547 | let line_number_width = last_layout.line_number_width; |
| 548 | |
| 549 | let active_id = state.active_selection().id; |
| 550 | let mut scroll_offset = state.scroll_handle.offset(); |
| 551 | let mut current_row = None; |
| 552 | let mut cursor_infos: Vec<CursorRenderInfo> = Vec::with_capacity(state.selections.len()); |
| 553 | |
| 554 | // Padding kept between the cursor and the viewport's top/bottom |
| 555 | // edges, used by the auto-scroll-into-view computation below. |
| 556 | let top_bottom_margin = cursor_surrounding_padding( |
| 557 | state.mode.is_auto_grow(), |
| 558 | state.cursor_surrounding_lines, |
| 559 | viewport_visible_lines(bounds.size.height, line_height), |
| 560 | line_height, |
| 561 | ); |
| 562 | |
| 563 | // Resolve a cursor or selection endpoint to a content-space position. |
| 564 | let visible_buffer_lines = &last_layout.visible_buffer_lines; |
| 565 | let caret_for = |row: usize, offset: usize, affinity: bool| -> (Point<Pixels>, Pixels) { |
| 566 | // y of the top of buffer line `row` in content space. |
| 567 | let top = state.display_map.row_top( |
| 568 | state.display_map.buffer_line_to_display_row(row), |
| 569 | line_height, |
| 570 | ); |
| 571 | let line_origin = point(px(0.), top); |
| 572 | |
| 573 | if let Some(vi) = visible_buffer_lines.iter().position(|&bl| bl == row) { |
| 574 | let line = &lines[vi]; |
| 575 | let line_start = last_layout.visible_line_byte_offsets[vi]; |
| 576 | let local = offset.saturating_sub(line_start); |
| 577 | if let Some(pos) = line.position_for_index(local, last_layout, affinity) { |
| 578 | let row_height = line |
| 579 | .row_at_y(pos.y, line_height) |
| 580 | .map_or(line_height, |ix| line.row_height(ix, line_height)); |
| 581 | return (line_origin + pos, row_height); |
| 582 | } |
| 583 | } |
| 584 | (line_origin, line_height) |
| 585 | }; |
| 586 | |
| 587 | for selection in state.selections.iter() { |
| 588 | let is_active = selection.id == active_id; |
| 589 | |
| 590 | let mut selected_range = *selection; |
| 591 | let mut cursor = selection.cursor_offset(); |
| 592 | if is_active { |
| 593 | if let Some(ime_marked_range) = &state.ime_marked_range { |
| 594 | selected_range = (ime_marked_range.end..ime_marked_range.end).into(); |
| 595 | cursor = ime_marked_range.end; |
| 596 | } |
| 597 | } |
| 598 | let is_selected_all = selected_range.len() == state.text.len(); |
| 599 | |
| 600 | // Buffer rows from the raw (pre-mask) offsets, used to locate the cursor line. |
| 601 | let cursor_row = state.text.offset_to_point(cursor).row; |
| 602 | |
| 603 | // Skip inactive cursors that are far outside the visible range. The |
| 604 | // active cursor is always processed so scroll tracking keeps working. |
| 605 | if !is_active |
| 606 | && (cursor_row + 2 < visible_range.start || cursor_row > visible_range.end + 2) |
| 607 | { |
| 608 | continue; |
| 609 | } |
| 610 | |
| 611 | let sel_start_row = state.text.offset_to_point(selected_range.start).row; |
| 612 | let sel_end_row = state.text.offset_to_point(selected_range.end).row; |
| 613 | if state.masked { |
| 614 | selected_range.start = masked_display_offset(&state.text, selected_range.start); |
| 615 | selected_range.end = masked_display_offset(&state.text, selected_range.end); |
| 616 | cursor = masked_display_offset(&state.text, cursor); |
| 617 | } |
| 618 | |
| 619 | let affinity = is_active && state.cursor_line_end_affinity; |
| 620 | let (cursor_pos, row_height) = caret_for(cursor_row, cursor, affinity); |
| 621 | let (cursor_start, _) = caret_for(sel_start_row, selected_range.start, false); |
| 622 | let (cursor_end, _) = caret_for(sel_end_row, selected_range.end, false); |
| 623 | let cursor_height = if row_height == line_height { |
| 624 | 0.85 * line_height |
| 625 | } else { |
| 626 | row_height |
| 627 | }; |
| 628 | |
| 629 | if is_active { |
| 630 | current_row = Some(cursor_row); |
| 631 | |
| 632 | let selection_changed = state.last_selected_range != Some(selected_range); |
| 633 | let auto_scrolling = state.auto_scroll.is_active(); |
| 634 | let viewport_changed = state.mode.is_auto_grow() |
| 635 | && state |
| 636 | .last_bounds |
| 637 | .is_some_and(|last| last.size.height != bounds.size.height); |
| 638 | if (selection_changed || viewport_changed) && !is_selected_all { |
| 639 | // For Right alignment use 0 margin: cursor is clamped to bounds separately, |
| 640 | // so we never scroll the text for cursor-at-edge, avoiding a first-click jump. |
| 641 | let safety_margin = match last_layout.text_align { |
| 642 | TextAlign::Left => RIGHT_MARGIN, |
| 643 | TextAlign::Right => px(0.), |
| 644 | TextAlign::Center => CURSOR_WIDTH, |
| 645 | }; |
| 646 | |
| 647 | scroll_offset.x = if scroll_offset.x + cursor_pos.x |
| 648 | > (bounds.size.width - line_number_width - safety_margin) |
| 649 | { |
| 650 | // cursor is out of right |
| 651 | bounds.size.width - line_number_width - safety_margin - cursor_pos.x |
| 652 | } else if scroll_offset.x + cursor_pos.x < px(0.) { |
| 653 | // cursor is out of left |
| 654 | -cursor_pos.x |
| 655 | } else { |
| 656 | scroll_offset.x |
| 657 | }; |
| 658 | |
| 659 | // Vertical cursor-follow is suppressed while auto-scroll manages the y axis, |
| 660 | // to prevent fighting the background scroll task. |
| 661 | if !auto_scrolling { |
| 662 | // Scroll straight to the caret's line. This runs only on |
| 663 | // the frame the selection changed, so a one-line step |
| 664 | // would leave a far-off caret (e.g. after typing at the |
| 665 | // end of a long paste) outside the viewport. |
| 666 | scroll_offset.y = if scroll_offset.y + cursor_pos.y |
| 667 | > bounds.size.height - top_bottom_margin |
| 668 | { |
| 669 | // cursor is out of bottom |
| 670 | bounds.size.height - top_bottom_margin - cursor_pos.y |
| 671 | } else if scroll_offset.y + cursor_pos.y < top_bottom_margin { |
| 672 | // cursor is out of top |
| 673 | (top_bottom_margin - cursor_pos.y).min(px(0.)) |
| 674 | } else { |
| 675 | scroll_offset.y |
| 676 | }; |
| 677 | } |
| 678 | |
| 679 | // For selection to move scroll |
| 680 | if selection.reversed { |
| 681 | if scroll_offset.x + cursor_start.x < px(0.) { |
| 682 | // selection start is out of left |
| 683 | scroll_offset.x = -cursor_start.x; |
| 684 | } |
| 685 | if !auto_scrolling && scroll_offset.y + cursor_start.y < px(0.) { |
| 686 | // selection start is out of top |
| 687 | scroll_offset.y = -cursor_start.y; |
| 688 | } |
| 689 | } else { |
| 690 | // TODO: Consider to remove this part, |
| 691 | // maybe is not necessary (But selection_reversed is needed). |
| 692 | if scroll_offset.x + cursor_end.x <= px(0.) { |
| 693 | // selection end is out of left |
| 694 | scroll_offset.x = -cursor_end.x; |
| 695 | } |
| 696 | if !auto_scrolling && scroll_offset.y + cursor_end.y <= px(0.) { |
| 697 | // selection end is out of top |
| 698 | scroll_offset.y = -cursor_end.y; |
| 699 | } |
| 700 | } |
| 701 | } |
| 702 | } |
| 703 | |
| 704 | // Apply the final horizontal offset to every caret after cursor-follow and |
| 705 | // deferred scrolling have been resolved, regardless of selection order. |
| 706 | let cursor_x = bounds.left() + cursor_pos.x + line_number_width; |
| 707 | cursor_infos.push(CursorRenderInfo { |
| 708 | bounds: Bounds::new( |
| 709 | point( |
| 710 | cursor_x, |
| 711 | bounds.top() + cursor_pos.y + ((row_height - cursor_height) / 2.), |
| 712 | ), |
| 713 | size(CURSOR_WIDTH, cursor_height), |
| 714 | ), |
| 715 | is_active, |
| 716 | }); |
| 717 | } |
| 718 | |
| 719 | if let Some(deferred_scroll_offset) = state.deferred_scroll_offset { |
| 720 | scroll_offset = deferred_scroll_offset; |
| 721 | } |
| 722 | scroll_offset.x = clamp_horizontal_scroll_offset( |
| 723 | scroll_offset.x, |
| 724 | scroll_size.width, |
| 725 | bounds.size.width, |
| 726 | last_layout.text_align, |
| 727 | ); |
| 728 | for info in &mut cursor_infos { |
| 729 | info.bounds.origin.x += scroll_offset.x; |
| 730 | // Right-aligned text keeps the caret inside the viewport edge. |
| 731 | if last_layout.text_align == TextAlign::Right { |
| 732 | info.bounds.origin.x = info.bounds.origin.x.min(bounds.right() - CURSOR_WIDTH); |
| 733 | } |
| 734 | } |
| 735 | scroll_offset.y = clamp_auto_grow_vertical_scroll_offset( |
| 736 | &state.mode, |
| 737 | scroll_offset.y, |
| 738 | scroll_size.height, |
| 739 | bounds.size.height, |
| 740 | ); |
| 741 | |
| 742 | bounds.origin = bounds.origin + scroll_offset; |
| 743 | |
| 744 | (cursor_infos, scroll_offset, current_row) |
| 745 | } |
| 746 | |
| 747 | /// Layout the match range to a Path. |
| 748 | pub(crate) fn layout_match_range( |
| 749 | range: Range<usize>, |
| 750 | last_layout: &LastLayout, |
| 751 | bounds: &Bounds<Pixels>, |
| 752 | ) -> Option<Path<Pixels>> { |
| 753 | let corners = Self::layout_range_corners(&range, last_layout)?; |
| 754 | let points = frame_outline_points(&corners); |
| 755 | let origin = bounds.origin + point(last_layout.line_number_width, px(0.)); |
| 756 | let mut builder = gpui::PathBuilder::fill(); |
| 757 | builder.move_to(origin + *points.first()?); |
| 758 | for point in points.iter().skip(1) { |
| 759 | builder.line_to(origin + *point); |
| 760 | } |
| 761 | builder.close(); |
| 762 | builder.build().ok() |
| 763 | } |
| 764 | |
| 765 | /// Project a buffer range through the visible (non-folded) shaped lines. |
| 766 | /// Half-open intersections give soft-wrap ends their trailing affinity and |
| 767 | /// prevent ranges on later lines from painting an earlier line's first glyph. |
| 768 | fn layout_range_corners( |
| 769 | range: &Range<usize>, |
| 770 | last_layout: &LastLayout, |
| 771 | ) -> Option<Vec<Corners<Point<Pixels>>>> { |
| 772 | let range = range.start.max(last_layout.visible_range_offset.start) |
| 773 | ..range.end.min(last_layout.visible_range_offset.end); |
| 774 | if range.is_empty() { |
| 775 | return None; |
| 776 | } |
| 777 | |
| 778 | let mut y = last_layout.visible_top; |
| 779 | let mut corners = Vec::new(); |
| 780 | for (&line_offset, line) in last_layout |
| 781 | .visible_line_byte_offsets |
| 782 | .iter() |
| 783 | .zip(last_layout.lines.iter()) |
| 784 | { |
| 785 | let mut offset = line_offset; |
| 786 | let alignment = last_layout.alignment_offset(line.longest_width); |
| 787 | for (row, shaped) in line.wrapped_lines.iter().enumerate() { |
| 788 | let end = offset + shaped.len; |
| 789 | let start_ix = range.start.max(offset); |
| 790 | let end_ix = range.end.min(end); |
| 791 | let is_last = row + 1 == line.wrapped_lines.len(); |
| 792 | // A selected newline has a one-space cell, including empty lines. |
| 793 | // A wrap boundary is not a newline and must not get such a cell. |
| 794 | let newline = is_last && range.start <= end && range.end > end; |
| 795 | if start_ix < end_ix || newline { |
| 796 | let indent = line.line_indent(row); |
| 797 | let left = alignment + indent + shaped.x_for_index(start_ix.min(end) - offset); |
| 798 | let right = alignment |
| 799 | + indent |
| 800 | + if newline { |
| 801 | shaped.width + last_layout.space_width |
| 802 | } else { |
| 803 | shaped.x_for_index(end_ix - offset) |
| 804 | }; |
| 805 | let bottom = y + line.row_height(row, last_layout.line_height); |
| 806 | corners.push(Corners { |
| 807 | top_left: point(left, y), |
| 808 | top_right: point(right, y), |
| 809 | bottom_left: point(left, bottom), |
| 810 | bottom_right: point(right, bottom), |
| 811 | }); |
| 812 | } |
| 813 | offset = end; |
| 814 | y += line.row_height(row, last_layout.line_height); |
| 815 | } |
| 816 | } |
| 817 | (!corners.is_empty()).then_some(corners) |
| 818 | } |
| 819 | |
| 820 | fn layout_range_decorations( |
| 821 | &self, |
| 822 | last_layout: &LastLayout, |
| 823 | bounds: &Bounds<Pixels>, |
| 824 | window: &Window, |
| 825 | content_mask: Bounds<Pixels>, |
| 826 | cx: &App, |
| 827 | ) -> (Vec<(Path<Pixels>, Hsla)>, Vec<(Path<Pixels>, Hsla)>) { |
| 828 | let state = self.state.read(cx); |
| 829 | let mut fills = Vec::new(); |
| 830 | let mut frames = Vec::new(); |
| 831 | // Query separate buffer spans across folds instead of scanning annotations |
| 832 | // in the hidden text between the first and last visible buffer offsets. |
| 833 | let mut visible_spans: Vec<Range<usize>> = Vec::new(); |
| 834 | for (&offset, line) in last_layout |
| 835 | .visible_line_byte_offsets |
| 836 | .iter() |
| 837 | .zip(last_layout.lines.iter()) |
| 838 | { |
| 839 | let end = (offset + line.len() + 1).min(last_layout.visible_range_offset.end); |
| 840 | if let Some(previous) = visible_spans.last_mut().filter(|span| span.end == offset) { |
| 841 | previous.end = end; |
| 842 | } else if offset < end { |
| 843 | visible_spans.push(offset..end); |
| 844 | } |
| 845 | } |
| 846 | for decoration in state.extras.range_decorations(&visible_spans) { |
| 847 | match decoration.style() { |
| 848 | RangeDecorationStyle::Pill |
| 849 | | RangeDecorationStyle::Block |
| 850 | | RangeDecorationStyle::Bar => {} |
| 851 | RangeDecorationStyle::Fill => { |
| 852 | let color = decoration |
| 853 | .color() |
| 854 | .unwrap_or(state.editor_style.foreground.opacity(0.12)); |
| 855 | if let Some(path) = |
| 856 | Self::layout_match_range(decoration.range().clone(), last_layout, bounds) |
| 857 | { |
| 858 | fills.push((path, color)); |
| 859 | } |
| 860 | } |
| 861 | RangeDecorationStyle::Frame => { |
| 862 | let color = decoration.color().unwrap_or(state.editor_style.foreground); |
| 863 | let Some(corners) = Self::layout_range_corners(decoration.range(), last_layout) |
| 864 | else { |
| 865 | continue; |
| 866 | }; |
| 867 | let origin = bounds.origin + point(last_layout.line_number_width, px(0.)); |
| 868 | let corners = pad_frame_corners(&corners, px(1.)); |
| 869 | let points = frame_outline_points(&corners) |
| 870 | .into_iter() |
| 871 | .map(|point| origin + point) |
| 872 | .collect::<Vec<_>>(); |
| 873 | let (stroke_width, points) = |
| 874 | snap_frame_outline(&points, px(1.), window.scale_factor()); |
| 875 | let points = clamp_frame_to_content_mask(points, stroke_width, content_mask); |
| 876 | let Some(first) = points.first().copied() else { |
| 877 | continue; |
| 878 | }; |
| 879 | let mut builder = gpui::PathBuilder::stroke(stroke_width); |
| 880 | builder.move_to(first); |
| 881 | for point in points.iter().skip(1) { |
| 882 | builder.line_to(*point); |
| 883 | } |
| 884 | builder.close(); |
| 885 | if let Ok(path) = builder.build() { |
| 886 | frames.push((path, color)); |
| 887 | } |
| 888 | } |
| 889 | } |
| 890 | } |
| 891 | (fills, frames) |
| 892 | } |
| 893 | |
| 894 | /// Rounded pills, blocks and bars, painted as quads with the fills. |
| 895 | fn layout_range_decoration_quads( |
| 896 | &self, |
| 897 | last_layout: &LastLayout, |
| 898 | bounds: &Bounds<Pixels>, |
| 899 | cx: &App, |
| 900 | ) -> Vec<PaintQuad> { |
| 901 | let state = self.state.read(cx); |
| 902 | let origin = bounds.origin + point(last_layout.line_number_width, px(0.)); |
| 903 | let mut visible_spans: Vec<Range<usize>> = Vec::new(); |
| 904 | for (&offset, line) in last_layout |
| 905 | .visible_line_byte_offsets |
| 906 | .iter() |
| 907 | .zip(last_layout.lines.iter()) |
| 908 | { |
| 909 | let end = (offset + line.len() + 1).min(last_layout.visible_range_offset.end + 1); |
| 910 | if let Some(previous) = visible_spans.last_mut().filter(|span| span.end == offset) { |
| 911 | previous.end = end; |
| 912 | } else if offset < end { |
| 913 | visible_spans.push(offset..end); |
| 914 | } |
| 915 | } |
| 916 | let mut quads = Vec::new(); |
| 917 | for decoration in state.extras.range_decorations(&visible_spans) { |
| 918 | let color = decoration |
| 919 | .color() |
| 920 | .unwrap_or(state.editor_style.foreground.opacity(0.12)); |
| 921 | let border = decoration.border(); |
| 922 | let radius = decoration.radius(); |
| 923 | let range = decoration.range().clone(); |
| 924 | match decoration.style() { |
| 925 | RangeDecorationStyle::Pill => { |
| 926 | let Some(corners) = Self::layout_range_corners(&range, last_layout) else { |
| 927 | continue; |
| 928 | }; |
| 929 | for row in corners { |
| 930 | let row_bounds = Bounds::from_corners( |
| 931 | origin + row.top_left + point(-PILL_PADDING, px(1.)), |
| 932 | origin + row.bottom_right + point(PILL_PADDING, px(-1.)), |
| 933 | ); |
| 934 | quads.push(rounded_quad(row_bounds, radius, color, border)); |
| 935 | } |
| 936 | } |
| 937 | RangeDecorationStyle::Block | RangeDecorationStyle::Bar => { |
| 938 | let mut top: Option<Pixels> = None; |
| 939 | let mut bottom = px(0.); |
| 940 | let mut y = last_layout.visible_top; |
| 941 | for (&line_start, line) in last_layout |
| 942 | .visible_line_byte_offsets |
| 943 | .iter() |
| 944 | .zip(last_layout.lines.iter()) |
| 945 | { |
| 946 | let height = line |
| 947 | .size(last_layout.line_height) |
| 948 | .height |
| 949 | .max(last_layout.line_height); |
| 950 | let covered = (range.start..=range.end).contains(&line_start); |
| 951 | if covered { |
| 952 | top.get_or_insert(y); |
| 953 | bottom = y + height; |
| 954 | } |
| 955 | y += height; |
| 956 | } |
| 957 | let Some(top) = top else { |
| 958 | continue; |
| 959 | }; |
| 960 | let width = match decoration.style() { |
| 961 | RangeDecorationStyle::Bar => radius.max(px(1.)), |
| 962 | _ => last_layout.content_width - last_layout.line_number_width, |
| 963 | }; |
| 964 | let block_bounds = Bounds::from_corners( |
| 965 | origin + point(px(0.), top), |
| 966 | origin + point(width, bottom), |
| 967 | ); |
| 968 | let corner = match decoration.style() { |
| 969 | RangeDecorationStyle::Bar => px(0.), |
| 970 | _ => radius, |
| 971 | }; |
| 972 | quads.push(rounded_quad(block_bounds, corner, color, border)); |
| 973 | } |
| 974 | RangeDecorationStyle::Fill | RangeDecorationStyle::Frame => {} |
| 975 | } |
| 976 | } |
| 977 | quads |
| 978 | } |
| 979 | |
| 980 | fn layout_search_matches( |
| 981 | &self, |
| 982 | last_layout: &LastLayout, |
| 983 | bounds: &Bounds<Pixels>, |
| 984 | cx: &mut App, |
| 985 | ) -> Vec<(Path<Pixels>, bool)> { |
| 986 | let state = self.state.read(cx); |
| 987 | if !state.search_session.is_active() { |
| 988 | return vec![]; |
| 989 | } |
| 990 | let ranges = state.search_session.matcher.matched_ranges(); |
| 991 | let current_match_ix = state.search_session.matcher.current_match_index(); |
| 992 | |
| 993 | // Matches are sorted and do not overlap, so only the ones that reach |
| 994 | // into the visible range need a layout. |
| 995 | let visible_range = &last_layout.visible_range_offset; |
| 996 | let first = ranges.partition_point(|range| range.end <= visible_range.start); |
| 997 | let mut paths = Vec::new(); |
| 998 | for (index, range) in ranges |
| 999 | .iter() |
| 1000 | .enumerate() |
| 1001 | .skip(first) |
| 1002 | .take_while(|(_, range)| range.start < visible_range.end) |
| 1003 | { |
| 1004 | if let Some(path) = Self::layout_match_range(range.clone(), last_layout, bounds) { |
| 1005 | paths.push((path, current_match_ix == index)); |
| 1006 | } |
| 1007 | } |
| 1008 | |
| 1009 | paths |
| 1010 | } |
| 1011 | |
| 1012 | fn layout_hover_highlight( |
| 1013 | &self, |
| 1014 | last_layout: &LastLayout, |
| 1015 | bounds: &Bounds<Pixels>, |
| 1016 | cx: &mut App, |
| 1017 | ) -> Option<Path<Pixels>> { |
| 1018 | let state = self.state.read(cx); |
| 1019 | let Some(symbol_range) = state.extras.hover_symbol_range() else { |
| 1020 | return None; |
| 1021 | }; |
| 1022 | |
| 1023 | Self::layout_match_range(symbol_range, last_layout, bounds) |
| 1024 | } |
| 1025 | |
| 1026 | fn layout_document_colors( |
| 1027 | &self, |
| 1028 | document_colors: &[(Range<usize>, Hsla)], |
| 1029 | last_layout: &LastLayout, |
| 1030 | bounds: &Bounds<Pixels>, |
| 1031 | _cx: &mut App, |
| 1032 | ) -> Vec<(Path<Pixels>, Hsla)> { |
| 1033 | let mut paths = vec![]; |
| 1034 | for (range, color) in document_colors.iter() { |
| 1035 | if let Some(path) = Self::layout_match_range(range.clone(), last_layout, bounds) { |
| 1036 | paths.push((path, *color)); |
| 1037 | } |
| 1038 | } |
| 1039 | |
| 1040 | paths |
| 1041 | } |
| 1042 | |
| 1043 | fn layout_selections( |
| 1044 | &self, |
| 1045 | last_layout: &LastLayout, |
| 1046 | bounds: &mut Bounds<Pixels>, |
| 1047 | window: &mut Window, |
| 1048 | cx: &mut App, |
| 1049 | ) -> Vec<Path<Pixels>> { |
| 1050 | let state = self.state.read(cx); |
| 1051 | if !state.focus_handle.is_focused(window) { |
| 1052 | return vec![]; |
| 1053 | } |
| 1054 | |
| 1055 | let active_id = state.active_selection().id; |
| 1056 | let mut paths = Vec::new(); |
| 1057 | |
| 1058 | for selection in state.selections.iter() { |
| 1059 | let is_active = selection.id == active_id; |
| 1060 | let mut selected_range = *selection; |
| 1061 | |
| 1062 | // IME composition replaces the active selection with a collapsed |
| 1063 | // caret, so it never paints a selection highlight. |
| 1064 | if is_active { |
| 1065 | if let Some(ime_marked_range) = &state.ime_marked_range { |
| 1066 | if !ime_marked_range.is_empty() { |
| 1067 | selected_range = (ime_marked_range.end..ime_marked_range.end).into(); |
| 1068 | } |
| 1069 | } |
| 1070 | } |
| 1071 | if selected_range.is_empty() { |
| 1072 | continue; |
| 1073 | } |
| 1074 | |
| 1075 | if state.masked { |
| 1076 | selected_range.start = masked_display_offset(&state.text, selected_range.start); |
| 1077 | selected_range.end = masked_display_offset(&state.text, selected_range.end); |
| 1078 | } |
| 1079 | |
| 1080 | let (start_ix, end_ix) = if selected_range.start < selected_range.end { |
| 1081 | (selected_range.start, selected_range.end) |
| 1082 | } else { |
| 1083 | (selected_range.end, selected_range.start) |
| 1084 | }; |
| 1085 | |
| 1086 | let range = start_ix.max(last_layout.visible_range_offset.start) |
| 1087 | ..end_ix.min(last_layout.visible_range_offset.end); |
| 1088 | |
| 1089 | if range.is_empty() { |
| 1090 | continue; |
| 1091 | } |
| 1092 | |
| 1093 | // A selected token shows its own selected state, so the text |
| 1094 | // highlight stops at its edges instead of painting behind it. |
| 1095 | let mut start = range.start; |
| 1096 | if state.tokens_visible() { |
| 1097 | let spans = state.token_spans(); |
| 1098 | let first = spans.partition_point(|s| s.range().end <= range.start); |
| 1099 | for span in spans[first..] |
| 1100 | .iter() |
| 1101 | .take_while(|s| s.range().start < range.end) |
| 1102 | { |
| 1103 | if start < span.range().start { |
| 1104 | paths.extend(Self::layout_match_range( |
| 1105 | start..span.range().start, |
| 1106 | last_layout, |
| 1107 | bounds, |
| 1108 | )); |
| 1109 | } |
| 1110 | start = span.range().end.max(start); |
| 1111 | } |
| 1112 | } |
| 1113 | if start < range.end { |
| 1114 | paths.extend(Self::layout_match_range( |
| 1115 | start..range.end, |
| 1116 | last_layout, |
| 1117 | bounds, |
| 1118 | )); |
| 1119 | } |
| 1120 | } |
| 1121 | |
| 1122 | paths |
| 1123 | } |
| 1124 | |
| 1125 | /// Calculate the visible range of lines in the viewport. |
| 1126 | /// |
| 1127 | /// Returns |
| 1128 | /// |
| 1129 | /// - visible_range: The visible range is based on unwrapped lines (Zero based). |
| 1130 | /// - visible_buffer_lines: Indices of non-hidden buffer lines within the visible range. |
| 1131 | /// - visible_top: The top position of the first visible line in the scroll viewport. |
| 1132 | fn calculate_visible_range( |
| 1133 | &self, |
| 1134 | state: &InputBaseState<M>, |
| 1135 | line_height: Pixels, |
| 1136 | input_height: Pixels, |
| 1137 | ) -> (Range<usize>, Vec<usize>, Pixels) { |
| 1138 | // Add extra rows to avoid showing empty space when scroll to bottom. |
| 1139 | let extra_rows = 1; |
| 1140 | if state.is_single_line() { |
| 1141 | return (0..1, vec![0], px(0.)); |
| 1142 | } |
| 1143 | |
| 1144 | let display_count = state.display_map.display_row_count(); |
| 1145 | let buffer_line_count = state.display_map.buffer_line_count(); |
| 1146 | if display_count == 0 || buffer_line_count == 0 { |
| 1147 | return (0..0, Vec::new(), px(0.)); |
| 1148 | } |
| 1149 | |
| 1150 | let mut scroll_top = if let Some(deferred_scroll_offset) = state.deferred_scroll_offset { |
| 1151 | deferred_scroll_offset.y |
| 1152 | } else { |
| 1153 | state.scroll_handle.offset().y |
| 1154 | }; |
| 1155 | scroll_top = clamp_auto_grow_vertical_scroll_offset( |
| 1156 | &state.mode, |
| 1157 | scroll_top, |
| 1158 | state.display_map.content_height(line_height), |
| 1159 | input_height, |
| 1160 | ); |
| 1161 | |
| 1162 | let viewport_top = (-scroll_top).max(px(0.)); |
| 1163 | let viewport_bottom = viewport_top + input_height; |
| 1164 | let first_display = state |
| 1165 | .display_map |
| 1166 | .row_at_y(viewport_top, line_height) |
| 1167 | .min(display_count - 1); |
| 1168 | let bottom_row = state.display_map.row_at_y(viewport_bottom, line_height); |
| 1169 | let last_display = |
| 1170 | if state.display_map.row_top(bottom_row, line_height) < viewport_bottom { |
| 1171 | bottom_row + 1 |
| 1172 | } else { |
| 1173 | bottom_row |
| 1174 | } |
| 1175 | .min(display_count - 1); |
| 1176 | |
| 1177 | let start_line = state.display_map.display_row_to_buffer_line(first_display); |
| 1178 | let end_line = state.display_map.display_row_to_buffer_line(last_display); |
| 1179 | |
| 1180 | // y of the top of the first visible buffer line (in content space). |
| 1181 | let visible_top = match state |
| 1182 | .display_map |
| 1183 | .buffer_line_to_display_row_range(start_line) |
| 1184 | { |
| 1185 | Some(range) => state.display_map.row_top(range.start, line_height), |
| 1186 | None => state.display_map.row_top(first_display, line_height), |
| 1187 | }; |
| 1188 | |
| 1189 | let visible_range = start_line..(end_line + 1 + extra_rows).min(buffer_line_count); |
| 1190 | |
| 1191 | // Collect non-hidden buffer lines within the visible range |
| 1192 | let mut visible_buffer_lines = Vec::with_capacity(visible_range.len()); |
| 1193 | for ix in visible_range.clone() { |
| 1194 | if state.display_map.visible_wrap_row_count_for_buffer_line(ix) > 0 { |
| 1195 | visible_buffer_lines.push(ix); |
| 1196 | } |
| 1197 | } |
| 1198 | |
| 1199 | (visible_range, visible_buffer_lines, visible_top) |
| 1200 | } |
| 1201 | |
| 1202 | /// Return (line_number_width, line_number_len) |
| 1203 | fn layout_line_numbers( |
| 1204 | state: &InputBaseState<M>, |
| 1205 | text: &Rope, |
| 1206 | font_size: Pixels, |
| 1207 | style: &TextStyle, |
| 1208 | window: &mut Window, |
| 1209 | ) -> (Pixels, usize) { |
| 1210 | let total_lines = text.lines_len(); |
| 1211 | // Reserve three digits for small documents, then follow the actual |
| 1212 | // line count up to seven digits. |
| 1213 | let line_number_len = line_number_len(total_lines); |
| 1214 | |
| 1215 | let mut line_number_width = if state.mode.line_number() { |
| 1216 | let empty_line_number = window.text_system().shape_line( |
| 1217 | "+".repeat(line_number_len).into(), |
| 1218 | font_size, |
| 1219 | &[TextRun { |
| 1220 | len: line_number_len, |
| 1221 | font: style.font(), |
| 1222 | color: gpui::black(), |
| 1223 | background_color: None, |
| 1224 | underline: None, |
| 1225 | strikethrough: None, |
| 1226 | }], |
| 1227 | None, |
| 1228 | ); |
| 1229 | |
| 1230 | empty_line_number.width + LINE_NUMBER_RIGHT_MARGIN |
| 1231 | } else if state.is_code_editor() { |
| 1232 | LINE_NUMBER_RIGHT_MARGIN |
| 1233 | } else { |
| 1234 | px(0.) |
| 1235 | }; |
| 1236 | |
| 1237 | if state.mode.is_folding() { |
| 1238 | // Add extra space for fold icons |
| 1239 | line_number_width += FOLD_ICON_HITBOX_WIDTH |
| 1240 | } |
| 1241 | |
| 1242 | (line_number_width, line_number_len) |
| 1243 | } |
| 1244 | |
| 1245 | /// Layout shaped lines for whitespace indicators (space and tab). |
| 1246 | /// |
| 1247 | /// Returns `WhitespaceIndicators` with shaped lines for space and tab characters. |
| 1248 | fn layout_whitespace_indicators( |
| 1249 | state: &InputBaseState<M>, |
| 1250 | text_size: Pixels, |
| 1251 | style: &TextStyle, |
| 1252 | window: &mut Window, |
| 1253 | _cx: &App, |
| 1254 | ) -> Option<WhitespaceIndicators> { |
| 1255 | if !state.show_whitespaces { |
| 1256 | return None; |
| 1257 | } |
| 1258 | |
| 1259 | let invisible_color = state |
| 1260 | .editor_style |
| 1261 | .editor_invisible |
| 1262 | .unwrap_or(state.editor_style.muted_foreground); |
| 1263 | |
| 1264 | let space_font_size = text_size.half(); |
| 1265 | let tab_font_size = text_size; |
| 1266 | |
| 1267 | let space_text = SharedString::new_static("•"); |
| 1268 | let space = window.text_system().shape_line( |
| 1269 | space_text.clone(), |
| 1270 | space_font_size, |
| 1271 | &[TextRun { |
| 1272 | len: space_text.len(), |
| 1273 | font: style.font(), |
| 1274 | color: invisible_color, |
| 1275 | background_color: None, |
| 1276 | underline: None, |
| 1277 | strikethrough: None, |
| 1278 | }], |
| 1279 | None, |
| 1280 | ); |
| 1281 | |
| 1282 | let tab_text = SharedString::new_static("→"); |
| 1283 | let tab = window.text_system().shape_line( |
| 1284 | tab_text.clone(), |
| 1285 | tab_font_size, |
| 1286 | &[TextRun { |
| 1287 | len: tab_text.len(), |
| 1288 | font: style.font(), |
| 1289 | color: invisible_color, |
| 1290 | background_color: None, |
| 1291 | underline: None, |
| 1292 | strikethrough: None, |
| 1293 | }], |
| 1294 | None, |
| 1295 | ); |
| 1296 | |
| 1297 | Some(WhitespaceIndicators { space, tab }) |
| 1298 | } |
| 1299 | |
| 1300 | /// Compute inline completion ghost lines for rendering. |
| 1301 | /// |
| 1302 | /// Returns (first_line, ghost_lines) where: |
| 1303 | /// - first_line: Shaped text for the first line (goes after cursor on same line) |
| 1304 | /// - ghost_lines: Shaped lines for subsequent lines (shift content down) |
| 1305 | fn layout_inline_completion( |
| 1306 | state: &InputBaseState<M>, |
| 1307 | visible_range: &Range<usize>, |
| 1308 | font_size: Pixels, |
| 1309 | window: &mut Window, |
| 1310 | _cx: &App, |
| 1311 | ) -> (Option<ShapedLine>, Vec<ShapedLine>) { |
| 1312 | // Must be focused to show inline completion |
| 1313 | if !state.focus_handle.is_focused(window) { |
| 1314 | return (None, vec![]); |
| 1315 | } |
| 1316 | |
| 1317 | let Some(completion_item) = state.extras.inline_completion_item() else { |
| 1318 | return (None, vec![]); |
| 1319 | }; |
| 1320 | |
| 1321 | // Get cursor row from cursor position |
| 1322 | let cursor_row = state.cursor_position().line as usize; |
| 1323 | |
| 1324 | // Only show if cursor row is visible |
| 1325 | if cursor_row < visible_range.start || cursor_row >= visible_range.end { |
| 1326 | return (None, vec![]); |
| 1327 | } |
| 1328 | |
| 1329 | let completion_text = &completion_item.insert_text; |
| 1330 | let completion_color = state.editor_style.muted_foreground.opacity(0.5); |
| 1331 | |
| 1332 | let text_style = window.text_style(); |
| 1333 | let font = text_style.font(); |
| 1334 | |
| 1335 | let lines: Vec<&str> = completion_text.split('\n').collect(); |
| 1336 | if lines.is_empty() { |
| 1337 | return (None, vec![]); |
| 1338 | } |
| 1339 | |
| 1340 | // Shape first line (goes after cursor) |
| 1341 | let first_text: SharedString = lines[0].to_string().into(); |
| 1342 | let first_line = if !first_text.is_empty() { |
| 1343 | let first_run = TextRun { |
| 1344 | len: first_text.len(), |
| 1345 | font: font.clone(), |
| 1346 | color: completion_color, |
| 1347 | background_color: None, |
| 1348 | underline: None, |
| 1349 | strikethrough: None, |
| 1350 | }; |
| 1351 | Some( |
| 1352 | window |
| 1353 | .text_system() |
| 1354 | .shape_line(first_text, font_size, &[first_run], None), |
| 1355 | ) |
| 1356 | } else { |
| 1357 | None |
| 1358 | }; |
| 1359 | |
| 1360 | // Shape ghost lines (lines 2+ that shift content down) |
| 1361 | let ghost_lines: Vec<ShapedLine> = lines[1..] |
| 1362 | .iter() |
| 1363 | .map(|line_text| { |
| 1364 | let text: SharedString = line_text.to_string().into(); |
| 1365 | let len = text.len().max(1); // Ensure at least 1 for empty lines |
| 1366 | let run = TextRun { |
| 1367 | len, |
| 1368 | font: font.clone(), |
| 1369 | color: completion_color, |
| 1370 | background_color: None, |
| 1371 | underline: None, |
| 1372 | strikethrough: None, |
| 1373 | }; |
| 1374 | // Use space for empty lines so they take up height |
| 1375 | let shaped_text = if text.is_empty() { " ".into() } else { text }; |
| 1376 | window |
| 1377 | .text_system() |
| 1378 | .shape_line(shaped_text, font_size, &[run], None) |
| 1379 | }) |
| 1380 | .collect(); |
| 1381 | |
| 1382 | (first_line, ghost_lines) |
| 1383 | } |
| 1384 | |
| 1385 | /// Return (line_number_width, line_number_len) |
| 1386 | /// Layout fold icon hitboxes during prepaint phase. |
| 1387 | /// |
| 1388 | /// This creates hitboxes for the fold icon area, positioned to the right of line numbers. |
| 1389 | /// Icons are created and prepainted here to avoid panics. |
| 1390 | fn layout_fold_icons( |
| 1391 | &self, |
| 1392 | origin_x: Pixels, |
| 1393 | bounds: &Bounds<Pixels>, |
| 1394 | last_layout: &LastLayout, |
| 1395 | window: &mut Window, |
| 1396 | cx: &mut App, |
| 1397 | ) -> FoldIconLayout { |
| 1398 | // First pass: collect fold information from state |
| 1399 | struct FoldInfo { |
| 1400 | buffer_line: usize, |
| 1401 | is_folded: bool, |
| 1402 | display_row: usize, |
| 1403 | offset_y: Pixels, |
| 1404 | } |
| 1405 | |
| 1406 | let line_number_hitbox = window.insert_hitbox( |
| 1407 | Bounds::new( |
| 1408 | point(origin_x, bounds.origin.y + last_layout.visible_top), |
| 1409 | size(last_layout.line_number_width, bounds.size.height), |
| 1410 | ), |
| 1411 | HitboxBehavior::Normal, |
| 1412 | ); |
| 1413 | |
| 1414 | let mut icon_layout = FoldIconLayout { |
| 1415 | line_number_hitbox, |
| 1416 | icons: vec![], |
| 1417 | }; |
| 1418 | |
| 1419 | let fold_infos: Vec<FoldInfo> = { |
| 1420 | let state = self.state.read(cx); |
| 1421 | if !state.mode.is_folding() { |
| 1422 | return icon_layout; |
| 1423 | } |
| 1424 | |
| 1425 | let mut infos = Vec::with_capacity(last_layout.visible_buffer_lines.len()); |
| 1426 | let mut offset_y = last_layout.visible_top; |
| 1427 | |
| 1428 | for (line, &buffer_line) in last_layout |
| 1429 | .lines |
| 1430 | .iter() |
| 1431 | .zip(last_layout.visible_buffer_lines.iter()) |
| 1432 | { |
| 1433 | if state.display_map.is_fold_candidate(buffer_line) { |
| 1434 | let is_folded = state.display_map.is_folded_at(buffer_line); |
| 1435 | infos.push(FoldInfo { |
| 1436 | buffer_line, |
| 1437 | is_folded, |
| 1438 | display_row: buffer_line, |
| 1439 | offset_y, |
| 1440 | }); |
| 1441 | } |
| 1442 | |
| 1443 | offset_y += line.wrapped_lines.len() * last_layout.line_height; |
| 1444 | } |
| 1445 | |
| 1446 | infos |
| 1447 | }; // state is dropped here |
| 1448 | |
| 1449 | // Second pass: create and prepaint icons |
| 1450 | let line_height = last_layout.line_height; |
| 1451 | let line_number_width = |
| 1452 | last_layout.line_number_width - LINE_NUMBER_RIGHT_MARGIN - FOLD_ICON_HITBOX_WIDTH; |
| 1453 | let icon_relative_pos = point( |
| 1454 | (FOLD_ICON_HITBOX_WIDTH - FOLD_ICON_WIDTH).half(), |
| 1455 | (line_height - FOLD_ICON_WIDTH).half(), |
| 1456 | ); |
| 1457 | |
| 1458 | for (ix, info) in fold_infos.iter().enumerate() { |
| 1459 | // Position fold icon to the right of line numbers. |
| 1460 | // Use origin_x (unscrolled) so icons stay fixed in the gutter during horizontal scroll. |
| 1461 | let fold_icon_bounds = Bounds::new( |
| 1462 | point( |
| 1463 | origin_x + icon_relative_pos.x + line_number_width, |
| 1464 | bounds.origin.y + icon_relative_pos.y + info.offset_y, |
| 1465 | ), |
| 1466 | size(FOLD_ICON_HITBOX_WIDTH, line_height), |
| 1467 | ); |
| 1468 | |
| 1469 | // Create and prepaint icon |
| 1470 | let child = self |
| 1471 | .state |
| 1472 | .read(cx) |
| 1473 | .editor_style |
| 1474 | .fold_icon_renderer |
| 1475 | .as_ref() |
| 1476 | .map(|render| render(ix, info.is_folded)) |
| 1477 | .unwrap_or_else(|| { |
| 1478 | let (path, svg) = if info.is_folded { |
| 1479 | ("input-fold-chevron-right", FOLD_CHEVRON_RIGHT_SVG) |
| 1480 | } else { |
| 1481 | ("input-fold-chevron-down", FOLD_CHEVRON_DOWN_SVG) |
| 1482 | }; |
| 1483 | gpui::canvas( |
| 1484 | |_, _, _| {}, |
| 1485 | move |bounds, _, window, cx| { |
| 1486 | let color = window.text_style().color; |
| 1487 | let _ = window.paint_svg( |
| 1488 | bounds, |
| 1489 | path.into(), |
| 1490 | Some(svg), |
| 1491 | gpui::TransformationMatrix::default(), |
| 1492 | color, |
| 1493 | cx, |
| 1494 | ); |
| 1495 | }, |
| 1496 | ) |
| 1497 | .size(FOLD_ICON_WIDTH) |
| 1498 | .into_any_element() |
| 1499 | }); |
| 1500 | let mut icon = gpui::div() |
| 1501 | .id(("fold", ix)) |
| 1502 | .size(FOLD_ICON_WIDTH) |
| 1503 | .child(child) |
| 1504 | .on_mouse_down(MouseButton::Left, { |
| 1505 | let state = self.state.clone(); |
| 1506 | let buffer_line = info.buffer_line; |
| 1507 | move |_, _: &mut Window, cx: &mut App| { |
| 1508 | cx.stop_propagation(); |
| 1509 | |
| 1510 | state.update(cx, |state, cx| { |
| 1511 | state.display_map.toggle_fold(buffer_line); |
| 1512 | cx.notify(); |
| 1513 | }); |
| 1514 | } |
| 1515 | }) |
| 1516 | .into_any_element(); |
| 1517 | |
| 1518 | icon.prepaint_as_root( |
| 1519 | fold_icon_bounds.origin, |
| 1520 | fold_icon_bounds.size.into(), |
| 1521 | window, |
| 1522 | cx, |
| 1523 | ); |
| 1524 | |
| 1525 | icon_layout |
| 1526 | .icons |
| 1527 | .push((info.display_row, info.is_folded, icon)); |
| 1528 | } |
| 1529 | |
| 1530 | icon_layout |
| 1531 | } |
| 1532 | |
| 1533 | /// Paint fold icons using prepaint hitboxes. |
| 1534 | /// |
| 1535 | /// This handles: |
| 1536 | /// - Rendering fold icons (chevron-right for folded, chevron-down for expanded) |
| 1537 | /// - Mouse click handling to toggle fold state |
| 1538 | /// - Cursor style changes on hover |
| 1539 | /// - Only show icon on hover or for current line |
| 1540 | fn paint_fold_icons( |
| 1541 | &mut self, |
| 1542 | fold_icon_layout: &mut FoldIconLayout, |
| 1543 | current_row: Option<usize>, |
| 1544 | window: &mut Window, |
| 1545 | cx: &mut App, |
| 1546 | ) { |
| 1547 | let is_hovered = fold_icon_layout.line_number_hitbox.is_hovered(window); |
| 1548 | if !fold_icon_layout.icons.is_empty() { |
| 1549 | // Mouse moves do not repaint the editor, so repaint when the pointer |
| 1550 | // enters or leaves the gutter to show or hide the hover chevrons. |
| 1551 | let hitbox = fold_icon_layout.line_number_hitbox.clone(); |
| 1552 | let entity_id = self.state.entity_id(); |
| 1553 | window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| { |
| 1554 | if phase.bubble() && hitbox.is_hovered(window) != is_hovered { |
| 1555 | cx.notify(entity_id); |
| 1556 | } |
| 1557 | }); |
| 1558 | } |
| 1559 | for (display_row, is_folded, icon) in fold_icon_layout.icons.iter_mut() { |
| 1560 | let is_current_line = current_row == Some(*display_row); |
| 1561 | |
| 1562 | if !is_hovered && !is_current_line && !*is_folded { |
| 1563 | continue; |
| 1564 | } |
| 1565 | |
| 1566 | icon.paint(window, cx); |
| 1567 | } |
| 1568 | } |
| 1569 | |
| 1570 | fn token_element( |
| 1571 | &self, |
| 1572 | token: &super::InlineTokenContext, |
| 1573 | window: &mut Window, |
| 1574 | cx: &mut App, |
| 1575 | ) -> AnyElement { |
| 1576 | use gpui::{ |
| 1577 | InteractiveElement as _, StatefulInteractiveElement as _, prelude::FluentBuilder as _, |
| 1578 | }; |
| 1579 | let presentation = self.state.read(cx).token_presentation.clone(); |
| 1580 | let child = presentation.render(token, window, cx); |
| 1581 | // Preserve interaction state only for the same token occurrence and |
| 1582 | // hover eligibility. Replacements and re-enabling start fresh. |
| 1583 | let start = token.range().start; |
| 1584 | let down_state = self.state.clone(); |
| 1585 | let click_state = self.state.clone(); |
| 1586 | let move_state = self.state.clone(); |
| 1587 | let hover_state = self.state.clone(); |
| 1588 | let hover_token = token.token().clone(); |
| 1589 | let disabled = token.is_disabled(); |
| 1590 | let hover_enabled = presentation.has_hover_listener() && !disabled; |
| 1591 | let id = gpui::ElementId::from(("inline-token", start)); |
| 1592 | let id = gpui::ElementId::from((id, token.token().id().clone())); |
| 1593 | let id = gpui::ElementId::from((id, token.token().text().clone())); |
| 1594 | let id = gpui::ElementId::from((id, token.token().label().clone())); |
| 1595 | let id = gpui::ElementId::from(( |
| 1596 | id, |
| 1597 | gpui::SharedString::from(if hover_enabled { |
| 1598 | "hover-enabled" |
| 1599 | } else { |
| 1600 | "hover-disabled" |
| 1601 | }), |
| 1602 | )); |
| 1603 | let accessible = presentation.has_listener() && !disabled; |
| 1604 | let accessible_state = self.state.clone(); |
| 1605 | gpui::div() |
| 1606 | .id(id) |
| 1607 | .flex() |
| 1608 | .items_center() |
| 1609 | .when(!token.is_block(), |this| this.h(token.line_height())) |
| 1610 | .max_w(token.available_width()) |
| 1611 | .overflow_hidden() |
| 1612 | // A token is an object, not text: the arrow, never the I-beam. |
| 1613 | .cursor_default() |
| 1614 | .when(accessible, |this| { |
| 1615 | this.role(gpui::Role::Button) |
| 1616 | .aria_label(token.token().label().clone()) |
| 1617 | .on_a11y_action(gpui::AccessibleAction::Click, move |_, window, cx| { |
| 1618 | let state = accessible_state.read(cx); |
| 1619 | let activation = state |
| 1620 | .token_spans() |
| 1621 | .iter() |
| 1622 | .find(|s| s.range().start == start) |
| 1623 | .and_then(|span| { |
| 1624 | state.range_to_bounds(&span.range()).and_then(|bounds| { |
| 1625 | state.token_activation( |
| 1626 | start, |
| 1627 | bounds, |
| 1628 | gpui::ClickEvent::Keyboard(gpui::KeyboardClickEvent { |
| 1629 | bounds, |
| 1630 | ..Default::default() |
| 1631 | }), |
| 1632 | ) |
| 1633 | }) |
| 1634 | }); |
| 1635 | if let Some((listener, event)) = activation { |
| 1636 | listener(&event, window, cx); |
| 1637 | } |
| 1638 | }) |
| 1639 | }) |
| 1640 | .capture_any_mouse_down(move |_, window, cx| { |
| 1641 | if disabled { |
| 1642 | window.prevent_default(); |
| 1643 | cx.stop_propagation(); |
| 1644 | } |
| 1645 | }) |
| 1646 | .capture_any_mouse_up(move |_, window, cx| { |
| 1647 | if disabled { |
| 1648 | window.prevent_default(); |
| 1649 | cx.stop_propagation(); |
| 1650 | } |
| 1651 | }) |
| 1652 | .capture_key_down(move |_, _, cx| { |
| 1653 | if disabled { |
| 1654 | cx.stop_propagation(); |
| 1655 | } |
| 1656 | }) |
| 1657 | .on_mouse_down(MouseButton::Left, move |event, window, cx| { |
| 1658 | if window.default_prevented() { |
| 1659 | return; |
| 1660 | } |
| 1661 | down_state.update(cx, |state, cx| { |
| 1662 | state.pressed_token = None; |
| 1663 | if event.click_count == 2 { |
| 1664 | if let Some(span) = state |
| 1665 | .token_spans() |
| 1666 | .iter() |
| 1667 | .find(|s| s.range().start == start) |
| 1668 | { |
| 1669 | state.set_selected_range(span.range(), cx); |
| 1670 | state.focus(window, cx); |
| 1671 | window.prevent_default(); |
| 1672 | } |
| 1673 | } else if event.click_count == 1 |
| 1674 | && !event.modifiers.shift |
| 1675 | && !event.modifiers.alt |
| 1676 | { |
| 1677 | state.pressed_token = |
| 1678 | Some((start, state.document_revision, event.position)); |
| 1679 | } |
| 1680 | }); |
| 1681 | }) |
| 1682 | .on_mouse_move(move |event, _, cx| { |
| 1683 | move_state.update(cx, |state, _| { |
| 1684 | if state.pressed_token.as_ref().is_some_and(|(_, _, p)| { |
| 1685 | (event.position.x - p.x).abs() + (event.position.y - p.y).abs() > px(4.) |
| 1686 | }) { |
| 1687 | state.pressed_token = None; |
| 1688 | } |
| 1689 | }); |
| 1690 | }) |
| 1691 | .on_click(move |event, window, cx| { |
| 1692 | let activation = click_state.update(cx, |state, cx| { |
| 1693 | let (pressed, revision, _) = state.pressed_token.take()?; |
| 1694 | if pressed != start || revision != state.document_revision { |
| 1695 | return None; |
| 1696 | } |
| 1697 | if event.modifiers().shift || event.modifiers().alt { |
| 1698 | return None; |
| 1699 | } |
| 1700 | let span = state |
| 1701 | .token_spans() |
| 1702 | .iter() |
| 1703 | .find(|s| s.range().start == start)? |
| 1704 | .clone(); |
| 1705 | // A click selects the whole token; opening it is the |
| 1706 | // listener's decision. |
| 1707 | state.set_selected_range(span.range(), cx); |
| 1708 | let bounds = state.range_to_bounds(&span.range())?; |
| 1709 | state.token_activation(start, bounds, event.clone()) |
| 1710 | }); |
| 1711 | if let Some((listener, event)) = activation { |
| 1712 | listener(&event, window, cx); |
| 1713 | } |
| 1714 | }) |
| 1715 | .on_hover(move |hovered, window, cx| { |
| 1716 | // Hover never selects or edits; it only reports presence so the |
| 1717 | // application can show a tooltip or run custom logic. |
| 1718 | let hovered = *hovered; |
| 1719 | let activation = hover_state.update(cx, |state, _| { |
| 1720 | // Anchor to the real laid-out token rect, not the |
| 1721 | // range-to-bounds guess: a token at a soft-wrap boundary |
| 1722 | // would otherwise report a zero/negative width or a |
| 1723 | // two-row height. |
| 1724 | let bounds = if hovered { |
| 1725 | state.token_bounds.get(&start).copied()? |
| 1726 | } else { |
| 1727 | // Exits use entry geometry even if an earlier callback |
| 1728 | // removed the token and its current bounds. |
| 1729 | Bounds::default() |
| 1730 | }; |
| 1731 | state.token_hover(start, bounds, hovered, Some(&hover_token)) |
| 1732 | }); |
| 1733 | if let Some((listener, event)) = activation { |
| 1734 | listener(&event, window, cx); |
| 1735 | } |
| 1736 | }) |
| 1737 | .child(child) |
| 1738 | .into_any_element() |
| 1739 | } |
| 1740 | |
| 1741 | fn token_available_space( |
| 1742 | token: &super::InlineTokenContext, |
| 1743 | line_height: Pixels, |
| 1744 | ) -> Size<gpui::AvailableSpace> { |
| 1745 | size( |
| 1746 | gpui::AvailableSpace::MaxContent, |
| 1747 | if token.is_block() { |
| 1748 | gpui::AvailableSpace::MinContent |
| 1749 | } else { |
| 1750 | gpui::AvailableSpace::Definite(line_height) |
| 1751 | }, |
| 1752 | ) |
| 1753 | } |
| 1754 | |
| 1755 | fn measure_tokens( |
| 1756 | &self, |
| 1757 | width: Pixels, |
| 1758 | line_height: Pixels, |
| 1759 | viewport: Pixels, |
| 1760 | window: &mut Window, |
| 1761 | cx: &mut App, |
| 1762 | ) -> std::collections::HashMap<usize, (AnyElement, Size<Pixels>)> { |
| 1763 | let style = window.text_style(); |
| 1764 | let state = self.state.read(cx); |
| 1765 | let key = ( |
| 1766 | style.font(), |
| 1767 | style.font_size.to_pixels(window.rem_size()), |
| 1768 | width, |
| 1769 | line_height, |
| 1770 | state.is_single_line() || !state.soft_wrap, |
| 1771 | ); |
| 1772 | if !state.tokens_visible() { |
| 1773 | if state.token_layout_cache.is_none() { |
| 1774 | let mut exit = self.state.update(cx, |state, _| { |
| 1775 | state.token_bounds.clear(); |
| 1776 | state.reconcile_token_hover() |
| 1777 | }); |
| 1778 | while let Some((listener, event)) = exit { |
| 1779 | listener(&event, window, cx); |
| 1780 | exit = self |
| 1781 | .state |
| 1782 | .update(cx, |state, _| state.reconcile_token_hover()); |
| 1783 | } |
| 1784 | return Default::default(); |
| 1785 | } |
| 1786 | self.state.update(cx, |state, cx| { |
| 1787 | state.display_map.set_inline_metrics(Rc::from([]), cx) |
| 1788 | }); |
| 1789 | let mut exit = self.state.update(cx, |state, _| { |
| 1790 | state.token_bounds.clear(); |
| 1791 | state.reconcile_token_hover() |
| 1792 | }); |
| 1793 | while let Some((listener, event)) = exit { |
| 1794 | listener(&event, window, cx); |
| 1795 | exit = self |
| 1796 | .state |
| 1797 | .update(cx, |state, _| state.reconcile_token_hover()); |
| 1798 | } |
| 1799 | return Default::default(); |
| 1800 | } |
| 1801 | let revision = state.document_revision; |
| 1802 | let cache = state.token_layout_cache.as_ref(); |
| 1803 | let (visible, _, _) = self.calculate_visible_range(state, line_height, viewport); |
| 1804 | let start = state.text.line_start_offset(visible.start); |
| 1805 | let end = state.text.line_end_offset(visible.end.saturating_sub(1)); |
| 1806 | let spans = state.token_spans(); |
| 1807 | let contexts: Vec<_> = spans |
| 1808 | .iter() |
| 1809 | .filter(|span| { |
| 1810 | let range = span.range(); |
| 1811 | span.token().is_block() |
| 1812 | || (range.start <= end && range.end >= start) |
| 1813 | || cache.is_none_or(|cache| { |
| 1814 | cache.key.as_ref() != Some(&key) || !cache.sizes.contains_key(span.token()) |
| 1815 | }) |
| 1816 | }) |
| 1817 | .map(|span| state.token_context(span, line_height, width)) |
| 1818 | .collect(); |
| 1819 | let mut elements = std::collections::HashMap::new(); |
| 1820 | let mut measured = Vec::new(); |
| 1821 | for token in contexts { |
| 1822 | let mut element = self.token_element(&token, window, cx); |
| 1823 | let size = element.layout_as_root( |
| 1824 | Self::token_available_space(&token, line_height), |
| 1825 | window, |
| 1826 | cx, |
| 1827 | ); |
| 1828 | measured.push(( |
| 1829 | token.token().clone(), |
| 1830 | gpui::Size { |
| 1831 | width: size.width.min(width).max(px(1.)), |
| 1832 | height: size.height.max(px(1.)), |
| 1833 | }, |
| 1834 | )); |
| 1835 | elements.insert(token.range().start, (element, size)); |
| 1836 | } |
| 1837 | self.state.update(cx, |state, cx| { |
| 1838 | let mut cache = state.token_layout_cache.take().unwrap_or_default(); |
| 1839 | let mut changed = cache.key.as_ref() != Some(&key) || cache.revision != revision; |
| 1840 | if cache.key.as_ref() != Some(&key) { |
| 1841 | cache.sizes.clear(); |
| 1842 | } |
| 1843 | for (token, token_size) in measured { |
| 1844 | changed |= cache.sizes.get(&token) != Some(&token_size); |
| 1845 | cache.sizes.insert(token, token_size); |
| 1846 | } |
| 1847 | cache.key = Some(key); |
| 1848 | if changed { |
| 1849 | let spans = state.token_spans(); |
| 1850 | let tokens: std::collections::HashSet<_> = |
| 1851 | spans.iter().map(|s| s.token()).collect(); |
| 1852 | cache.sizes.retain(|token, _| tokens.contains(token)); |
| 1853 | cache.metrics = spans |
| 1854 | .iter() |
| 1855 | .filter_map(|span| { |
| 1856 | cache |
| 1857 | .sizes |
| 1858 | .get(span.token()) |
| 1859 | .map(|token_size| InlineMetric { |
| 1860 | range: span.range(), |
| 1861 | width: token_size.width, |
| 1862 | height: span.token().is_block().then_some(token_size.height), |
| 1863 | }) |
| 1864 | }) |
| 1865 | .collect(); |
| 1866 | cache.revision = revision; |
| 1867 | if state.is_single_line() || !state.soft_wrap { |
| 1868 | let mut rows: Vec<_> = spans |
| 1869 | .iter() |
| 1870 | .map(|s| state.text.offset_to_point(s.range().start).row) |
| 1871 | .collect(); |
| 1872 | rows.push(state.display_map.longest_row()); |
| 1873 | rows.sort_unstable(); |
| 1874 | rows.dedup(); |
| 1875 | cache.unwrapped_width = rows |
| 1876 | .into_iter() |
| 1877 | .map(|row| { |
| 1878 | let start = state.text.line_start_offset(row); |
| 1879 | let text = state.text.slice_line(row).to_string(); |
| 1880 | let mut offset = 0; |
| 1881 | let mut width = px(0.); |
| 1882 | let first = spans.partition_point(|s| s.range().end <= start); |
| 1883 | for span in spans[first..] |
| 1884 | .iter() |
| 1885 | .take_while(|s| s.range().start < start + text.len()) |
| 1886 | { |
| 1887 | let local = span.range().start - start..span.range().end - start; |
| 1888 | let part = &text[offset..local.start]; |
| 1889 | width += window |
| 1890 | .text_system() |
| 1891 | .shape_line( |
| 1892 | part.to_owned().into(), |
| 1893 | style.font_size.to_pixels(window.rem_size()), |
| 1894 | &[style.to_run(part.len())], |
| 1895 | None, |
| 1896 | ) |
| 1897 | .width; |
| 1898 | width += cache |
| 1899 | .sizes |
| 1900 | .get(span.token()) |
| 1901 | .map_or(px(0.), |token_size| token_size.width); |
| 1902 | offset = local.end; |
| 1903 | } |
| 1904 | let part = &text[offset..]; |
| 1905 | width |
| 1906 | + window |
| 1907 | .text_system() |
| 1908 | .shape_line( |
| 1909 | part.to_owned().into(), |
| 1910 | style.font_size.to_pixels(window.rem_size()), |
| 1911 | &[style.to_run(part.len())], |
| 1912 | None, |
| 1913 | ) |
| 1914 | .width |
| 1915 | }) |
| 1916 | .max() |
| 1917 | .unwrap_or_default(); |
| 1918 | } |
| 1919 | } |
| 1920 | let metrics = cache.metrics.clone(); |
| 1921 | state.token_layout_cache = Some(cache); |
| 1922 | state.display_map.set_inline_metrics(metrics, cx); |
| 1923 | if state.mode.is_auto_grow() { |
| 1924 | let rows = state.mode.rows(); |
| 1925 | state.mode.update_auto_grow(&state.display_map, line_height); |
| 1926 | if state.mode.rows() != rows { |
| 1927 | cx.notify(); |
| 1928 | } |
| 1929 | } |
| 1930 | }); |
| 1931 | elements |
| 1932 | } |
| 1933 | |
| 1934 | fn layout_token_lines( |
| 1935 | state: &InputBaseState<M>, |
| 1936 | last_layout: &LastLayout, |
| 1937 | font_size: Pixels, |
| 1938 | runs: &[TextRun], |
| 1939 | window: &mut Window, |
| 1940 | ) -> Vec<LineLayout> { |
| 1941 | use crate::input::display_map::{InlineFragment, InputLine}; |
| 1942 | let spans = state.token_spans(); |
| 1943 | let cache = state |
| 1944 | .token_layout_cache |
| 1945 | .as_ref() |
| 1946 | .expect("tokens measured before shaping"); |
| 1947 | let mut run_offset = 0; |
| 1948 | last_layout |
| 1949 | .visible_buffer_lines |
| 1950 | .iter() |
| 1951 | .map(|&row| { |
| 1952 | let line_start = state.text.line_start_offset(row); |
| 1953 | let text: String = state.text.slice_line(row).into(); |
| 1954 | let ranges = if state.is_single_line() { |
| 1955 | smallvec::smallvec![0..text.len()] |
| 1956 | } else { |
| 1957 | state |
| 1958 | .display_map |
| 1959 | .line(row) |
| 1960 | .expect("prepared line") |
| 1961 | .wrapped_lines |
| 1962 | .clone() |
| 1963 | }; |
| 1964 | let mut lines: SmallVec<[InputLine; 1]> = SmallVec::new(); |
| 1965 | for range in ranges { |
| 1966 | let mut fragments = Vec::new(); |
| 1967 | let mut block_height = None; |
| 1968 | let mut offset = range.start; |
| 1969 | let mut x = px(0.); |
| 1970 | let first = |
| 1971 | spans.partition_point(|s| s.range().end <= line_start + range.start); |
| 1972 | for span in spans[first..] |
| 1973 | .iter() |
| 1974 | .take_while(|s| s.range().start < line_start + range.end) |
| 1975 | { |
| 1976 | let local = span.range().start - line_start..span.range().end - line_start; |
| 1977 | if offset < local.start { |
| 1978 | let part = offset..local.start; |
| 1979 | let shaped = window.text_system().shape_line( |
| 1980 | text[part.clone()].to_owned().into(), |
| 1981 | font_size, |
| 1982 | &runs_for_range(runs, run_offset, &part), |
| 1983 | None, |
| 1984 | ); |
| 1985 | let width = shaped.width; |
| 1986 | fragments.push(InlineFragment { |
| 1987 | range: part.start - range.start..part.end - range.start, |
| 1988 | x, |
| 1989 | width, |
| 1990 | text: Some(shaped), |
| 1991 | }); |
| 1992 | x += width; |
| 1993 | } |
| 1994 | let token_size = cache.sizes.get(span.token()).copied().unwrap_or_default(); |
| 1995 | let width = token_size.width; |
| 1996 | if span.token().is_block() && local == range { |
| 1997 | block_height = Some(token_size.height); |
| 1998 | } |
| 1999 | fragments.push(InlineFragment { |
| 2000 | range: local.start - range.start..local.end - range.start, |
| 2001 | x, |
| 2002 | width, |
| 2003 | text: None, |
| 2004 | }); |
| 2005 | x += width; |
| 2006 | offset = local.end; |
| 2007 | } |
| 2008 | if offset < range.end { |
| 2009 | let part = offset..range.end; |
| 2010 | let shaped = window.text_system().shape_line( |
| 2011 | text[part.clone()].to_owned().into(), |
| 2012 | font_size, |
| 2013 | &runs_for_range(runs, run_offset, &part), |
| 2014 | None, |
| 2015 | ); |
| 2016 | let width = shaped.width; |
| 2017 | fragments.push(InlineFragment { |
| 2018 | range: part.start - range.start..part.end - range.start, |
| 2019 | x, |
| 2020 | width, |
| 2021 | text: Some(shaped), |
| 2022 | }); |
| 2023 | } |
| 2024 | lines.push( |
| 2025 | InputLine::inline(text[range].to_owned().into(), fragments) |
| 2026 | .with_height(block_height), |
| 2027 | ); |
| 2028 | } |
| 2029 | let indent = state.display_map.line(row).map_or(0, |line| line.indent); |
| 2030 | let wrap_indent = if indent > 0 && lines.len() > 1 { |
| 2031 | let bytes = text |
| 2032 | .char_indices() |
| 2033 | .nth(indent as usize) |
| 2034 | .map_or(text.len(), |(ix, _)| ix); |
| 2035 | lines[0].x_for_index(bytes) |
| 2036 | } else { |
| 2037 | px(0.) |
| 2038 | }; |
| 2039 | run_offset += text.len() + 1; |
| 2040 | LineLayout::new() |
| 2041 | .inline_lines(lines) |
| 2042 | .wrap_indent(wrap_indent) |
| 2043 | .first_indent(state.display_map.line_indent(line_start)) |
| 2044 | }) |
| 2045 | .collect() |
| 2046 | } |
| 2047 | |
| 2048 | fn prepaint_tokens( |
| 2049 | &self, |
| 2050 | layout: &LastLayout, |
| 2051 | bounds: Bounds<Pixels>, |
| 2052 | mut measured: std::collections::HashMap<usize, (AnyElement, Size<Pixels>)>, |
| 2053 | window: &mut Window, |
| 2054 | cx: &mut App, |
| 2055 | ) -> Vec<AnyElement> { |
| 2056 | let state = self.state.read(cx); |
| 2057 | if !state.tokens_visible() { |
| 2058 | let mut exit = self.state.update(cx, |state, _| { |
| 2059 | state.token_bounds.clear(); |
| 2060 | state.reconcile_token_hover() |
| 2061 | }); |
| 2062 | while let Some((listener, event)) = exit { |
| 2063 | listener(&event, window, cx); |
| 2064 | exit = self |
| 2065 | .state |
| 2066 | .update(cx, |state, _| state.reconcile_token_hover()); |
| 2067 | } |
| 2068 | return vec![]; |
| 2069 | } |
| 2070 | let width = state |
| 2071 | .token_layout_cache |
| 2072 | .as_ref() |
| 2073 | .and_then(|c| c.key.as_ref()) |
| 2074 | .map_or(bounds.size.width, |k| k.2); |
| 2075 | let mut placements = Vec::new(); |
| 2076 | let mut y = layout.visible_top; |
| 2077 | for (ix, &row) in layout.visible_buffer_lines.iter().enumerate() { |
| 2078 | let start = state.text.line_start_offset(row); |
| 2079 | let end = state.text.line_end_offset(row); |
| 2080 | let spans = state.token_spans(); |
| 2081 | let first = spans.partition_point(|s| s.range().end <= start); |
| 2082 | for span in spans[first..].iter().take_while(|s| s.range().start < end) { |
| 2083 | if let Some(position) = |
| 2084 | layout.lines[ix].position_for_index(span.range().start - start, layout, false) |
| 2085 | { |
| 2086 | placements.push(( |
| 2087 | state.token_context(span, layout.line_height, width), |
| 2088 | bounds.origin + position + point(layout.line_number_width, y), |
| 2089 | )); |
| 2090 | } |
| 2091 | } |
| 2092 | y += layout.lines[ix].size(layout.line_height).height; |
| 2093 | } |
| 2094 | let mut out = Vec::new(); |
| 2095 | let mut token_bounds = std::collections::HashMap::new(); |
| 2096 | for (token, origin) in placements { |
| 2097 | let (mut element, element_size) = match measured.remove(&token.range().start) { |
| 2098 | Some(found) => found, |
| 2099 | None => { |
| 2100 | let mut element = self.token_element(&token, window, cx); |
| 2101 | let element_size = element.layout_as_root( |
| 2102 | Self::token_available_space(&token, layout.line_height), |
| 2103 | window, |
| 2104 | cx, |
| 2105 | ); |
| 2106 | (element, element_size) |
| 2107 | } |
| 2108 | }; |
| 2109 | element.prepaint_at(origin, window, cx); |
| 2110 | token_bounds.insert(token.range().start, Bounds::new(origin, element_size)); |
| 2111 | out.push(element); |
| 2112 | } |
| 2113 | let mut exit = self.state.update(cx, |state, _| { |
| 2114 | state.token_bounds = token_bounds; |
| 2115 | state.reconcile_token_hover() |
| 2116 | }); |
| 2117 | while let Some((listener, event)) = exit { |
| 2118 | listener(&event, window, cx); |
| 2119 | exit = self |
| 2120 | .state |
| 2121 | .update(cx, |state, _| state.reconcile_token_hover()); |
| 2122 | } |
| 2123 | out |
| 2124 | } |
| 2125 | |
| 2126 | #[allow(clippy::too_many_arguments)] |
| 2127 | fn layout_lines( |
| 2128 | state: &InputBaseState<M>, |
| 2129 | display_text: &Rope, |
| 2130 | last_layout: &LastLayout, |
| 2131 | font_size: Pixels, |
| 2132 | runs: &[TextRun], |
| 2133 | bg_segments: &[(Range<usize>, Hsla)], |
| 2134 | whitespace_indicators: Option<WhitespaceIndicators>, |
| 2135 | window: &mut Window, |
| 2136 | ) -> Vec<LineLayout> { |
| 2137 | let is_single_line = state.is_single_line(); |
| 2138 | if state.tokens_visible() { |
| 2139 | return Self::layout_token_lines(state, last_layout, font_size, runs, window); |
| 2140 | } |
| 2141 | |
| 2142 | if is_single_line { |
| 2143 | let text: SharedString = display_text.to_string().into(); |
| 2144 | let aligned_runs = align_runs_to_char_boundaries(&text, runs); |
| 2145 | let line_runs = aligned_runs.as_deref().unwrap_or(runs); |
| 2146 | let shaped_line = window |
| 2147 | .text_system() |
| 2148 | .shape_line(text, font_size, line_runs, None); |
| 2149 | |
| 2150 | let line_layout = LineLayout::new() |
| 2151 | .lines(smallvec::smallvec![shaped_line]) |
| 2152 | .with_background(has_background(line_runs)) |
| 2153 | .with_whitespaces(whitespace_indicators); |
| 2154 | return vec![line_layout]; |
| 2155 | } |
| 2156 | |
| 2157 | // Empty to use placeholder, the placeholder is not in the wrapper map. |
| 2158 | if state.text.len() == 0 { |
| 2159 | let placeholder_text = display_text.to_string(); |
| 2160 | let mut placeholder_lines = SmallVec::new(); |
| 2161 | let mut line_has_background = false; |
| 2162 | |
| 2163 | for (line, line_runs) in placeholder_line_runs(&placeholder_text, runs) { |
| 2164 | let shaped_line = window.text_system().shape_line( |
| 2165 | line.to_string().into(), |
| 2166 | font_size, |
| 2167 | &line_runs, |
| 2168 | None, |
| 2169 | ); |
| 2170 | line_has_background |= has_background(&line_runs); |
| 2171 | placeholder_lines.push(shaped_line); |
| 2172 | } |
| 2173 | |
| 2174 | // Keep placeholder lines in a single layout to stay parallel with visible_* metadata. |
| 2175 | let line_layout = LineLayout::new() |
| 2176 | .lines(placeholder_lines) |
| 2177 | .with_background(line_has_background) |
| 2178 | .with_whitespaces(whitespace_indicators); |
| 2179 | return vec![line_layout]; |
| 2180 | } |
| 2181 | |
| 2182 | let mut lines = Vec::with_capacity(last_layout.visible_buffer_lines.len()); |
| 2183 | // run_offset tracks position in the runs vec coordinate space (only visible line bytes). |
| 2184 | // This is separate from the visible_text offset because runs from highlight_lines |
| 2185 | // only cover visible (non-folded) lines. |
| 2186 | let mut run_offset = 0; |
| 2187 | |
| 2188 | for (vi, &buffer_line) in last_layout.visible_buffer_lines.iter().enumerate() { |
| 2189 | let line_text: String = display_text.slice_line(buffer_line).into(); |
| 2190 | let line_item = state |
| 2191 | .display_map |
| 2192 | .line(buffer_line) |
| 2193 | .expect("line should exists in wrapper"); |
| 2194 | |
| 2195 | debug_assert_eq!(line_item.len(), line_text.len()); |
| 2196 | |
| 2197 | let mut wrapped_lines: SmallVec<[ShapedLine; 1]> = SmallVec::with_capacity(1); |
| 2198 | let mut line_has_background = false; |
| 2199 | |
| 2200 | for range in &line_item.wrapped_lines { |
| 2201 | let line_runs = runs_for_range(runs, run_offset, &range); |
| 2202 | let line_runs = if bg_segments.is_empty() { |
| 2203 | line_runs |
| 2204 | } else { |
| 2205 | split_runs_by_bg_segments( |
| 2206 | last_layout.visible_line_byte_offsets[vi] + (range.start), |
| 2207 | &line_runs, |
| 2208 | bg_segments, |
| 2209 | ) |
| 2210 | }; |
| 2211 | |
| 2212 | let sub_line: SharedString = line_text[range.clone()].to_string().into(); |
| 2213 | let line_runs = |
| 2214 | align_runs_to_char_boundaries(&sub_line, &line_runs).unwrap_or(line_runs); |
| 2215 | let shaped_line = window |
| 2216 | .text_system() |
| 2217 | .shape_line(sub_line, font_size, &line_runs, None); |
| 2218 | |
| 2219 | line_has_background |= has_background(&line_runs); |
| 2220 | wrapped_lines.push(shaped_line); |
| 2221 | } |
| 2222 | |
| 2223 | // Use the first visual line's indentation width for continuation lines. |
| 2224 | let wrap_indent = if line_item.indent > 0 && wrapped_lines.len() > 1 { |
| 2225 | let indent_byte_len = line_text |
| 2226 | .char_indices() |
| 2227 | .nth(line_item.indent as usize) |
| 2228 | .map(|(ix, _)| ix) |
| 2229 | .unwrap_or(line_text.len()); |
| 2230 | wrapped_lines[0].x_for_index(indent_byte_len) |
| 2231 | } else { |
| 2232 | px(0.) |
| 2233 | }; |
| 2234 | |
| 2235 | let line_layout = LineLayout::new() |
| 2236 | .lines(wrapped_lines) |
| 2237 | .wrap_indent(wrap_indent) |
| 2238 | .first_indent( |
| 2239 | state |
| 2240 | .display_map |
| 2241 | .line_indent(last_layout.visible_line_byte_offsets[vi]), |
| 2242 | ) |
| 2243 | .with_background(line_has_background) |
| 2244 | .with_whitespaces(whitespace_indicators.clone()); |
| 2245 | lines.push(line_layout); |
| 2246 | |
| 2247 | // +1 for the `\n` |
| 2248 | run_offset += line_text.len() + 1; |
| 2249 | } |
| 2250 | |
| 2251 | lines |
| 2252 | } |
| 2253 | |
| 2254 | /// First usize is the offset of skipped. |
| 2255 | fn highlight_lines( |
| 2256 | &mut self, |
| 2257 | visible_buffer_lines: &[usize], |
| 2258 | _visible_top: Pixels, |
| 2259 | visible_byte_range: Range<usize>, |
| 2260 | cx: &mut App, |
| 2261 | ) -> Option<Vec<(Range<usize>, HighlightStyle)>> { |
| 2262 | let state = self.state.read(cx); |
| 2263 | let text = &state.text; |
| 2264 | let is_multi_line = state.is_multi_line(); |
| 2265 | |
| 2266 | let (mut highlighter, diagnostics) = match &state.mode { |
| 2267 | LayoutMode::CodeEditor { |
| 2268 | highlighter, |
| 2269 | diagnostics, |
| 2270 | .. |
| 2271 | } => (highlighter.borrow_mut(), diagnostics), |
| 2272 | _ => { |
| 2273 | return (!state.masked) |
| 2274 | .then(|| { |
| 2275 | compose_decoration_collections( |
| 2276 | Vec::new(), |
| 2277 | state.extras.decoration_layers().into_iter(), |
| 2278 | visible_byte_range, |
| 2279 | ) |
| 2280 | }) |
| 2281 | .flatten(); |
| 2282 | } |
| 2283 | }; |
| 2284 | let Some(highlighter) = highlighter.as_mut() else { |
| 2285 | return (!state.masked) |
| 2286 | .then(|| { |
| 2287 | compose_decoration_collections( |
| 2288 | Vec::new(), |
| 2289 | state.extras.decoration_layers().into_iter(), |
| 2290 | visible_byte_range, |
| 2291 | ) |
| 2292 | }) |
| 2293 | .flatten(); |
| 2294 | }; |
| 2295 | |
| 2296 | let mut styles = Vec::with_capacity(visible_buffer_lines.len()); |
| 2297 | // Byte ranges of the flushed line groups; the composed styles are |
| 2298 | // clipped to these at the end so the resulting runs cover exactly the |
| 2299 | // visible (non-folded) lines' bytes. |
| 2300 | let mut group_ranges: Vec<Range<usize>> = Vec::new(); |
| 2301 | |
| 2302 | // Helper to flush a contiguous range of lines. These ranges are disjoint, |
| 2303 | // so appending avoids repeatedly cloning and recombining prior styles. |
| 2304 | let mut flush_range = |
| 2305 | |start_line: usize, end_line: usize, skip: bool, styles: &mut Vec<_>| { |
| 2306 | let byte_start = text.line_start_offset(start_line); |
| 2307 | let byte_end = if is_multi_line { |
| 2308 | // +1 for `\n` |
| 2309 | text.line_start_offset(end_line + 1) |
| 2310 | } else { |
| 2311 | text.line_end_offset(end_line) |
| 2312 | }; |
| 2313 | let range_styles = if skip { |
| 2314 | vec![(byte_start..byte_end, HighlightStyle::default())] |
| 2315 | } else { |
| 2316 | highlighter.styles( |
| 2317 | &(byte_start..byte_end), |
| 2318 | state.editor_style.highlight_styles.as_ref(), |
| 2319 | ) |
| 2320 | }; |
| 2321 | |
| 2322 | group_ranges.push(byte_start..byte_end); |
| 2323 | styles.extend(range_styles); |
| 2324 | }; |
| 2325 | |
| 2326 | // Group contiguous visible lines into ranges and call styles() once per range |
| 2327 | let mut visible_iter = visible_buffer_lines.iter().peekable(); |
| 2328 | let mut range_start: Option<usize> = None; |
| 2329 | |
| 2330 | while let Some(&line) = visible_iter.next() { |
| 2331 | // Check if this line is too long for highlighting |
| 2332 | let line_len = text.slice_line(line).len(); |
| 2333 | if line_len > MAX_HIGHLIGHT_LINE_LENGTH { |
| 2334 | // Flush any accumulated range first |
| 2335 | if let Some(start) = range_start.take() { |
| 2336 | flush_range(start, line - 1, false, &mut styles); |
| 2337 | } |
| 2338 | |
| 2339 | flush_range(line, line, true, &mut styles); |
| 2340 | continue; |
| 2341 | } |
| 2342 | |
| 2343 | range_start.get_or_insert(line); |
| 2344 | |
| 2345 | // Check if next line is contiguous, if so keep accumulating |
| 2346 | if visible_iter |
| 2347 | .peek() |
| 2348 | .map(|&&next| next == line + 1) |
| 2349 | .unwrap_or(false) |
| 2350 | { |
| 2351 | continue; |
| 2352 | } |
| 2353 | |
| 2354 | // Flush the contiguous range |
| 2355 | let start_line = range_start.take().unwrap(); |
| 2356 | flush_range(start_line, line, false, &mut styles); |
| 2357 | } |
| 2358 | |
| 2359 | let diagnostic_styles: Vec<_> = diagnostics |
| 2360 | .range(visible_byte_range.clone()) |
| 2361 | .map(|entry| { |
| 2362 | ( |
| 2363 | entry.range.clone(), |
| 2364 | diagnostic_highlight_style(entry.severity, state.editor_style.diagnostics), |
| 2365 | ) |
| 2366 | }) |
| 2367 | .collect(); |
| 2368 | |
| 2369 | // Range semantic tokens, resolved from the LSP provider's cached |
| 2370 | // result through the active highlight theme so it shares the same |
| 2371 | // colour vocabulary as the tree-sitter path. Empty Vec when no |
| 2372 | // provider is set, so `combine_highlights` short-circuits. |
| 2373 | let custom_styles = state.extras.semantic_token_styles( |
| 2374 | text, |
| 2375 | &visible_byte_range, |
| 2376 | state.editor_style.highlight_styles.as_ref(), |
| 2377 | ); |
| 2378 | |
| 2379 | // hover definition style |
| 2380 | if let Some(hover_style) = M::hover_definition_style(self.state.read(cx), cx) { |
| 2381 | styles.push(hover_style); |
| 2382 | } |
| 2383 | |
| 2384 | // Compose tree-sitter, semantic, application, then diagnostic styles. |
| 2385 | styles = gpui::combine_highlights(custom_styles, styles).collect(); |
| 2386 | if !state.masked { |
| 2387 | styles = compose_decoration_collections( |
| 2388 | styles, |
| 2389 | state.extras.decoration_layers().into_iter(), |
| 2390 | visible_byte_range.clone(), |
| 2391 | ) |
| 2392 | .unwrap_or_default(); |
| 2393 | } |
| 2394 | styles = gpui::combine_highlights(diagnostic_styles, styles).collect(); |
| 2395 | |
| 2396 | // Some sources reach outside the flushed groups — a diagnostic |
| 2397 | // straddling the viewport edge, or any range inside a folded region — |
| 2398 | // which would inject extra bytes into the runs coordinate space and |
| 2399 | // shift every later run boundary (see `layout_lines`). Clip the |
| 2400 | // composed styles back to the groups. |
| 2401 | styles = clip_styles_to_ranges(styles, &group_ranges); |
| 2402 | |
| 2403 | Some(styles) |
| 2404 | } |
| 2405 | } |
| 2406 | |
| 2407 | /// Layout data for a single caret, produced by [`TextElement::layout_cursors`]. |
| 2408 | #[derive(Clone, Debug)] |
| 2409 | struct CursorRenderInfo { |
| 2410 | bounds: Bounds<Pixels>, |
| 2411 | is_active: bool, |
| 2412 | } |
| 2413 | |
| 2414 | pub(super) struct PrepaintState { |
| 2415 | /// The lines of entire lines. |
| 2416 | last_layout: LastLayout, |
| 2417 | token_elements: Vec<AnyElement>, |
| 2418 | /// The lines only contains the visible lines in the viewport, based on `visible_range`. |
| 2419 | /// |
| 2420 | /// The child is the soft lines. |
| 2421 | line_numbers: Option<Vec<SmallVec<[ShapedLine; 1]>>>, |
| 2422 | /// Size of the scrollable area by entire lines. |
| 2423 | scroll_size: Size<Pixels>, |
| 2424 | /// Caret bounds for every selection, active flagged. |
| 2425 | cursor_infos: Vec<CursorRenderInfo>, |
| 2426 | cursor_scroll_offset: Point<Pixels>, |
| 2427 | /// row index (zero based), no wrap, same line as the cursor. |
| 2428 | current_row: Option<usize>, |
| 2429 | selection_paths: Vec<Path<Pixels>>, |
| 2430 | hover_highlight_path: Option<Path<Pixels>>, |
| 2431 | search_match_paths: Vec<(Path<Pixels>, bool)>, |
| 2432 | document_color_paths: Vec<(Path<Pixels>, Hsla)>, |
| 2433 | range_decoration_fills: Vec<(Path<Pixels>, Hsla)>, |
| 2434 | range_decoration_frames: Vec<(Path<Pixels>, Hsla)>, |
| 2435 | range_decoration_quads: Vec<PaintQuad>, |
| 2436 | hover_definition_hitbox: Option<Hitbox>, |
| 2437 | indent_guides_path: Option<Path<Pixels>>, |
| 2438 | /// The whole input, for deciding whether a long press started in it. |
| 2439 | hitbox: Hitbox, |
| 2440 | bounds: Bounds<Pixels>, |
| 2441 | /// Fold icon layout data |
| 2442 | fold_icon_layout: FoldIconLayout, |
| 2443 | // Inline completion rendering data |
| 2444 | /// Shaped ghost lines to paint after cursor row (completion lines 2+) |
| 2445 | ghost_lines: Vec<ShapedLine>, |
| 2446 | /// First line of inline completion (painted after cursor on same line) |
| 2447 | ghost_first_line: Option<ShapedLine>, |
| 2448 | ghost_lines_height: Pixels, |
| 2449 | } |
| 2450 | |
| 2451 | impl PrepaintState { |
| 2452 | /// Returns all cursor infos adjusted for scroll offset. |
| 2453 | fn cursor_infos_with_scroll(&self) -> Vec<CursorRenderInfo> { |
| 2454 | self.cursor_infos |
| 2455 | .iter() |
| 2456 | .map(|info| { |
| 2457 | let mut bounds = info.bounds; |
| 2458 | bounds.origin.y += self.cursor_scroll_offset.y; |
| 2459 | CursorRenderInfo { |
| 2460 | bounds, |
| 2461 | is_active: info.is_active, |
| 2462 | } |
| 2463 | }) |
| 2464 | .collect() |
| 2465 | } |
| 2466 | } |
| 2467 | |
| 2468 | impl<M: InputModeKind> IntoElement for TextElement<M> { |
| 2469 | type Element = Self; |
| 2470 | |
| 2471 | fn into_element(self) -> Self::Element { |
| 2472 | self |
| 2473 | } |
| 2474 | } |
| 2475 | |
| 2476 | /// A debug function to print points as SVG path. |
| 2477 | #[allow(unused)] |
| 2478 | fn print_points_as_svg_path( |
| 2479 | line_corners: &Vec<gpui::Corners<Pixels>>, |
| 2480 | points: &Vec<Point<Pixels>>, |
| 2481 | ) { |
| 2482 | for corners in line_corners { |
| 2483 | println!( |
| 2484 | "tl: ({}, {}), tr: ({}, {}), bl: ({}, {}), br: ({}, {})", |
| 2485 | corners.top_left.as_f32() as i32, |
| 2486 | corners.top_left.as_f32() as i32, |
| 2487 | corners.top_right.as_f32() as i32, |
| 2488 | corners.top_right.as_f32() as i32, |
| 2489 | corners.bottom_left.as_f32() as i32, |
| 2490 | corners.bottom_left.as_f32() as i32, |
| 2491 | corners.bottom_right.as_f32() as i32, |
| 2492 | corners.bottom_right.as_f32() as i32, |
| 2493 | ); |
| 2494 | } |
| 2495 | |
| 2496 | if points.len() > 0 { |
| 2497 | println!( |
| 2498 | "M{},{}", |
| 2499 | points[0].x.as_f32() as i32, |
| 2500 | points[0].y.as_f32() as i32 |
| 2501 | ); |
| 2502 | for p in points.iter().skip(1) { |
| 2503 | println!("L{},{}", p.x.as_f32() as i32, p.y.as_f32() as i32); |
| 2504 | } |
| 2505 | } |
| 2506 | } |
| 2507 | |
| 2508 | const PILL_PADDING: Pixels = px(2.); |
| 2509 | |
| 2510 | fn rounded_quad( |
| 2511 | bounds: Bounds<Pixels>, |
| 2512 | radius: Pixels, |
| 2513 | color: Hsla, |
| 2514 | border: Option<Hsla>, |
| 2515 | ) -> PaintQuad { |
| 2516 | gpui::quad( |
| 2517 | bounds, |
| 2518 | radius, |
| 2519 | color, |
| 2520 | if border.is_some() { px(1.) } else { px(0.) }, |
| 2521 | border.unwrap_or(gpui::transparent_black()), |
| 2522 | gpui::BorderStyle::default(), |
| 2523 | ) |
| 2524 | } |
| 2525 | |
| 2526 | fn frame_outline_points(corners: &[Corners<Point<Pixels>>]) -> Vec<Point<Pixels>> { |
| 2527 | let rects = corners |
| 2528 | .iter() |
| 2529 | .map(|corners| (corners.top_left, corners.bottom_right)) |
| 2530 | .collect::<Vec<_>>(); |
| 2531 | let mut points = Vec::with_capacity(rects.len() * 4); |
| 2532 | let first = rects[0]; |
| 2533 | let last = rects[rects.len() - 1]; |
| 2534 | points.push(first.0); |
| 2535 | points.push(point(first.1.x, first.0.y)); |
| 2536 | for pair in rects.windows(2) { |
| 2537 | let current = pair[0]; |
| 2538 | let next = pair[1]; |
| 2539 | points.push(current.1); |
| 2540 | points.push(point(next.1.x, current.1.y)); |
| 2541 | points.push(point(next.1.x, next.1.y)); |
| 2542 | } |
| 2543 | if points.last() != Some(&last.1) { |
| 2544 | points.push(last.1); |
| 2545 | } |
| 2546 | points.push(point(last.0.x, last.1.y)); |
| 2547 | for pair in rects.windows(2).rev() { |
| 2548 | let current = pair[1]; |
| 2549 | let next = pair[0]; |
| 2550 | points.push(point(current.0.x, current.0.y)); |
| 2551 | points.push(point(next.0.x, current.0.y)); |
| 2552 | points.push(point(next.0.x, next.0.y)); |
| 2553 | } |
| 2554 | if points.last() != points.first() { |
| 2555 | points.push(points[0]); |
| 2556 | } |
| 2557 | points |
| 2558 | } |
| 2559 | |
| 2560 | fn pad_frame_corners( |
| 2561 | corners: &[Corners<Point<Pixels>>], |
| 2562 | horizontal_padding: Pixels, |
| 2563 | ) -> Vec<Corners<Point<Pixels>>> { |
| 2564 | corners |
| 2565 | .iter() |
| 2566 | .map(|corners| Corners { |
| 2567 | top_left: point(corners.top_left.x - horizontal_padding, corners.top_left.y), |
| 2568 | top_right: point( |
| 2569 | corners.top_right.x + horizontal_padding, |
| 2570 | corners.top_right.y, |
| 2571 | ), |
| 2572 | bottom_left: point( |
| 2573 | corners.bottom_left.x - horizontal_padding, |
| 2574 | corners.bottom_left.y, |
| 2575 | ), |
| 2576 | bottom_right: point( |
| 2577 | corners.bottom_right.x + horizontal_padding, |
| 2578 | corners.bottom_right.y, |
| 2579 | ), |
| 2580 | }) |
| 2581 | .collect() |
| 2582 | } |
| 2583 | |
| 2584 | fn snap_frame_outline( |
| 2585 | points: &[Point<Pixels>], |
| 2586 | stroke_width: Pixels, |
| 2587 | scale_factor: f32, |
| 2588 | ) -> (Pixels, Vec<Point<Pixels>>) { |
| 2589 | let physical_width = ((stroke_width.as_f32() * scale_factor).abs() - 0.5) |
| 2590 | .ceil() |
| 2591 | .max(1.); |
| 2592 | let stroke_width = px(physical_width / scale_factor); |
| 2593 | let center_offset = if physical_width % 2. == 0. { 0. } else { 0.5 }; |
| 2594 | let snap = |value: Pixels| { |
| 2595 | px( |
| 2596 | ((value.as_f32() * scale_factor - center_offset).round() + center_offset) |
| 2597 | / scale_factor, |
| 2598 | ) |
| 2599 | }; |
| 2600 | ( |
| 2601 | stroke_width, |
| 2602 | points |
| 2603 | .iter() |
| 2604 | .map(|point| point.map(snap)) |
| 2605 | .collect::<Vec<_>>(), |
| 2606 | ) |
| 2607 | } |
| 2608 | |
| 2609 | fn clamp_frame_to_content_mask( |
| 2610 | points: Vec<Point<Pixels>>, |
| 2611 | stroke_width: Pixels, |
| 2612 | content_mask: Bounds<Pixels>, |
| 2613 | ) -> Vec<Point<Pixels>> { |
| 2614 | let half_width = stroke_width / 2.; |
| 2615 | let min_x = content_mask.left() + half_width; |
| 2616 | let max_x = (content_mask.right() - half_width).max(min_x); |
| 2617 | points |
| 2618 | .into_iter() |
| 2619 | .map(|p| point(p.x.max(min_x).min(max_x), p.y)) |
| 2620 | .collect() |
| 2621 | } |
| 2622 | |
| 2623 | impl<M: InputModeKind> Element for TextElement<M> { |
| 2624 | type RequestLayoutState = (); |
| 2625 | type PrepaintState = PrepaintState; |
| 2626 | |
| 2627 | fn id(&self) -> Option<ElementId> { |
| 2628 | None |
| 2629 | } |
| 2630 | |
| 2631 | fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { |
| 2632 | None |
| 2633 | } |
| 2634 | |
| 2635 | fn request_layout( |
| 2636 | &mut self, |
| 2637 | _id: Option<&GlobalElementId>, |
| 2638 | _: Option<&gpui::InspectorElementId>, |
| 2639 | window: &mut Window, |
| 2640 | cx: &mut App, |
| 2641 | ) -> (LayoutId, Self::RequestLayoutState) { |
| 2642 | let state = self.state.read(cx); |
| 2643 | let line_height = window.line_height(); |
| 2644 | |
| 2645 | let mut style = Style::default(); |
| 2646 | style.size.width = relative(1.).into(); |
| 2647 | if state.is_multi_line() { |
| 2648 | style.flex_grow = 1.0; |
| 2649 | style.size.height = relative(1.).into(); |
| 2650 | // At least `rows` tall (auto grow: the content's rows, capped at |
| 2651 | // `max_rows` plus the rows of block tokens); a taller parent still fills it. |
| 2652 | let rows = state.mode.rows(); |
| 2653 | style.min_size.height = (rows * line_height).into(); |
| 2654 | } else { |
| 2655 | // For single-line inputs, the minimum height should be the line height |
| 2656 | style.size.height = line_height.into(); |
| 2657 | }; |
| 2658 | |
| 2659 | (window.request_layout(style, [], cx), ()) |
| 2660 | } |
| 2661 | |
| 2662 | fn prepaint( |
| 2663 | &mut self, |
| 2664 | _id: Option<&GlobalElementId>, |
| 2665 | _: Option<&gpui::InspectorElementId>, |
| 2666 | bounds: Bounds<Pixels>, |
| 2667 | _request_layout: &mut Self::RequestLayoutState, |
| 2668 | window: &mut Window, |
| 2669 | cx: &mut App, |
| 2670 | ) -> Self::PrepaintState { |
| 2671 | let style = window.text_style(); |
| 2672 | let font = style.font(); |
| 2673 | let text_size = style.font_size.to_pixels(window.rem_size()); |
| 2674 | // Past the end of a line there are no glyphs to hit-test against, so a pointer |
| 2675 | // out there is measured in spaces instead. |
| 2676 | let space_width = { |
| 2677 | let font_id = window.text_system().resolve_font(&font); |
| 2678 | window.text_system().layout_width(font_id, text_size, ' ') |
| 2679 | }; |
| 2680 | |
| 2681 | let font_overrides: Rc<[(Range<usize>, crate::input::decorations::FontOverride)]> = { |
| 2682 | let state = self.state.read(cx); |
| 2683 | if state.masked { |
| 2684 | Rc::from([]) |
| 2685 | } else { |
| 2686 | font_override_spans(&state.extras.decoration_layers()).into() |
| 2687 | } |
| 2688 | }; |
| 2689 | self.state.update(cx, |state, cx| { |
| 2690 | state.display_map.set_font(font, text_size, cx); |
| 2691 | state.display_map.ensure_text_prepared(&state.text, cx); |
| 2692 | state |
| 2693 | .display_map |
| 2694 | .set_font_overrides(font_overrides.clone(), cx); |
| 2695 | }); |
| 2696 | |
| 2697 | let state = self.state.read(cx); |
| 2698 | let multi_line = state.is_multi_line(); |
| 2699 | let text = state.text.clone(); |
| 2700 | let is_empty = text.len() == 0; |
| 2701 | let placeholder = self.placeholder.clone(); |
| 2702 | |
| 2703 | let text_style = window.text_style(); |
| 2704 | let disabled = state.disabled; |
| 2705 | let dim = |color: Hsla| if disabled { color.opacity(0.5) } else { color }; |
| 2706 | let fg = dim(text_style.color); |
| 2707 | let (display_text, text_color) = if is_empty { |
| 2708 | ( |
| 2709 | &Rope::from(placeholder.as_str()), |
| 2710 | dim(state.editor_style.muted_foreground), |
| 2711 | ) |
| 2712 | } else if state.masked { |
| 2713 | ( |
| 2714 | &Rope::from(MASK_CHAR.to_string().repeat(text.chars().count())), |
| 2715 | fg, |
| 2716 | ) |
| 2717 | } else { |
| 2718 | (&text, fg) |
| 2719 | }; |
| 2720 | |
| 2721 | // Calculate the width of the line numbers |
| 2722 | let (line_number_width, line_number_len) = |
| 2723 | Self::layout_line_numbers(&state, &text, text_size, &text_style, window); |
| 2724 | |
| 2725 | let mut bounds = bounds; |
| 2726 | let wrap_width = if multi_line && state.soft_wrap { |
| 2727 | Some(bounds.size.width - line_number_width - RIGHT_MARGIN) |
| 2728 | } else { |
| 2729 | None |
| 2730 | }; |
| 2731 | |
| 2732 | let wrapping_indent = state.wrapping_indent; |
| 2733 | let wrap_width_changed = state |
| 2734 | .last_layout |
| 2735 | .as_ref() |
| 2736 | .map(|l| l.wrap_width != wrap_width) |
| 2737 | .unwrap_or(true); |
| 2738 | |
| 2739 | let wrapping_indent_changed = state |
| 2740 | .last_layout |
| 2741 | .as_ref() |
| 2742 | .map(|l| l.wrapping_indent != wrapping_indent) |
| 2743 | .unwrap_or(true); |
| 2744 | |
| 2745 | if wrap_width_changed || wrapping_indent_changed { |
| 2746 | self.state.update(cx, |state, cx| { |
| 2747 | state.display_map.on_layout_changed(wrap_width, cx); |
| 2748 | state.display_map.set_wrapping_indent(wrapping_indent, cx); |
| 2749 | }); |
| 2750 | } |
| 2751 | |
| 2752 | let line_height = window.line_height(); |
| 2753 | let token_elements = self.measure_tokens( |
| 2754 | (bounds.size.width - line_number_width - RIGHT_MARGIN).max(px(1.)), |
| 2755 | line_height, |
| 2756 | bounds.size.height, |
| 2757 | window, |
| 2758 | cx, |
| 2759 | ); |
| 2760 | let state = self.state.read(cx); |
| 2761 | |
| 2762 | let (visible_range, visible_buffer_lines, visible_top) = |
| 2763 | self.calculate_visible_range(&state, line_height, bounds.size.height); |
| 2764 | let visible_start_offset = state.text.line_start_offset(visible_range.start); |
| 2765 | let visible_end_offset = state |
| 2766 | .text |
| 2767 | .line_end_offset(visible_range.end.saturating_sub(1)); |
| 2768 | |
| 2769 | let highlight_styles = self.highlight_lines( |
| 2770 | &visible_buffer_lines, |
| 2771 | visible_top, |
| 2772 | visible_start_offset..visible_end_offset, |
| 2773 | cx, |
| 2774 | ); |
| 2775 | |
| 2776 | let state = self.state.read(cx); |
| 2777 | |
| 2778 | let visible_line_byte_offsets: Vec<usize> = visible_buffer_lines |
| 2779 | .iter() |
| 2780 | .map(|&bl| state.text.line_start_offset(bl)) |
| 2781 | .collect(); |
| 2782 | |
| 2783 | // For password input (masked: true), convert byte offsets to masked display byte offsets so that |
| 2784 | // layout_match_range and position_for_index work in the correct coordinate space. |
| 2785 | let (visible_line_byte_offsets, visible_range_offset) = if state.masked { |
| 2786 | let offsets = visible_line_byte_offsets |
| 2787 | .iter() |
| 2788 | .map(|&o| masked_display_offset(&text, o)) |
| 2789 | .collect(); |
| 2790 | let range_offset = masked_display_offset(&text, visible_start_offset) |
| 2791 | ..masked_display_offset(&text, visible_end_offset); |
| 2792 | (offsets, range_offset) |
| 2793 | } else { |
| 2794 | ( |
| 2795 | visible_line_byte_offsets, |
| 2796 | visible_start_offset..visible_end_offset, |
| 2797 | ) |
| 2798 | }; |
| 2799 | |
| 2800 | let mut last_layout = LastLayout { |
| 2801 | visible_range, |
| 2802 | visible_buffer_lines, |
| 2803 | visible_line_byte_offsets, |
| 2804 | visible_top, |
| 2805 | visible_range_offset, |
| 2806 | line_height, |
| 2807 | wrap_width, |
| 2808 | wrapping_indent, |
| 2809 | line_number_width, |
| 2810 | space_width, |
| 2811 | lines: Rc::new(vec![]), |
| 2812 | cursor_bounds: None, |
| 2813 | text_align: state.text_align, |
| 2814 | content_width: bounds.size.width, |
| 2815 | }; |
| 2816 | |
| 2817 | let run = TextRun { |
| 2818 | len: display_text.len(), |
| 2819 | font: style.font(), |
| 2820 | color: text_color, |
| 2821 | background_color: None, |
| 2822 | underline: None, |
| 2823 | strikethrough: None, |
| 2824 | }; |
| 2825 | let marked_run = TextRun { |
| 2826 | len: 0, |
| 2827 | font: style.font(), |
| 2828 | color: text_color, |
| 2829 | background_color: None, |
| 2830 | underline: Some(UnderlineStyle { |
| 2831 | thickness: px(1.), |
| 2832 | color: Some(text_color), |
| 2833 | wavy: false, |
| 2834 | }), |
| 2835 | strikethrough: None, |
| 2836 | }; |
| 2837 | |
| 2838 | let ime_marked_range = ime_marked_display_range( |
| 2839 | &text, |
| 2840 | state.ime_marked_range.as_ref().map(|m| m.start..m.end), |
| 2841 | state.masked, |
| 2842 | ); |
| 2843 | |
| 2844 | let runs = if let (false, Some(highlight_styles)) = (is_empty, highlight_styles) { |
| 2845 | let mut runs = Vec::with_capacity(highlight_styles.len() + 2); |
| 2846 | |
| 2847 | for (range, style) in &highlight_styles { |
| 2848 | let mut run = text_style.clone().highlight(*style).to_run(range.len()); |
| 2849 | if disabled { |
| 2850 | run.color = run.color.opacity(0.5); |
| 2851 | } |
| 2852 | |
| 2853 | let mut start = range.start; |
| 2854 | for run in split_run_by_font_overrides(run, range.clone(), &font_overrides) { |
| 2855 | let run_range = start..start + run.len; |
| 2856 | start = run_range.end; |
| 2857 | runs.extend(split_run_for_ime_underline( |
| 2858 | run, |
| 2859 | run_range, |
| 2860 | ime_marked_range.clone(), |
| 2861 | marked_run.underline, |
| 2862 | )); |
| 2863 | } |
| 2864 | } |
| 2865 | runs |
| 2866 | } else { |
| 2867 | split_run_for_ime_underline( |
| 2868 | run, |
| 2869 | 0..display_text.len(), |
| 2870 | ime_marked_range, |
| 2871 | marked_run.underline, |
| 2872 | ) |
| 2873 | .into_vec() |
| 2874 | }; |
| 2875 | |
| 2876 | let document_colors = state |
| 2877 | .extras |
| 2878 | .document_color_swatches(&text, &last_layout.visible_range); |
| 2879 | |
| 2880 | // Create shaped lines for whitespace indicators before layout |
| 2881 | let whitespace_indicators = |
| 2882 | Self::layout_whitespace_indicators(&state, text_size, &text_style, window, cx); |
| 2883 | |
| 2884 | let lines = Self::layout_lines( |
| 2885 | &state, |
| 2886 | &display_text, |
| 2887 | &last_layout, |
| 2888 | text_size, |
| 2889 | &runs, |
| 2890 | &document_colors, |
| 2891 | whitespace_indicators, |
| 2892 | window, |
| 2893 | ); |
| 2894 | |
| 2895 | let mut longest_line_width = wrap_width.unwrap_or(px(0.)); |
| 2896 | // 1. Single line |
| 2897 | // 2. Multi-line with soft wrap disabled. |
| 2898 | if state.is_single_line() || !state.soft_wrap { |
| 2899 | let longest_row = state.display_map.longest_row(); |
| 2900 | let longest_line = state.text.slice_line(longest_row); |
| 2901 | let key = LongestLineKey { |
| 2902 | document_revision: state.document_revision, |
| 2903 | row: longest_row, |
| 2904 | len: longest_line.len(), |
| 2905 | font: style.font(), |
| 2906 | text_size, |
| 2907 | wrap_width, |
| 2908 | }; |
| 2909 | let cached = state |
| 2910 | .longest_line_width |
| 2911 | .take() |
| 2912 | .filter(|(cached_key, _)| *cached_key == key); |
| 2913 | longest_line_width = match cached { |
| 2914 | Some((_, width)) => width, |
| 2915 | None => { |
| 2916 | let longest_line: SharedString = longest_line.to_string().into(); |
| 2917 | window |
| 2918 | .text_system() |
| 2919 | .shape_line( |
| 2920 | longest_line.clone(), |
| 2921 | text_size, |
| 2922 | &[TextRun { |
| 2923 | len: longest_line.len(), |
| 2924 | font: key.font.clone(), |
| 2925 | color: gpui::black(), |
| 2926 | background_color: None, |
| 2927 | underline: None, |
| 2928 | strikethrough: None, |
| 2929 | }], |
| 2930 | wrap_width, |
| 2931 | ) |
| 2932 | .width |
| 2933 | } |
| 2934 | }; |
| 2935 | state |
| 2936 | .longest_line_width |
| 2937 | .set(Some((key, longest_line_width))); |
| 2938 | } |
| 2939 | if state.tokens_visible() { |
| 2940 | longest_line_width = if let Some(width) = wrap_width { |
| 2941 | width |
| 2942 | } else { |
| 2943 | state |
| 2944 | .token_layout_cache |
| 2945 | .as_ref() |
| 2946 | .map_or(px(0.), |cache| cache.unwrapped_width) |
| 2947 | }; |
| 2948 | } |
| 2949 | last_layout.lines = Rc::new(lines); |
| 2950 | |
| 2951 | let (ghost_first_line, ghost_lines) = Self::layout_inline_completion( |
| 2952 | state, |
| 2953 | &last_layout.visible_range, |
| 2954 | text_size, |
| 2955 | window, |
| 2956 | cx, |
| 2957 | ); |
| 2958 | let ghost_line_count = ghost_lines.len(); |
| 2959 | let ghost_lines_height = ghost_line_count as f32 * line_height; |
| 2960 | |
| 2961 | let empty_bottom_height = empty_bottom_height( |
| 2962 | state.is_code_editor(), |
| 2963 | state.scroll_beyond_last_line, |
| 2964 | bounds.size.height, |
| 2965 | line_height, |
| 2966 | ); |
| 2967 | |
| 2968 | // Empty bottom and ghost lines both describe extra height past the |
| 2969 | // last content row, so take the max rather than summing — summing |
| 2970 | // left a band of empty space the cursor could never reach. |
| 2971 | let mut scroll_size = size( |
| 2972 | if longest_line_width + line_number_width + RIGHT_MARGIN > bounds.size.width { |
| 2973 | longest_line_width + line_number_width + RIGHT_MARGIN |
| 2974 | } else { |
| 2975 | longest_line_width |
| 2976 | }, |
| 2977 | (state.display_map.content_height(line_height) |
| 2978 | + empty_bottom_height.max(ghost_lines_height)) |
| 2979 | .max(bounds.size.height), |
| 2980 | ); |
| 2981 | |
| 2982 | // TODO: should be add some gap to right, to convenient to focus on boundary position |
| 2983 | if last_layout.text_align == TextAlign::Right || last_layout.text_align == TextAlign::Center |
| 2984 | { |
| 2985 | scroll_size.width = longest_line_width + line_number_width; |
| 2986 | } |
| 2987 | |
| 2988 | // `position_for_index` for example |
| 2989 | // |
| 2990 | // #### text |
| 2991 | // |
| 2992 | // Hello 世界,this is GPUI component. |
| 2993 | // The GPUI Component is a collection of UI components for |
| 2994 | // GPUI framework, including Button, Input, Checkbox, Radio, |
| 2995 | // Dropdown, Tab, and more... |
| 2996 | // |
| 2997 | // wrap_width: 444px, line_height: 20px |
| 2998 | // |
| 2999 | // #### lines[0] |
| 3000 | // |
| 3001 | // | index | pos | line | |
| 3002 | // |-------|------------------|------| |
| 3003 | // | 5 | (37 px, 0.0) | 0 | |
| 3004 | // | 38 | (261.7 px, 20.0) | 0 | |
| 3005 | // | 40 | None | - | |
| 3006 | // |
| 3007 | // #### lines[1] |
| 3008 | // |
| 3009 | // | index | position | line | |
| 3010 | // |-------|-----------------------|------| |
| 3011 | // | 5 | (43.578125 px, 0.0) | 0 | |
| 3012 | // | 56 | (422.21094 px, 0.0) | 0 | |
| 3013 | // | 57 | (11.6328125 px, 20.0) | 1 | |
| 3014 | // | 114 | (429.85938 px, 20.0) | 1 | |
| 3015 | // | 115 | (11.3125 px, 40.0) | 2 | |
| 3016 | |
| 3017 | // Calculate the scroll offset to keep the cursor in view |
| 3018 | |
| 3019 | // Save the unscrolled x before layout_cursors modifies bounds.origin with scroll_offset. |
| 3020 | // Fold icons and their hitboxes must use this value so they stay fixed in the gutter |
| 3021 | // regardless of horizontal scroll position. |
| 3022 | let input_bounds = bounds; |
| 3023 | let original_x = bounds.origin.x; |
| 3024 | |
| 3025 | let (cursor_infos, cursor_scroll_offset, current_row) = |
| 3026 | self.layout_cursors(&last_layout, &mut bounds, scroll_size, window, cx); |
| 3027 | // Completion/code-action menus position at the active caret. |
| 3028 | last_layout.cursor_bounds = cursor_infos |
| 3029 | .iter() |
| 3030 | .find(|info| info.is_active) |
| 3031 | .map(|info| info.bounds); |
| 3032 | |
| 3033 | let search_match_paths = self.layout_search_matches(&last_layout, &mut bounds, cx); |
| 3034 | let selection_paths = self.layout_selections(&last_layout, &mut bounds, window, cx); |
| 3035 | let hover_highlight_path = self.layout_hover_highlight(&last_layout, &mut bounds, cx); |
| 3036 | let document_color_paths = |
| 3037 | self.layout_document_colors(&document_colors, &last_layout, &bounds, cx); |
| 3038 | let (range_decoration_fills, range_decoration_frames) = self.layout_range_decorations( |
| 3039 | &last_layout, |
| 3040 | &bounds, |
| 3041 | window, |
| 3042 | window.content_mask().bounds, |
| 3043 | cx, |
| 3044 | ); |
| 3045 | let range_decoration_quads = self.layout_range_decoration_quads(&last_layout, &bounds, cx); |
| 3046 | |
| 3047 | let state = self.state.read(cx); |
| 3048 | let line_numbers = if state.mode.line_number() { |
| 3049 | let mut line_numbers = Vec::with_capacity(last_layout.visible_buffer_lines.len()); |
| 3050 | let other_line_runs = vec![TextRun { |
| 3051 | len: line_number_len, |
| 3052 | font: style.font(), |
| 3053 | color: state.editor_style.muted_foreground, |
| 3054 | background_color: None, |
| 3055 | underline: None, |
| 3056 | strikethrough: None, |
| 3057 | }]; |
| 3058 | let current_line_runs = vec![TextRun { |
| 3059 | len: line_number_len, |
| 3060 | font: style.font(), |
| 3061 | color: state.editor_style.foreground, |
| 3062 | background_color: None, |
| 3063 | underline: None, |
| 3064 | strikethrough: None, |
| 3065 | }]; |
| 3066 | |
| 3067 | // build line numbers |
| 3068 | for (line, &buffer_line) in last_layout |
| 3069 | .lines |
| 3070 | .iter() |
| 3071 | .zip(last_layout.visible_buffer_lines.iter()) |
| 3072 | { |
| 3073 | let line_no: SharedString = format!( |
| 3074 | "{:>width$}", |
| 3075 | displayed_line_number(buffer_line + 1), |
| 3076 | width = line_number_len |
| 3077 | ) |
| 3078 | .into(); |
| 3079 | |
| 3080 | let runs = if current_row == Some(buffer_line) { |
| 3081 | ¤t_line_runs |
| 3082 | } else { |
| 3083 | &other_line_runs |
| 3084 | }; |
| 3085 | |
| 3086 | let mut sub_lines: SmallVec<[ShapedLine; 1]> = SmallVec::new(); |
| 3087 | sub_lines.push( |
| 3088 | window |
| 3089 | .text_system() |
| 3090 | .shape_line(line_no, text_size, &runs, None), |
| 3091 | ); |
| 3092 | for _ in 0..line.wrapped_lines.len().saturating_sub(1) { |
| 3093 | sub_lines.push(ShapedLine::default()); |
| 3094 | } |
| 3095 | line_numbers.push(sub_lines); |
| 3096 | } |
| 3097 | Some(line_numbers) |
| 3098 | } else { |
| 3099 | None |
| 3100 | }; |
| 3101 | |
| 3102 | let hover_definition_hitbox = M::hover_definition_hitbox(state, window, cx); |
| 3103 | let indent_guides_path = |
| 3104 | self.layout_indent_guides(state, &bounds, &last_layout, &text_style, window); |
| 3105 | state |
| 3106 | .editor_scrollbar_snapshot |
| 3107 | .set(Some(EditorScrollbarSnapshot::new( |
| 3108 | input_bounds, |
| 3109 | &last_layout, |
| 3110 | scroll_size, |
| 3111 | cursor_scroll_offset, |
| 3112 | state, |
| 3113 | ))); |
| 3114 | let fold_icon_layout = |
| 3115 | self.layout_fold_icons(original_x, &bounds, &last_layout, window, cx); |
| 3116 | let hitbox = window.insert_hitbox(input_bounds, HitboxBehavior::Normal); |
| 3117 | |
| 3118 | let token_elements = self.prepaint_tokens(&last_layout, bounds, token_elements, window, cx); |
| 3119 | PrepaintState { |
| 3120 | token_elements, |
| 3121 | hitbox, |
| 3122 | bounds, |
| 3123 | last_layout, |
| 3124 | scroll_size, |
| 3125 | line_numbers, |
| 3126 | cursor_infos, |
| 3127 | cursor_scroll_offset, |
| 3128 | current_row, |
| 3129 | selection_paths, |
| 3130 | search_match_paths, |
| 3131 | hover_highlight_path, |
| 3132 | hover_definition_hitbox, |
| 3133 | document_color_paths, |
| 3134 | range_decoration_fills, |
| 3135 | range_decoration_frames, |
| 3136 | range_decoration_quads, |
| 3137 | indent_guides_path, |
| 3138 | fold_icon_layout, |
| 3139 | ghost_first_line, |
| 3140 | ghost_lines, |
| 3141 | ghost_lines_height, |
| 3142 | } |
| 3143 | } |
| 3144 | |
| 3145 | fn paint( |
| 3146 | &mut self, |
| 3147 | _id: Option<&GlobalElementId>, |
| 3148 | _: Option<&gpui::InspectorElementId>, |
| 3149 | input_bounds: Bounds<Pixels>, |
| 3150 | _request_layout: &mut Self::RequestLayoutState, |
| 3151 | prepaint: &mut Self::PrepaintState, |
| 3152 | window: &mut Window, |
| 3153 | cx: &mut App, |
| 3154 | ) { |
| 3155 | let (focus_handle, show_cursor, disabled, selected_range, editor_style, editor_paddings) = { |
| 3156 | let state = self.state.read(cx); |
| 3157 | ( |
| 3158 | state.focus_handle.clone(), |
| 3159 | state.show_cursor(window, cx), |
| 3160 | state.disabled, |
| 3161 | *state.active_selection(), |
| 3162 | state.editor_style.clone(), |
| 3163 | state.editor_paddings, |
| 3164 | ) |
| 3165 | }; |
| 3166 | let focused = focus_handle.is_focused(window); |
| 3167 | let bounds = prepaint.bounds; |
| 3168 | let text_align = prepaint.last_layout.text_align; |
| 3169 | |
| 3170 | window.handle_input( |
| 3171 | &focus_handle, |
| 3172 | ElementInputHandler::new(bounds, self.state.clone()), |
| 3173 | cx, |
| 3174 | ); |
| 3175 | |
| 3176 | // Paint multi line text |
| 3177 | let line_height = window.line_height(); |
| 3178 | let origin = bounds.origin; |
| 3179 | |
| 3180 | let invisible_top_padding = prepaint.last_layout.visible_top; |
| 3181 | let active_line_color = editor_style |
| 3182 | .editor_active_line |
| 3183 | .map(|color| if disabled { color.opacity(0.5) } else { color }); |
| 3184 | let editor_background = if disabled { |
| 3185 | editor_style.background.opacity(0.5) |
| 3186 | } else { |
| 3187 | editor_style.background |
| 3188 | }; |
| 3189 | |
| 3190 | // Paint active line |
| 3191 | let mut offset_y = px(0.); |
| 3192 | if let Some(line_numbers) = prepaint.line_numbers.as_ref() { |
| 3193 | offset_y += invisible_top_padding; |
| 3194 | |
| 3195 | // Each item is the normal lines. |
| 3196 | for (lines, &buffer_line) in line_numbers |
| 3197 | .iter() |
| 3198 | .zip(prepaint.last_layout.visible_buffer_lines.iter()) |
| 3199 | { |
| 3200 | let is_active = prepaint.current_row == Some(buffer_line); |
| 3201 | let p = point(input_bounds.origin.x, origin.y + offset_y); |
| 3202 | let height = line_height * lines.len() as f32; |
| 3203 | // Paint the current line background |
| 3204 | if is_active { |
| 3205 | if let Some(bg_color) = active_line_color { |
| 3206 | window.paint_quad(fill( |
| 3207 | Bounds::new(p, size(bounds.size.width, height)), |
| 3208 | bg_color, |
| 3209 | )); |
| 3210 | } |
| 3211 | } |
| 3212 | offset_y += height; |
| 3213 | } |
| 3214 | } |
| 3215 | |
| 3216 | // Keep scrollbar offset always be positive,Start from the left position |
| 3217 | let scroll_offset = if text_align == TextAlign::Right { |
| 3218 | (prepaint.scroll_size.width - prepaint.bounds.size.width).max(px(0.)) |
| 3219 | } else if text_align == TextAlign::Center { |
| 3220 | (prepaint.scroll_size.width - prepaint.bounds.size.width) |
| 3221 | .half() |
| 3222 | .max(px(0.)) |
| 3223 | } else { |
| 3224 | px(0.) |
| 3225 | }; |
| 3226 | |
| 3227 | // Paint glyph backgrounds |
| 3228 | // |
| 3229 | // gpui's `paint` only draws glyphs, underlines, and strikethroughs, so decoration |
| 3230 | // backgrounds need their own pass. It runs ahead of the indent guides, selections, |
| 3231 | // and text so a highlighted range sits under them instead of covering them. |
| 3232 | let mut offset_y = invisible_top_padding; |
| 3233 | for (line, &buffer_line) in prepaint |
| 3234 | .last_layout |
| 3235 | .lines |
| 3236 | .iter() |
| 3237 | .zip(prepaint.last_layout.visible_buffer_lines.iter()) |
| 3238 | { |
| 3239 | let p = point( |
| 3240 | origin.x + prepaint.last_layout.line_number_width + scroll_offset, |
| 3241 | origin.y + offset_y, |
| 3242 | ); |
| 3243 | |
| 3244 | line.paint_background( |
| 3245 | p, |
| 3246 | line_height, |
| 3247 | text_align, |
| 3248 | Some(prepaint.last_layout.content_width), |
| 3249 | window, |
| 3250 | cx, |
| 3251 | ); |
| 3252 | |
| 3253 | offset_y += line.size(line_height).height; |
| 3254 | |
| 3255 | // Ghost lines shift every later line down. |
| 3256 | if Some(buffer_line) == prepaint.current_row { |
| 3257 | offset_y += prepaint.ghost_lines_height; |
| 3258 | } |
| 3259 | } |
| 3260 | |
| 3261 | // Paint indent guides |
| 3262 | if let Some(path) = prepaint.indent_guides_path.take() { |
| 3263 | window.paint_path(path, editor_style.border.opacity(0.85)); |
| 3264 | } |
| 3265 | |
| 3266 | // Application decorations sit below the user's selection. |
| 3267 | for quad in &prepaint.range_decoration_quads { |
| 3268 | window.paint_quad(quad.clone()); |
| 3269 | } |
| 3270 | for (path, color) in &prepaint.range_decoration_fills { |
| 3271 | window.paint_path(path.clone(), *color); |
| 3272 | } |
| 3273 | for (path, color) in &prepaint.range_decoration_frames { |
| 3274 | window.paint_path(path.clone(), *color); |
| 3275 | } |
| 3276 | |
| 3277 | // Paint selections |
| 3278 | if window.is_window_active() { |
| 3279 | let secondary_selection = Hsla { |
| 3280 | s: 0.1, |
| 3281 | ..editor_style.selection |
| 3282 | }; |
| 3283 | for (path, is_active) in prepaint.search_match_paths.iter() { |
| 3284 | window.paint_path(path.clone(), secondary_selection); |
| 3285 | |
| 3286 | if *is_active { |
| 3287 | window.paint_path(path.clone(), editor_style.selection); |
| 3288 | } |
| 3289 | } |
| 3290 | |
| 3291 | for path in prepaint.selection_paths.drain(..) { |
| 3292 | window.paint_path(path, editor_style.selection); |
| 3293 | } |
| 3294 | |
| 3295 | // Paint hover highlight |
| 3296 | if let Some(path) = prepaint.hover_highlight_path.take() { |
| 3297 | window.paint_path(path, secondary_selection); |
| 3298 | } |
| 3299 | } |
| 3300 | |
| 3301 | // Paint document colors |
| 3302 | for (path, color) in prepaint.document_color_paths.iter() { |
| 3303 | let color = if disabled { color.opacity(0.5) } else { *color }; |
| 3304 | window.paint_path(path.clone(), color); |
| 3305 | } |
| 3306 | |
| 3307 | // Paint text with inline completion ghost line support |
| 3308 | let mut offset_y = invisible_top_padding; |
| 3309 | let ghost_lines = &prepaint.ghost_lines; |
| 3310 | let has_ghost_lines = !ghost_lines.is_empty(); |
| 3311 | |
| 3312 | // Track the y-position of the cursor row for positioning the first line suffix |
| 3313 | let mut cursor_row_y = None; |
| 3314 | |
| 3315 | for (line, &buffer_line) in prepaint |
| 3316 | .last_layout |
| 3317 | .lines |
| 3318 | .iter() |
| 3319 | .zip(prepaint.last_layout.visible_buffer_lines.iter()) |
| 3320 | { |
| 3321 | let row = buffer_line; |
| 3322 | let line_y = origin.y + offset_y; |
| 3323 | let p = point( |
| 3324 | origin.x + prepaint.last_layout.line_number_width + (scroll_offset), |
| 3325 | line_y, |
| 3326 | ); |
| 3327 | |
| 3328 | // Paint the actual line |
| 3329 | _ = line.paint( |
| 3330 | p, |
| 3331 | line_height, |
| 3332 | text_align, |
| 3333 | Some(prepaint.last_layout.content_width), |
| 3334 | window, |
| 3335 | cx, |
| 3336 | ); |
| 3337 | offset_y += line.size(line_height).height; |
| 3338 | |
| 3339 | if Some(row) == prepaint.current_row { |
| 3340 | cursor_row_y = Some(line_y); |
| 3341 | } |
| 3342 | |
| 3343 | // After the cursor row, paint ghost lines (which shifts subsequent content down) |
| 3344 | if has_ghost_lines && Some(row) == prepaint.current_row { |
| 3345 | let ghost_x = origin.x + prepaint.last_layout.line_number_width; |
| 3346 | |
| 3347 | for ghost_line in ghost_lines { |
| 3348 | let ghost_p = point(ghost_x, origin.y + offset_y); |
| 3349 | |
| 3350 | // Paint semi-transparent background for ghost line |
| 3351 | let ghost_bounds = Bounds::new( |
| 3352 | ghost_p, |
| 3353 | size( |
| 3354 | bounds.size.width - prepaint.last_layout.line_number_width, |
| 3355 | line_height, |
| 3356 | ), |
| 3357 | ); |
| 3358 | window.paint_quad(fill(ghost_bounds, editor_background)); |
| 3359 | |
| 3360 | // Paint ghost line text |
| 3361 | _ = ghost_line.paint( |
| 3362 | ghost_p, |
| 3363 | line_height, |
| 3364 | text_align, |
| 3365 | Some(prepaint.last_layout.content_width), |
| 3366 | window, |
| 3367 | cx, |
| 3368 | ); |
| 3369 | offset_y += line_height; |
| 3370 | } |
| 3371 | } |
| 3372 | } |
| 3373 | |
| 3374 | for element in &mut prepaint.token_elements { |
| 3375 | element.paint(window, cx); |
| 3376 | } |
| 3377 | |
| 3378 | // Paint blinking cursors (shared blink state for all carets) |
| 3379 | if focused && show_cursor { |
| 3380 | for cursor_info in prepaint.cursor_infos_with_scroll() { |
| 3381 | window.paint_quad(fill(cursor_info.bounds, editor_style.caret)); |
| 3382 | } |
| 3383 | } |
| 3384 | |
| 3385 | // Paint line numbers |
| 3386 | let mut offset_y = px(0.); |
| 3387 | if let Some(line_numbers) = prepaint.line_numbers.as_ref() { |
| 3388 | offset_y += invisible_top_padding; |
| 3389 | |
| 3390 | // The gutter is a fixed overlay above horizontally scrolling text. |
| 3391 | // Always give it an opaque editor background when the theme does not |
| 3392 | // provide a dedicated gutter color, and cover the complete gutter so |
| 3393 | // text cannot show through its right-side spacing/fold-icon area. |
| 3394 | let gutter_bg = editor_style |
| 3395 | .editor_gutter_background |
| 3396 | .unwrap_or(editor_background); |
| 3397 | let gutter_bounds = editor_gutter_bounds( |
| 3398 | input_bounds, |
| 3399 | prepaint.last_layout.line_number_width, |
| 3400 | prepaint.ghost_lines_height, |
| 3401 | editor_paddings, |
| 3402 | ); |
| 3403 | window.paint_quad(fill(gutter_bounds, gutter_bg)); |
| 3404 | |
| 3405 | // Each item is the normal lines. |
| 3406 | for (lines, &buffer_line) in line_numbers |
| 3407 | .iter() |
| 3408 | .zip(prepaint.last_layout.visible_buffer_lines.iter()) |
| 3409 | { |
| 3410 | let p = point(input_bounds.origin.x, origin.y + offset_y); |
| 3411 | let is_active = prepaint.current_row == Some(buffer_line); |
| 3412 | |
| 3413 | let height = line_height * lines.len() as f32; |
| 3414 | // paint active line number background |
| 3415 | if is_active { |
| 3416 | if let Some(bg_color) = active_line_color { |
| 3417 | window.paint_quad(fill( |
| 3418 | Bounds::new( |
| 3419 | point(gutter_bounds.origin.x, p.y), |
| 3420 | size(gutter_bounds.size.width, height), |
| 3421 | ), |
| 3422 | bg_color, |
| 3423 | )); |
| 3424 | } |
| 3425 | } |
| 3426 | |
| 3427 | for line in lines { |
| 3428 | _ = line.paint(p, line_height, TextAlign::Left, None, window, cx); |
| 3429 | offset_y += line_height; |
| 3430 | } |
| 3431 | |
| 3432 | // Add ghost line height after cursor row for line numbers alignment |
| 3433 | if !prepaint.ghost_lines.is_empty() && prepaint.current_row == Some(buffer_line) { |
| 3434 | offset_y += prepaint.ghost_lines_height; |
| 3435 | } |
| 3436 | } |
| 3437 | } |
| 3438 | |
| 3439 | // Paint fold icons (only visible on hover or for current line) |
| 3440 | self.paint_fold_icons( |
| 3441 | &mut prepaint.fold_icon_layout, |
| 3442 | prepaint.current_row, |
| 3443 | window, |
| 3444 | cx, |
| 3445 | ); |
| 3446 | |
| 3447 | self.state.update(cx, |state, cx| { |
| 3448 | let geometry_changed = state.last_bounds != Some(bounds) |
| 3449 | || state.input_bounds != input_bounds |
| 3450 | || state.scroll_size != prepaint.scroll_size |
| 3451 | || state.last_layout.as_ref().is_none_or(|layout| { |
| 3452 | layout.cursor_bounds != prepaint.last_layout.cursor_bounds |
| 3453 | || layout.line_height != prepaint.last_layout.line_height |
| 3454 | }); |
| 3455 | state.last_layout = Some(prepaint.last_layout.clone()); |
| 3456 | state.last_bounds = Some(bounds); |
| 3457 | state.last_cursor = Some(state.cursor()); |
| 3458 | state.set_input_bounds(input_bounds, cx); |
| 3459 | state.last_selected_range = Some(selected_range); |
| 3460 | state.scroll_size = prepaint.scroll_size; |
| 3461 | state.update_scroll_offset(Some(prepaint.cursor_scroll_offset), cx); |
| 3462 | state.deferred_scroll_offset = None; |
| 3463 | |
| 3464 | // Layout consumers need changed geometry, not another notification |
| 3465 | // for every paint of an unchanged input. |
| 3466 | if geometry_changed { |
| 3467 | cx.notify(); |
| 3468 | } |
| 3469 | }); |
| 3470 | |
| 3471 | if let Some(hitbox) = prepaint.hover_definition_hitbox.as_ref() |
| 3472 | && !window.modifiers().alt |
| 3473 | { |
| 3474 | window.set_cursor_style(gpui::CursorStyle::PointingHand, &hitbox); |
| 3475 | } |
| 3476 | |
| 3477 | // Paint inline completion first line suffix (after cursor on same line) |
| 3478 | if focused { |
| 3479 | if let Some(first_line) = &prepaint.ghost_first_line { |
| 3480 | let active_cursor = prepaint |
| 3481 | .cursor_infos_with_scroll() |
| 3482 | .into_iter() |
| 3483 | .find(|info| info.is_active); |
| 3484 | if let (Some(cursor_info), Some(cursor_row_y)) = (active_cursor, cursor_row_y) { |
| 3485 | let cursor_bounds = cursor_info.bounds; |
| 3486 | let first_line_x = cursor_bounds.origin.x + cursor_bounds.size.width; |
| 3487 | let p = point(first_line_x, cursor_row_y); |
| 3488 | |
| 3489 | // Paint background to cover any existing text |
| 3490 | let bg_bounds = Bounds::new(p, size(first_line.width + px(4.), line_height)); |
| 3491 | window.paint_quad(fill(bg_bounds, editor_background)); |
| 3492 | |
| 3493 | // Paint first line completion text |
| 3494 | _ = first_line.paint(p, line_height, text_align, None, window, cx); |
| 3495 | } |
| 3496 | } |
| 3497 | } |
| 3498 | |
| 3499 | self.paint_mouse_listeners(&prepaint.hitbox, window, cx); |
| 3500 | } |
| 3501 | } |
| 3502 | |
| 3503 | /// Split placeholder text into display lines and trim runs to each line. |
| 3504 | fn placeholder_line_runs<'a>( |
| 3505 | display_text: &'a str, |
| 3506 | runs: &[TextRun], |
| 3507 | ) -> Vec<(&'a str, Vec<TextRun>)> { |
| 3508 | let mut result = Vec::new(); |
| 3509 | let mut line_offset = 0; |
| 3510 | |
| 3511 | for line in display_text.split('\n') { |
| 3512 | let line_runs = runs_for_range(runs, line_offset, &(0..line.len())); |
| 3513 | debug_assert_eq!( |
| 3514 | line_runs.iter().map(|run| run.len).sum::<usize>(), |
| 3515 | line.len() |
| 3516 | ); |
| 3517 | result.push((line, line_runs)); |
| 3518 | // Advance in the whole-placeholder coordinate space, including the separator. |
| 3519 | line_offset += line.len() + 1; |
| 3520 | } |
| 3521 | |
| 3522 | result |
| 3523 | } |
| 3524 | |
| 3525 | /// Get the runs for the given range. |
| 3526 | /// |
| 3527 | /// The range is the byte range of the wrapped line. |
| 3528 | pub(super) fn runs_for_range( |
| 3529 | runs: &[TextRun], |
| 3530 | line_offset: usize, |
| 3531 | range: &Range<usize>, |
| 3532 | ) -> Vec<TextRun> { |
| 3533 | let mut result = vec![]; |
| 3534 | let range = (line_offset + range.start)..(line_offset + range.end); |
| 3535 | let mut cursor = 0; |
| 3536 | |
| 3537 | for run in runs { |
| 3538 | let run_start = cursor; |
| 3539 | let run_end = cursor + run.len; |
| 3540 | |
| 3541 | if run_end <= range.start { |
| 3542 | cursor = run_end; |
| 3543 | continue; |
| 3544 | } |
| 3545 | |
| 3546 | if run_start >= range.end { |
| 3547 | break; |
| 3548 | } |
| 3549 | |
| 3550 | let start = range.start.max(run_start) - run_start; |
| 3551 | let end = range.end.min(run_end) - run_start; |
| 3552 | let len = end - start; |
| 3553 | |
| 3554 | if len > 0 { |
| 3555 | result.push(TextRun { len, ..run.clone() }); |
| 3556 | } |
| 3557 | |
| 3558 | cursor = run_end; |
| 3559 | } |
| 3560 | |
| 3561 | result |
| 3562 | } |
| 3563 | |
| 3564 | /// Clip sorted `styles` to the sorted, disjoint `ranges`, splitting styles |
| 3565 | /// that span several ranges and dropping coverage in the gaps between them. |
| 3566 | fn clip_styles_to_ranges( |
| 3567 | styles: Vec<(Range<usize>, HighlightStyle)>, |
| 3568 | ranges: &[Range<usize>], |
| 3569 | ) -> Vec<(Range<usize>, HighlightStyle)> { |
| 3570 | let mut result = Vec::with_capacity(styles.len()); |
| 3571 | let mut range_ix = 0; |
| 3572 | |
| 3573 | for (style_range, style) in styles { |
| 3574 | while range_ix < ranges.len() && ranges[range_ix].end <= style_range.start { |
| 3575 | range_ix += 1; |
| 3576 | } |
| 3577 | |
| 3578 | let mut ix = range_ix; |
| 3579 | while ix < ranges.len() && ranges[ix].start < style_range.end { |
| 3580 | let start = style_range.start.max(ranges[ix].start); |
| 3581 | let end = style_range.end.min(ranges[ix].end); |
| 3582 | if start < end { |
| 3583 | result.push((start..end, style)); |
| 3584 | } |
| 3585 | ix += 1; |
| 3586 | } |
| 3587 | } |
| 3588 | |
| 3589 | result |
| 3590 | } |
| 3591 | |
| 3592 | /// Snap run boundaries to char boundaries of `text` and cap them at its |
| 3593 | /// length. Style ranges are byte offsets that can drift off char boundaries |
| 3594 | /// (a stale syntax tree, a range in the wrong coordinate space) and the |
| 3595 | /// platform text system panics when a run splits a multi-byte character. |
| 3596 | /// |
| 3597 | /// Returns `None` when the runs are already aligned (the common case). |
| 3598 | pub(super) fn align_runs_to_char_boundaries(text: &str, runs: &[TextRun]) -> Option<Vec<TextRun>> { |
| 3599 | let mut end = 0; |
| 3600 | let aligned = runs.iter().all(|run| { |
| 3601 | end += run.len; |
| 3602 | end <= text.len() && text.is_char_boundary(end) |
| 3603 | }); |
| 3604 | if aligned { |
| 3605 | return None; |
| 3606 | } |
| 3607 | |
| 3608 | let mut result = Vec::with_capacity(runs.len()); |
| 3609 | let mut cursor = 0; |
| 3610 | let mut raw_end = 0; |
| 3611 | for run in runs { |
| 3612 | raw_end = (raw_end + run.len).min(text.len()); |
| 3613 | let mut end = raw_end; |
| 3614 | while !text.is_char_boundary(end) { |
| 3615 | end += 1; |
| 3616 | } |
| 3617 | if end > cursor { |
| 3618 | result.push(TextRun { |
| 3619 | len: end - cursor, |
| 3620 | ..run.clone() |
| 3621 | }); |
| 3622 | cursor = end; |
| 3623 | } |
| 3624 | } |
| 3625 | |
| 3626 | Some(result) |
| 3627 | } |
| 3628 | |
| 3629 | fn split_run_for_ime_underline( |
| 3630 | run: TextRun, |
| 3631 | run_range: Range<usize>, |
| 3632 | marked_range: Option<Range<usize>>, |
| 3633 | marked_underline: Option<UnderlineStyle>, |
| 3634 | ) -> SmallVec<[TextRun; 3]> { |
| 3635 | if run.len == 0 { |
| 3636 | return SmallVec::new(); |
| 3637 | } |
| 3638 | |
| 3639 | let Some(marked) = marked_range else { |
| 3640 | return [run].into_iter().collect(); |
| 3641 | }; |
| 3642 | |
| 3643 | let intersection_start = run_range.start.max(marked.start); |
| 3644 | let intersection_end = run_range.end.min(marked.end); |
| 3645 | if intersection_start >= intersection_end { |
| 3646 | return [run].into_iter().collect(); |
| 3647 | } |
| 3648 | |
| 3649 | [ |
| 3650 | TextRun { |
| 3651 | len: intersection_start - run_range.start, |
| 3652 | ..run.clone() |
| 3653 | }, |
| 3654 | TextRun { |
| 3655 | len: intersection_end - intersection_start, |
| 3656 | underline: marked_underline, |
| 3657 | ..run.clone() |
| 3658 | }, |
| 3659 | TextRun { |
| 3660 | len: run_range.end - intersection_end, |
| 3661 | ..run |
| 3662 | }, |
| 3663 | ] |
| 3664 | .into_iter() |
| 3665 | .filter(|run| run.len > 0) |
| 3666 | .collect() |
| 3667 | } |
| 3668 | |
| 3669 | /// Whether any of these runs paints a glyph background, used to skip the background |
| 3670 | /// paint pass for lines without highlights. |
| 3671 | fn has_background(runs: &[TextRun]) -> bool { |
| 3672 | runs.iter().any(|run| run.background_color.is_some()) |
| 3673 | } |
| 3674 | |
| 3675 | fn split_runs_by_bg_segments( |
| 3676 | start_offset: usize, |
| 3677 | runs: &[TextRun], |
| 3678 | bg_segments: &[(Range<usize>, Hsla)], |
| 3679 | ) -> Vec<TextRun> { |
| 3680 | let mut result = vec![]; |
| 3681 | |
| 3682 | let mut cursor = start_offset; |
| 3683 | for run in runs { |
| 3684 | let mut run_start = cursor; |
| 3685 | let run_end = cursor + run.len; |
| 3686 | |
| 3687 | for (bg_range, bg_color) in bg_segments { |
| 3688 | if run_end <= bg_range.start || run_start >= bg_range.end { |
| 3689 | continue; |
| 3690 | } |
| 3691 | |
| 3692 | // Overlap exists |
| 3693 | if run_start < bg_range.start { |
| 3694 | // Add the part before the background range |
| 3695 | result.push(TextRun { |
| 3696 | len: bg_range.start - run_start, |
| 3697 | ..run.clone() |
| 3698 | }); |
| 3699 | } |
| 3700 | |
| 3701 | // Add the overlapping part with background color |
| 3702 | let overlap_start = run_start.max(bg_range.start); |
| 3703 | let overlap_end = run_end.min(bg_range.end); |
| 3704 | let text_color = if bg_color.l >= 0.5 { |
| 3705 | gpui::black() |
| 3706 | } else { |
| 3707 | gpui::white() |
| 3708 | }; |
| 3709 | |
| 3710 | let run_len = overlap_end.saturating_sub(overlap_start); |
| 3711 | if run_len > 0 { |
| 3712 | result.push(TextRun { |
| 3713 | len: run_len, |
| 3714 | color: text_color, |
| 3715 | ..run.clone() |
| 3716 | }); |
| 3717 | |
| 3718 | cursor = bg_range.end; |
| 3719 | run_start = cursor; |
| 3720 | } |
| 3721 | } |
| 3722 | |
| 3723 | if run_end > cursor { |
| 3724 | // Add the part after the background range |
| 3725 | result.push(TextRun { |
| 3726 | len: run_end - cursor, |
| 3727 | ..run.clone() |
| 3728 | }); |
| 3729 | } |
| 3730 | |
| 3731 | cursor = run_end; |
| 3732 | } |
| 3733 | |
| 3734 | result |
| 3735 | } |
| 3736 | |
| 3737 | #[cfg(test)] |
| 3738 | mod tests { |
| 3739 | use super::*; |
| 3740 | use crate::input::{EditorMode, EditorState, FoldRange, RangeDecoration, Redo, Undo}; |
| 3741 | use gpui::{ |
| 3742 | AppContext as _, Context, EntityInputHandler as _, Render, TestAppContext, |
| 3743 | VisualTestContext, div, |
| 3744 | }; |
| 3745 | |
| 3746 | #[test] |
| 3747 | fn line_number_column_stays_at_three_digits_then_grows_up_to_seven() { |
| 3748 | assert_eq!(line_number_len(1), 3); |
| 3749 | assert_eq!(line_number_len(9), 3); |
| 3750 | assert_eq!(line_number_len(10), 3); |
| 3751 | assert_eq!(line_number_len(999), 3); |
| 3752 | assert_eq!(line_number_len(1_000), 4); |
| 3753 | assert_eq!(line_number_len(999_999), 6); |
| 3754 | assert_eq!(line_number_len(9_999_999), 7); |
| 3755 | assert_eq!(line_number_len(10_000_000), 7); |
| 3756 | } |
| 3757 | |
| 3758 | #[test] |
| 3759 | fn displayed_line_number_stays_within_seven_digits() { |
| 3760 | assert_eq!(displayed_line_number(42), 42); |
| 3761 | assert_eq!(displayed_line_number(9_999_999), 9_999_999); |
| 3762 | assert_eq!(displayed_line_number(10_000_000), 9_999_999); |
| 3763 | } |
| 3764 | |
| 3765 | struct DecorationHarness(Entity<EditorState>); |
| 3766 | |
| 3767 | impl Render for DecorationHarness { |
| 3768 | fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { |
| 3769 | div().size_full().child(self.0.clone()) |
| 3770 | } |
| 3771 | } |
| 3772 | |
| 3773 | fn decoration_editor( |
| 3774 | cx: &mut TestAppContext, |
| 3775 | text: &str, |
| 3776 | wrap: bool, |
| 3777 | ) -> (Entity<EditorState>, gpui::WindowHandle<DecorationHarness>) { |
| 3778 | cx.update(crate::init); |
| 3779 | let mut editor = None; |
| 3780 | let window = cx.open_window(size(px(240.), px(140.)), |window, cx| { |
| 3781 | let state = cx.new(|cx| { |
| 3782 | EditorState::new(window, cx) |
| 3783 | .soft_wrap(wrap) |
| 3784 | .folding(true) |
| 3785 | .default_value(text) |
| 3786 | }); |
| 3787 | editor = Some(state.clone()); |
| 3788 | DecorationHarness(state) |
| 3789 | }); |
| 3790 | (editor.unwrap(), window) |
| 3791 | } |
| 3792 | |
| 3793 | #[cfg(target_os = "linux")] |
| 3794 | #[test] |
| 3795 | fn font_family_decorations_shape_wrap_and_hit_test_in_that_font() { |
| 3796 | let platform = gpui_platform::current_platform(true); |
| 3797 | let mut cx = TestAppContext::build_with_text_system( |
| 3798 | gpui::TestDispatcher::new(0), |
| 3799 | None, |
| 3800 | platform.text_system(), |
| 3801 | ); |
| 3802 | let text = "iiiiiiii ".repeat(8); |
| 3803 | let mono_range = 9..35; |
| 3804 | let (editor, window) = decoration_editor(&mut cx, &text, true); |
| 3805 | let mut cx = VisualTestContext::from_window(window.into(), &mut cx); |
| 3806 | cx.update(|window, cx| { |
| 3807 | window.draw(cx).clear(cx); |
| 3808 | let plain_rows = editor.read(cx).last_layout.as_ref().unwrap().lines[0] |
| 3809 | .wrapped_lines |
| 3810 | .len(); |
| 3811 | editor.update(cx, |state, cx| { |
| 3812 | state.create_decorations_collection( |
| 3813 | vec![ |
| 3814 | TextDecoration::new(mono_range.clone(), HighlightStyle::default()) |
| 3815 | .with_font_family("DejaVu Sans Mono"), |
| 3816 | ], |
| 3817 | cx, |
| 3818 | ); |
| 3819 | }); |
| 3820 | window.draw(cx).clear(cx); |
| 3821 | let state = editor.read(cx); |
| 3822 | let layout = state.last_layout.as_ref().unwrap(); |
| 3823 | let line = &layout.lines[0]; |
| 3824 | assert!(line.wrapped_lines.len() > plain_rows); |
| 3825 | for row in line.wrapped_lines.iter() { |
| 3826 | assert!(row.width <= layout.wrap_width.unwrap()); |
| 3827 | } |
| 3828 | |
| 3829 | let mono_offset = mono_range.start + 4; |
| 3830 | let position = line.position_for_index(mono_offset, layout, false).unwrap(); |
| 3831 | let next = line |
| 3832 | .position_for_index(mono_offset + 1, layout, false) |
| 3833 | .unwrap(); |
| 3834 | let mono_glyph_width = window |
| 3835 | .text_system() |
| 3836 | .shape_line( |
| 3837 | "i".into(), |
| 3838 | window.text_style().font_size.to_pixels(window.rem_size()), |
| 3839 | &[TextRun { |
| 3840 | len: 1, |
| 3841 | font: gpui::font("DejaVu Sans Mono"), |
| 3842 | color: gpui::black(), |
| 3843 | background_color: None, |
| 3844 | underline: None, |
| 3845 | strikethrough: None, |
| 3846 | }], |
| 3847 | None, |
| 3848 | ) |
| 3849 | .width; |
| 3850 | assert_eq!(next.x - position.x, mono_glyph_width); |
| 3851 | let (hit, _) = line |
| 3852 | .closest_index_for_position( |
| 3853 | point(position.x + mono_glyph_width / 4., position.y), |
| 3854 | layout, |
| 3855 | ) |
| 3856 | .unwrap(); |
| 3857 | assert_eq!(hit, mono_offset); |
| 3858 | }); |
| 3859 | } |
| 3860 | |
| 3861 | struct TextareaHarness(Entity<crate::input::TextareaState>); |
| 3862 | |
| 3863 | impl Render for TextareaHarness { |
| 3864 | fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { |
| 3865 | div().size_full().child(self.0.clone()) |
| 3866 | } |
| 3867 | } |
| 3868 | |
| 3869 | #[cfg(target_os = "linux")] |
| 3870 | #[test] |
| 3871 | fn pills_blocks_and_bars_paint_as_quads_only() { |
| 3872 | let platform = gpui_platform::current_platform(true); |
| 3873 | let mut cx = TestAppContext::build_with_text_system( |
| 3874 | gpui::TestDispatcher::new(0), |
| 3875 | None, |
| 3876 | platform.text_system(), |
| 3877 | ); |
| 3878 | cx.update(crate::init); |
| 3879 | let mut textarea = None; |
| 3880 | let window = cx.open_window(size(px(240.), px(140.)), |window, cx| { |
| 3881 | let state = cx.new(|cx| { |
| 3882 | crate::input::TextareaState::new(window, cx) |
| 3883 | .rows(4) |
| 3884 | .default_value("ab\ncd\nef\n") |
| 3885 | }); |
| 3886 | textarea = Some(state.clone()); |
| 3887 | TextareaHarness(state) |
| 3888 | }); |
| 3889 | let textarea = textarea.unwrap(); |
| 3890 | let mut cx = VisualTestContext::from_window(window.into(), &mut cx); |
| 3891 | cx.update(|window, cx| { |
| 3892 | textarea.update(cx, |state, cx| { |
| 3893 | state.create_range_decorations_collection( |
| 3894 | vec![ |
| 3895 | RangeDecoration::new(0..1) |
| 3896 | .with_style(RangeDecorationStyle::Pill) |
| 3897 | .with_radius(px(4.)), |
| 3898 | RangeDecoration::new(3..8).with_style(RangeDecorationStyle::Block), |
| 3899 | RangeDecoration::new(9..9) |
| 3900 | .with_style(RangeDecorationStyle::Bar) |
| 3901 | .with_radius(px(3.)), |
| 3902 | ], |
| 3903 | cx, |
| 3904 | ); |
| 3905 | }); |
| 3906 | window.draw(cx).clear(cx); |
| 3907 | let state = textarea.read(cx); |
| 3908 | let layout = state.last_layout.as_ref().unwrap(); |
| 3909 | let element = TextElement::new(textarea.clone()); |
| 3910 | let (fills, frames) = element.layout_range_decorations( |
| 3911 | layout, |
| 3912 | &state.input_bounds, |
| 3913 | window, |
| 3914 | state.input_bounds, |
| 3915 | cx, |
| 3916 | ); |
| 3917 | assert!(fills.is_empty() && frames.is_empty()); |
| 3918 | let quads = element.layout_range_decoration_quads(layout, &state.input_bounds, cx); |
| 3919 | assert_eq!(quads.len(), 3); |
| 3920 | let line_height = layout.line_height; |
| 3921 | assert_eq!(quads[1].bounds.size.height, line_height * 2.); |
| 3922 | assert_eq!(quads[2].bounds.size.width, px(3.)); |
| 3923 | assert_eq!(quads[2].bounds.size.height, line_height); |
| 3924 | }); |
| 3925 | } |
| 3926 | |
| 3927 | #[cfg(target_os = "linux")] |
| 3928 | #[test] |
| 3929 | fn block_token_selection_and_block_decoration_span_the_row_height() { |
| 3930 | use crate::input::{InlineToken, InlineTokenPresentation}; |
| 3931 | let platform = gpui_platform::current_platform(true); |
| 3932 | let mut cx = TestAppContext::build_with_text_system( |
| 3933 | gpui::TestDispatcher::new(0), |
| 3934 | None, |
| 3935 | platform.text_system(), |
| 3936 | ); |
| 3937 | cx.update(crate::init); |
| 3938 | let mut textarea = None; |
| 3939 | let window = cx.open_window(size(px(400.), px(300.)), |window, cx| { |
| 3940 | let state = cx.new(|cx| { |
| 3941 | crate::input::TextareaState::new(window, cx) |
| 3942 | .rows(4) |
| 3943 | .default_value("ab[img]cd") |
| 3944 | }); |
| 3945 | textarea = Some(state.clone()); |
| 3946 | TextareaHarness(state) |
| 3947 | }); |
| 3948 | let textarea = textarea.unwrap(); |
| 3949 | let mut cx = VisualTestContext::from_window(window.into(), &mut cx); |
| 3950 | cx.update(|window, cx| { |
| 3951 | textarea.update(cx, |state, cx| { |
| 3952 | state.set_token_presentation( |
| 3953 | InlineTokenPresentation::default() |
| 3954 | .token(|_, _, _| div().w(px(200.)).h(px(120.))), |
| 3955 | ); |
| 3956 | state |
| 3957 | .replace_range_with_token( |
| 3958 | 2..7, |
| 3959 | InlineToken::new("img", "[img]").block(), |
| 3960 | window, |
| 3961 | cx, |
| 3962 | ) |
| 3963 | .unwrap(); |
| 3964 | state.create_range_decorations_collection( |
| 3965 | vec![RangeDecoration::new(0..0).with_style(RangeDecorationStyle::Block)], |
| 3966 | cx, |
| 3967 | ); |
| 3968 | }); |
| 3969 | window.draw(cx).clear(cx); |
| 3970 | window.draw(cx).clear(cx); |
| 3971 | let state = textarea.read(cx); |
| 3972 | let layout = state.last_layout.as_ref().unwrap(); |
| 3973 | let line_height = layout.line_height; |
| 3974 | let corners = |
| 3975 | TextElement::<crate::input::TextareaMode>::layout_range_corners(&(2..7), layout) |
| 3976 | .unwrap(); |
| 3977 | assert_eq!(corners.len(), 1); |
| 3978 | assert_eq!(corners[0].top_left.y, layout.visible_top + line_height); |
| 3979 | assert_eq!(corners[0].bottom_left.y - corners[0].top_left.y, px(120.)); |
| 3980 | assert_eq!( |
| 3981 | (corners[0].top_left.x, corners[0].top_right.x), |
| 3982 | (px(0.), px(200.)) |
| 3983 | ); |
| 3984 | let element = TextElement::new(textarea.clone()); |
| 3985 | let quads = element.layout_range_decoration_quads(layout, &state.input_bounds, cx); |
| 3986 | assert_eq!(quads[0].bounds.size.height, line_height * 2. + px(120.)); |
| 3987 | }); |
| 3988 | } |
| 3989 | |
| 3990 | #[cfg(target_os = "linux")] |
| 3991 | #[test] |
| 3992 | fn textarea_decorations_render_fill_and_wrap_like_the_editor() { |
| 3993 | let platform = gpui_platform::current_platform(true); |
| 3994 | let mut cx = TestAppContext::build_with_text_system( |
| 3995 | gpui::TestDispatcher::new(0), |
| 3996 | None, |
| 3997 | platform.text_system(), |
| 3998 | ); |
| 3999 | cx.update(crate::init); |
| 4000 | let text = "iiiiiiii ".repeat(8); |
| 4001 | let mono_range = 9..35; |
| 4002 | let mut textarea = None; |
| 4003 | let window = cx.open_window(size(px(240.), px(140.)), |window, cx| { |
| 4004 | let state = cx.new(|cx| { |
| 4005 | crate::input::TextareaState::new(window, cx) |
| 4006 | .rows(4) |
| 4007 | .default_value(text.clone()) |
| 4008 | }); |
| 4009 | textarea = Some(state.clone()); |
| 4010 | TextareaHarness(state) |
| 4011 | }); |
| 4012 | let textarea = textarea.unwrap(); |
| 4013 | let mut cx = VisualTestContext::from_window(window.into(), &mut cx); |
| 4014 | cx.update(|window, cx| { |
| 4015 | window.draw(cx).clear(cx); |
| 4016 | let plain_rows: Vec<_> = textarea.read(cx).last_layout.as_ref().unwrap().lines[0] |
| 4017 | .wrapped_lines |
| 4018 | .iter() |
| 4019 | .map(|row| row.len) |
| 4020 | .collect(); |
| 4021 | let collection = textarea.update(cx, |state, cx| { |
| 4022 | state.create_range_decorations_collection( |
| 4023 | vec![ |
| 4024 | RangeDecoration::new(mono_range.clone()) |
| 4025 | .with_style(RangeDecorationStyle::Fill), |
| 4026 | ], |
| 4027 | cx, |
| 4028 | ); |
| 4029 | state.create_decorations_collection(Vec::new(), cx) |
| 4030 | }); |
| 4031 | collection.set( |
| 4032 | vec![ |
| 4033 | TextDecoration::new(mono_range.clone(), HighlightStyle::default()) |
| 4034 | .with_font_family("DejaVu Sans Mono"), |
| 4035 | ], |
| 4036 | cx, |
| 4037 | ); |
| 4038 | window.draw(cx).clear(cx); |
| 4039 | let state = textarea.read(cx); |
| 4040 | let layout = state.last_layout.as_ref().unwrap(); |
| 4041 | let line = &layout.lines[0]; |
| 4042 | let rows: Vec<_> = line.wrapped_lines.iter().map(|row| row.len).collect(); |
| 4043 | assert!(rows[0] < plain_rows[0], "{rows:?} vs {plain_rows:?}"); |
| 4044 | for row in line.wrapped_lines.iter() { |
| 4045 | assert!(row.width <= layout.wrap_width.unwrap()); |
| 4046 | } |
| 4047 | let (fills, frames) = TextElement::new(textarea.clone()).layout_range_decorations( |
| 4048 | layout, |
| 4049 | &state.input_bounds, |
| 4050 | window, |
| 4051 | state.input_bounds, |
| 4052 | cx, |
| 4053 | ); |
| 4054 | assert_eq!(fills.len(), 1); |
| 4055 | assert!(frames.is_empty()); |
| 4056 | assert_eq!(collection.get_ranges(cx), vec![mono_range.clone()]); |
| 4057 | }); |
| 4058 | cx.update(|window, cx| { |
| 4059 | textarea.update(cx, |state, cx| { |
| 4060 | state.set_selected_range(0..0, cx); |
| 4061 | state.replace_text_in_range(None, "X", window, cx); |
| 4062 | let layers = state.extras.decoration_layers(); |
| 4063 | assert_eq!(layers.into_iter().flatten().next().unwrap().range, 10..36); |
| 4064 | }); |
| 4065 | }); |
| 4066 | } |
| 4067 | |
| 4068 | #[gpui::test] |
| 4069 | fn horizontal_scroll_is_clamped_before_text_and_caret_layout(cx: &mut TestAppContext) { |
| 4070 | let (editor, window) = decoration_editor(cx, "short text", false); |
| 4071 | let mut cx = VisualTestContext::from_window(window.into(), cx); |
| 4072 | cx.update(|window, cx| { |
| 4073 | window.draw(cx).clear(cx); |
| 4074 | let state = editor.read(cx); |
| 4075 | let layout = state.last_layout.clone().unwrap(); |
| 4076 | let input_bounds = state.input_bounds; |
| 4077 | let scroll_size = input_bounds.size; |
| 4078 | let element = TextElement::new(editor.clone()); |
| 4079 | let mut bounds = input_bounds; |
| 4080 | let (baseline, _, _) = |
| 4081 | element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx); |
| 4082 | |
| 4083 | // Both a stale offset after deletion and a deferred scroll target must |
| 4084 | // be limited before either text or carets are positioned this frame. |
| 4085 | for deferred in [None, Some(point(px(-80.), px(0.)))] { |
| 4086 | editor.update(cx, |state, _| { |
| 4087 | state.scroll_handle.set_offset(point(px(-40.), px(0.))); |
| 4088 | state.deferred_scroll_offset = deferred; |
| 4089 | }); |
| 4090 | let mut bounds = input_bounds; |
| 4091 | let (carets, offset, _) = |
| 4092 | element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx); |
| 4093 | assert_eq!(offset.x, px(0.)); |
| 4094 | assert_eq!(bounds.origin.x, input_bounds.origin.x); |
| 4095 | assert_eq!(carets.len(), baseline.len()); |
| 4096 | for (caret, original) in carets.iter().zip(&baseline) { |
| 4097 | assert_eq!(caret.bounds.origin.x, original.bounds.origin.x); |
| 4098 | } |
| 4099 | editor.update(cx, |state, cx| { |
| 4100 | state.scroll_size = scroll_size; |
| 4101 | state.update_scroll_offset(Some(offset), cx); |
| 4102 | assert_eq!(state.scroll_handle.offset().x, offset.x); |
| 4103 | }); |
| 4104 | } |
| 4105 | }); |
| 4106 | } |
| 4107 | |
| 4108 | #[gpui::test] |
| 4109 | fn aligned_horizontal_scroll_clamps_deferred_targets(cx: &mut TestAppContext) { |
| 4110 | let (editor, window) = decoration_editor(cx, &"wide text ".repeat(80), false); |
| 4111 | let mut cx = VisualTestContext::from_window(window.into(), cx); |
| 4112 | cx.update(|window, cx| { |
| 4113 | window.draw(cx).clear(cx); |
| 4114 | let mut layout = editor.read(cx).last_layout.clone().unwrap(); |
| 4115 | let input_bounds = editor.read(cx).input_bounds; |
| 4116 | let element = TextElement::new(editor.clone()); |
| 4117 | |
| 4118 | for alignment in [TextAlign::Left, TextAlign::Right, TextAlign::Center] { |
| 4119 | layout.text_align = alignment; |
| 4120 | for overflow in [px(0.), px(120.)] { |
| 4121 | let scroll_size = |
| 4122 | size(input_bounds.size.width + overflow, input_bounds.size.height); |
| 4123 | let minimum = if alignment == TextAlign::Left { |
| 4124 | -overflow |
| 4125 | } else { |
| 4126 | -overflow - CURSOR_WIDTH |
| 4127 | }; |
| 4128 | editor.update(cx, |state, _| { |
| 4129 | state.text_align = alignment; |
| 4130 | state.last_selected_range = Some(*state.active_selection()); |
| 4131 | state.deferred_scroll_offset = Some(point(minimum, px(0.))); |
| 4132 | }); |
| 4133 | let mut bounds = input_bounds; |
| 4134 | let (expected, _, _) = |
| 4135 | element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx); |
| 4136 | |
| 4137 | for target in [minimum - px(100.), px(100.)] { |
| 4138 | editor.update(cx, |state, _| { |
| 4139 | state.deferred_scroll_offset = Some(point(target, px(0.))); |
| 4140 | }); |
| 4141 | let mut bounds = input_bounds; |
| 4142 | let (carets, offset, _) = |
| 4143 | element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx); |
| 4144 | let expected_offset = if target < minimum { minimum } else { px(0.) }; |
| 4145 | assert_eq!(offset.x, expected_offset); |
| 4146 | assert_eq!(bounds.left(), input_bounds.left() + expected_offset); |
| 4147 | if target < minimum { |
| 4148 | assert_eq!(carets[0].bounds, expected[0].bounds); |
| 4149 | } |
| 4150 | if alignment == TextAlign::Right { |
| 4151 | assert!(carets[0].bounds.right() <= input_bounds.right()); |
| 4152 | } |
| 4153 | editor.update(cx, |state, cx| { |
| 4154 | state.scroll_size = scroll_size; |
| 4155 | state.update_scroll_offset(Some(offset), cx); |
| 4156 | assert_eq!(state.scroll_handle.offset().x, expected_offset); |
| 4157 | }); |
| 4158 | } |
| 4159 | } |
| 4160 | } |
| 4161 | }); |
| 4162 | } |
| 4163 | |
| 4164 | #[gpui::test] |
| 4165 | fn deferred_horizontal_scroll_moves_every_caret(cx: &mut TestAppContext) { |
| 4166 | use super::super::{cursor::CursorSelection, selection::CursorId}; |
| 4167 | |
| 4168 | let (editor, window) = decoration_editor(cx, &"wide text ".repeat(80), false); |
| 4169 | let mut cx = VisualTestContext::from_window(window.into(), cx); |
| 4170 | cx.update(|window, cx| { |
| 4171 | window.draw(cx).clear(cx); |
| 4172 | let layout = editor.read(cx).last_layout.clone().unwrap(); |
| 4173 | let input_bounds = editor.read(cx).input_bounds; |
| 4174 | let scroll_size = size(input_bounds.size.width + px(120.), input_bounds.size.height); |
| 4175 | let element = TextElement::new(editor.clone()); |
| 4176 | |
| 4177 | for offsets in [[0, 2, 4], [0, 4, 2], [4, 0, 2]] { |
| 4178 | editor.update(cx, |state, _| { |
| 4179 | state.selections.replace_all( |
| 4180 | offsets |
| 4181 | .into_iter() |
| 4182 | .enumerate() |
| 4183 | .map(|(id, offset)| { |
| 4184 | CursorSelection::new(CursorId::new(id), offset, offset) |
| 4185 | }) |
| 4186 | .collect(), |
| 4187 | ); |
| 4188 | state.last_selected_range = Some(*state.active_selection()); |
| 4189 | state.scroll_handle.set_offset(point(px(0.), px(0.))); |
| 4190 | state.deferred_scroll_offset = None; |
| 4191 | }); |
| 4192 | let mut bounds = input_bounds; |
| 4193 | let (baseline, _, _) = |
| 4194 | element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx); |
| 4195 | editor.update(cx, |state, _| { |
| 4196 | state.deferred_scroll_offset = Some(point(px(-60.), px(0.))); |
| 4197 | }); |
| 4198 | let mut bounds = input_bounds; |
| 4199 | let (carets, offset, _) = |
| 4200 | element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx); |
| 4201 | assert_eq!(offset.x, px(-60.)); |
| 4202 | assert_eq!(carets.len(), 3); |
| 4203 | for (caret, original) in carets.iter().zip(baseline) { |
| 4204 | assert_eq!(caret.bounds.left(), original.bounds.left() - px(60.)); |
| 4205 | } |
| 4206 | } |
| 4207 | }); |
| 4208 | } |
| 4209 | |
| 4210 | #[gpui::test] |
| 4211 | fn editor_line_number_gutter_resizes_with_document_lines(cx: &mut TestAppContext) { |
| 4212 | let (editor, window) = decoration_editor(cx, &"x\n".repeat(8), false); |
| 4213 | let mut cx = VisualTestContext::from_window(window.into(), cx); |
| 4214 | cx.update(|window, cx| { |
| 4215 | window.draw(cx).clear(cx); |
| 4216 | let narrow = editor |
| 4217 | .read(cx) |
| 4218 | .last_layout |
| 4219 | .as_ref() |
| 4220 | .unwrap() |
| 4221 | .line_number_width; |
| 4222 | |
| 4223 | let longer_text = "x\n".repeat(99); |
| 4224 | editor.update(cx, |state, cx| { |
| 4225 | state.set_value(longer_text.as_str(), window, cx) |
| 4226 | }); |
| 4227 | window.draw(cx).clear(cx); |
| 4228 | let middle = editor |
| 4229 | .read(cx) |
| 4230 | .last_layout |
| 4231 | .as_ref() |
| 4232 | .unwrap() |
| 4233 | .line_number_width; |
| 4234 | assert_eq!(middle, narrow, "one to three digits must share a width"); |
| 4235 | |
| 4236 | let longest_text = "x\n".repeat(999); |
| 4237 | editor.update(cx, |state, cx| { |
| 4238 | state.set_value(longest_text.as_str(), window, cx) |
| 4239 | }); |
| 4240 | window.draw(cx).clear(cx); |
| 4241 | let wide = editor |
| 4242 | .read(cx) |
| 4243 | .last_layout |
| 4244 | .as_ref() |
| 4245 | .unwrap() |
| 4246 | .line_number_width; |
| 4247 | |
| 4248 | assert!( |
| 4249 | wide > narrow, |
| 4250 | "more line-number digits must widen the gutter" |
| 4251 | ); |
| 4252 | }); |
| 4253 | } |
| 4254 | |
| 4255 | #[gpui::test] |
| 4256 | fn geometric_decorations_clip_scrolled_viewport_and_cull_offscreen_ranges( |
| 4257 | cx: &mut TestAppContext, |
| 4258 | ) { |
| 4259 | let text = "abcdefghij\n".repeat(100); |
| 4260 | let (editor, window) = decoration_editor(cx, &text, false); |
| 4261 | let mut cx = VisualTestContext::from_window(window.into(), cx); |
| 4262 | cx.update(|window, cx| { |
| 4263 | editor.update(cx, |state, cx| { |
| 4264 | state.create_range_decorations_collection( |
| 4265 | vec![ |
| 4266 | RangeDecoration::new(0..text.len()).with_style(RangeDecorationStyle::Fill), |
| 4267 | RangeDecoration::new(0..text.len()), |
| 4268 | RangeDecoration::new(0..3), |
| 4269 | RangeDecoration::new(text.len() - 3..text.len()), |
| 4270 | ], |
| 4271 | cx, |
| 4272 | ); |
| 4273 | }); |
| 4274 | window.draw(cx).clear(cx); |
| 4275 | editor.update(cx, |state, cx| { |
| 4276 | let height = state.last_layout.as_ref().unwrap().line_height; |
| 4277 | state.set_scroll_offset(point(px(0.), -height * 40.), cx); |
| 4278 | }); |
| 4279 | // Deferred scroll is committed by prepaint and reflected next frame. |
| 4280 | window.draw(cx).clear(cx); |
| 4281 | window.draw(cx).clear(cx); |
| 4282 | let state = editor.read(cx); |
| 4283 | let layout = state.last_layout.as_ref().unwrap(); |
| 4284 | assert!(layout.visible_range_offset.start > 0); |
| 4285 | assert!(layout.visible_range_offset.end < text.len()); |
| 4286 | let all = |
| 4287 | TextElement::<EditorMode>::layout_range_corners(&(0..text.len()), layout).unwrap(); |
| 4288 | let clipped = TextElement::<EditorMode>::layout_range_corners( |
| 4289 | &layout.visible_range_offset, |
| 4290 | layout, |
| 4291 | ) |
| 4292 | .unwrap(); |
| 4293 | assert_eq!(all, clipped); |
| 4294 | assert!(!all.is_empty()); |
| 4295 | assert!(TextElement::<EditorMode>::layout_range_corners(&(0..3), layout).is_none()); |
| 4296 | // Also execute the production path building seam, not just the corner helper. |
| 4297 | let (fills, frames) = TextElement::new(editor.clone()).layout_range_decorations( |
| 4298 | layout, |
| 4299 | &state.input_bounds, |
| 4300 | window, |
| 4301 | state.input_bounds, |
| 4302 | cx, |
| 4303 | ); |
| 4304 | assert_eq!(fills.len(), 1); |
| 4305 | assert_eq!(frames.len(), 1); |
| 4306 | }); |
| 4307 | } |
| 4308 | |
| 4309 | #[gpui::test] |
| 4310 | fn geometric_decorations_use_shaped_wrap_boundaries_and_newline_cells(cx: &mut TestAppContext) { |
| 4311 | let text = " héllo world héllo world héllo world héllo world\n\nlast"; |
| 4312 | let (editor, window) = decoration_editor(cx, text, true); |
| 4313 | let mut cx = VisualTestContext::from_window(window.into(), cx); |
| 4314 | cx.update(|window, cx| { |
| 4315 | window.draw(cx).clear(cx); |
| 4316 | let state = editor.read(cx); |
| 4317 | let layout = state.last_layout.as_ref().unwrap(); |
| 4318 | let first = &layout.lines[0]; |
| 4319 | assert!(first.wrapped_lines.len() > 1); |
| 4320 | assert!(first.wrap_indent > px(0.)); |
| 4321 | let boundary = first.wrapped_lines[0].len; |
| 4322 | let first_row = |
| 4323 | TextElement::<EditorMode>::layout_range_corners(&(0..boundary), layout).unwrap(); |
| 4324 | assert_eq!( |
| 4325 | first_row.len(), |
| 4326 | 1, |
| 4327 | "a wrap end must not open the next visual row" |
| 4328 | ); |
| 4329 | assert_eq!(first_row[0].top_right.x, first.wrapped_lines[0].width); |
| 4330 | let rest = |
| 4331 | TextElement::<EditorMode>::layout_range_corners(&(boundary..first.len()), layout) |
| 4332 | .unwrap(); |
| 4333 | assert_eq!(rest.len(), first.wrapped_lines.len() - 1); |
| 4334 | assert_eq!(rest[0].top_left.y, layout.visible_top + layout.line_height); |
| 4335 | for (index, corners) in rest.iter().enumerate() { |
| 4336 | assert_eq!( |
| 4337 | corners.top_right.x, |
| 4338 | first.wrap_indent + first.wrapped_lines[index + 1].width |
| 4339 | ); |
| 4340 | assert_eq!( |
| 4341 | corners.bottom_left.y - corners.top_left.y, |
| 4342 | layout.line_height |
| 4343 | ); |
| 4344 | } |
| 4345 | let blank_offset = text.find("\n\n").unwrap() + 1; |
| 4346 | let blank = TextElement::<EditorMode>::layout_range_corners( |
| 4347 | &(blank_offset..blank_offset + 1), |
| 4348 | layout, |
| 4349 | ) |
| 4350 | .unwrap(); |
| 4351 | assert_eq!(blank.len(), 1); |
| 4352 | assert_eq!( |
| 4353 | blank[0].top_right.x - blank[0].top_left.x, |
| 4354 | layout.space_width |
| 4355 | ); |
| 4356 | // A later-line decoration cannot paint the first row via saturating_sub. |
| 4357 | let last_offset = text.rfind("last").unwrap(); |
| 4358 | let last = |
| 4359 | TextElement::<EditorMode>::layout_range_corners(&(last_offset..text.len()), layout) |
| 4360 | .unwrap(); |
| 4361 | assert_eq!(last.len(), 1); |
| 4362 | assert!(last[0].top_left.y > rest.last().unwrap().top_left.y); |
| 4363 | }); |
| 4364 | } |
| 4365 | |
| 4366 | #[gpui::test] |
| 4367 | fn geometric_decorations_include_crlf_boundaries(cx: &mut TestAppContext) { |
| 4368 | let text = "one\r\ntwo\r\nthree"; |
| 4369 | let (editor, window) = decoration_editor(cx, text, false); |
| 4370 | let mut cx = VisualTestContext::from_window(window.into(), cx); |
| 4371 | cx.update(|window, cx| { |
| 4372 | editor.update(cx, |state, cx| { |
| 4373 | state.create_range_decorations_collection( |
| 4374 | vec![ |
| 4375 | RangeDecoration::new(0..8), |
| 4376 | RangeDecoration::new(3..5), |
| 4377 | RangeDecoration::new(4..5), |
| 4378 | RangeDecoration::new(5..8), |
| 4379 | RangeDecoration::new(9..10), |
| 4380 | ], |
| 4381 | cx, |
| 4382 | ); |
| 4383 | }); |
| 4384 | window.draw(cx).clear(cx); |
| 4385 | let state = editor.read(cx); |
| 4386 | let layout = state.last_layout.as_ref().unwrap(); |
| 4387 | // Shaping retains '\r'; only '\n' needs an additional newline cell. |
| 4388 | assert_eq!(layout.lines[0].len(), "one\r".len()); |
| 4389 | assert_eq!(layout.visible_line_byte_offsets, vec![0, 5, 10]); |
| 4390 | let spanning = |
| 4391 | TextElement::<EditorMode>::layout_range_corners(&(0..8), layout).unwrap(); |
| 4392 | assert_eq!(spanning.len(), 2); |
| 4393 | for range in [3..5, 4..5, 9..10] { |
| 4394 | let corners = |
| 4395 | TextElement::<EditorMode>::layout_range_corners(&range, layout).unwrap(); |
| 4396 | assert_eq!(corners.len(), 1); |
| 4397 | assert!(corners[0].top_right.x > corners[0].top_left.x); |
| 4398 | } |
| 4399 | let (fills, frames) = TextElement::new(editor.clone()).layout_range_decorations( |
| 4400 | layout, |
| 4401 | &state.input_bounds, |
| 4402 | window, |
| 4403 | state.input_bounds, |
| 4404 | cx, |
| 4405 | ); |
| 4406 | assert!(fills.is_empty()); |
| 4407 | assert_eq!(frames.len(), 5); |
| 4408 | }); |
| 4409 | } |
| 4410 | |
| 4411 | #[gpui::test] |
| 4412 | fn geometric_decorations_project_folds_without_changing_tracked_ranges( |
| 4413 | cx: &mut TestAppContext, |
| 4414 | ) { |
| 4415 | let text = "top\nhidden one\nhidden two\nend\nlast"; |
| 4416 | let (editor, window) = decoration_editor(cx, text, false); |
| 4417 | let mut cx = VisualTestContext::from_window(window.into(), cx); |
| 4418 | cx.update(|window, cx| { |
| 4419 | let hidden = 4..text.find("end").unwrap(); |
| 4420 | let collection = editor.update(cx, |state, cx| { |
| 4421 | state.apply_highlighter_fold_candidates(vec![FoldRange::new(0, 3)], cx); |
| 4422 | state.display_map.set_folded(0, true); |
| 4423 | state.create_range_decorations_collection( |
| 4424 | vec![RangeDecoration::new(hidden.clone())], |
| 4425 | cx, |
| 4426 | ) |
| 4427 | }); |
| 4428 | window.draw(cx).clear(cx); |
| 4429 | { |
| 4430 | let state = editor.read(cx); |
| 4431 | let layout = state.last_layout.as_ref().unwrap(); |
| 4432 | assert_eq!(layout.visible_buffer_lines, vec![0, 3, 4]); |
| 4433 | assert!(TextElement::<EditorMode>::layout_range_corners(&hidden, layout).is_none()); |
| 4434 | let (_, frames) = TextElement::new(editor.clone()).layout_range_decorations( |
| 4435 | layout, |
| 4436 | &state.input_bounds, |
| 4437 | window, |
| 4438 | state.input_bounds, |
| 4439 | cx, |
| 4440 | ); |
| 4441 | assert!(frames.is_empty()); |
| 4442 | let spanning = |
| 4443 | TextElement::<EditorMode>::layout_range_corners(&(0..text.len()), layout) |
| 4444 | .unwrap(); |
| 4445 | assert_eq!(spanning.len(), 3); |
| 4446 | assert_eq!(spanning[1].top_left.y, spanning[0].bottom_left.y); |
| 4447 | } |
| 4448 | assert_eq!(collection.get_ranges(cx), vec![hidden.clone()]); |
| 4449 | editor.update(cx, |state, cx| { |
| 4450 | state.display_map.set_folded(0, false); |
| 4451 | cx.notify(); |
| 4452 | }); |
| 4453 | window.draw(cx).clear(cx); |
| 4454 | let state = editor.read(cx); |
| 4455 | let layout = state.last_layout.as_ref().unwrap(); |
| 4456 | let revealed = |
| 4457 | TextElement::<EditorMode>::layout_range_corners(&hidden, layout).unwrap(); |
| 4458 | assert_eq!(revealed.len(), 2); |
| 4459 | assert_eq!(collection.get_ranges(cx), vec![hidden]); |
| 4460 | }); |
| 4461 | } |
| 4462 | |
| 4463 | #[gpui::test] |
| 4464 | fn geometric_decorations_track_edits_history_replacement_and_owner_lifetime( |
| 4465 | cx: &mut TestAppContext, |
| 4466 | ) { |
| 4467 | let (editor, window) = decoration_editor(cx, "abc def", false); |
| 4468 | let mut cx = VisualTestContext::from_window(window.into(), cx); |
| 4469 | cx.update(|window, cx| { |
| 4470 | let (first, second) = editor.update(cx, |state, cx| { |
| 4471 | ( |
| 4472 | state.create_range_decorations_collection(vec![RangeDecoration::new(4..7)], cx), |
| 4473 | state.create_range_decorations_collection(vec![RangeDecoration::new(0..3)], cx), |
| 4474 | ) |
| 4475 | }); |
| 4476 | editor.update(cx, |state, cx| { |
| 4477 | state.set_selected_range(0..0, cx); |
| 4478 | state.replace_text_in_range(None, "\n", window, cx); |
| 4479 | }); |
| 4480 | assert_eq!(first.get_ranges(cx), vec![5..8]); |
| 4481 | editor.update(cx, |state, cx| state.undo(&Undo, window, cx)); |
| 4482 | assert_eq!(first.get_ranges(cx), vec![4..7]); |
| 4483 | editor.update(cx, |state, cx| state.redo(&Redo, window, cx)); |
| 4484 | assert_eq!(first.get_ranges(cx), vec![5..8]); |
| 4485 | first.clear(cx); |
| 4486 | assert_eq!(second.get_ranges(cx), vec![1..4]); |
| 4487 | first.append(vec![RangeDecoration::new(5..8)], cx); |
| 4488 | editor.update(cx, |state, cx| state.replace_all("formatted", window, cx)); |
| 4489 | assert_eq!(first.get_ranges(cx), vec![0..9]); |
| 4490 | editor.update(cx, |state, cx| state.undo(&Undo, window, cx)); |
| 4491 | // Annotations are transformed, not snapshotted in undo history. |
| 4492 | assert_eq!(first.get_ranges(cx), vec![0..8]); |
| 4493 | editor.update(cx, |state, cx| state.set_value("new", window, cx)); |
| 4494 | assert_eq!(first.get_ranges(cx), vec![0..3]); |
| 4495 | let clone = first.clone(); |
| 4496 | first.dispose(cx); |
| 4497 | clone.append(vec![RangeDecoration::new(0..1)], cx); |
| 4498 | assert!(clone.get_ranges(cx).is_empty()); |
| 4499 | assert_eq!(second.get_ranges(cx), vec![0..3]); |
| 4500 | editor.update(cx, |state, cx| state.set_value("", window, cx)); |
| 4501 | assert!(second.get_ranges(cx).is_empty()); |
| 4502 | window.draw(cx).clear(cx); |
| 4503 | }); |
| 4504 | } |
| 4505 | |
| 4506 | #[test] |
| 4507 | fn frame_outline_is_continuous_across_different_line_widths() { |
| 4508 | let corners = [ |
| 4509 | Corners { |
| 4510 | top_left: point(px(2.), px(0.)), |
| 4511 | top_right: point(px(20.), px(0.)), |
| 4512 | bottom_left: point(px(2.), px(10.)), |
| 4513 | bottom_right: point(px(20.), px(10.)), |
| 4514 | }, |
| 4515 | Corners { |
| 4516 | top_left: point(px(0.), px(10.)), |
| 4517 | top_right: point(px(12.), px(10.)), |
| 4518 | bottom_left: point(px(0.), px(20.)), |
| 4519 | bottom_right: point(px(12.), px(20.)), |
| 4520 | }, |
| 4521 | ]; |
| 4522 | |
| 4523 | assert_eq!( |
| 4524 | frame_outline_points(&corners), |
| 4525 | vec![ |
| 4526 | point(px(2.), px(0.)), |
| 4527 | point(px(20.), px(0.)), |
| 4528 | point(px(20.), px(10.)), |
| 4529 | point(px(12.), px(10.)), |
| 4530 | point(px(12.), px(20.)), |
| 4531 | point(px(0.), px(20.)), |
| 4532 | point(px(0.), px(10.)), |
| 4533 | point(px(2.), px(10.)), |
| 4534 | point(px(2.), px(0.)), |
| 4535 | ] |
| 4536 | ); |
| 4537 | } |
| 4538 | |
| 4539 | #[test] |
| 4540 | fn frame_outline_keeps_horizontal_space_between_the_stroke_and_text() { |
| 4541 | let corners = [Corners { |
| 4542 | top_left: point(px(2.), px(0.)), |
| 4543 | top_right: point(px(20.), px(0.)), |
| 4544 | bottom_left: point(px(2.), px(10.)), |
| 4545 | bottom_right: point(px(20.), px(10.)), |
| 4546 | }]; |
| 4547 | |
| 4548 | assert_eq!( |
| 4549 | pad_frame_corners(&corners, px(1.)), |
| 4550 | vec![Corners { |
| 4551 | top_left: point(px(1.), px(0.)), |
| 4552 | top_right: point(px(21.), px(0.)), |
| 4553 | bottom_left: point(px(1.), px(10.)), |
| 4554 | bottom_right: point(px(21.), px(10.)), |
| 4555 | }] |
| 4556 | ); |
| 4557 | |
| 4558 | let points = frame_outline_points(&corners); |
| 4559 | assert_eq!(points.first(), points.last()); |
| 4560 | } |
| 4561 | |
| 4562 | #[test] |
| 4563 | fn frame_outline_stroke_is_aligned_to_physical_pixels_at_each_scale_factor() { |
| 4564 | let points = vec![point(px(0.2), px(1.8)), point(px(10.7), px(20.3))]; |
| 4565 | |
| 4566 | for (scale_factor, expected_width, expected_points) in [ |
| 4567 | ( |
| 4568 | 1., |
| 4569 | px(1.), |
| 4570 | vec![point(px(0.5), px(1.5)), point(px(10.5), px(20.5))], |
| 4571 | ), |
| 4572 | ( |
| 4573 | 1.5, |
| 4574 | px(2. / 3.), |
| 4575 | vec![ |
| 4576 | point(px(1. / 3.), px(5. / 3.)), |
| 4577 | point(px(11.), px(61. / 3.)), |
| 4578 | ], |
| 4579 | ), |
| 4580 | ( |
| 4581 | 2., |
| 4582 | px(1.), |
| 4583 | vec![point(px(0.), px(2.)), point(px(10.5), px(20.5))], |
| 4584 | ), |
| 4585 | ] { |
| 4586 | let (width, snapped) = snap_frame_outline(&points, px(1.), scale_factor); |
| 4587 | assert_eq!(width, expected_width); |
| 4588 | assert_eq!(snapped, expected_points); |
| 4589 | } |
| 4590 | } |
| 4591 | |
| 4592 | #[test] |
| 4593 | fn frame_outline_keeps_its_vertical_edges_inside_the_content_mask() { |
| 4594 | let points = vec![ |
| 4595 | point(px(9.5), px(2.5)), |
| 4596 | point(px(20.5), px(2.5)), |
| 4597 | point(px(20.5), px(10.5)), |
| 4598 | point(px(9.5), px(10.5)), |
| 4599 | point(px(9.5), px(2.5)), |
| 4600 | ]; |
| 4601 | let mask = Bounds::new(point(px(10.), px(0.)), size(px(10.), px(20.))); |
| 4602 | |
| 4603 | assert_eq!( |
| 4604 | clamp_frame_to_content_mask(points, px(1.), mask), |
| 4605 | vec![ |
| 4606 | point(px(10.5), px(2.5)), |
| 4607 | point(px(19.5), px(2.5)), |
| 4608 | point(px(19.5), px(10.5)), |
| 4609 | point(px(10.5), px(10.5)), |
| 4610 | point(px(10.5), px(2.5)), |
| 4611 | ] |
| 4612 | ); |
| 4613 | } |
| 4614 | |
| 4615 | #[test] |
| 4616 | fn test_plain_text_decorations_include_unstyled_gaps() { |
| 4617 | let decoration = HighlightStyle { |
| 4618 | background_color: Some(gpui::red()), |
| 4619 | ..Default::default() |
| 4620 | }; |
| 4621 | let styles = compose_decorations(Vec::new(), [(2..5, decoration)], 0..10).unwrap(); |
| 4622 | |
| 4623 | assert_eq!( |
| 4624 | styles |
| 4625 | .iter() |
| 4626 | .map(|(range, _)| range.clone()) |
| 4627 | .collect::<Vec<_>>(), |
| 4628 | vec![0..2, 2..5, 5..10] |
| 4629 | ); |
| 4630 | assert_eq!(styles[0].1, HighlightStyle::default()); |
| 4631 | assert_eq!(styles[1].1.background_color, Some(gpui::red())); |
| 4632 | assert_eq!(styles[2].1, HighlightStyle::default()); |
| 4633 | } |
| 4634 | |
| 4635 | #[test] |
| 4636 | fn test_first_decoration_collection_has_precedence() { |
| 4637 | let first = [TextDecoration::new( |
| 4638 | 0..4, |
| 4639 | HighlightStyle { |
| 4640 | background_color: Some(gpui::red()), |
| 4641 | ..Default::default() |
| 4642 | }, |
| 4643 | )]; |
| 4644 | let second = [TextDecoration::new( |
| 4645 | 0..4, |
| 4646 | HighlightStyle { |
| 4647 | background_color: Some(gpui::blue()), |
| 4648 | ..Default::default() |
| 4649 | }, |
| 4650 | )]; |
| 4651 | |
| 4652 | let styles = |
| 4653 | compose_decoration_collections(Vec::new(), [&first[..], &second[..]], 0..4).unwrap(); |
| 4654 | |
| 4655 | assert_eq!(styles.len(), 1); |
| 4656 | assert_eq!(styles[0].1.background_color, Some(gpui::red())); |
| 4657 | } |
| 4658 | |
| 4659 | #[test] |
| 4660 | fn test_decorations_override_syntax_highlights() { |
| 4661 | let syntax = vec![( |
| 4662 | 0..8, |
| 4663 | HighlightStyle { |
| 4664 | color: Some(gpui::blue()), |
| 4665 | ..Default::default() |
| 4666 | }, |
| 4667 | )]; |
| 4668 | let decoration = HighlightStyle { |
| 4669 | color: Some(gpui::red()), |
| 4670 | font_style: Some(gpui::FontStyle::Italic), |
| 4671 | ..Default::default() |
| 4672 | }; |
| 4673 | |
| 4674 | let styles = compose_decorations(syntax, [(2..6, decoration)], 0..8).unwrap(); |
| 4675 | |
| 4676 | assert_eq!(styles[1].0, 2..6); |
| 4677 | assert_eq!(styles[1].1.color, Some(gpui::red())); |
| 4678 | assert_eq!(styles[1].1.font_style, Some(gpui::FontStyle::Italic)); |
| 4679 | } |
| 4680 | |
| 4681 | #[test] |
| 4682 | fn test_editor_scrollbar_layout_uses_current_scroll_size() { |
| 4683 | let input_bounds = Bounds::new(point(px(10.), px(20.)), size(px(300.), px(80.))); |
| 4684 | let paddings = Edges { |
| 4685 | top: px(2.), |
| 4686 | right: px(3.), |
| 4687 | bottom: px(5.), |
| 4688 | left: px(7.), |
| 4689 | }; |
| 4690 | |
| 4691 | let layout = |
| 4692 | EditorScrollbarLayout::new(input_bounds, px(40.), size(px(1000.), px(200.)), paddings); |
| 4693 | |
| 4694 | assert_eq!( |
| 4695 | layout.bounds, |
| 4696 | Bounds::new(point(px(51.), px(18.)), size(px(262.), px(87.))) |
| 4697 | ); |
| 4698 | assert_eq!(layout.scroll_size, size(px(972.), px(200.))); |
| 4699 | |
| 4700 | let layout_without_gutter = |
| 4701 | EditorScrollbarLayout::new(input_bounds, px(0.), size(px(500.), px(120.)), paddings); |
| 4702 | |
| 4703 | assert_eq!( |
| 4704 | layout_without_gutter.bounds, |
| 4705 | Bounds::new(point(px(10.), px(18.)), size(px(303.), px(87.))) |
| 4706 | ); |
| 4707 | assert_eq!(layout_without_gutter.scroll_size, size(px(513.), px(120.))); |
| 4708 | } |
| 4709 | |
| 4710 | #[test] |
| 4711 | fn test_editor_gutter_covers_the_complete_fixed_column() { |
| 4712 | let input_bounds = Bounds::new(point(px(10.), px(20.)), size(px(300.), px(80.))); |
| 4713 | |
| 4714 | assert_eq!( |
| 4715 | editor_gutter_bounds( |
| 4716 | input_bounds, |
| 4717 | px(48.), |
| 4718 | px(16.), |
| 4719 | Edges { |
| 4720 | top: px(2.), |
| 4721 | right: px(3.), |
| 4722 | bottom: px(5.), |
| 4723 | left: px(7.), |
| 4724 | }, |
| 4725 | ), |
| 4726 | Bounds::new(point(px(3.), px(18.)), size(px(55.), px(103.))) |
| 4727 | ); |
| 4728 | } |
| 4729 | |
| 4730 | #[test] |
| 4731 | fn test_auto_grow_scroll_offset_is_clamped_to_current_viewport() { |
| 4732 | let mode = LayoutMode::auto_grow(3, 8); |
| 4733 | |
| 4734 | assert_eq!( |
| 4735 | clamp_auto_grow_vertical_scroll_offset(&mode, px(-260.), px(340.), px(160.)), |
| 4736 | px(-180.) |
| 4737 | ); |
| 4738 | assert_eq!( |
| 4739 | clamp_auto_grow_vertical_scroll_offset(&mode, px(-40.), px(340.), px(160.)), |
| 4740 | px(-40.) |
| 4741 | ); |
| 4742 | assert_eq!( |
| 4743 | clamp_auto_grow_vertical_scroll_offset(&mode, px(20.), px(340.), px(160.)), |
| 4744 | px(0.) |
| 4745 | ); |
| 4746 | |
| 4747 | let plain_text = LayoutMode::plain_text(); |
| 4748 | assert_eq!( |
| 4749 | clamp_auto_grow_vertical_scroll_offset(&plain_text, px(-260.), px(340.), px(160.)), |
| 4750 | px(-260.) |
| 4751 | ); |
| 4752 | } |
| 4753 | |
| 4754 | #[test] |
| 4755 | fn test_runs_for_range() { |
| 4756 | let run = TextRun { |
| 4757 | len: 0, |
| 4758 | font: gpui::font(".SystemUIFont"), |
| 4759 | color: gpui::black(), |
| 4760 | background_color: None, |
| 4761 | underline: None, |
| 4762 | strikethrough: None, |
| 4763 | }; |
| 4764 | |
| 4765 | // use hello this-is-test |
| 4766 | let runs = vec![ |
| 4767 | // use |
| 4768 | TextRun { |
| 4769 | len: 3, |
| 4770 | ..run.clone() |
| 4771 | }, |
| 4772 | // \s |
| 4773 | TextRun { |
| 4774 | len: 1, |
| 4775 | ..run.clone() |
| 4776 | }, |
| 4777 | // hello |
| 4778 | TextRun { |
| 4779 | len: 5, |
| 4780 | ..run.clone() |
| 4781 | }, |
| 4782 | // \s |
| 4783 | TextRun { |
| 4784 | len: 1, |
| 4785 | ..run.clone() |
| 4786 | }, |
| 4787 | // this-is-test |
| 4788 | TextRun { |
| 4789 | len: 12, |
| 4790 | ..run.clone() |
| 4791 | }, |
| 4792 | ]; |
| 4793 | |
| 4794 | #[track_caller] |
| 4795 | fn assert_runs(actual: Vec<TextRun>, expected: &[usize]) { |
| 4796 | let left = actual.iter().map(|run| run.len).collect::<Vec<_>>(); |
| 4797 | assert_eq!(left, expected); |
| 4798 | } |
| 4799 | |
| 4800 | assert_runs(runs_for_range(&runs, 0, &(0..0)), &[]); |
| 4801 | assert_runs(runs_for_range(&runs, 0, &(0..100)), &[3, 1, 5, 1, 12]); |
| 4802 | |
| 4803 | assert_runs(runs_for_range(&runs, 0, &(0..6)), &[3, 1, 2]); |
| 4804 | assert_runs(runs_for_range(&runs, 0, &(1..6)), &[2, 1, 2]); |
| 4805 | assert_runs(runs_for_range(&runs, 0, &(3..10)), &[1, 5, 1]); |
| 4806 | assert_runs(runs_for_range(&runs, 0, &(5..8)), &[3]); |
| 4807 | assert_runs(runs_for_range(&runs, 3, &(0..3)), &[1, 2]); |
| 4808 | assert_runs(runs_for_range(&runs, 3, &(2..10)), &[4, 1, 3]); |
| 4809 | assert_runs(runs_for_range(&runs, 9, &(0..8)), &[1, 7]); |
| 4810 | } |
| 4811 | |
| 4812 | #[test] |
| 4813 | fn test_split_runs_preserve_ime_underline_across_highlight_boundaries() { |
| 4814 | let underline = UnderlineStyle { |
| 4815 | thickness: px(1.), |
| 4816 | color: Some(gpui::black()), |
| 4817 | wavy: false, |
| 4818 | }; |
| 4819 | |
| 4820 | let runs = [0..4, 4..10] |
| 4821 | .into_iter() |
| 4822 | .flat_map(|range| { |
| 4823 | split_run_for_ime_underline( |
| 4824 | TextStyle::default().to_run(range.len()), |
| 4825 | range, |
| 4826 | Some(2..7), |
| 4827 | Some(underline), |
| 4828 | ) |
| 4829 | }) |
| 4830 | .collect::<Vec<_>>(); |
| 4831 | |
| 4832 | assert_eq!( |
| 4833 | runs.iter() |
| 4834 | .map(|run| (run.len, run.underline.is_some())) |
| 4835 | .collect::<Vec<_>>(), |
| 4836 | vec![(2, false), (2, true), (3, true), (3, false)] |
| 4837 | ); |
| 4838 | } |
| 4839 | |
| 4840 | #[test] |
| 4841 | fn test_split_run_applies_ime_underline_without_highlighting() { |
| 4842 | let underline = UnderlineStyle { |
| 4843 | thickness: px(1.), |
| 4844 | color: Some(gpui::black()), |
| 4845 | wavy: false, |
| 4846 | }; |
| 4847 | |
| 4848 | let runs = split_run_for_ime_underline( |
| 4849 | TextStyle::default().to_run(10), |
| 4850 | 0..10, |
| 4851 | Some(2..7), |
| 4852 | Some(underline), |
| 4853 | ); |
| 4854 | |
| 4855 | assert_eq!( |
| 4856 | runs.iter() |
| 4857 | .map(|run| (run.len, run.underline.is_some())) |
| 4858 | .collect::<Vec<_>>(), |
| 4859 | vec![(2, false), (5, true), (3, false)] |
| 4860 | ); |
| 4861 | assert!( |
| 4862 | split_run_for_ime_underline(TextStyle::default().to_run(0), 0..0, None, None) |
| 4863 | .is_empty() |
| 4864 | ); |
| 4865 | } |
| 4866 | |
| 4867 | #[test] |
| 4868 | fn test_masked_ime_underline_splits_on_mask_char_boundaries() { |
| 4869 | let underline = UnderlineStyle { |
| 4870 | thickness: px(1.), |
| 4871 | color: Some(gpui::black()), |
| 4872 | wavy: false, |
| 4873 | }; |
| 4874 | let text = Rope::from("abcdef"); |
| 4875 | let mask_len = MASK_CHAR.len_utf8(); |
| 4876 | |
| 4877 | assert_eq!( |
| 4878 | ime_marked_display_range(&text, Some(4..6), false), |
| 4879 | Some(4..6) |
| 4880 | ); |
| 4881 | assert_eq!(ime_marked_display_range(&text, None, true), None); |
| 4882 | assert_eq!( |
| 4883 | ime_marked_display_range(&text, Some(4..6), true), |
| 4884 | Some(4 * mask_len..6 * mask_len) |
| 4885 | ); |
| 4886 | |
| 4887 | let display_text = MASK_CHAR.to_string().repeat(text.chars().count()); |
| 4888 | let runs = split_run_for_ime_underline( |
| 4889 | TextStyle::default().to_run(display_text.len()), |
| 4890 | 0..display_text.len(), |
| 4891 | ime_marked_display_range(&text, Some(4..6), true), |
| 4892 | Some(underline), |
| 4893 | ); |
| 4894 | |
| 4895 | let mut offset = 0; |
| 4896 | for run in &runs { |
| 4897 | assert!(display_text.is_char_boundary(offset)); |
| 4898 | offset += run.len; |
| 4899 | } |
| 4900 | assert_eq!(offset, display_text.len()); |
| 4901 | } |
| 4902 | |
| 4903 | #[test] |
| 4904 | fn test_placeholder_line_runs() { |
| 4905 | let run = TextRun { |
| 4906 | len: 0, |
| 4907 | font: gpui::font(".SystemUIFont"), |
| 4908 | color: gpui::black(), |
| 4909 | background_color: None, |
| 4910 | underline: None, |
| 4911 | strikethrough: None, |
| 4912 | }; |
| 4913 | |
| 4914 | let runs = vec![ |
| 4915 | TextRun { |
| 4916 | len: 2, |
| 4917 | ..run.clone() |
| 4918 | }, |
| 4919 | TextRun { |
| 4920 | len: 2, |
| 4921 | ..run.clone() |
| 4922 | }, |
| 4923 | TextRun { len: 1, ..run }, |
| 4924 | ]; |
| 4925 | |
| 4926 | let placeholder_runs = placeholder_line_runs("ab\n\nc", &runs); |
| 4927 | |
| 4928 | let lines = placeholder_runs |
| 4929 | .iter() |
| 4930 | .map(|(line, _)| *line) |
| 4931 | .collect::<Vec<_>>(); |
| 4932 | assert_eq!(lines, vec!["ab", "", "c"]); |
| 4933 | |
| 4934 | let run_lengths = placeholder_runs |
| 4935 | .iter() |
| 4936 | .map(|(_, line_runs)| line_runs.iter().map(|run| run.len).collect::<Vec<_>>()) |
| 4937 | .collect::<Vec<_>>(); |
| 4938 | assert_eq!(run_lengths, vec![vec![2], vec![], vec![1]]); |
| 4939 | } |
| 4940 | |
| 4941 | #[test] |
| 4942 | fn test_align_runs_to_char_boundaries() { |
| 4943 | let run = TextRun { |
| 4944 | len: 0, |
| 4945 | font: gpui::font(".SystemUIFont"), |
| 4946 | color: gpui::blue(), |
| 4947 | background_color: None, |
| 4948 | underline: None, |
| 4949 | strikethrough: None, |
| 4950 | }; |
| 4951 | let runs = |lens: &[usize]| { |
| 4952 | lens.iter() |
| 4953 | .map(|&len| TextRun { len, ..run.clone() }) |
| 4954 | .collect::<Vec<_>>() |
| 4955 | }; |
| 4956 | let lens = |runs: &[TextRun]| runs.iter().map(|run| run.len).collect::<Vec<_>>(); |
| 4957 | |
| 4958 | // "你好,世界" is 15 bytes; boundaries at 0, 3, 6, 9, 12, 15. |
| 4959 | let text = "你好,世界"; |
| 4960 | |
| 4961 | // Aligned runs pass through untouched. |
| 4962 | assert_eq!(align_runs_to_char_boundaries(text, &runs(&[3, 12])), None); |
| 4963 | |
| 4964 | // A mid-char boundary (4) snaps up to the next boundary (6). |
| 4965 | let aligned = align_runs_to_char_boundaries(text, &runs(&[4, 11])).unwrap(); |
| 4966 | assert_eq!(lens(&aligned), vec![6, 9]); |
| 4967 | |
| 4968 | // Several boundaries inside the same char collapse into one run. |
| 4969 | let aligned = align_runs_to_char_boundaries(text, &runs(&[1, 1, 13])).unwrap(); |
| 4970 | assert_eq!(lens(&aligned), vec![3, 12]); |
| 4971 | |
| 4972 | // Overshooting runs are capped at the text length. |
| 4973 | let aligned = align_runs_to_char_boundaries(text, &runs(&[3, 20])).unwrap(); |
| 4974 | assert_eq!(lens(&aligned), vec![3, 12]); |
| 4975 | |
| 4976 | // Undershooting runs keep the shortfall (the tail is left unshaped, |
| 4977 | // matching `runs_for_range` clipping). |
| 4978 | assert_eq!(align_runs_to_char_boundaries(text, &runs(&[3, 3])), None); |
| 4979 | } |
| 4980 | |
| 4981 | #[test] |
| 4982 | fn test_clip_styles_to_ranges() { |
| 4983 | let style = HighlightStyle::default(); |
| 4984 | let styles = vec![(0..4, style), (4..10, style), (12..20, style)]; |
| 4985 | |
| 4986 | // Ranges with a gap (a folded region) drop the gap coverage and split |
| 4987 | // styles that span a range edge. |
| 4988 | let clipped = clip_styles_to_ranges(styles.clone(), &[2..6, 14..18]); |
| 4989 | assert_eq!( |
| 4990 | clipped |
| 4991 | .iter() |
| 4992 | .map(|(range, _)| range.clone()) |
| 4993 | .collect::<Vec<_>>(), |
| 4994 | vec![2..4, 4..6, 14..18] |
| 4995 | ); |
| 4996 | |
| 4997 | // Styles fully inside the ranges are unchanged. |
| 4998 | let clipped = clip_styles_to_ranges(styles.clone(), &[0..20]); |
| 4999 | assert_eq!( |
| 5000 | clipped |
| 5001 | .iter() |
| 5002 | .map(|(range, _)| range.clone()) |
| 5003 | .collect::<Vec<_>>(), |
| 5004 | vec![0..4, 4..10, 12..20] |
| 5005 | ); |
| 5006 | |
| 5007 | // A single style spanning several ranges splits into one piece per range. |
| 5008 | let clipped = clip_styles_to_ranges(vec![(0..30, style)], &[5..10, 20..25]); |
| 5009 | assert_eq!( |
| 5010 | clipped |
| 5011 | .iter() |
| 5012 | .map(|(range, _)| range.clone()) |
| 5013 | .collect::<Vec<_>>(), |
| 5014 | vec![5..10, 20..25] |
| 5015 | ); |
| 5016 | |
| 5017 | assert!(clip_styles_to_ranges(styles, &[]).is_empty()); |
| 5018 | } |
| 5019 | |
| 5020 | #[test] |
| 5021 | fn test_split_runs_by_bg_segments() { |
| 5022 | let run = TextRun { |
| 5023 | len: 0, |
| 5024 | font: gpui::font(".SystemUIFont"), |
| 5025 | color: gpui::blue(), |
| 5026 | background_color: None, |
| 5027 | underline: None, |
| 5028 | strikethrough: None, |
| 5029 | }; |
| 5030 | |
| 5031 | let runs = vec![ |
| 5032 | TextRun { |
| 5033 | len: 5, |
| 5034 | ..run.clone() |
| 5035 | }, |
| 5036 | TextRun { |
| 5037 | len: 7, |
| 5038 | ..run.clone() |
| 5039 | }, |
| 5040 | TextRun { |
| 5041 | len: 24, |
| 5042 | ..run.clone() |
| 5043 | }, |
| 5044 | ]; |
| 5045 | |
| 5046 | let bg_segments = vec![(8..12, gpui::red()), (12..18, gpui::blue())]; |
| 5047 | let result = split_runs_by_bg_segments(5, &runs, &bg_segments); |
| 5048 | assert_eq!( |
| 5049 | result.iter().map(|run| run.len).collect::<Vec<_>>(), |
| 5050 | vec![3, 2, 2, 5, 1, 23] |
| 5051 | ); |
| 5052 | assert_eq!(result[0].color, gpui::blue()); |
| 5053 | assert_eq!(result[1].color, gpui::black()); |
| 5054 | assert_eq!(result[2].color, gpui::black()); |
| 5055 | assert_eq!(result[3].color, gpui::black()); |
| 5056 | assert_eq!(result[4].color, gpui::black()); |
| 5057 | assert_eq!(result[5].color, gpui::blue()); |
| 5058 | } |
| 5059 | |
| 5060 | #[test] |
| 5061 | fn test_empty_bottom_height_outside_code_editor() { |
| 5062 | // Single-line / plain-text / auto-grow modes never reserve empty |
| 5063 | // bottom space, regardless of any override. |
| 5064 | for override_rows in [None, Some(0), Some(3), Some(99)] { |
| 5065 | assert_eq!( |
| 5066 | empty_bottom_height(false, override_rows, px(800.), px(20.)), |
| 5067 | px(0.), |
| 5068 | ); |
| 5069 | } |
| 5070 | } |
| 5071 | |
| 5072 | #[test] |
| 5073 | fn test_empty_bottom_height_code_editor_default() { |
| 5074 | // `None`: roughly half the viewport, floored at |
| 5075 | // `BOTTOM_MARGIN_ROWS * line_height` so the empty area never |
| 5076 | // collapses to "less than a few lines" on tiny viewports. |
| 5077 | let line_height = px(20.); |
| 5078 | |
| 5079 | // Viewport much taller than the floor → half-viewport wins. |
| 5080 | assert_eq!( |
| 5081 | empty_bottom_height(true, None, px(800.), line_height), |
| 5082 | px(400.), |
| 5083 | ); |
| 5084 | |
| 5085 | // Viewport shorter than 2 × floor → floor wins. |
| 5086 | let floor = BOTTOM_MARGIN_ROWS * line_height; |
| 5087 | assert_eq!(empty_bottom_height(true, None, px(40.), line_height), floor); |
| 5088 | } |
| 5089 | |
| 5090 | #[test] |
| 5091 | fn test_empty_bottom_height_explicit_row_count() { |
| 5092 | // `Some(n)`: exactly `n` line-heights. Caller fully controls |
| 5093 | // the trailing empty space; viewport size doesn't amplify it. |
| 5094 | let line_height = px(20.); |
| 5095 | |
| 5096 | for rows in [0_usize, 1, 3, 8, 64] { |
| 5097 | let expected = rows as f32 * line_height; |
| 5098 | assert_eq!( |
| 5099 | empty_bottom_height(true, Some(rows), px(800.), line_height), |
| 5100 | expected, |
| 5101 | ); |
| 5102 | // Tiny viewport: still exactly `n × line_height`, no floor |
| 5103 | // applied when caller supplied an explicit count. |
| 5104 | assert_eq!( |
| 5105 | empty_bottom_height(true, Some(rows), px(20.), line_height), |
| 5106 | expected, |
| 5107 | ); |
| 5108 | } |
| 5109 | } |
| 5110 | |
| 5111 | #[test] |
| 5112 | fn test_cursor_surrounding_padding_auto_grow() { |
| 5113 | // Auto-grow inputs always pad by one line, regardless of any |
| 5114 | // override or visible-lines count. |
| 5115 | let line_height = px(20.); |
| 5116 | for override_lines in [None, Some(0), Some(3), Some(99)] { |
| 5117 | for visible_lines in [0_usize, 1, 8, 64] { |
| 5118 | assert_eq!( |
| 5119 | cursor_surrounding_padding(true, override_lines, visible_lines, line_height,), |
| 5120 | line_height, |
| 5121 | ); |
| 5122 | } |
| 5123 | } |
| 5124 | } |
| 5125 | |
| 5126 | #[test] |
| 5127 | fn test_cursor_surrounding_padding_default() { |
| 5128 | // `None`: historical heuristic — `BOTTOM_MARGIN_ROWS` for normal |
| 5129 | // viewports, falls back to one line on small viewports (less |
| 5130 | // than `BOTTOM_MARGIN_ROWS × 8` rows tall). |
| 5131 | let line_height = px(20.); |
| 5132 | |
| 5133 | // Small viewport → 1-line fallback. |
| 5134 | let small = BOTTOM_MARGIN_ROWS * 8 - 1; |
| 5135 | assert_eq!( |
| 5136 | cursor_surrounding_padding(false, None, small, line_height), |
| 5137 | line_height, |
| 5138 | ); |
| 5139 | |
| 5140 | // Boundary at `BOTTOM_MARGIN_ROWS × 8` flips to the full margin. |
| 5141 | let boundary = BOTTOM_MARGIN_ROWS * 8; |
| 5142 | assert_eq!( |
| 5143 | cursor_surrounding_padding(false, None, boundary, line_height), |
| 5144 | BOTTOM_MARGIN_ROWS * line_height, |
| 5145 | ); |
| 5146 | |
| 5147 | // Comfortably-large viewport. |
| 5148 | assert_eq!( |
| 5149 | cursor_surrounding_padding(false, None, 100, line_height), |
| 5150 | BOTTOM_MARGIN_ROWS * line_height, |
| 5151 | ); |
| 5152 | } |
| 5153 | |
| 5154 | #[test] |
| 5155 | fn test_cursor_surrounding_padding_explicit() { |
| 5156 | // `Some(n)`: exactly `n × line_height` when the viewport has |
| 5157 | // room for it; saturated against half the viewport when it |
| 5158 | // doesn't. |
| 5159 | let line_height = px(20.); |
| 5160 | |
| 5161 | for lines in [0_usize, 1, 2, 5, 50] { |
| 5162 | let raw = lines as f32 * line_height; |
| 5163 | for visible_lines in [0_usize, 1, 8, 100] { |
| 5164 | let viewport_half = (visible_lines as f32 * line_height).half(); |
| 5165 | assert_eq!( |
| 5166 | cursor_surrounding_padding(false, Some(lines), visible_lines, line_height,), |
| 5167 | raw.min(viewport_half), |
| 5168 | ); |
| 5169 | } |
| 5170 | } |
| 5171 | } |
| 5172 | |
| 5173 | #[test] |
| 5174 | fn test_cursor_surrounding_padding_saturates_against_viewport() { |
| 5175 | // An aggressive override on a small viewport must not produce a |
| 5176 | // padding larger than half the visible region — otherwise the |
| 5177 | // bottom-edge auto-scroll-into-view threshold sinks below the |
| 5178 | // top-edge threshold and the per-frame scroll adjustment loses |
| 5179 | // a stable fixed point. |
| 5180 | let line_height = px(20.); |
| 5181 | |
| 5182 | // Override much larger than viewport → clamped to half. |
| 5183 | let visible_lines = 10; |
| 5184 | let viewport_half = (visible_lines as f32 * line_height).half(); |
| 5185 | assert_eq!( |
| 5186 | cursor_surrounding_padding(false, Some(50), visible_lines, line_height), |
| 5187 | viewport_half, |
| 5188 | ); |
| 5189 | |
| 5190 | // Override that fits → returned unchanged. |
| 5191 | let visible_lines = 40; |
| 5192 | assert_eq!( |
| 5193 | cursor_surrounding_padding(false, Some(3), visible_lines, line_height), |
| 5194 | 3.0 * line_height, |
| 5195 | ); |
| 5196 | |
| 5197 | // Default heuristic still saturates if BOTTOM_MARGIN_ROWS would |
| 5198 | // exceed the half-viewport bound (only possible at extreme |
| 5199 | // sizes — kept for defensive completeness). |
| 5200 | let visible_lines = BOTTOM_MARGIN_ROWS * 8; |
| 5201 | let half = (visible_lines as f32 * line_height).half(); |
| 5202 | let raw = BOTTOM_MARGIN_ROWS * line_height; |
| 5203 | assert_eq!( |
| 5204 | cursor_surrounding_padding(false, None, visible_lines, line_height), |
| 5205 | raw.min(half), |
| 5206 | ); |
| 5207 | } |
| 5208 | } |