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