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#[derive(Clone, Debug, PartialEq, Eq)]
28pub(crate) enum DisplayRow {
29 File(usize),
31 Notice(usize),
33 Hunk {
34 file: usize,
35 hunk: usize,
36 },
37 Fold {
38 file: usize,
39 pairs: Range<usize>,
40 },
41 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub(crate) enum FoldExpansion {
71 Up,
73 Down,
75 All,
76}
77
78#[derive(Clone, Debug)]
80#[non_exhaustive]
81pub enum DiffEvent {
82 SelectionStarted(DiffLineRange),
84 SelectionChanged(Option<DiffLineRange>),
86 SelectionEnded(DiffLineRange),
88 FileExpanded(SharedString),
90 FileCollapsed(SharedString),
92 ConflictResolved(SharedString, usize),
95}
96
97#[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#[derive(Default)]
137struct FileRows {
138 original: Vec<Option<usize>>,
139 modified: Vec<Option<usize>>,
140}
141
142#[derive(Clone, Debug, PartialEq, Eq)]
144pub(crate) enum SelectedLines {
145 Side {
147 file: usize,
148 side: DiffSide,
149 lines: Range<usize>,
150 },
151 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 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
206pub struct DiffState {
213 files: Vec<DiffFile>,
214 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 hinted_width: Option<Pixels>,
245 annotations: HashSet<(Option<DiffLinePosition>, SharedString, ElementId)>,
246 window: Option<WindowId>,
247 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 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 state.selection_anchor = None;
321 state.selection_cursor = None;
322 if changed {
323 cx.emit(DiffEvent::SelectionChanged(None));
324 }
325 }
326 TextSelectionEvent::Cleared => {
327 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 pub fn with_mode(mut self, mode: DiffMode) -> Self {
391 self.mode = mode;
392 self.rebuild(true);
393 self
394 }
395
396 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 pub fn with_expansion_lines(mut self, lines: usize) -> Self {
406 self.expansion_lines = lines.max(1);
407 self
408 }
409
410 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub(crate) fn viewport(&self) -> Size<Pixels> {
591 self.viewport
592 }
593 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn has_line(&self, position: &DiffLinePosition) -> bool {
886 self.line_index(position).is_some()
887 }
888
889 pub fn scroll_to_file(&mut self, path: &str, cx: &mut Context<Self>) {
891 let Some(item_ix) = self
892 .file_ix(path)
893 .and_then(|file| self.header_rows.get(file).copied())
894 else {
895 return;
896 };
897 self.list.scroll_to(ListOffset {
898 item_ix,
899 offset_in_item: px(0.),
900 });
901 cx.notify();
902 }
903
904 pub fn next_change(&mut self, cx: &mut Context<Self>) {
907 self.move_change(true, cx);
908 }
909 pub fn previous_change(&mut self, cx: &mut Context<Self>) {
911 self.move_change(false, cx);
912 }
913
914 pub(crate) fn expand_fold(
916 &mut self,
917 file: usize,
918 pairs: Range<usize>,
919 expansion: FoldExpansion,
920 cx: &mut Context<Self>,
921 ) {
922 let lines = self.expansion_lines;
923 let revealed = match expansion {
924 FoldExpansion::All => pairs,
925 FoldExpansion::Up => pairs.end.saturating_sub(lines).max(pairs.start)..pairs.end,
926 FoldExpansion::Down => pairs.start..(pairs.start + lines).min(pairs.end),
927 };
928 if let Some(expanded) = self.expanded.get_mut(file) {
929 expanded.push(revealed);
930 self.rebuild_at_anchor();
931 cx.notify();
932 }
933 }
934
935 pub(crate) fn choose_conflict(
937 &mut self,
938 file: usize,
939 ix: usize,
940 resolution: Option<DiffConflictResolution>,
941 cx: &mut Context<Self>,
942 ) {
943 let path = self.files[file].path().clone();
944 self.resolve_conflict(&path, ix, resolution, cx);
945 cx.emit(DiffEvent::ConflictResolved(path, ix));
946 }
947
948 pub(crate) fn toggle_file_collapsed(&mut self, file: usize, cx: &mut Context<Self>) {
950 let path = self.files[file].path().clone();
951 let collapsed = !self.collapsed.contains(&path);
952 self.set_file_collapsed(&path, collapsed, cx);
953 cx.emit(if collapsed {
954 DiffEvent::FileCollapsed(path)
955 } else {
956 DiffEvent::FileExpanded(path)
957 });
958 }
959
960 pub(crate) fn begin_line_selection(
963 &mut self,
964 position: DiffLinePosition,
965 extend: bool,
966 window: &mut Window,
967 cx: &mut Context<Self>,
968 ) {
969 if self.line_index(&position).is_none() {
970 return;
971 }
972 let anchor = self
973 .selection_anchor
974 .clone()
975 .filter(|anchor| extend && self.can_extend(anchor, &position))
976 .unwrap_or_else(|| position.clone());
977 TextSelection::clear(window, cx);
978 window.focus(&self.focus, cx);
979 self.selecting = true;
980 cx.emit(DiffEvent::SelectionStarted(range_between(
981 &anchor, &position,
982 )));
983 self.select_user_range(anchor, position, cx);
984 }
985
986 pub(crate) fn drag_line_selection(
988 &mut self,
989 position: DiffLinePosition,
990 cx: &mut Context<Self>,
991 ) {
992 let Some(anchor) = self.selection_anchor.clone() else {
993 return;
994 };
995 if !self.selecting
996 || !self.can_extend(&anchor, &position)
997 || self.selection_cursor.as_ref() == Some(&position)
998 || self.line_index(&position).is_none()
999 {
1000 return;
1001 }
1002 self.select_user_range(anchor, position, cx);
1003 }
1004
1005 fn can_extend(&self, anchor: &DiffLinePosition, position: &DiffLinePosition) -> bool {
1009 anchor.path() == position.path()
1010 && (anchor.side() == position.side() || self.mode == DiffMode::Unified)
1011 }
1012
1013 pub(crate) fn end_line_selection(&mut self, cx: &mut Context<Self>) {
1015 if !std::mem::take(&mut self.selecting) {
1016 return;
1017 }
1018 if let Some(range) = self.selected_lines.clone() {
1019 cx.emit(DiffEvent::SelectionEnded(range));
1020 }
1021 }
1022
1023 #[cfg(test)]
1025 pub(crate) fn click_line(
1026 &mut self,
1027 position: DiffLinePosition,
1028 extend: bool,
1029 window: &mut Window,
1030 cx: &mut Context<Self>,
1031 ) {
1032 self.begin_line_selection(position, extend, window, cx);
1033 self.end_line_selection(cx);
1034 }
1035
1036 pub(crate) fn keyboard_select(
1037 &mut self,
1038 direction: isize,
1039 extend: bool,
1040 window: &mut Window,
1041 cx: &mut Context<Self>,
1042 ) {
1043 let Some((file, side)) = self.active_side(cx) else {
1044 return;
1045 };
1046 let count = self.files[file].lines_count(side);
1047 let ix = self
1048 .selection_cursor
1049 .as_ref()
1050 .filter(|position| {
1051 position.side() == side && self.file_ix(position.path()) == Some(file)
1052 })
1053 .and_then(|position| self.line_index(position))
1054 .map(|ix| ix.saturating_add_signed(direction).min(count - 1))
1055 .unwrap_or(0);
1056 let position = self.position(file, side, ix);
1057 let anchor = self
1058 .selection_anchor
1059 .clone()
1060 .filter(|anchor| extend && anchor.path() == position.path())
1061 .unwrap_or_else(|| position.clone());
1062 TextSelection::clear(window, cx);
1063 window.focus(&self.focus, cx);
1064 let range = self.select_user_range(anchor, position.clone(), cx);
1065 cx.emit(DiffEvent::SelectionEnded(range));
1066 if let Some(row) = self.expand_line(&position) {
1067 self.list.scroll_to_reveal_item(row);
1068 }
1069 }
1070
1071 pub(crate) fn select_all(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1072 let Some((file, side)) = self.active_side(cx) else {
1073 return;
1074 };
1075 let count = self.files[file].lines_count(side);
1076 TextSelection::clear(window, cx);
1077 window.focus(&self.focus, cx);
1078 let range = self.select_user_range(
1079 self.position(file, side, 0),
1080 self.position(file, side, count - 1),
1081 cx,
1082 );
1083 cx.emit(DiffEvent::SelectionEnded(range));
1084 }
1085
1086 pub(crate) fn selected_span(&self) -> Option<SelectedLines> {
1088 let range = self.selected_lines.as_ref()?;
1089 let file = self.file_ix(range.path())?;
1090 if range.is_single_side() {
1091 let (start, end) = (
1092 range.start().min(range.end()),
1093 range.start().max(range.end()),
1094 );
1095 return Some(SelectedLines::Side {
1096 file,
1097 side: range.side(),
1098 lines: start..end + 1,
1099 });
1100 }
1101 let document = &self.files[file];
1102 let start = document.patch_ix(
1103 range.side(),
1104 document.line_index(range.side(), range.start())?,
1105 );
1106 let end = document.patch_ix(
1107 range.end_side(),
1108 document.line_index(range.end_side(), range.end())?,
1109 );
1110 Some(SelectedLines::Patch {
1111 file,
1112 patch: start.min(end)..start.max(end) + 1,
1113 })
1114 }
1115
1116 pub(crate) fn set_window(&mut self, window: WindowId) {
1118 self.window = Some(window);
1119 }
1120
1121 pub(crate) fn update_layout(&mut self, key: LayoutKey, row_height: Pixels) -> bool {
1124 if self.layout.as_ref() == Some(&key) {
1125 return false;
1126 }
1127 if self.layout.is_some() {
1128 self.list.remeasure();
1129 }
1130 self.layout = Some(key);
1131 self.row_height = Some(row_height);
1132 self.apply_row_height_hint();
1133 true
1134 }
1135
1136 pub(crate) fn sync_annotations(&mut self, annotations: &[DiffAnnotation]) {
1140 let current = annotations
1141 .iter()
1142 .map(|annotation| {
1143 (
1144 annotation.position().cloned(),
1145 annotation.path().clone(),
1146 annotation.id().clone(),
1147 )
1148 })
1149 .collect::<HashSet<_>>();
1150 if current == self.annotations {
1151 return;
1152 }
1153 let rows = current
1154 .symmetric_difference(&self.annotations)
1155 .filter_map(|(position, path, _)| match position {
1156 Some(position) => self.source_row(position),
1157 None => self
1158 .file_ix(path)
1159 .and_then(|file| self.header_rows.get(file).copied()),
1160 })
1161 .collect::<Vec<_>>();
1162 for row in rows {
1163 self.list.remeasure_items(row..row + 1);
1164 }
1165 self.annotations = current;
1166 }
1167
1168 pub(crate) fn position(&self, file: usize, side: DiffSide, ix: usize) -> DiffLinePosition {
1169 let document = &self.files[file];
1170 DiffLinePosition::new(
1171 document.path().clone(),
1172 side,
1173 document.line_number(side, ix),
1174 )
1175 }
1176
1177 fn file_ix(&self, path: &str) -> Option<usize> {
1178 self.file_ixs.get(path).copied()
1179 }
1180
1181 fn line_index(&self, position: &DiffLinePosition) -> Option<usize> {
1182 self.files[self.file_ix(position.path())?].line_index(position.side(), position.line())
1183 }
1184
1185 fn clip_range(&self, range: &DiffLineRange) -> Option<DiffLineRange> {
1187 let file = &self.files[self.file_ix(range.path())?];
1188 let first_at_or_after = |side: DiffSide, line: usize| {
1189 let lines = file.lines(side);
1190 lines
1191 .get(lines.partition_point(|source| source.line_number() < line))
1192 .map(|source| source.line_number())
1193 };
1194 let last_at_or_before = |side: DiffSide, line: usize| {
1195 let lines = file.lines(side);
1196 lines
1197 .partition_point(|source| source.line_number() <= line)
1198 .checked_sub(1)
1199 .map(|ix| lines[ix].line_number())
1200 };
1201 if range.is_single_side() {
1202 let (start, end) = (
1203 range.start().min(range.end()),
1204 range.start().max(range.end()),
1205 );
1206 let start = first_at_or_after(range.side(), start)?;
1207 let end = last_at_or_before(range.side(), end)?;
1208 return (start <= end)
1209 .then(|| DiffLineRange::new(range.path().clone(), range.side(), start, end));
1210 }
1211 let start = first_at_or_after(range.side(), range.start())
1212 .or_else(|| last_at_or_before(range.side(), range.start()))?;
1213 let end = last_at_or_before(range.end_side(), range.end())
1214 .or_else(|| first_at_or_after(range.end_side(), range.end()))?;
1215 Some(
1216 DiffLineRange::new(range.path().clone(), range.side(), start, end)
1217 .with_end_side(range.end_side()),
1218 )
1219 }
1220
1221 fn selection_is_local(&self, cx: &App) -> bool {
1222 let entity = Some(self.selection.entity_id());
1223 self.selection
1224 .snapshot(cx)
1225 .is_some_and(|snapshot| snapshot.anchor().entity_id() == entity)
1226 }
1227
1228 fn active_side(&self, cx: &App) -> Option<(usize, DiffSide)> {
1230 let (file, side) = self
1231 .selection_cursor
1232 .as_ref()
1233 .and_then(|cursor| Some((self.file_ix(cursor.path())?, Some(cursor.side()))))
1234 .filter(|_| self.selected_lines.is_some())
1235 .or_else(|| {
1236 super::selection::selected_source_range(&self.selection, cx)
1237 .map(|(file, side, _)| (file, Some(side)))
1238 })
1239 .or_else(|| {
1240 let top = self.list.logical_scroll_top().item_ix;
1241 self.rows.get(top).map(|row| (row.file(), None))
1242 })?;
1243 let document = self.files.get(file)?;
1244 let side = side.unwrap_or(if document.lines_count(DiffSide::Modified) > 0 {
1245 DiffSide::Modified
1246 } else {
1247 DiffSide::Original
1248 });
1249 (document.lines_count(side) > 0).then_some((file, side))
1250 }
1251
1252 fn expand_line(&mut self, position: &DiffLinePosition) -> Option<usize> {
1253 let row = self.source_row(position)?;
1254 if let Some(DisplayRow::Fold { file, pairs }) = self.rows.get(row) {
1255 let (file, pairs) = (*file, pairs.clone());
1256 self.expanded[file].push(pairs);
1257 self.rebuild_at_anchor();
1258 }
1259 self.source_row(position)
1260 }
1261
1262 fn select_user_range(
1264 &mut self,
1265 anchor: DiffLinePosition,
1266 cursor: DiffLinePosition,
1267 cx: &mut Context<Self>,
1268 ) -> DiffLineRange {
1269 let range = range_between(&anchor, &cursor);
1270 let changed = self.selected_lines.as_ref() != Some(&range);
1271 self.selected_lines = Some(range.clone());
1272 self.selection_anchor = Some(anchor);
1273 self.selection_cursor = Some(cursor);
1274 self.selection.set_local_selection(true, cx);
1275 if changed {
1276 cx.emit(DiffEvent::SelectionChanged(Some(range.clone())));
1277 }
1278 cx.notify();
1279 range
1280 }
1281
1282 fn move_change(&mut self, forward: bool, cx: &mut Context<Self>) {
1283 let top = self.list.logical_scroll_top().item_ix;
1284 let groups = &self.change_rows;
1285 let target = if forward {
1286 let at_end = self
1291 .list
1292 .item_count()
1293 .checked_sub(1)
1294 .and_then(|last| self.list.bounds_for_item(last))
1295 .is_some_and(|last| last.bottom() <= self.list.viewport_bounds().bottom());
1296 groups
1297 .get(groups.partition_point(|ix| *ix <= top))
1298 .copied()
1299 .filter(|_| !at_end)
1300 .or(groups.first().copied())
1301 } else {
1302 groups
1303 .partition_point(|ix| *ix < top)
1304 .checked_sub(1)
1305 .and_then(|ix| groups.get(ix))
1306 .copied()
1307 .or(groups.last().copied())
1308 };
1309 if let Some(ix) = target {
1310 self.list.scroll_to(ListOffset {
1311 item_ix: ix,
1312 offset_in_item: px(0.),
1313 });
1314 cx.notify();
1315 }
1316 }
1317
1318 fn row_position(&self, ix: usize) -> Option<DiffLinePosition> {
1320 let row = self.rows.get(ix)?;
1321 let file = row.file();
1322 let pair_position = |original: Option<usize>, modified: Option<usize>| {
1323 modified
1324 .map(|ix| self.position(file, DiffSide::Modified, ix))
1325 .or_else(|| original.map(|ix| self.position(file, DiffSide::Original, ix)))
1326 };
1327 match row {
1328 DisplayRow::Code {
1329 original, modified, ..
1330 } => pair_position(*original, *modified),
1331 DisplayRow::Fold { pairs, .. } => self.files[file]
1332 .pairs()
1333 .get(pairs.start)
1334 .and_then(|pair| pair_position(pair.original(), pair.modified())),
1335 DisplayRow::File(_)
1336 | DisplayRow::Notice(_)
1337 | DisplayRow::Hunk { .. }
1338 | DisplayRow::Conflict { .. } => self
1339 .rows
1340 .get(ix + 1)
1341 .filter(|next| next.file() == file)
1342 .and_then(|_| self.row_position(ix + 1)),
1343 }
1344 }
1345
1346 pub(crate) fn source_row(&self, position: &DiffLinePosition) -> Option<usize> {
1347 let rows = self.file_rows.get(self.file_ix(position.path())?)?;
1348 let rows = match position.side() {
1349 DiffSide::Original => &rows.original,
1350 DiffSide::Modified => &rows.modified,
1351 };
1352 rows.get(self.line_index(position)?).copied().flatten()
1353 }
1354
1355 fn reveal_line(&self, position: &DiffLinePosition) {
1356 if let Some(item_ix) = self.source_row(position) {
1357 self.list.scroll_to(ListOffset {
1358 item_ix,
1359 offset_in_item: px(0.),
1360 });
1361 }
1362 }
1363
1364 fn rebuild_at_anchor(&mut self) {
1366 let anchor = self.row_position(self.list.logical_scroll_top().item_ix);
1367 self.rebuild(false);
1368 if let Some(anchor) = anchor {
1369 self.reveal_line(&anchor);
1370 }
1371 }
1372
1373 fn rebuild(&mut self, reset: bool) {
1376 let rows = self.project_rows();
1377 self.file_rows = source_rows(&self.files, &rows);
1378 self.change_rows = changed_groups(&rows);
1379 self.header_rows = rows
1380 .iter()
1381 .enumerate()
1382 .filter_map(|(ix, row)| matches!(row, DisplayRow::File(_)).then_some(ix))
1383 .collect();
1384 if reset {
1385 self.list.reset(rows.len());
1386 } else {
1387 let old = &self.rows;
1388 let prefix = old.iter().zip(&rows).take_while(|(a, b)| a == b).count();
1389 let suffix = old
1390 .iter()
1391 .rev()
1392 .zip(rows.iter().rev())
1393 .take(old.len().min(rows.len()) - prefix)
1394 .take_while(|(a, b)| a == b)
1395 .count();
1396 self.list
1397 .splice(prefix..old.len() - suffix, rows.len() - prefix - suffix);
1398 }
1399 self.rows = Rc::new(rows);
1400 self.apply_row_height_hint();
1401 }
1402
1403 fn project_rows(&self) -> Vec<DisplayRow> {
1404 let mut rows = Vec::new();
1405 for (ix, file) in self.files.iter().enumerate() {
1406 rows.push(DisplayRow::File(ix));
1407 if self.collapsed.contains(file.path()) {
1408 continue;
1409 }
1410 if file.pairs().is_empty() {
1411 rows.push(DisplayRow::Notice(ix));
1412 } else if file.status() == DiffFileStatus::Unchanged {
1413 rows.extend((0..file.pairs().len()).map(|line| DisplayRow::Code {
1414 file: ix,
1415 original: None,
1416 modified: Some(line),
1417 changed: false,
1418 }));
1419 } else if file.status() == DiffFileStatus::Conflicted {
1420 let resolutions = (0..file.conflicts().len())
1421 .map(|conflict| {
1422 self.resolutions
1423 .get(&(file.path().clone(), conflict))
1424 .copied()
1425 })
1426 .collect::<Vec<_>>();
1427 let visible = visible_pairs(
1428 file,
1429 self.context_lines,
1430 self.min_collapsed_lines,
1431 &self.expanded[ix],
1432 );
1433 project_conflicts(&mut rows, ix, file, &visible, &resolutions);
1434 } else {
1435 project_file(
1436 &mut rows,
1437 ix,
1438 file,
1439 self.mode,
1440 self.context_lines,
1441 self.min_collapsed_lines,
1442 &self.expanded[ix],
1443 );
1444 }
1445 }
1446 rows
1447 }
1448
1449 pub(crate) fn keep_row_height_hint(&mut self) -> bool {
1458 let width = self.list.viewport_bounds().size.width;
1459 if self.row_height.is_none() || self.hinted_width == Some(width) {
1460 return false;
1461 }
1462 self.hinted_width = Some(width);
1463 self.apply_row_height_hint();
1464 true
1465 }
1466
1467 fn apply_row_height_hint(&self) {
1470 if let Some(height) = self.row_height {
1471 let _ = self.list.clone().with_uniform_item_height(height);
1472 }
1473 }
1474
1475 fn reset_presentation(&mut self) {
1477 self.presentations = vec![None; self.files.len()];
1478 self.presentation_generation += 1;
1479 self.preparing = None;
1480 self._presentation = Task::ready(());
1481 }
1482
1483 pub(crate) fn ensure_presentation(&mut self, cx: &mut Context<Self>) {
1487 let generation = self.presentation_generation;
1488 if self.preparing == Some(generation) {
1489 return;
1490 }
1491 let pending = self
1492 .presentations
1493 .iter()
1494 .enumerate()
1495 .filter(|(_, presentation)| presentation.is_none())
1496 .map(|(ix, _)| (ix, self.files[ix].clone()))
1497 .collect::<Vec<_>>();
1498 if pending.is_empty() {
1499 return;
1500 }
1501 let options = self.presentation_options;
1502 let custom = self.syntax_highlighter.clone();
1503 self.preparing = Some(generation);
1504 self._presentation = cx.spawn(async move |this, cx| {
1505 let mut highlighters = Some(SyntaxHighlighters::default());
1506 for (ix, file) in pending {
1507 let mut moved = highlighters.take();
1508 let custom = custom.clone();
1509 let (presentation, returned) = cx
1510 .background_spawn(async move {
1511 let presentation = FilePresentation::prepare(
1512 &file,
1513 options,
1514 moved.get_or_insert_default(),
1515 custom.as_ref(),
1516 );
1517 (presentation, moved)
1518 })
1519 .await;
1520 highlighters = returned;
1521 let current = this.update(cx, |state, cx| {
1522 if state.presentation_generation != generation {
1523 return false;
1524 }
1525 if let Some(slot) = state.presentations.get_mut(ix) {
1526 *slot = Some(Arc::new(presentation));
1527 }
1528 cx.notify();
1529 true
1530 });
1531 if !matches!(current, Ok(true)) {
1532 return;
1533 }
1534 }
1535 });
1536 }
1537}
1538
1539fn range_between(anchor: &DiffLinePosition, cursor: &DiffLinePosition) -> DiffLineRange {
1541 if anchor.side() == cursor.side() {
1542 DiffLineRange::new(
1543 cursor.path().clone(),
1544 cursor.side(),
1545 anchor.line().min(cursor.line()),
1546 anchor.line().max(cursor.line()),
1547 )
1548 } else {
1549 DiffLineRange::new(
1550 cursor.path().clone(),
1551 anchor.side(),
1552 anchor.line(),
1553 cursor.line(),
1554 )
1555 .with_end_side(cursor.side())
1556 }
1557}
1558
1559fn file_ixs(files: &[DiffFile]) -> HashMap<SharedString, usize> {
1560 let mut ixs = HashMap::with_capacity(files.len());
1561 for (ix, file) in files.iter().enumerate() {
1562 ixs.entry(file.path().clone()).or_insert(ix);
1563 }
1564 ixs
1565}
1566
1567fn source_rows(files: &[DiffFile], rows: &[DisplayRow]) -> Vec<FileRows> {
1571 let mut file_rows = files
1572 .iter()
1573 .map(|file| FileRows {
1574 original: vec![None; file.lines_count(DiffSide::Original)],
1575 modified: vec![None; file.lines_count(DiffSide::Modified)],
1576 })
1577 .collect::<Vec<_>>();
1578 for (row_ix, row) in rows.iter().enumerate() {
1579 let mut map = |file: usize, original: Option<usize>, modified: Option<usize>| {
1580 if let Some(line) = original {
1581 file_rows[file].original[line] = Some(row_ix);
1582 }
1583 if let Some(line) = modified {
1584 file_rows[file].modified[line] = Some(row_ix);
1585 }
1586 };
1587 match row {
1588 DisplayRow::Code {
1589 file,
1590 original,
1591 modified,
1592 ..
1593 } => map(*file, *original, *modified),
1594 DisplayRow::Fold { file, pairs } => {
1595 for pair in &files[*file].pairs()[pairs.clone()] {
1596 map(*file, pair.original(), pair.modified());
1597 }
1598 }
1599 DisplayRow::File(_)
1600 | DisplayRow::Notice(_)
1601 | DisplayRow::Hunk { .. }
1602 | DisplayRow::Conflict { .. } => {}
1603 }
1604 }
1605 file_rows
1606}
1607
1608fn changed_groups(rows: &[DisplayRow]) -> Vec<usize> {
1609 let changed = |row: &DisplayRow| matches!(row, DisplayRow::Code { changed: true, .. });
1610 rows.iter()
1611 .enumerate()
1612 .filter_map(|(ix, row)| {
1613 (changed(row)
1614 && (ix == 0 || !changed(&rows[ix - 1]) || rows[ix - 1].file() != row.file()))
1615 .then_some(ix)
1616 })
1617 .collect()
1618}
1619
1620const SIDE_BIT: u64 = 1 << 40;
1621const OFFSET_MASK: u64 = SIDE_BIT - 1;
1622
1623pub(crate) fn encode_key(file: usize, side: DiffSide, offset: usize) -> u64 {
1625 ((file as u64) << 41)
1626 | if side == DiffSide::Modified {
1627 SIDE_BIT
1628 } else {
1629 0
1630 }
1631 | (offset as u64 & OFFSET_MASK)
1632}
1633pub(crate) fn decode_key(key: u64) -> (usize, DiffSide, usize) {
1634 (
1635 (key >> 41) as usize,
1636 if key & SIDE_BIT == 0 {
1637 DiffSide::Original
1638 } else {
1639 DiffSide::Modified
1640 },
1641 (key & OFFSET_MASK) as usize,
1642 )
1643}
1644
1645fn hunk_ends(document: &DiffFile) -> Vec<usize> {
1647 let pairs = document.pairs();
1648 let mut hunk_end = vec![pairs.len(); pairs.len()];
1649 for hunk in document.hunks() {
1650 hunk_end[hunk.pairs()].fill(hunk.pairs().end);
1651 }
1652 hunk_end
1653}
1654
1655fn visible_pairs(
1658 document: &DiffFile,
1659 context: Option<usize>,
1660 min_collapsed_lines: usize,
1661 expanded: &[Range<usize>],
1662) -> Vec<bool> {
1663 let pairs = document.pairs();
1664 let hunks = document.hunks();
1665 let mut hunk_end = vec![pairs.len(); pairs.len()];
1666 let mut hunk_start = vec![0; pairs.len()];
1667 for hunk in hunks {
1668 hunk_start[hunk.pairs()].fill(hunk.pairs().start);
1669 hunk_end[hunk.pairs()].fill(hunk.pairs().end);
1670 }
1671 let mut boundaries = vec![0isize; pairs.len() + 1];
1674 if let Some(context) = context {
1675 let mut ix = 0;
1676 while ix < pairs.len() {
1677 if !pairs[ix].is_changed() {
1678 ix += 1;
1679 continue;
1680 }
1681 let start = ix;
1682 while ix < pairs.len() && ix < hunk_end[start] && pairs[ix].is_changed() {
1683 ix += 1;
1684 }
1685 boundaries[start.saturating_sub(context).max(hunk_start[start])] += 1;
1686 boundaries[ix.saturating_add(context).min(hunk_end[start])] -= 1;
1687 }
1688 } else {
1689 boundaries[0] += 1;
1690 boundaries[pairs.len()] -= 1;
1691 }
1692 for range in expanded {
1693 let start = range.start.min(pairs.len());
1694 let end = range.end.min(pairs.len());
1695 if start < end {
1696 boundaries[start] += 1;
1697 boundaries[end] -= 1;
1698 }
1699 }
1700 let mut active = 0;
1701 let mut visible = boundaries[..pairs.len()]
1702 .iter()
1703 .map(|boundary| {
1704 active += boundary;
1705 active > 0
1706 })
1707 .collect::<Vec<_>>();
1708 let mut ix = 0;
1710 while ix < pairs.len() {
1711 if visible[ix] {
1712 ix += 1;
1713 continue;
1714 }
1715 let start = ix;
1716 while ix < pairs.len() && ix < hunk_end[start] && !visible[ix] {
1717 ix += 1;
1718 }
1719 if ix - start < min_collapsed_lines {
1720 visible[start..ix].fill(true);
1721 }
1722 }
1723 visible
1724}
1725
1726fn project_file(
1727 rows: &mut Vec<DisplayRow>,
1728 file: usize,
1729 document: &DiffFile,
1730 mode: DiffMode,
1731 context: Option<usize>,
1732 min_collapsed_lines: usize,
1733 expanded: &[Range<usize>],
1734) {
1735 let pairs = document.pairs();
1736 let hunks = document.hunks();
1737 let hunk_end = hunk_ends(document);
1738 let visible = visible_pairs(document, context, min_collapsed_lines, expanded);
1739 let mut hunk_ix = 0;
1740 let mut ix = 0;
1741 while ix < pairs.len() {
1742 while let Some(hunk) = hunks.get(hunk_ix) {
1743 if hunk.pairs().start != ix {
1744 break;
1745 }
1746 rows.push(DisplayRow::Hunk {
1747 file,
1748 hunk: hunk_ix,
1749 });
1750 hunk_ix += 1;
1751 }
1752 if !visible[ix] {
1753 let start = ix;
1754 while ix < pairs.len() && ix < hunk_end[start] && !visible[ix] {
1755 ix += 1;
1756 }
1757 rows.push(DisplayRow::Fold {
1758 file,
1759 pairs: start..ix,
1760 });
1761 } else if mode == DiffMode::Unified && pairs[ix].is_changed() {
1762 let start = ix;
1763 while ix < pairs.len() && ix < hunk_end[start] && pairs[ix].is_changed() {
1764 ix += 1;
1765 }
1766 for pair in &pairs[start..ix] {
1767 if let Some(original) = pair.original() {
1768 rows.push(DisplayRow::Code {
1769 file,
1770 original: Some(original),
1771 modified: None,
1772 changed: true,
1773 });
1774 }
1775 }
1776 for pair in &pairs[start..ix] {
1777 if let Some(modified) = pair.modified() {
1778 rows.push(DisplayRow::Code {
1779 file,
1780 original: None,
1781 modified: Some(modified),
1782 changed: true,
1783 });
1784 }
1785 }
1786 } else {
1787 let pair = pairs[ix];
1788 rows.push(DisplayRow::Code {
1789 file,
1790 original: pair.original(),
1791 modified: pair.modified(),
1792 changed: pair.is_changed(),
1793 });
1794 ix += 1;
1795 }
1796 }
1797}
1798
1799fn project_conflicts(
1802 rows: &mut Vec<DisplayRow>,
1803 file: usize,
1804 document: &DiffFile,
1805 visible: &[bool],
1806 resolutions: &[Option<DiffConflictResolution>],
1807) {
1808 let code = |line: usize, changed: bool| DisplayRow::Code {
1810 file,
1811 original: None,
1812 modified: Some(line),
1813 changed,
1814 };
1815 let conflicts = document.conflicts();
1816 let mut next = 0;
1817 let mut ix = 0;
1818 while ix < visible.len() {
1819 if let Some(conflict) = conflicts.get(next)
1820 && conflict.source_lines().start == ix
1821 {
1822 match resolutions[next] {
1823 None => {
1824 for part in [
1825 ConflictPart::Current,
1826 ConflictPart::Base,
1827 ConflictPart::Incoming,
1828 ] {
1829 if let Some(lines) = conflict.part(part) {
1830 rows.push(DisplayRow::Conflict {
1831 file,
1832 conflict: next,
1833 part,
1834 });
1835 rows.extend(lines.map(|line| code(line, true)));
1836 }
1837 }
1838 }
1839 Some(resolution) => {
1840 rows.push(DisplayRow::Conflict {
1841 file,
1842 conflict: next,
1843 part: ConflictPart::Current,
1844 });
1845 for lines in conflict.kept(resolution) {
1846 rows.extend(lines.map(|line| code(line, false)));
1847 }
1848 }
1849 }
1850 ix = conflict.source_lines().end;
1851 next += 1;
1852 continue;
1853 }
1854 if visible[ix] {
1855 rows.push(code(ix, false));
1856 ix += 1;
1857 continue;
1858 }
1859 let start = ix;
1860 while ix < visible.len() && !visible[ix] {
1861 ix += 1;
1862 }
1863 rows.push(DisplayRow::Fold {
1864 file,
1865 pairs: start..ix,
1866 });
1867 }
1868}