Skip to main content

gpui_component/diff/
state.rs

1use std::{
2    cell::RefCell,
3    collections::{HashMap, HashSet},
4    ops::Range,
5    rc::Rc,
6    sync::Arc,
7};
8
9use gpui::{
10    App, AppContext as _, Context, ElementId, EventEmitter, FocusHandle, Focusable, HighlightStyle,
11    ListAlignment, ListOffset, ListState, Pixels, ScrollHandle, SharedString, Size, Subscription,
12    Task, Window, WindowId, point, px,
13};
14use gpui_base::{TextSelection, TextSelectionContentKey, TextSelectionEvent, TextSelectionHandle};
15
16use super::{
17    DiffAnnotation, DiffConflictResolution, DiffFile, DiffFileStatus, DiffInlineUnit,
18    DiffLinePosition, DiffLineRange, DiffMode, DiffSide,
19    conflict::ConflictPart,
20    presentation::{
21        DiffSyntaxHighlighter, FilePresentation, PresentationOptions, SyntaxHighlighters,
22    },
23    selection::SelectionGeometry,
24};
25
26/// One virtualized row. Every row belongs to exactly one file.
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub(crate) enum DisplayRow {
29    /// The file header, with any file-level annotations.
30    File(usize),
31    /// Binary, metadata-only or empty file summary, for a file without source rows.
32    Notice(usize),
33    Hunk {
34        file: usize,
35        hunk: usize,
36    },
37    Fold {
38        file: usize,
39        pairs: Range<usize>,
40    },
41    /// The heading of one part of a merge conflict; for a resolved conflict,
42    /// the [`ConflictPart::Current`] heading stands for the whole conflict.
43    Conflict {
44        file: usize,
45        conflict: usize,
46        part: ConflictPart,
47    },
48    Code {
49        file: usize,
50        original: Option<usize>,
51        modified: Option<usize>,
52        changed: bool,
53    },
54}
55
56impl DisplayRow {
57    pub(crate) fn file(&self) -> usize {
58        match self {
59            Self::File(file) | Self::Notice(file) => *file,
60            Self::Hunk { file, .. }
61            | Self::Fold { file, .. }
62            | Self::Conflict { file, .. }
63            | Self::Code { file, .. } => *file,
64        }
65    }
66}
67
68/// Which part of a collapsed unchanged range a disclosure reveals.
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub(crate) enum FoldExpansion {
71    /// The lines just above the following source.
72    Up,
73    /// The lines just below the preceding source.
74    Down,
75    All,
76}
77
78/// Notifications from the readonly comparison surface.
79#[derive(Clone, Debug)]
80#[non_exhaustive]
81pub enum DiffEvent {
82    /// A pointer gesture began selecting source lines from a line number.
83    SelectionStarted(DiffLineRange),
84    /// A pointer, gutter or keyboard operation changed the selected source lines.
85    SelectionChanged(Option<DiffLineRange>),
86    /// A selection gesture finished; the range is ready to act on.
87    SelectionEnded(DiffLineRange),
88    /// The user expanded a collapsed file from its header.
89    FileExpanded(SharedString),
90    /// The user collapsed a file from its header.
91    FileCollapsed(SharedString),
92    /// The user resolved a merge conflict, or undid its resolution; read it
93    /// with [`DiffState::conflict_resolution`].
94    ConflictResolved(SharedString, usize),
95}
96
97/// Inputs that determine row heights and content width.
98#[derive(Clone, Debug, PartialEq)]
99pub(crate) struct LayoutKey {
100    rem: Pixels,
101    font_size: Pixels,
102    font_family: SharedString,
103    mode: DiffMode,
104    line_number: bool,
105    marker_lane: bool,
106    soft_wrap: bool,
107    split_ratio: f32,
108}
109
110impl LayoutKey {
111    #[allow(clippy::too_many_arguments)]
112    pub(crate) fn new(
113        rem: Pixels,
114        font_size: Pixels,
115        font_family: SharedString,
116        mode: DiffMode,
117        line_number: bool,
118        marker_lane: bool,
119        soft_wrap: bool,
120        split_ratio: f32,
121    ) -> Self {
122        Self {
123            rem,
124            font_size,
125            font_family,
126            mode,
127            line_number,
128            marker_lane,
129            soft_wrap,
130            split_ratio,
131        }
132    }
133}
134
135/// The row showing each source line, or the disclosure hiding it.
136#[derive(Default)]
137struct FileRows {
138    original: Vec<Option<usize>>,
139    modified: Vec<Option<usize>>,
140}
141
142/// The selected source lines of one file, resolved for membership tests.
143#[derive(Clone, Debug, PartialEq, Eq)]
144pub(crate) enum SelectedLines {
145    /// Lines numbered `lines` on one side.
146    Side {
147        file: usize,
148        side: DiffSide,
149        lines: Range<usize>,
150    },
151    /// Patch lines in `patch` order, across both sides.
152    Patch { file: usize, patch: Range<usize> },
153}
154
155impl SelectedLines {
156    pub(crate) fn contains(
157        &self,
158        files: &[DiffFile],
159        file: usize,
160        side: DiffSide,
161        ix: usize,
162    ) -> bool {
163        match self {
164            Self::Side {
165                file: selected,
166                side: selected_side,
167                lines,
168            } => {
169                *selected == file
170                    && *selected_side == side
171                    && lines.contains(&files[file].line_number(side, ix))
172            }
173            Self::Patch {
174                file: selected,
175                patch,
176            } => *selected == file && patch.contains(&files[file].patch_ix(side, ix)),
177        }
178    }
179
180    /// The last selected line, where a selection's add-annotation button sits.
181    pub(crate) fn is_last(
182        &self,
183        files: &[DiffFile],
184        file: usize,
185        side: DiffSide,
186        ix: usize,
187    ) -> bool {
188        match self {
189            Self::Side {
190                file: selected,
191                side: selected_side,
192                lines,
193            } => {
194                *selected == file
195                    && *selected_side == side
196                    && files[file].line_number(side, ix) + 1 == lines.end
197            }
198            Self::Patch {
199                file: selected,
200                patch,
201            } => *selected == file && files[file].patch_ix(side, ix) + 1 == patch.end,
202        }
203    }
204}
205
206/// Retained focus, viewport, context expansion and selection for a
207/// [`super::Diff`] showing one or more files of a patch.
208///
209/// Create once in the owning view. Mutations notify observers; the application
210/// owns the patch and chooses when to install new files. Syntax and inline
211/// emphasis are prepared on a background thread and appear once ready.
212pub struct DiffState {
213    files: Vec<DiffFile>,
214    /// Each path's index in `files`; the first file wins a duplicated path.
215    file_ixs: HashMap<SharedString, usize>,
216    mode: DiffMode,
217    context_lines: Option<usize>,
218    expansion_lines: usize,
219    min_collapsed_lines: usize,
220    expanded: Vec<Vec<Range<usize>>>,
221    collapsed: HashSet<SharedString>,
222    resolutions: HashMap<(SharedString, usize), DiffConflictResolution>,
223    file_rows: Vec<FileRows>,
224    header_rows: Vec<usize>,
225    rows: Rc<Vec<DisplayRow>>,
226    change_rows: Vec<usize>,
227    list: ListState,
228    horizontal_scroll: ScrollHandle,
229    focus: FocusHandle,
230    selection: TextSelectionHandle,
231    geometry: Rc<RefCell<SelectionGeometry>>,
232    selected_lines: Option<DiffLineRange>,
233    selection_anchor: Option<DiffLinePosition>,
234    selection_cursor: Option<DiffLinePosition>,
235    selecting: bool,
236    presentation_options: PresentationOptions,
237    syntax_highlighter: Option<DiffSyntaxHighlighter>,
238    presentations: Vec<Option<Arc<FilePresentation>>>,
239    viewport: Size<Pixels>,
240    layout: Option<LayoutKey>,
241    content_width: Pixels,
242    row_height: Option<Pixels>,
243    /// The list width the row-height hint was last applied at.
244    hinted_width: Option<Pixels>,
245    annotations: HashSet<(Option<DiffLinePosition>, SharedString, ElementId)>,
246    window: Option<WindowId>,
247    /// Bumped when files or presentation options change, so a preparation
248    /// started for earlier ones never installs its results.
249    presentation_generation: usize,
250    preparing: Option<usize>,
251    _presentation: Task<()>,
252    _selection_subscription: Subscription,
253}
254
255impl EventEmitter<DiffEvent> for DiffState {}
256impl Focusable for DiffState {
257    fn focus_handle(&self, _: &App) -> FocusHandle {
258        self.focus.clone()
259    }
260}
261
262impl DiffState {
263    /// Creates a unified viewer with three unchanged lines around each change.
264    pub fn new(files: impl IntoIterator<Item = DiffFile>, cx: &mut Context<Self>) -> Self {
265        let focus = cx.focus_handle().tab_stop(true);
266        let selection = TextSelectionHandle::new("", cx);
267        let geometry = Rc::new(RefCell::new(SelectionGeometry::default()));
268        let weak = cx.entity().downgrade();
269        selection.resolve_content_key_with(
270            {
271                let weak = weak.clone();
272                let geometry = geometry.clone();
273                move |point, cx| {
274                    let state = weak.upgrade()?;
275                    let snapshot = state.read(cx).selection.snapshot(cx);
276                    let entity = Some(state.read(cx).selection.entity_id());
277                    let snapshot =
278                        snapshot.filter(|snapshot| snapshot.anchor().entity_id() == entity);
279                    let side = snapshot
280                        .and_then(|snapshot| snapshot.anchor().content_key())
281                        .map(|key| decode_key(key.value()).1);
282                    geometry
283                        .borrow()
284                        .key_at(point, side)
285                        .map(TextSelectionContentKey::new)
286                        .or_else(|| {
287                            snapshot
288                                .filter(|snapshot| snapshot.cursor().entity_id() == entity)
289                                .and_then(|snapshot| snapshot.cursor().content_key())
290                        })
291                }
292            },
293            cx,
294        );
295        selection.copy_with(
296            {
297                let weak = weak.clone();
298                move |cx| {
299                    weak.upgrade()
300                        .map_or_else(String::new, |state| state.read(cx).selected_text(cx))
301                }
302            },
303            cx,
304        );
305        selection.focus_with(
306            {
307                let focus = focus.clone();
308                move |window, cx| window.focus(&focus, cx)
309            },
310            cx,
311        );
312        let _selection_subscription = selection.subscribe(
313            move |event, cx| {
314                let _ = weak.update(cx, |state, cx| {
315                    if !state.selection.has_local_selection(cx) {
316                        match event {
317                            TextSelectionEvent::SelectionChanged(Some(_)) => {
318                                let changed = state.selected_lines.take().is_some();
319                                // A new text gesture ends the previous gutter anchor.
320                                state.selection_anchor = None;
321                                state.selection_cursor = None;
322                                if changed {
323                                    cx.emit(DiffEvent::SelectionChanged(None));
324                                }
325                            }
326                            TextSelectionEvent::Cleared => {
327                                // A replacement gutter gesture has local selection and
328                                // skips this branch. Keep its anchor for Shift-click,
329                                // but report a clear that leaves no replacement range.
330                                if state.selected_lines.take().is_some() {
331                                    cx.emit(DiffEvent::SelectionChanged(None));
332                                }
333                            }
334                            _ => {}
335                        }
336                    }
337                    cx.notify();
338                });
339            },
340            cx,
341        );
342        let files = files.into_iter().collect::<Vec<_>>();
343        let mut state = Self {
344            expanded: vec![Vec::new(); files.len()],
345            presentations: vec![None; files.len()],
346            file_ixs: file_ixs(&files),
347            files,
348            mode: DiffMode::Unified,
349            context_lines: Some(3),
350            expansion_lines: 20,
351            min_collapsed_lines: 2,
352            collapsed: HashSet::new(),
353            resolutions: HashMap::new(),
354            file_rows: Vec::new(),
355            header_rows: Vec::new(),
356            rows: Rc::default(),
357            change_rows: Vec::new(),
358            list: ListState::new(0, ListAlignment::Top, px(0.)),
359            horizontal_scroll: ScrollHandle::new(),
360            focus,
361            selection,
362            geometry,
363            selected_lines: None,
364            selection_anchor: None,
365            selection_cursor: None,
366            selecting: false,
367            presentation_options: PresentationOptions {
368                inline_unit: Some(DiffInlineUnit::Word),
369                inline_max_line_length: 1000,
370                syntax_max_line_length: 1000,
371            },
372            syntax_highlighter: None,
373            viewport: Size::default(),
374            layout: None,
375            content_width: px(0.),
376            row_height: None,
377            hinted_width: None,
378            annotations: HashSet::new(),
379            window: None,
380            presentation_generation: 0,
381            preparing: None,
382            _presentation: Task::ready(()),
383            _selection_subscription,
384        };
385        state.rebuild(true);
386        state
387    }
388
389    /// Sets the initial display mode. Default is [`DiffMode::Unified`].
390    pub fn with_mode(mut self, mode: DiffMode) -> Self {
391        self.mode = mode;
392        self.rebuild(true);
393        self
394    }
395
396    /// Sets the initial unchanged context around each change. Default is
397    /// `Some(3)`; `None` shows every supplied patch line.
398    pub fn with_context_lines(mut self, lines: Option<usize>) -> Self {
399        self.context_lines = lines;
400        self.rebuild(true);
401        self
402    }
403
404    /// Sets how many lines an up or down disclosure reveals. Default is 20.
405    pub fn with_expansion_lines(mut self, lines: usize) -> Self {
406        self.expansion_lines = lines.max(1);
407        self
408    }
409
410    /// Sets the shortest unchanged range that collapses; shorter ranges stay
411    /// visible. Default is 2.
412    pub fn with_min_collapsed_lines(mut self, lines: usize) -> Self {
413        self.min_collapsed_lines = lines.max(1);
414        self.rebuild(true);
415        self
416    }
417
418    /// Sets the unit inline changes between paired lines are emphasized in,
419    /// or `None` to emphasize whole lines only. Default is [`DiffInlineUnit::Word`].
420    pub fn with_inline_unit(mut self, unit: Option<DiffInlineUnit>) -> Self {
421        self.presentation_options.inline_unit = unit;
422        self.reset_presentation();
423        self
424    }
425
426    /// Sets the longest line, in bytes, compared for inline changes. Default is 1,000.
427    pub fn with_inline_max_line_length(mut self, length: usize) -> Self {
428        self.presentation_options.inline_max_line_length = length;
429        self.reset_presentation();
430        self
431    }
432
433    /// Sets the longest line, in bytes, given syntax emphasis. Default is 1,000.
434    pub fn with_syntax_max_line_length(mut self, length: usize) -> Self {
435        self.presentation_options.syntax_max_line_length = length;
436        self.reset_presentation();
437        self
438    }
439
440    /// Highlights syntax with the application's highlighter instead of GPUI
441    /// Kit's. Given a file's [language](DiffFile::language) and the source
442    /// text of one side of one hunk, it returns byte ranges into that text
443    /// with their styles; a range that splits a character is ignored.
444    ///
445    /// It runs on the background executor, once for each side of each hunk,
446    /// so an unterminated comment in one hunk cannot color the next. Styles
447    /// are kept as returned rather than resolved against the theme when a line
448    /// paints; set a new highlighter when its colors change.
449    pub fn with_syntax_highlighter<F>(mut self, highlighter: F) -> Self
450    where
451        F: Fn(&str, &str) -> Vec<(Range<usize>, HighlightStyle)> + Send + Sync + 'static,
452    {
453        self.syntax_highlighter = Some(Arc::new(highlighter));
454        self.reset_presentation();
455        self
456    }
457
458    /// Replaces the application's highlighter, preparing syntax again without
459    /// resetting selection or scrolling. See [`Self::with_syntax_highlighter`].
460    pub fn set_syntax_highlighter<F>(&mut self, highlighter: F, cx: &mut Context<Self>)
461    where
462        F: Fn(&str, &str) -> Vec<(Range<usize>, HighlightStyle)> + Send + Sync + 'static,
463    {
464        self.replace_syntax_highlighter(Some(Arc::new(highlighter)), cx);
465    }
466
467    /// Returns to GPUI Kit's highlighter, preparing syntax again without
468    /// resetting selection or scrolling.
469    pub fn clear_syntax_highlighter(&mut self, cx: &mut Context<Self>) {
470        self.replace_syntax_highlighter(None, cx);
471    }
472
473    fn replace_syntax_highlighter(
474        &mut self,
475        highlighter: Option<DiffSyntaxHighlighter>,
476        cx: &mut Context<Self>,
477    ) {
478        self.syntax_highlighter = highlighter;
479        self.reset_presentation();
480        self.ensure_presentation(cx);
481        cx.notify();
482    }
483
484    /// Changes the number of lines each disclosure reveals, preserving selection and scrolling.
485    pub fn set_expansion_lines(&mut self, lines: usize, cx: &mut Context<Self>) {
486        let lines = lines.max(1);
487        if self.expansion_lines == lines {
488            return;
489        }
490        self.expansion_lines = lines;
491        cx.notify();
492    }
493
494    /// Changes the shortest unchanged range that collapses, preserving selection and scrolling.
495    pub fn set_min_collapsed_lines(&mut self, lines: usize, cx: &mut Context<Self>) {
496        let lines = lines.max(1);
497        if self.min_collapsed_lines == lines {
498            return;
499        }
500        self.min_collapsed_lines = lines;
501        self.rebuild_at_anchor();
502        cx.notify();
503    }
504
505    /// Changes the inline comparison unit without resetting selection or scrolling.
506    pub fn set_inline_unit(&mut self, unit: Option<DiffInlineUnit>, cx: &mut Context<Self>) {
507        if self.presentation_options.inline_unit == unit {
508            return;
509        }
510        self.presentation_options.inline_unit = unit;
511        self.reset_presentation();
512        self.ensure_presentation(cx);
513        cx.notify();
514    }
515
516    /// Changes the inline comparison line limit in bytes without resetting selection or scrolling.
517    pub fn set_inline_max_line_length(&mut self, length: usize, cx: &mut Context<Self>) {
518        if self.presentation_options.inline_max_line_length == length {
519            return;
520        }
521        self.presentation_options.inline_max_line_length = length;
522        self.reset_presentation();
523        self.ensure_presentation(cx);
524        cx.notify();
525    }
526
527    /// Changes the syntax emphasis line limit in bytes without resetting selection or scrolling.
528    pub fn set_syntax_max_line_length(&mut self, length: usize, cx: &mut Context<Self>) {
529        if self.presentation_options.syntax_max_line_length == length {
530            return;
531        }
532        self.presentation_options.syntax_max_line_length = length;
533        self.reset_presentation();
534        self.ensure_presentation(cx);
535        cx.notify();
536    }
537
538    /// The files in patch order.
539    pub fn files(&self) -> &[DiffFile] {
540        &self.files
541    }
542    pub fn mode(&self) -> DiffMode {
543        self.mode
544    }
545    pub fn context_lines(&self) -> Option<usize> {
546        self.context_lines
547    }
548    pub fn expansion_lines(&self) -> usize {
549        self.expansion_lines
550    }
551    pub fn min_collapsed_lines(&self) -> usize {
552        self.min_collapsed_lines
553    }
554    pub fn inline_unit(&self) -> Option<DiffInlineUnit> {
555        self.presentation_options.inline_unit
556    }
557    pub fn inline_max_line_length(&self) -> usize {
558        self.presentation_options.inline_max_line_length
559    }
560    pub fn syntax_max_line_length(&self) -> usize {
561        self.presentation_options.syntax_max_line_length
562    }
563    pub fn selected_lines(&self) -> Option<DiffLineRange> {
564        self.selected_lines.clone()
565    }
566    /// Whether the file at `path` shows only its header.
567    pub fn is_file_collapsed(&self, path: &str) -> bool {
568        self.collapsed.contains(path)
569    }
570
571    pub(crate) fn rows(&self) -> &Rc<Vec<DisplayRow>> {
572        &self.rows
573    }
574    pub(crate) fn list(&self) -> &ListState {
575        &self.list
576    }
577    pub(crate) fn horizontal_scroll(&self) -> &ScrollHandle {
578        &self.horizontal_scroll
579    }
580    pub(crate) fn selection(&self) -> &TextSelectionHandle {
581        &self.selection
582    }
583    pub(crate) fn geometry(&self) -> &Rc<RefCell<SelectionGeometry>> {
584        &self.geometry
585    }
586    pub(crate) fn presentations(&self) -> &[Option<Arc<FilePresentation>>] {
587        &self.presentations
588    }
589    /// The body's size as of the last paint.
590    pub(crate) fn viewport(&self) -> Size<Pixels> {
591        self.viewport
592    }
593    /// The width rows need to show their longest line.
594    pub(crate) fn content_width(&self) -> Pixels {
595        self.content_width
596    }
597    pub(crate) fn set_content_width(&mut self, width: Pixels) {
598        self.content_width = width;
599    }
600    /// Records the painted body size and widest painted row. Returns whether
601    /// either changed, so the frame must be laid out again.
602    pub(crate) fn record_paint(&mut self, viewport: Size<Pixels>, painted_width: Pixels) -> bool {
603        let wider = painted_width > self.content_width;
604        if wider {
605            self.content_width = painted_width;
606        }
607        let resized = self.viewport != viewport;
608        self.viewport = viewport;
609        wider || resized
610    }
611
612    /// Replaces the files and resets expansion, selection and viewport.
613    /// Collapsed files stay collapsed when their path is still present.
614    pub fn set_files(&mut self, files: impl IntoIterator<Item = DiffFile>, cx: &mut Context<Self>) {
615        if let Some(window) = self.window
616            && self.selection_is_local(cx)
617        {
618            TextSelection::clear_for_window(window, cx);
619        }
620        self.files = files.into_iter().collect();
621        self.file_ixs = file_ixs(&self.files);
622        self.collapsed
623            .retain(|path| self.file_ixs.contains_key(path));
624        self.resolutions.clear();
625        self.expanded = vec![Vec::new(); self.files.len()];
626        self.reset_presentation();
627        self.layout = None;
628        self.annotations.clear();
629        self.selection.set_local_selection(false, cx);
630        self.selection.set_fallback_copy_text("", cx);
631        self.selected_lines = None;
632        self.selection_anchor = None;
633        self.selection_cursor = None;
634        self.selecting = false;
635        self.geometry.borrow_mut().clear();
636        self.rebuild(true);
637        self.horizontal_scroll.set_offset(point(px(0.), px(0.)));
638        self.ensure_presentation(cx);
639        cx.notify();
640    }
641
642    /// Changes the display mode while preserving source-line selection and a
643    /// nearby source row.
644    pub fn set_mode(&mut self, mode: DiffMode, cx: &mut Context<Self>) {
645        if self.mode == mode {
646            return;
647        }
648        self.mode = mode;
649        // A diff shown from its top stays there: the top row's anchor is the
650        // file's first line, and revealing it scrolls the header off when
651        // rows wrap to heights the list has not measured yet.
652        let top = self.list.logical_scroll_top();
653        let at_top = top.item_ix == 0 && top.offset_in_item <= px(0.);
654        self.rebuild_at_anchor();
655        if at_top {
656            self.list.scroll_to(ListOffset {
657                item_ix: 0,
658                offset_in_item: px(0.),
659            });
660        }
661        self.horizontal_scroll.set_offset(point(px(0.), px(0.)));
662        cx.notify();
663    }
664
665    /// Sets surrounding context. `None` shows every supplied patch line.
666    pub fn set_context_lines(&mut self, lines: Option<usize>, cx: &mut Context<Self>) {
667        if self.context_lines == lines {
668            return;
669        }
670        self.context_lines = lines;
671        self.expanded.iter_mut().for_each(Vec::clear);
672        self.rebuild_at_anchor();
673        cx.notify();
674    }
675
676    /// Reveals all unchanged source while preserving the configured context count.
677    pub fn expand_unchanged(&mut self, cx: &mut Context<Self>) {
678        for (expanded, file) in self.expanded.iter_mut().zip(&self.files) {
679            *expanded = vec![0..file.pairs().len()];
680        }
681        self.rebuild_at_anchor();
682        cx.notify();
683    }
684
685    /// Restores the configured context disclosures.
686    pub fn collapse_unchanged(&mut self, cx: &mut Context<Self>) {
687        self.expanded.iter_mut().for_each(Vec::clear);
688        self.rebuild_at_anchor();
689        cx.notify();
690    }
691
692    /// Collapses the given files to their headers, or expands them, without
693    /// emitting a user event. One rebuild covers the whole change; calling
694    /// [`Self::set_file_collapsed`] per file rebuilds the rows each time,
695    /// which freezes a view of thousands of files.
696    pub fn set_files_collapsed(
697        &mut self,
698        paths: impl IntoIterator<Item = SharedString>,
699        collapsed: bool,
700        cx: &mut Context<Self>,
701    ) {
702        let mut changed = false;
703        for path in paths {
704            let Some(ix) = self.file_ix(&path) else {
705                continue;
706            };
707            let path = self.files[ix].path().clone();
708            changed |= if collapsed {
709                self.collapsed.insert(path)
710            } else {
711                self.collapsed.remove(&path)
712            };
713        }
714        if changed {
715            self.rebuild_at_anchor();
716            cx.notify();
717        }
718    }
719
720    /// Collapses every file to its header, or expands them all, in one
721    /// rebuild like [`Self::set_files_collapsed`].
722    pub fn set_all_files_collapsed(&mut self, collapsed: bool, cx: &mut Context<Self>) {
723        let paths: Vec<SharedString> = self.files.iter().map(|file| file.path().clone()).collect();
724        self.set_files_collapsed(paths, collapsed, cx);
725    }
726
727    /// Collapses the file at `path` to its header, or expands it, without
728    /// emitting a user event.
729    pub fn set_file_collapsed(&mut self, path: &str, collapsed: bool, cx: &mut Context<Self>) {
730        let Some(file) = self.file_ix(path) else {
731            return;
732        };
733        let path = self.files[file].path().clone();
734        let changed = if collapsed {
735            self.collapsed.insert(path)
736        } else {
737            self.collapsed.remove(&path)
738        };
739        if changed {
740            self.rebuild_at_anchor();
741            cx.notify();
742        }
743    }
744
745    /// The resolution of conflict `ix` in the file at `path`, if any.
746    /// Use [`DiffFile::conflicts`] to enumerate valid indices; `None` means
747    /// unresolved, or that the file or index does not exist.
748    pub fn conflict_resolution(&self, path: &str, ix: usize) -> Option<DiffConflictResolution> {
749        let file = &self.files[self.file_ix(path)?];
750        self.resolutions.get(&(file.path().clone(), ix)).copied()
751    }
752
753    /// Resolves conflict `ix` (an index in [`DiffFile::conflicts`]) in the file
754    /// at `path`, or clears its resolution
755    /// with `None`, without emitting a user event.
756    pub fn resolve_conflict(
757        &mut self,
758        path: &str,
759        ix: usize,
760        resolution: Option<DiffConflictResolution>,
761        cx: &mut Context<Self>,
762    ) {
763        let Some(file) = self.file_ix(path) else {
764            return;
765        };
766        if ix >= self.files[file].conflicts().len() {
767            return;
768        }
769        let key = (self.files[file].path().clone(), ix);
770        let previous = match resolution {
771            Some(resolution) => self.resolutions.insert(key, resolution),
772            None => self.resolutions.remove(&key),
773        };
774        if previous != resolution {
775            self.rebuild_at_anchor();
776            cx.notify();
777        }
778    }
779
780    /// The working file with every conflict replaced by its resolution, or
781    /// `None` while a conflict is unresolved or `path` names no conflicted file.
782    pub fn resolved_text(&self, path: &str) -> Option<String> {
783        let file = &self.files[self.file_ix(path)?];
784        if file.status() != DiffFileStatus::Conflicted {
785            return None;
786        }
787        let lines = file.lines(DiffSide::Modified);
788        let source = file.source(DiffSide::Modified);
789        let mut text = String::with_capacity(source.len());
790        let mut ix = 0;
791        for (conflict_ix, conflict) in file.conflicts().iter().enumerate() {
792            let resolution = *self.resolutions.get(&(file.path().clone(), conflict_ix))?;
793            for line in &lines[ix..conflict.source_lines().start] {
794                text.push_str(&source[line.source()]);
795            }
796            for range in conflict.kept(resolution) {
797                for line in &lines[range] {
798                    text.push_str(&source[line.source()]);
799                }
800            }
801            ix = conflict.source_lines().end;
802        }
803        for line in &lines[ix..] {
804            text.push_str(&source[line.source()]);
805        }
806        Some(text)
807    }
808
809    /// Synchronizes source-line selection without emitting a user event.
810    /// Clips to supplied patch lines; a range containing none clears selection.
811    pub fn set_selected_lines(&mut self, range: Option<DiffLineRange>, cx: &mut Context<Self>) {
812        let range = range.and_then(|range| self.clip_range(&range));
813        if self.selected_lines == range {
814            return;
815        }
816        self.selection_anchor = range.as_ref().map(DiffLineRange::start_position);
817        self.selection_cursor = range.as_ref().map(DiffLineRange::end_position);
818        self.selection.set_local_selection(range.is_some(), cx);
819        self.selected_lines = range;
820        cx.notify();
821    }
822
823    /// Returns selected source without gutters, diff markers or annotation content.
824    pub fn selected_text(&self, cx: &App) -> String {
825        if self.selection.has_local_selection(cx)
826            && let Some(selected) = self.selected_span()
827        {
828            return match selected {
829                SelectedLines::Side { file, side, lines } => {
830                    self.files[file].text_for_lines(side, lines.start, lines.end - 1)
831                }
832                SelectedLines::Patch { file, patch } => {
833                    let file = &self.files[file];
834                    let mut text = String::new();
835                    for line in &file.patch_lines()[patch] {
836                        // An unchanged line reads the same on both sides.
837                        let (side, ix) = match line.line(DiffSide::Modified) {
838                            Some(ix) => (DiffSide::Modified, ix),
839                            None => (
840                                DiffSide::Original,
841                                line.line(DiffSide::Original).unwrap_or(0),
842                            ),
843                        };
844                        // A side's unterminated final line can precede the
845                        // other side's lines in patch order.
846                        if !text.is_empty() && !text.ends_with('\n') {
847                            text.push('\n');
848                        }
849                        text.push_str(&file.source(side)[file.lines(side)[ix].source()]);
850                    }
851                    text
852                }
853            };
854        }
855        let Some((file, side, range)) =
856            super::selection::selected_source_range(&self.selection, cx)
857        else {
858            return String::new();
859        };
860        self.files
861            .get(file)
862            .and_then(|file| file.source(side).get(range))
863            .unwrap_or("")
864            .to_owned()
865    }
866
867    /// Reveals and scrolls to a source line, expanding its file and hidden
868    /// context if needed.
869    pub fn scroll_to_line(&mut self, position: DiffLinePosition, cx: &mut Context<Self>) {
870        if self.line_index(&position).is_none() {
871            return;
872        }
873        if self.collapsed.remove(position.path().as_str()) {
874            self.rebuild_at_anchor();
875        }
876        if self.expand_line(&position).is_some() {
877            self.reveal_line(&position);
878            cx.notify();
879        }
880    }
881
882    /// Scrolls to the header of the file at `path`, a [`DiffFile::path`].
883    pub fn scroll_to_file(&mut self, path: &str, cx: &mut Context<Self>) {
884        let Some(item_ix) = self
885            .file_ix(path)
886            .and_then(|file| self.header_rows.get(file).copied())
887        else {
888            return;
889        };
890        self.list.scroll_to(ListOffset {
891            item_ix,
892            offset_in_item: px(0.),
893        });
894        cx.notify();
895    }
896
897    /// Moves to the next changed group after the current viewport, across files,
898    /// wrapping to the first once the list is scrolled to its end.
899    pub fn next_change(&mut self, cx: &mut Context<Self>) {
900        self.move_change(true, cx);
901    }
902    /// Moves to the previous changed group before the current viewport, across files.
903    pub fn previous_change(&mut self, cx: &mut Context<Self>) {
904        self.move_change(false, cx);
905    }
906
907    /// Reveals part or all of a collapsed unchanged range.
908    pub(crate) fn expand_fold(
909        &mut self,
910        file: usize,
911        pairs: Range<usize>,
912        expansion: FoldExpansion,
913        cx: &mut Context<Self>,
914    ) {
915        let lines = self.expansion_lines;
916        let revealed = match expansion {
917            FoldExpansion::All => pairs,
918            FoldExpansion::Up => pairs.end.saturating_sub(lines).max(pairs.start)..pairs.end,
919            FoldExpansion::Down => pairs.start..(pairs.start + lines).min(pairs.end),
920        };
921        if let Some(expanded) = self.expanded.get_mut(file) {
922            expanded.push(revealed);
923            self.rebuild_at_anchor();
924            cx.notify();
925        }
926    }
927
928    /// Resolves a conflict from its heading and reports the user's change.
929    pub(crate) fn choose_conflict(
930        &mut self,
931        file: usize,
932        ix: usize,
933        resolution: Option<DiffConflictResolution>,
934        cx: &mut Context<Self>,
935    ) {
936        let path = self.files[file].path().clone();
937        self.resolve_conflict(&path, ix, resolution, cx);
938        cx.emit(DiffEvent::ConflictResolved(path, ix));
939    }
940
941    /// Toggles a file from its header and reports the user's change.
942    pub(crate) fn toggle_file_collapsed(&mut self, file: usize, cx: &mut Context<Self>) {
943        let path = self.files[file].path().clone();
944        let collapsed = !self.collapsed.contains(&path);
945        self.set_file_collapsed(&path, collapsed, cx);
946        cx.emit(if collapsed {
947            DiffEvent::FileCollapsed(path)
948        } else {
949            DiffEvent::FileExpanded(path)
950        });
951    }
952
953    /// Starts a line-number selection gesture, extending the current anchor in
954    /// the same file when `extend` is set.
955    pub(crate) fn begin_line_selection(
956        &mut self,
957        position: DiffLinePosition,
958        extend: bool,
959        window: &mut Window,
960        cx: &mut Context<Self>,
961    ) {
962        if self.line_index(&position).is_none() {
963            return;
964        }
965        let anchor = self
966            .selection_anchor
967            .clone()
968            .filter(|anchor| extend && self.can_extend(anchor, &position))
969            .unwrap_or_else(|| position.clone());
970        TextSelection::clear(window, cx);
971        window.focus(&self.focus, cx);
972        self.selecting = true;
973        cx.emit(DiffEvent::SelectionStarted(range_between(
974            &anchor, &position,
975        )));
976        self.select_user_range(anchor, position, cx);
977    }
978
979    /// Extends an active line-number gesture to `position` in the same file.
980    pub(crate) fn drag_line_selection(
981        &mut self,
982        position: DiffLinePosition,
983        cx: &mut Context<Self>,
984    ) {
985        let Some(anchor) = self.selection_anchor.clone() else {
986            return;
987        };
988        if !self.selecting
989            || !self.can_extend(&anchor, &position)
990            || self.selection_cursor.as_ref() == Some(&position)
991            || self.line_index(&position).is_none()
992        {
993            return;
994        }
995        self.select_user_range(anchor, position, cx);
996    }
997
998    /// Whether a selection anchored at `anchor` may extend to `position`:
999    /// within one file, and across sides only in Unified mode, whose rows
1000    /// follow patch order.
1001    fn can_extend(&self, anchor: &DiffLinePosition, position: &DiffLinePosition) -> bool {
1002        anchor.path() == position.path()
1003            && (anchor.side() == position.side() || self.mode == DiffMode::Unified)
1004    }
1005
1006    /// Finishes an active line-number gesture.
1007    pub(crate) fn end_line_selection(&mut self, cx: &mut Context<Self>) {
1008        if !std::mem::take(&mut self.selecting) {
1009            return;
1010        }
1011        if let Some(range) = self.selected_lines.clone() {
1012            cx.emit(DiffEvent::SelectionEnded(range));
1013        }
1014    }
1015
1016    /// Selects one line, or extends to it, as a complete gesture.
1017    #[cfg(test)]
1018    pub(crate) fn click_line(
1019        &mut self,
1020        position: DiffLinePosition,
1021        extend: bool,
1022        window: &mut Window,
1023        cx: &mut Context<Self>,
1024    ) {
1025        self.begin_line_selection(position, extend, window, cx);
1026        self.end_line_selection(cx);
1027    }
1028
1029    pub(crate) fn keyboard_select(
1030        &mut self,
1031        direction: isize,
1032        extend: bool,
1033        window: &mut Window,
1034        cx: &mut Context<Self>,
1035    ) {
1036        let Some((file, side)) = self.active_side(cx) else {
1037            return;
1038        };
1039        let count = self.files[file].lines_count(side);
1040        let ix = self
1041            .selection_cursor
1042            .as_ref()
1043            .filter(|position| {
1044                position.side() == side && self.file_ix(position.path()) == Some(file)
1045            })
1046            .and_then(|position| self.line_index(position))
1047            .map(|ix| ix.saturating_add_signed(direction).min(count - 1))
1048            .unwrap_or(0);
1049        let position = self.position(file, side, ix);
1050        let anchor = self
1051            .selection_anchor
1052            .clone()
1053            .filter(|anchor| extend && anchor.path() == position.path())
1054            .unwrap_or_else(|| position.clone());
1055        TextSelection::clear(window, cx);
1056        window.focus(&self.focus, cx);
1057        let range = self.select_user_range(anchor, position.clone(), cx);
1058        cx.emit(DiffEvent::SelectionEnded(range));
1059        if let Some(row) = self.expand_line(&position) {
1060            self.list.scroll_to_reveal_item(row);
1061        }
1062    }
1063
1064    pub(crate) fn select_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1065        let Some((file, side)) = self.active_side(cx) else {
1066            return;
1067        };
1068        let count = self.files[file].lines_count(side);
1069        TextSelection::clear(window, cx);
1070        window.focus(&self.focus, cx);
1071        let range = self.select_user_range(
1072            self.position(file, side, 0),
1073            self.position(file, side, count - 1),
1074            cx,
1075        );
1076        cx.emit(DiffEvent::SelectionEnded(range));
1077    }
1078
1079    /// The selected lines, resolved for membership tests.
1080    pub(crate) fn selected_span(&self) -> Option<SelectedLines> {
1081        let range = self.selected_lines.as_ref()?;
1082        let file = self.file_ix(range.path())?;
1083        if range.is_single_side() {
1084            let (start, end) = (
1085                range.start().min(range.end()),
1086                range.start().max(range.end()),
1087            );
1088            return Some(SelectedLines::Side {
1089                file,
1090                side: range.side(),
1091                lines: start..end + 1,
1092            });
1093        }
1094        let document = &self.files[file];
1095        let start = document.patch_ix(
1096            range.side(),
1097            document.line_index(range.side(), range.start())?,
1098        );
1099        let end = document.patch_ix(
1100            range.end_side(),
1101            document.line_index(range.end_side(), range.end())?,
1102        );
1103        Some(SelectedLines::Patch {
1104            file,
1105            patch: start.min(end)..start.max(end) + 1,
1106        })
1107    }
1108
1109    /// Records the window that renders this state, for clearing its text selection.
1110    pub(crate) fn set_window(&mut self, window: WindowId) {
1111        self.window = Some(window);
1112    }
1113
1114    /// Updates width and row-height measurement when fonts or layout change.
1115    /// Returns whether content width must be measured again.
1116    pub(crate) fn update_layout(&mut self, key: LayoutKey, row_height: Pixels) -> bool {
1117        if self.layout.as_ref() == Some(&key) {
1118            return false;
1119        }
1120        if self.layout.is_some() {
1121            self.list.remeasure();
1122        }
1123        self.layout = Some(key);
1124        self.row_height = Some(row_height);
1125        self.apply_row_height_hint();
1126        true
1127    }
1128
1129    /// Re-measures rows whose annotations were added, removed or replaced.
1130    /// Visible rows are re-measured every frame, so content changes inside an
1131    /// annotation need no notification.
1132    pub(crate) fn sync_annotations(&mut self, annotations: &[DiffAnnotation]) {
1133        let current = annotations
1134            .iter()
1135            .map(|annotation| {
1136                (
1137                    annotation.position().cloned(),
1138                    annotation.path().clone(),
1139                    annotation.id().clone(),
1140                )
1141            })
1142            .collect::<HashSet<_>>();
1143        if current == self.annotations {
1144            return;
1145        }
1146        let rows = current
1147            .symmetric_difference(&self.annotations)
1148            .filter_map(|(position, path, _)| match position {
1149                Some(position) => self.source_row(position),
1150                None => self
1151                    .file_ix(path)
1152                    .and_then(|file| self.header_rows.get(file).copied()),
1153            })
1154            .collect::<Vec<_>>();
1155        for row in rows {
1156            self.list.remeasure_items(row..row + 1);
1157        }
1158        self.annotations = current;
1159    }
1160
1161    pub(crate) fn position(&self, file: usize, side: DiffSide, ix: usize) -> DiffLinePosition {
1162        let document = &self.files[file];
1163        DiffLinePosition::new(
1164            document.path().clone(),
1165            side,
1166            document.line_number(side, ix),
1167        )
1168    }
1169
1170    fn file_ix(&self, path: &str) -> Option<usize> {
1171        self.file_ixs.get(path).copied()
1172    }
1173
1174    fn line_index(&self, position: &DiffLinePosition) -> Option<usize> {
1175        self.files[self.file_ix(position.path())?].line_index(position.side(), position.line())
1176    }
1177
1178    /// Clips a range to supplied lines, normalizing a single-side range.
1179    fn clip_range(&self, range: &DiffLineRange) -> Option<DiffLineRange> {
1180        let file = &self.files[self.file_ix(range.path())?];
1181        let first_at_or_after = |side: DiffSide, line: usize| {
1182            let lines = file.lines(side);
1183            lines
1184                .get(lines.partition_point(|source| source.line_number() < line))
1185                .map(|source| source.line_number())
1186        };
1187        let last_at_or_before = |side: DiffSide, line: usize| {
1188            let lines = file.lines(side);
1189            lines
1190                .partition_point(|source| source.line_number() <= line)
1191                .checked_sub(1)
1192                .map(|ix| lines[ix].line_number())
1193        };
1194        if range.is_single_side() {
1195            let (start, end) = (
1196                range.start().min(range.end()),
1197                range.start().max(range.end()),
1198            );
1199            let start = first_at_or_after(range.side(), start)?;
1200            let end = last_at_or_before(range.side(), end)?;
1201            return (start <= end)
1202                .then(|| DiffLineRange::new(range.path().clone(), range.side(), start, end));
1203        }
1204        let start = first_at_or_after(range.side(), range.start())
1205            .or_else(|| last_at_or_before(range.side(), range.start()))?;
1206        let end = last_at_or_before(range.end_side(), range.end())
1207            .or_else(|| first_at_or_after(range.end_side(), range.end()))?;
1208        Some(
1209            DiffLineRange::new(range.path().clone(), range.side(), start, end)
1210                .with_end_side(range.end_side()),
1211        )
1212    }
1213
1214    fn selection_is_local(&self, cx: &App) -> bool {
1215        let entity = Some(self.selection.entity_id());
1216        self.selection
1217            .snapshot(cx)
1218            .is_some_and(|snapshot| snapshot.anchor().entity_id() == entity)
1219    }
1220
1221    /// The file and side that keyboard selection and Select All act on.
1222    fn active_side(&self, cx: &App) -> Option<(usize, DiffSide)> {
1223        let (file, side) = self
1224            .selection_cursor
1225            .as_ref()
1226            .and_then(|cursor| Some((self.file_ix(cursor.path())?, Some(cursor.side()))))
1227            .filter(|_| self.selected_lines.is_some())
1228            .or_else(|| {
1229                super::selection::selected_source_range(&self.selection, cx)
1230                    .map(|(file, side, _)| (file, Some(side)))
1231            })
1232            .or_else(|| {
1233                let top = self.list.logical_scroll_top().item_ix;
1234                self.rows.get(top).map(|row| (row.file(), None))
1235            })?;
1236        let document = self.files.get(file)?;
1237        let side = side.unwrap_or(if document.lines_count(DiffSide::Modified) > 0 {
1238            DiffSide::Modified
1239        } else {
1240            DiffSide::Original
1241        });
1242        (document.lines_count(side) > 0).then_some((file, side))
1243    }
1244
1245    fn expand_line(&mut self, position: &DiffLinePosition) -> Option<usize> {
1246        let row = self.source_row(position)?;
1247        if let Some(DisplayRow::Fold { file, pairs }) = self.rows.get(row) {
1248            let (file, pairs) = (*file, pairs.clone());
1249            self.expanded[file].push(pairs);
1250            self.rebuild_at_anchor();
1251        }
1252        self.source_row(position)
1253    }
1254
1255    /// Selects from `anchor` to `cursor` in one file and reports a change.
1256    fn select_user_range(
1257        &mut self,
1258        anchor: DiffLinePosition,
1259        cursor: DiffLinePosition,
1260        cx: &mut Context<Self>,
1261    ) -> DiffLineRange {
1262        let range = range_between(&anchor, &cursor);
1263        let changed = self.selected_lines.as_ref() != Some(&range);
1264        self.selected_lines = Some(range.clone());
1265        self.selection_anchor = Some(anchor);
1266        self.selection_cursor = Some(cursor);
1267        self.selection.set_local_selection(true, cx);
1268        if changed {
1269            cx.emit(DiffEvent::SelectionChanged(Some(range.clone())));
1270        }
1271        cx.notify();
1272        range
1273    }
1274
1275    fn move_change(&mut self, forward: bool, cx: &mut Context<Self>) {
1276        let top = self.list.logical_scroll_top().item_ix;
1277        let groups = &self.change_rows;
1278        let target = if forward {
1279            // Scrolled to the end, the list clamps any later change below the
1280            // top, so the top never passes it and the key would stop there.
1281            // The last row's bounds answer even when the rows above the
1282            // viewport were never measured, as after a jump to the end.
1283            let at_end = self
1284                .list
1285                .item_count()
1286                .checked_sub(1)
1287                .and_then(|last| self.list.bounds_for_item(last))
1288                .is_some_and(|last| last.bottom() <= self.list.viewport_bounds().bottom());
1289            groups
1290                .get(groups.partition_point(|ix| *ix <= top))
1291                .copied()
1292                .filter(|_| !at_end)
1293                .or(groups.first().copied())
1294        } else {
1295            groups
1296                .partition_point(|ix| *ix < top)
1297                .checked_sub(1)
1298                .and_then(|ix| groups.get(ix))
1299                .copied()
1300                .or(groups.last().copied())
1301        };
1302        if let Some(ix) = target {
1303            self.list.scroll_to(ListOffset {
1304                item_ix: ix,
1305                offset_in_item: px(0.),
1306            });
1307            cx.notify();
1308        }
1309    }
1310
1311    /// The source line shown by a row, looking past headers within its file.
1312    fn row_position(&self, ix: usize) -> Option<DiffLinePosition> {
1313        let row = self.rows.get(ix)?;
1314        let file = row.file();
1315        let pair_position = |original: Option<usize>, modified: Option<usize>| {
1316            modified
1317                .map(|ix| self.position(file, DiffSide::Modified, ix))
1318                .or_else(|| original.map(|ix| self.position(file, DiffSide::Original, ix)))
1319        };
1320        match row {
1321            DisplayRow::Code {
1322                original, modified, ..
1323            } => pair_position(*original, *modified),
1324            DisplayRow::Fold { pairs, .. } => self.files[file]
1325                .pairs()
1326                .get(pairs.start)
1327                .and_then(|pair| pair_position(pair.original(), pair.modified())),
1328            DisplayRow::File(_)
1329            | DisplayRow::Notice(_)
1330            | DisplayRow::Hunk { .. }
1331            | DisplayRow::Conflict { .. } => self
1332                .rows
1333                .get(ix + 1)
1334                .filter(|next| next.file() == file)
1335                .and_then(|_| self.row_position(ix + 1)),
1336        }
1337    }
1338
1339    pub(crate) fn source_row(&self, position: &DiffLinePosition) -> Option<usize> {
1340        let rows = self.file_rows.get(self.file_ix(position.path())?)?;
1341        let rows = match position.side() {
1342            DiffSide::Original => &rows.original,
1343            DiffSide::Modified => &rows.modified,
1344        };
1345        rows.get(self.line_index(position)?).copied().flatten()
1346    }
1347
1348    fn reveal_line(&self, position: &DiffLinePosition) {
1349        if let Some(item_ix) = self.source_row(position) {
1350            self.list.scroll_to(ListOffset {
1351                item_ix,
1352                offset_in_item: px(0.),
1353            });
1354        }
1355    }
1356
1357    /// Rebuilds rows and restores the source line at the top of the viewport.
1358    fn rebuild_at_anchor(&mut self) {
1359        let anchor = self.row_position(self.list.logical_scroll_top().item_ix);
1360        self.rebuild(false);
1361        if let Some(anchor) = anchor {
1362            self.reveal_line(&anchor);
1363        }
1364    }
1365
1366    /// Projects rows. Without `reset`, only the changed middle is spliced so
1367    /// measured heights of unchanged rows survive disclosure changes.
1368    fn rebuild(&mut self, reset: bool) {
1369        let rows = self.project_rows();
1370        self.file_rows = source_rows(&self.files, &rows);
1371        self.change_rows = changed_groups(&rows);
1372        self.header_rows = rows
1373            .iter()
1374            .enumerate()
1375            .filter_map(|(ix, row)| matches!(row, DisplayRow::File(_)).then_some(ix))
1376            .collect();
1377        if reset {
1378            self.list.reset(rows.len());
1379        } else {
1380            let old = &self.rows;
1381            let prefix = old.iter().zip(&rows).take_while(|(a, b)| a == b).count();
1382            let suffix = old
1383                .iter()
1384                .rev()
1385                .zip(rows.iter().rev())
1386                .take(old.len().min(rows.len()) - prefix)
1387                .take_while(|(a, b)| a == b)
1388                .count();
1389            self.list
1390                .splice(prefix..old.len() - suffix, rows.len() - prefix - suffix);
1391        }
1392        self.rows = Rc::new(rows);
1393        self.apply_row_height_hint();
1394    }
1395
1396    fn project_rows(&self) -> Vec<DisplayRow> {
1397        let mut rows = Vec::new();
1398        for (ix, file) in self.files.iter().enumerate() {
1399            rows.push(DisplayRow::File(ix));
1400            if self.collapsed.contains(file.path()) {
1401                continue;
1402            }
1403            if file.pairs().is_empty() {
1404                rows.push(DisplayRow::Notice(ix));
1405            } else if file.status() == DiffFileStatus::Unchanged {
1406                rows.extend((0..file.pairs().len()).map(|line| DisplayRow::Code {
1407                    file: ix,
1408                    original: None,
1409                    modified: Some(line),
1410                    changed: false,
1411                }));
1412            } else if file.status() == DiffFileStatus::Conflicted {
1413                let resolutions = (0..file.conflicts().len())
1414                    .map(|conflict| {
1415                        self.resolutions
1416                            .get(&(file.path().clone(), conflict))
1417                            .copied()
1418                    })
1419                    .collect::<Vec<_>>();
1420                let visible = visible_pairs(
1421                    file,
1422                    self.context_lines,
1423                    self.min_collapsed_lines,
1424                    &self.expanded[ix],
1425                );
1426                project_conflicts(&mut rows, ix, file, &visible, &resolutions);
1427            } else {
1428                project_file(
1429                    &mut rows,
1430                    ix,
1431                    file,
1432                    self.mode,
1433                    self.context_lines,
1434                    self.min_collapsed_lines,
1435                    &self.expanded[ix],
1436                );
1437            }
1438        }
1439        rows
1440    }
1441
1442    /// Applies the row-height hint again once the list has laid out at a new
1443    /// width. Returns whether it did, so the frame must be laid out again.
1444    ///
1445    /// A list that lays out at a new width forgets every row height, hints
1446    /// included, which happens on its first layout too. The patch then
1447    /// measures only the rows rendered so far, and scrolling stops once the
1448    /// last of them reaches the bottom of the viewport. Call this after the
1449    /// list's prepaint, so the hint is back before the next wheel event.
1450    pub(crate) fn keep_row_height_hint(&mut self) -> bool {
1451        let width = self.list.viewport_bounds().size.width;
1452        if self.row_height.is_none() || self.hinted_width == Some(width) {
1453            return false;
1454        }
1455        self.hinted_width = Some(width);
1456        self.apply_row_height_hint();
1457        true
1458    }
1459
1460    /// Gives unmeasured rows a code-row height so the scrollbar is sized for
1461    /// the whole patch before every row has been rendered.
1462    fn apply_row_height_hint(&self) {
1463        if let Some(height) = self.row_height {
1464            let _ = self.list.clone().with_uniform_item_height(height);
1465        }
1466    }
1467
1468    /// Discards prepared emphasis after files or options change.
1469    fn reset_presentation(&mut self) {
1470        self.presentations = vec![None; self.files.len()];
1471        self.presentation_generation += 1;
1472        self.preparing = None;
1473        self._presentation = Task::ready(());
1474    }
1475
1476    /// Prepares syntax and inline emphasis for files that lack it, one file at
1477    /// a time on the background executor, reusing highlighters per language.
1478    /// Starts on first render, so builders applied after `new` take effect.
1479    pub(crate) fn ensure_presentation(&mut self, cx: &mut Context<Self>) {
1480        let generation = self.presentation_generation;
1481        if self.preparing == Some(generation) {
1482            return;
1483        }
1484        let pending = self
1485            .presentations
1486            .iter()
1487            .enumerate()
1488            .filter(|(_, presentation)| presentation.is_none())
1489            .map(|(ix, _)| (ix, self.files[ix].clone()))
1490            .collect::<Vec<_>>();
1491        if pending.is_empty() {
1492            return;
1493        }
1494        let options = self.presentation_options;
1495        let custom = self.syntax_highlighter.clone();
1496        self.preparing = Some(generation);
1497        self._presentation = cx.spawn(async move |this, cx| {
1498            let mut highlighters = Some(SyntaxHighlighters::default());
1499            for (ix, file) in pending {
1500                let mut moved = highlighters.take();
1501                let custom = custom.clone();
1502                let (presentation, returned) = cx
1503                    .background_spawn(async move {
1504                        let presentation = FilePresentation::prepare(
1505                            &file,
1506                            options,
1507                            moved.get_or_insert_default(),
1508                            custom.as_ref(),
1509                        );
1510                        (presentation, moved)
1511                    })
1512                    .await;
1513                highlighters = returned;
1514                let current = this.update(cx, |state, cx| {
1515                    if state.presentation_generation != generation {
1516                        return false;
1517                    }
1518                    if let Some(slot) = state.presentations.get_mut(ix) {
1519                        *slot = Some(Arc::new(presentation));
1520                    }
1521                    cx.notify();
1522                    true
1523                });
1524                if !matches!(current, Ok(true)) {
1525                    return;
1526                }
1527            }
1528        });
1529    }
1530}
1531
1532/// The range from `anchor` to `cursor`, normalized when both are on one side.
1533fn range_between(anchor: &DiffLinePosition, cursor: &DiffLinePosition) -> DiffLineRange {
1534    if anchor.side() == cursor.side() {
1535        DiffLineRange::new(
1536            cursor.path().clone(),
1537            cursor.side(),
1538            anchor.line().min(cursor.line()),
1539            anchor.line().max(cursor.line()),
1540        )
1541    } else {
1542        DiffLineRange::new(
1543            cursor.path().clone(),
1544            anchor.side(),
1545            anchor.line(),
1546            cursor.line(),
1547        )
1548        .with_end_side(cursor.side())
1549    }
1550}
1551
1552fn file_ixs(files: &[DiffFile]) -> HashMap<SharedString, usize> {
1553    let mut ixs = HashMap::with_capacity(files.len());
1554    for (ix, file) in files.iter().enumerate() {
1555        ixs.entry(file.path().clone()).or_insert(ix);
1556    }
1557    ixs
1558}
1559
1560/// Every source line maps to its code row or the disclosure hiding it; lines
1561/// of a collapsed file have no row. Disjoint folds visit each pair once, so
1562/// building the maps is linear.
1563fn source_rows(files: &[DiffFile], rows: &[DisplayRow]) -> Vec<FileRows> {
1564    let mut file_rows = files
1565        .iter()
1566        .map(|file| FileRows {
1567            original: vec![None; file.lines_count(DiffSide::Original)],
1568            modified: vec![None; file.lines_count(DiffSide::Modified)],
1569        })
1570        .collect::<Vec<_>>();
1571    for (row_ix, row) in rows.iter().enumerate() {
1572        let mut map = |file: usize, original: Option<usize>, modified: Option<usize>| {
1573            if let Some(line) = original {
1574                file_rows[file].original[line] = Some(row_ix);
1575            }
1576            if let Some(line) = modified {
1577                file_rows[file].modified[line] = Some(row_ix);
1578            }
1579        };
1580        match row {
1581            DisplayRow::Code {
1582                file,
1583                original,
1584                modified,
1585                ..
1586            } => map(*file, *original, *modified),
1587            DisplayRow::Fold { file, pairs } => {
1588                for pair in &files[*file].pairs()[pairs.clone()] {
1589                    map(*file, pair.original(), pair.modified());
1590                }
1591            }
1592            DisplayRow::File(_)
1593            | DisplayRow::Notice(_)
1594            | DisplayRow::Hunk { .. }
1595            | DisplayRow::Conflict { .. } => {}
1596        }
1597    }
1598    file_rows
1599}
1600
1601fn changed_groups(rows: &[DisplayRow]) -> Vec<usize> {
1602    let changed = |row: &DisplayRow| matches!(row, DisplayRow::Code { changed: true, .. });
1603    rows.iter()
1604        .enumerate()
1605        .filter_map(|(ix, row)| {
1606            (changed(row)
1607                && (ix == 0 || !changed(&rows[ix - 1]) || rows[ix - 1].file() != row.file()))
1608            .then_some(ix)
1609        })
1610        .collect()
1611}
1612
1613const SIDE_BIT: u64 = 1 << 40;
1614const OFFSET_MASK: u64 = SIDE_BIT - 1;
1615
1616/// Packs a source offset into a selection key, ordered by file, side and offset.
1617pub(crate) fn encode_key(file: usize, side: DiffSide, offset: usize) -> u64 {
1618    ((file as u64) << 41)
1619        | if side == DiffSide::Modified {
1620            SIDE_BIT
1621        } else {
1622            0
1623        }
1624        | (offset as u64 & OFFSET_MASK)
1625}
1626pub(crate) fn decode_key(key: u64) -> (usize, DiffSide, usize) {
1627    (
1628        (key >> 41) as usize,
1629        if key & SIDE_BIT == 0 {
1630            DiffSide::Original
1631        } else {
1632            DiffSide::Modified
1633        },
1634        (key & OFFSET_MASK) as usize,
1635    )
1636}
1637
1638/// The end of the hunk containing each pair; a fixture without hunks is one.
1639fn hunk_ends(document: &DiffFile) -> Vec<usize> {
1640    let pairs = document.pairs();
1641    let mut hunk_end = vec![pairs.len(); pairs.len()];
1642    for hunk in document.hunks() {
1643        hunk_end[hunk.pairs()].fill(hunk.pairs().end);
1644    }
1645    hunk_end
1646}
1647
1648/// Which pairs show as code: changes with their context, expanded ranges,
1649/// and collapsed ranges shorter than `min_collapsed_lines`.
1650fn visible_pairs(
1651    document: &DiffFile,
1652    context: Option<usize>,
1653    min_collapsed_lines: usize,
1654    expanded: &[Range<usize>],
1655) -> Vec<bool> {
1656    let pairs = document.pairs();
1657    let hunks = document.hunks();
1658    let mut hunk_end = vec![pairs.len(); pairs.len()];
1659    let mut hunk_start = vec![0; pairs.len()];
1660    for hunk in hunks {
1661        hunk_start[hunk.pairs()].fill(hunk.pairs().start);
1662        hunk_end[hunk.pairs()].fill(hunk.pairs().end);
1663    }
1664    // Interval boundaries avoid repeatedly filling overlapping context windows.
1665    // Projection remains linear in source lines plus the number of disclosures.
1666    let mut boundaries = vec![0isize; pairs.len() + 1];
1667    if let Some(context) = context {
1668        let mut ix = 0;
1669        while ix < pairs.len() {
1670            if !pairs[ix].is_changed() {
1671                ix += 1;
1672                continue;
1673            }
1674            let start = ix;
1675            while ix < pairs.len() && ix < hunk_end[start] && pairs[ix].is_changed() {
1676                ix += 1;
1677            }
1678            boundaries[start.saturating_sub(context).max(hunk_start[start])] += 1;
1679            boundaries[ix.saturating_add(context).min(hunk_end[start])] -= 1;
1680        }
1681    } else {
1682        boundaries[0] += 1;
1683        boundaries[pairs.len()] -= 1;
1684    }
1685    for range in expanded {
1686        let start = range.start.min(pairs.len());
1687        let end = range.end.min(pairs.len());
1688        if start < end {
1689            boundaries[start] += 1;
1690            boundaries[end] -= 1;
1691        }
1692    }
1693    let mut active = 0;
1694    let mut visible = boundaries[..pairs.len()]
1695        .iter()
1696        .map(|boundary| {
1697            active += boundary;
1698            active > 0
1699        })
1700        .collect::<Vec<_>>();
1701    // A disclosure shorter than the threshold would hide almost nothing.
1702    let mut ix = 0;
1703    while ix < pairs.len() {
1704        if visible[ix] {
1705            ix += 1;
1706            continue;
1707        }
1708        let start = ix;
1709        while ix < pairs.len() && ix < hunk_end[start] && !visible[ix] {
1710            ix += 1;
1711        }
1712        if ix - start < min_collapsed_lines {
1713            visible[start..ix].fill(true);
1714        }
1715    }
1716    visible
1717}
1718
1719fn project_file(
1720    rows: &mut Vec<DisplayRow>,
1721    file: usize,
1722    document: &DiffFile,
1723    mode: DiffMode,
1724    context: Option<usize>,
1725    min_collapsed_lines: usize,
1726    expanded: &[Range<usize>],
1727) {
1728    let pairs = document.pairs();
1729    let hunks = document.hunks();
1730    let hunk_end = hunk_ends(document);
1731    let visible = visible_pairs(document, context, min_collapsed_lines, expanded);
1732    let mut hunk_ix = 0;
1733    let mut ix = 0;
1734    while ix < pairs.len() {
1735        while let Some(hunk) = hunks.get(hunk_ix) {
1736            if hunk.pairs().start != ix {
1737                break;
1738            }
1739            rows.push(DisplayRow::Hunk {
1740                file,
1741                hunk: hunk_ix,
1742            });
1743            hunk_ix += 1;
1744        }
1745        if !visible[ix] {
1746            let start = ix;
1747            while ix < pairs.len() && ix < hunk_end[start] && !visible[ix] {
1748                ix += 1;
1749            }
1750            rows.push(DisplayRow::Fold {
1751                file,
1752                pairs: start..ix,
1753            });
1754        } else if mode == DiffMode::Unified && pairs[ix].is_changed() {
1755            let start = ix;
1756            while ix < pairs.len() && ix < hunk_end[start] && pairs[ix].is_changed() {
1757                ix += 1;
1758            }
1759            for pair in &pairs[start..ix] {
1760                if let Some(original) = pair.original() {
1761                    rows.push(DisplayRow::Code {
1762                        file,
1763                        original: Some(original),
1764                        modified: None,
1765                        changed: true,
1766                    });
1767                }
1768            }
1769            for pair in &pairs[start..ix] {
1770                if let Some(modified) = pair.modified() {
1771                    rows.push(DisplayRow::Code {
1772                        file,
1773                        original: None,
1774                        modified: Some(modified),
1775                        changed: true,
1776                    });
1777                }
1778            }
1779        } else {
1780            let pair = pairs[ix];
1781            rows.push(DisplayRow::Code {
1782                file,
1783                original: pair.original(),
1784                modified: pair.modified(),
1785                changed: pair.is_changed(),
1786            });
1787            ix += 1;
1788        }
1789    }
1790}
1791
1792/// Projects a conflicted working file: shared lines fold like context, and
1793/// each conflict shows its parts, or only the kept lines once resolved.
1794fn project_conflicts(
1795    rows: &mut Vec<DisplayRow>,
1796    file: usize,
1797    document: &DiffFile,
1798    visible: &[bool],
1799    resolutions: &[Option<DiffConflictResolution>],
1800) {
1801    // Each line of a conflicted file is its own pair.
1802    let code = |line: usize, changed: bool| DisplayRow::Code {
1803        file,
1804        original: None,
1805        modified: Some(line),
1806        changed,
1807    };
1808    let conflicts = document.conflicts();
1809    let mut next = 0;
1810    let mut ix = 0;
1811    while ix < visible.len() {
1812        if let Some(conflict) = conflicts.get(next)
1813            && conflict.source_lines().start == ix
1814        {
1815            match resolutions[next] {
1816                None => {
1817                    for part in [
1818                        ConflictPart::Current,
1819                        ConflictPart::Base,
1820                        ConflictPart::Incoming,
1821                    ] {
1822                        if let Some(lines) = conflict.part(part) {
1823                            rows.push(DisplayRow::Conflict {
1824                                file,
1825                                conflict: next,
1826                                part,
1827                            });
1828                            rows.extend(lines.map(|line| code(line, true)));
1829                        }
1830                    }
1831                }
1832                Some(resolution) => {
1833                    rows.push(DisplayRow::Conflict {
1834                        file,
1835                        conflict: next,
1836                        part: ConflictPart::Current,
1837                    });
1838                    for lines in conflict.kept(resolution) {
1839                        rows.extend(lines.map(|line| code(line, false)));
1840                    }
1841                }
1842            }
1843            ix = conflict.source_lines().end;
1844            next += 1;
1845            continue;
1846        }
1847        if visible[ix] {
1848            rows.push(code(ix, false));
1849            ix += 1;
1850            continue;
1851        }
1852        let start = ix;
1853        while ix < visible.len() && !visible[ix] {
1854            ix += 1;
1855        }
1856        rows.push(DisplayRow::Fold {
1857            file,
1858            pairs: start..ix,
1859        });
1860    }
1861}