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