Skip to main content

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