1mod conflict;
5mod decoration;
6mod document;
7mod parser;
8#[cfg(test)]
9mod parser_tests;
10mod presentation;
11mod selection;
12mod state;
13
14pub use conflict::{DiffConflict, DiffConflictResolution};
15pub use decoration::{DiffDecoration, DiffGutterMarker, DiffSpanHighlight};
16pub use document::{
17 DiffFile, DiffFileStatus, DiffLinePosition, DiffLineRange, DiffSide, DiffTextPosition,
18};
19pub use parser::{DiffParseError, DiffParseOptions};
20pub use presentation::DiffInlineUnit;
21pub use state::{DiffEvent, DiffState};
22
23use std::{collections::HashMap, rc::Rc, sync::Arc};
24
25use gpui::{
26 AnyElement, App, Axis, ClickEvent, ClipboardItem, Context, ElementId, Entity, Focusable as _,
27 HighlightStyle, Hsla, InteractiveElement as _, IntoElement, KeyBinding, ListOffset,
28 MouseButton, ParentElement as _, Pixels, RenderOnce, SharedString,
29 StatefulInteractiveElement as _, StyleRefinement, Styled, TextRun, Window, div, list, point,
30 prelude::FluentBuilder as _, px,
31};
32use gpui_base::TestSupportExt as _;
33use rust_i18n::t;
34
35use crate::{
36 ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt as _,
37 button::{Button, ButtonVariants as _},
38 h_flex,
39 input::{Copy, SelectAll},
40 scroll::{ScrollableMask, Scrollbar},
41 v_flex,
42};
43use actions::*;
44use conflict::ConflictPart;
45use decoration::{Decorations, GutterMarkers, SpanHighlights};
46use presentation::FilePresentation;
47use selection::{CodeText, SelectionLayer};
48use state::{DisplayRow, FoldExpansion, LayoutKey, SelectedLines};
49
50mod actions {
52 gpui::actions!(
53 diff,
54 [
55 ScrollUp,
56 ScrollDown,
57 ScrollLeft,
58 ScrollRight,
59 PageUp,
60 PageDown,
61 First,
62 Last,
63 ExtendUp,
64 ExtendDown
65 ]
66 );
67}
68
69pub(crate) fn init(cx: &mut App) {
70 cx.bind_keys([
71 KeyBinding::new("up", ScrollUp, Some("Diff")),
72 KeyBinding::new("down", ScrollDown, Some("Diff")),
73 KeyBinding::new("left", ScrollLeft, Some("Diff")),
74 KeyBinding::new("right", ScrollRight, Some("Diff")),
75 KeyBinding::new("pageup", PageUp, Some("Diff")),
76 KeyBinding::new("pagedown", PageDown, Some("Diff")),
77 KeyBinding::new("home", First, Some("Diff")),
78 KeyBinding::new("end", Last, Some("Diff")),
79 KeyBinding::new("shift-up", ExtendUp, Some("Diff")),
80 KeyBinding::new("shift-down", ExtendDown, Some("Diff")),
81 KeyBinding::new(
82 if cx.platform_info().is_mac() {
83 "cmd-c"
84 } else {
85 "ctrl-c"
86 },
87 Copy,
88 Some("Diff"),
89 ),
90 KeyBinding::new(
91 if cx.platform_info().is_mac() {
92 "cmd-a"
93 } else {
94 "ctrl-a"
95 },
96 SelectAll,
97 Some("Diff"),
98 ),
99 ]);
100}
101
102#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
104#[non_exhaustive]
105pub enum DiffMode {
106 Split,
108 #[default]
110 Unified,
111}
112
113#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
115#[non_exhaustive]
116pub enum DiffHoverHighlight {
117 #[default]
118 None,
119 Line,
121 LineNumber,
123 Both,
125}
126
127#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
129#[non_exhaustive]
130pub enum DiffHunkSeparator {
131 #[default]
133 Metadata,
134 LineInfo,
136 Simple,
138}
139
140#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
142#[non_exhaustive]
143pub enum DiffChangeIndicator {
144 #[default]
146 Signs,
147 Bars,
149 None,
151}
152
153#[derive(Clone)]
159pub struct DiffAnnotation {
160 id: ElementId,
161 path: SharedString,
162 position: Option<DiffLinePosition>,
163}
164
165impl DiffAnnotation {
166 pub fn line(id: impl Into<ElementId>, position: DiffLinePosition) -> Self {
168 Self {
169 id: id.into(),
170 path: position.path().clone(),
171 position: Some(position),
172 }
173 }
174 pub fn file(id: impl Into<ElementId>, path: impl Into<SharedString>) -> Self {
176 Self {
177 id: id.into(),
178 path: path.into(),
179 position: None,
180 }
181 }
182 pub fn id(&self) -> &ElementId {
183 &self.id
184 }
185 pub fn path(&self) -> &SharedString {
187 &self.path
188 }
189 pub fn position(&self) -> Option<&DiffLinePosition> {
191 self.position.as_ref()
192 }
193}
194
195type FileRenderer = Rc<dyn Fn(&DiffFile, &mut Window, &mut App) -> AnyElement>;
196type AnnotationRenderer = Rc<dyn Fn(&DiffAnnotation, &mut Window, &mut App) -> AnyElement>;
197type MarkerRenderer = Rc<dyn Fn(&DiffGutterMarker, &mut Window, &mut App) -> AnyElement>;
198type RangeHandler = Rc<dyn Fn(&DiffLineRange, &mut Window, &mut App)>;
199type ClickHandler = Rc<dyn Fn(&DiffLinePosition, &ClickEvent, &mut Window, &mut App)>;
200type HoverHandler = Rc<dyn Fn(Option<&DiffLinePosition>, &mut Window, &mut App)>;
201type TextHoverHandler =
202 Rc<dyn Fn(Option<&DiffTextPosition>, gpui::Modifiers, &mut Window, &mut App)>;
203type TextClickHandler = Rc<dyn Fn(&DiffTextPosition, &ClickEvent, &mut Window, &mut App) -> bool>;
204
205#[derive(Default)]
206struct HeaderSlots {
207 content: Option<FileRenderer>,
208 prefix: Option<FileRenderer>,
209 title_suffix: Option<FileRenderer>,
210 suffix: Option<FileRenderer>,
211}
212
213#[derive(Default)]
214struct Annotations {
215 items: Vec<DiffAnnotation>,
216 lines: HashMap<DiffLinePosition, Vec<usize>>,
217 files: HashMap<SharedString, Vec<usize>>,
218}
219
220#[derive(IntoElement)]
228pub struct Diff {
229 state: Entity<DiffState>,
230 style: StyleRefinement,
231 line_number: bool,
232 syntax_highlight: bool,
233 header_visible: bool,
234 hover_highlight: DiffHoverHighlight,
235 hunk_separator: DiffHunkSeparator,
236 change_indicator: DiffChangeIndicator,
237 change_background: bool,
238 soft_wrap: bool,
239 split_ratio: f32,
240 header: HeaderSlots,
241 annotations: Rc<Annotations>,
242 annotation_content: Option<AnnotationRenderer>,
243 decorations: Rc<Decorations>,
244 span_highlights: Rc<SpanHighlights>,
245 gutter_markers: Rc<GutterMarkers>,
246 gutter_marker_content: Option<MarkerRenderer>,
247 on_add_annotation: Option<RangeHandler>,
248 on_line_click: Option<ClickHandler>,
249 on_line_hover: Option<HoverHandler>,
250 on_text_hover: Option<TextHoverHandler>,
251 on_text_click: Option<TextClickHandler>,
252 text_cursor: Option<gpui::CursorStyle>,
253}
254
255fn file_renderer<F, E>(render: F) -> FileRenderer
256where
257 F: Fn(&DiffFile, &mut Window, &mut App) -> E + 'static,
258 E: IntoElement,
259{
260 Rc::new(move |file, window, cx| render(file, window, cx).into_any_element())
261}
262
263impl Diff {
264 pub fn new(state: &Entity<DiffState>) -> Self {
265 Self {
266 state: state.clone(),
267 style: StyleRefinement::default(),
268 line_number: true,
269 syntax_highlight: true,
270 header_visible: true,
271 hover_highlight: DiffHoverHighlight::default(),
272 hunk_separator: DiffHunkSeparator::default(),
273 change_indicator: DiffChangeIndicator::default(),
274 change_background: true,
275 soft_wrap: false,
276 split_ratio: 0.5,
277 header: HeaderSlots::default(),
278 annotations: Rc::default(),
279 annotation_content: None,
280 decorations: Rc::default(),
281 span_highlights: Rc::default(),
282 gutter_markers: Rc::default(),
283 gutter_marker_content: None,
284 on_add_annotation: None,
285 on_line_click: None,
286 on_line_hover: None,
287 on_text_hover: None,
288 on_text_click: None,
289 text_cursor: None,
290 }
291 }
292 pub fn line_number(mut self, value: bool) -> Self {
294 self.line_number = value;
295 self
296 }
297 pub fn syntax_highlight(mut self, value: bool) -> Self {
299 self.syntax_highlight = value;
300 self
301 }
302 pub fn header_visible(mut self, visible: bool) -> Self {
304 self.header_visible = visible;
305 self
306 }
307 pub fn hover_highlight(mut self, highlight: DiffHoverHighlight) -> Self {
309 self.hover_highlight = highlight;
310 self
311 }
312 pub fn hunk_separator(mut self, separator: DiffHunkSeparator) -> Self {
314 self.hunk_separator = separator;
315 self
316 }
317 pub fn change_indicator(mut self, indicator: DiffChangeIndicator) -> Self {
319 self.change_indicator = indicator;
320 self
321 }
322 pub fn change_background(mut self, value: bool) -> Self {
324 self.change_background = value;
325 self
326 }
327 pub fn soft_wrap(mut self, value: bool) -> Self {
330 self.soft_wrap = value;
331 self
332 }
333 pub fn split_ratio(mut self, ratio: f32) -> Self {
338 self.split_ratio = if ratio.is_finite() {
339 ratio.clamp(0.1, 0.9)
340 } else {
341 0.5
342 };
343 self
344 }
345 pub fn annotations(mut self, annotations: impl IntoIterator<Item = DiffAnnotation>) -> Self {
350 let mut index = Annotations {
351 items: annotations.into_iter().collect(),
352 ..Annotations::default()
353 };
354 for (ix, annotation) in index.items.iter().enumerate() {
355 match &annotation.position {
356 Some(position) => index.lines.entry(position.clone()).or_default().push(ix),
357 None => index
358 .files
359 .entry(annotation.path.clone())
360 .or_default()
361 .push(ix),
362 }
363 }
364 self.annotations = Rc::new(index);
365 self
366 }
367 pub fn render_annotation<F, E>(mut self, render: F) -> Self
369 where
370 F: Fn(&DiffAnnotation, &mut Window, &mut App) -> E + 'static,
371 E: IntoElement,
372 {
373 self.annotation_content = Some(Rc::new(move |annotation, window, cx| {
374 render(annotation, window, cx).into_any_element()
375 }));
376 self
377 }
378 pub fn decorations(mut self, decorations: impl IntoIterator<Item = DiffDecoration>) -> Self {
381 self.decorations = Rc::new(Decorations::new(decorations));
382 self
383 }
384 pub fn span_highlights(
387 mut self,
388 highlights: impl IntoIterator<Item = DiffSpanHighlight>,
389 ) -> Self {
390 self.span_highlights = Rc::new(SpanHighlights::new(highlights));
391 self
392 }
393 pub fn gutter_markers(mut self, markers: impl IntoIterator<Item = DiffGutterMarker>) -> Self {
399 self.gutter_markers = Rc::new(GutterMarkers::new(markers));
400 self
401 }
402 pub fn render_gutter_marker<F, E>(mut self, render: F) -> Self
408 where
409 F: Fn(&DiffGutterMarker, &mut Window, &mut App) -> E + 'static,
410 E: IntoElement,
411 {
412 self.gutter_marker_content = Some(Rc::new(move |marker, window, cx| {
413 render(marker, window, cx).into_any_element()
414 }));
415 self
416 }
417 pub fn render_header<F, E>(mut self, render: F) -> Self
420 where
421 F: Fn(&DiffFile, &mut Window, &mut App) -> E + 'static,
422 E: IntoElement,
423 {
424 self.header.content = Some(file_renderer(render));
425 self
426 }
427 pub fn render_header_prefix<F, E>(mut self, render: F) -> Self
429 where
430 F: Fn(&DiffFile, &mut Window, &mut App) -> E + 'static,
431 E: IntoElement,
432 {
433 self.header.prefix = Some(file_renderer(render));
434 self
435 }
436 pub fn render_header_title_suffix<F, E>(mut self, render: F) -> Self
438 where
439 F: Fn(&DiffFile, &mut Window, &mut App) -> E + 'static,
440 E: IntoElement,
441 {
442 self.header.title_suffix = Some(file_renderer(render));
443 self
444 }
445 pub fn render_header_suffix<F, E>(mut self, render: F) -> Self
447 where
448 F: Fn(&DiffFile, &mut Window, &mut App) -> E + 'static,
449 E: IntoElement,
450 {
451 self.header.suffix = Some(file_renderer(render));
452 self
453 }
454 pub fn annotation_content<F, E>(self, render: F) -> Self
456 where
457 F: Fn(&DiffAnnotation, &mut Window, &mut App) -> E + 'static,
458 E: IntoElement,
459 {
460 self.render_annotation(render)
461 }
462
463 pub fn header<F, E>(self, render: F) -> Self
465 where
466 F: Fn(&DiffFile, &mut Window, &mut App) -> E + 'static,
467 E: IntoElement,
468 {
469 self.render_header(render)
470 }
471
472 pub fn header_prefix<F, E>(self, render: F) -> Self
474 where
475 F: Fn(&DiffFile, &mut Window, &mut App) -> E + 'static,
476 E: IntoElement,
477 {
478 self.render_header_prefix(render)
479 }
480
481 pub fn header_title_suffix<F, E>(self, render: F) -> Self
483 where
484 F: Fn(&DiffFile, &mut Window, &mut App) -> E + 'static,
485 E: IntoElement,
486 {
487 self.render_header_title_suffix(render)
488 }
489
490 pub fn header_suffix<F, E>(self, render: F) -> Self
492 where
493 F: Fn(&DiffFile, &mut Window, &mut App) -> E + 'static,
494 E: IntoElement,
495 {
496 self.render_header_suffix(render)
497 }
498
499 pub fn on_add_annotation<F>(mut self, handler: F) -> Self
503 where
504 F: Fn(&DiffLineRange, &mut Window, &mut App) + 'static,
505 {
506 self.on_add_annotation = Some(Rc::new(handler));
507 self
508 }
509 pub fn on_line_click<F>(mut self, handler: F) -> Self
513 where
514 F: Fn(&DiffLinePosition, &ClickEvent, &mut Window, &mut App) + 'static,
515 {
516 self.on_line_click = Some(Rc::new(handler));
517 self
518 }
519 pub fn on_line_hover<F>(mut self, handler: F) -> Self
521 where
522 F: Fn(Option<&DiffLinePosition>, &mut Window, &mut App) + 'static,
523 {
524 self.on_line_hover = Some(Rc::new(handler));
525 self
526 }
527 pub fn on_text_hover<F>(mut self, handler: F) -> Self
532 where
533 F: Fn(Option<&DiffTextPosition>, gpui::Modifiers, &mut Window, &mut App) + 'static,
534 {
535 self.on_text_hover = Some(Rc::new(handler));
536 self
537 }
538 pub fn on_text_click<F>(mut self, handler: F) -> Self
545 where
546 F: Fn(&DiffTextPosition, &ClickEvent, &mut Window, &mut App) -> bool + 'static,
547 {
548 self.on_text_click = Some(Rc::new(handler));
549 self
550 }
551 pub fn text_cursor(mut self, cursor: gpui::CursorStyle) -> Self {
554 self.text_cursor = Some(cursor);
555 self
556 }
557}
558impl Styled for Diff {
559 fn style(&mut self) -> &mut StyleRefinement {
560 &mut self.style
561 }
562}
563
564impl RenderOnce for Diff {
565 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
566 let state = self.state.clone();
567 state.update(cx, |state, cx| render_diff(self, state, window, cx))
568 }
569}
570
571fn render_diff(
572 props: Diff,
573 state: &mut DiffState,
574 window: &mut Window,
575 cx: &mut Context<DiffState>,
576) -> AnyElement {
577 state.set_window(window.window_handle().window_id());
578 state.ensure_presentation(cx);
579 let rem = window.rem_size();
580 let font_size = rem * (f32::from(cx.theme().mono_font_size) / 16.);
581 let font_family = cx.theme().mono_font_family.clone();
582 let row_height = font_size * 1.6;
583 let digits = state
584 .files()
585 .iter()
586 .map(|file| file.line_number_digits())
587 .max()
588 .unwrap_or(1);
589 let gutter_width = if props.line_number {
590 font_size * 0.7 * digits as f32 + rem
591 } else {
592 px(0.)
593 };
594 let mode = state.mode();
595 let soft_wrap = props.soft_wrap;
596 let marker_lane = !props.gutter_markers.is_empty() && props.gutter_marker_content.is_some();
597 let lane_width = if marker_lane { row_height } else { px(0.) };
598 let layout = LayoutKey::new(
599 rem,
600 font_size,
601 font_family.clone(),
602 mode,
603 props.line_number,
604 marker_lane,
605 soft_wrap,
606 props.split_ratio,
607 );
608 if state.update_layout(layout, row_height) {
609 let width = if soft_wrap {
611 px(0.)
612 } else {
613 measure_code_width(
614 state.files(),
615 font_size,
616 &font_family,
617 gutter_width,
618 lane_width,
619 mode,
620 window,
621 cx,
622 )
623 };
624 state.set_content_width(width);
625 }
626 state.sync_annotations(&props.annotations.items);
627 let viewport_width = state.viewport().width;
628 let (content_width, column_width, modified_width, split_offset) = if mode == DiffMode::Split {
629 let original = viewport_width * props.split_ratio;
630 let modified = viewport_width * (1. - props.split_ratio);
631 let overflow = (state.content_width() / 2. - original.min(modified)).max(px(0.));
632 let offset = (!soft_wrap).then(|| {
633 (-state.horizontal_scroll().offset().x)
634 .max(px(0.))
635 .min(overflow)
636 });
637 (original + modified + overflow, original, modified, offset)
638 } else {
639 let width = state.content_width().max(viewport_width);
640 (width, width, width, None)
641 };
642 let code = Rc::new(CodePresentation {
643 files: state.files().to_vec(),
644 presentations: state.presentations().to_vec(),
645 mode,
646 content_width,
647 column_width,
648 modified_width,
649 split_offset,
650 font_size,
651 row_height,
652 gutter_width,
653 rem,
654 expansion_lines: state.expansion_lines(),
655 line_number: props.line_number,
656 syntax_highlight: props.syntax_highlight,
657 header_visible: props.header_visible,
658 hover_highlight: props.hover_highlight,
659 hunk_separator: props.hunk_separator,
660 change_indicator: props.change_indicator,
661 change_background: props.change_background,
662 soft_wrap,
663 header: props.header,
664 annotations: props.annotations.clone(),
665 annotation_content: props.annotation_content,
666 decorations: props.decorations,
667 span_highlights: props.span_highlights,
668 gutter_markers: props.gutter_markers,
669 gutter_marker_content: props.gutter_marker_content.filter(|_| marker_lane),
670 lane_width,
671 on_add_annotation: props.on_add_annotation,
672 on_line_click: props.on_line_click,
673 on_line_hover: props.on_line_hover,
674 on_text_click: props.on_text_click,
675 text_cursor: props.text_cursor,
676 selection: state.selection().clone(),
677 selected_lines: state.selected_lines(),
678 selected: state.selected_span(),
679 geometry: state.geometry().clone(),
680 state: cx.entity(),
681 });
682 let rows = state.rows().clone();
683 let scrollbar = state.list().clone();
684 let horizontal = state.horizontal_scroll().clone();
685 let has_rows = !rows.is_empty();
686 let label = match state.files() {
687 [file] => t!("Diff.Viewer", name = file.path().as_str()).to_string(),
688 files => t!("Diff.ViewerFiles", count = files.len()).to_string(),
689 };
690 let body = div()
691 .id("diff-body")
692 .relative()
693 .min_h_0()
694 .min_w_0()
695 .flex_1()
696 .child(SelectionLayer::new(
697 div()
698 .id("diff-horizontal")
699 .size_full()
700 .when(!soft_wrap, |this| this.overflow_x_hidden())
703 .track_scroll(&horizontal)
704 .child(gpui_base::ScrollBounce::new(
705 "diff-bounce",
706 &scrollbar,
707 list(scrollbar.clone(), move |ix, window, cx| {
708 let row = &rows[ix];
709 div()
710 .id(("diff-file", row.file()))
711 .w_full()
712 .child(render_row(row, code.clone(), window, cx))
713 .into_any_element()
714 })
715 .w(content_width)
716 .h_full(),
717 ))
718 .into_any_element(),
719 scrollbar.clone(),
720 horizontal.clone(),
721 state.selection().clone(),
722 state.geometry().clone(),
723 props.on_text_hover.clone(),
724 ))
725 .when(has_rows && !soft_wrap, |this| {
726 this.child(
727 ScrollableMask::new(Axis::Horizontal, &horizontal).id("diff-horizontal-wheel"),
728 )
729 })
730 .when(has_rows, |this| {
731 this.child(
732 div()
733 .absolute()
734 .inset_0()
735 .child(Scrollbar::vertical(&scrollbar).viewport_from_layout()),
736 )
737 .when(!soft_wrap, |this| {
738 this.child(Scrollbar::horizontal(&horizontal))
739 })
740 })
741 .on_mouse_up(
743 MouseButton::Left,
744 cx.listener(|this, _, _, cx| this.end_line_selection(cx)),
745 )
746 .on_mouse_up_out(
747 MouseButton::Left,
748 cx.listener(|this, _, _, cx| this.end_line_selection(cx)),
749 )
750 .on_action(cx.listener(|this, _: &ScrollUp, window, cx| {
751 if !body_focused(this, window, cx) {
752 return;
753 }
754 this.list().scroll_by(-window.rem_size() * 1.5);
755 cx.notify();
756 }))
757 .on_action(cx.listener(|this, _: &ScrollDown, window, cx| {
758 if !body_focused(this, window, cx) {
759 return;
760 }
761 this.list().scroll_by(window.rem_size() * 1.5);
762 cx.notify();
763 }))
764 .on_action(cx.listener(|this, _: &ScrollLeft, window, cx| {
765 if !body_focused(this, window, cx) {
766 return;
767 }
768 let offset = this.horizontal_scroll().offset();
769 this.horizontal_scroll()
770 .set_offset(point(offset.x + window.rem_size() * 3., offset.y));
771 cx.notify();
772 }))
773 .on_action(cx.listener(|this, _: &ScrollRight, window, cx| {
774 if !body_focused(this, window, cx) {
775 return;
776 }
777 let offset = this.horizontal_scroll().offset();
778 this.horizontal_scroll()
779 .set_offset(point(offset.x - window.rem_size() * 3., offset.y));
780 cx.notify();
781 }))
782 .on_action(cx.listener(|this, _: &PageUp, window, cx| {
783 if !body_focused(this, window, cx) {
784 return;
785 }
786 this.list().scroll_by(-this.viewport().height * 0.9);
787 cx.notify();
788 }))
789 .on_action(cx.listener(|this, _: &PageDown, window, cx| {
790 if !body_focused(this, window, cx) {
791 return;
792 }
793 this.list().scroll_by(this.viewport().height * 0.9);
794 cx.notify();
795 }))
796 .on_action(cx.listener(|this, _: &First, window, cx| {
797 if !body_focused(this, window, cx) {
798 return;
799 }
800 this.list().scroll_to(ListOffset::default());
801 cx.notify();
802 }))
803 .on_action(cx.listener(|this, _: &Last, window, cx| {
804 if !body_focused(this, window, cx) {
805 return;
806 }
807 this.list().scroll_to_end();
808 cx.notify();
809 }))
810 .on_action(cx.listener(|this, _: &ExtendUp, window, cx| {
811 if !body_focused(this, window, cx) {
812 return;
813 }
814 this.keyboard_select(-1, true, window, cx)
815 }))
816 .on_action(cx.listener(|this, _: &ExtendDown, window, cx| {
817 if !body_focused(this, window, cx) {
818 return;
819 }
820 this.keyboard_select(1, true, window, cx)
821 }))
822 .on_action(cx.listener(|this, _: &SelectAll, window, cx| {
823 if body_focused(this, window, cx) {
824 this.select_all(window, cx);
825 }
826 }))
827 .on_action(cx.listener(|this, _: &Copy, window, cx| {
828 if !body_focused(this, window, cx) {
829 return;
830 }
831 let text = this.selected_text(cx);
832 if text.is_empty() {
833 cx.propagate();
834 } else {
835 cx.write_to_clipboard(ClipboardItem::new_string(text));
836 }
837 }))
838 .child(
839 gpui::canvas(
840 {
841 let state = cx.entity();
842 move |bounds, _, cx| {
843 state.update(cx, |state, cx| {
844 let rehinted = state.keep_row_height_hint();
847 let painted = if soft_wrap {
850 px(0.)
851 } else {
852 let painted = state.geometry().borrow().painted_width();
853 code_width(painted, gutter_width, lane_width, rem, mode)
854 };
855 if state.record_paint(bounds.size, painted) || rehinted {
856 cx.notify();
857 }
858 });
859 }
860 },
861 |_, _, _, _| {},
862 )
863 .absolute()
864 .size_full(),
865 )
866 .test_support()
867 .track_focus(&state.focus_handle(cx))
868 .key_context("Diff")
869 .when_some(props.on_text_hover, |this, handler| {
872 let geometry = state.geometry().clone();
873 this.on_modifiers_changed(move |event, window, cx| {
874 let hover = geometry
877 .borrow()
878 .text_hover_after(window.mouse_position(), event.modifiers);
879 if let Some(hit) = hover {
880 handler(hit.as_ref(), event.modifiers, window, cx);
881 }
882 })
883 })
884 .role(gpui::accesskit::Role::Document)
885 .aria_label(label);
886 v_flex()
887 .id(("diff", cx.entity_id()))
888 .size_full()
889 .min_w_0()
890 .min_h_0()
891 .bg(cx.theme().background)
892 .text_color(cx.theme().foreground)
893 .text_sm()
894 .border_1()
895 .border_color(cx.theme().border)
896 .child(body)
897 .refine_style(&props.style)
898 .into_any_element()
899}
900
901fn body_focused(state: &DiffState, window: &Window, cx: &mut Context<DiffState>) -> bool {
902 if state.focus_handle(cx).is_focused(window) {
903 true
904 } else {
905 cx.propagate();
906 false
907 }
908}
909
910struct CodePresentation {
911 files: Vec<DiffFile>,
912 presentations: Vec<Option<Arc<FilePresentation>>>,
913 mode: DiffMode,
914 content_width: Pixels,
915 column_width: Pixels,
917 modified_width: Pixels,
919 split_offset: Option<Pixels>,
920 font_size: Pixels,
921 row_height: Pixels,
922 gutter_width: Pixels,
923 rem: Pixels,
924 expansion_lines: usize,
925 line_number: bool,
926 syntax_highlight: bool,
927 header_visible: bool,
928 hover_highlight: DiffHoverHighlight,
929 hunk_separator: DiffHunkSeparator,
930 change_indicator: DiffChangeIndicator,
931 change_background: bool,
932 soft_wrap: bool,
933 header: HeaderSlots,
934 annotations: Rc<Annotations>,
935 annotation_content: Option<AnnotationRenderer>,
936 decorations: Rc<Decorations>,
937 span_highlights: Rc<SpanHighlights>,
938 gutter_markers: Rc<GutterMarkers>,
939 gutter_marker_content: Option<MarkerRenderer>,
941 lane_width: Pixels,
942 on_add_annotation: Option<RangeHandler>,
943 on_line_click: Option<ClickHandler>,
944 on_line_hover: Option<HoverHandler>,
945 on_text_click: Option<TextClickHandler>,
946 text_cursor: Option<gpui::CursorStyle>,
947 selection: gpui_base::TextSelectionHandle,
948 selected_lines: Option<DiffLineRange>,
949 selected: Option<SelectedLines>,
950 geometry: Rc<std::cell::RefCell<selection::SelectionGeometry>>,
951 state: Entity<DiffState>,
952}
953
954impl CodePresentation {
955 fn position(&self, file: usize, side: DiffSide, ix: usize) -> DiffLinePosition {
956 let document = &self.files[file];
957 DiffLinePosition::new(
958 document.path().clone(),
959 side,
960 document.line_number(side, ix),
961 )
962 }
963
964 fn is_selected(&self, file: usize, side: DiffSide, ix: usize) -> bool {
965 self.selected
966 .as_ref()
967 .is_some_and(|selected| selected.contains(&self.files, file, side, ix))
968 }
969}
970
971fn code_width(
973 width: Pixels,
974 gutter_width: Pixels,
975 lane_width: Pixels,
976 rem: Pixels,
977 mode: DiffMode,
978) -> Pixels {
979 if mode == DiffMode::Split {
980 (width + gutter_width + lane_width + rem * 2.) * 2.
981 } else {
982 width + gutter_width * 2. + lane_width + rem * 2.
983 }
984}
985
986#[allow(clippy::too_many_arguments)]
989fn measure_code_width(
990 files: &[DiffFile],
991 font_size: Pixels,
992 family: &SharedString,
993 gutter_width: Pixels,
994 lane_width: Pixels,
995 mode: DiffMode,
996 window: &mut Window,
997 cx: &App,
998) -> Pixels {
999 const CANDIDATES: usize = 8;
1002 let mut candidates: Vec<(usize, &SharedString)> = Vec::with_capacity(CANDIDATES + 1);
1003 for file in files {
1004 for side in [DiffSide::Original, DiffSide::Modified] {
1005 for line in file.lines(side) {
1006 let cells = unicode_width::UnicodeWidthStr::width(line.display().as_str());
1007 if candidates.len() == CANDIDATES
1008 && candidates
1009 .last()
1010 .is_some_and(|(widest, _)| *widest >= cells)
1011 {
1012 continue;
1013 }
1014 let ix = candidates.partition_point(|(widest, _)| *widest >= cells);
1015 candidates.insert(ix, (cells, line.display()));
1016 candidates.truncate(CANDIDATES);
1017 }
1018 }
1019 }
1020 let font = gpui::Font {
1021 family: family.clone(),
1022 ..Default::default()
1023 };
1024 let width = candidates
1025 .into_iter()
1026 .map(|(_, text)| {
1027 window
1028 .text_system()
1029 .shape_line(
1030 text.clone(),
1031 font_size,
1032 &[TextRun {
1033 len: text.len(),
1034 font: font.clone(),
1035 color: cx.theme().foreground,
1036 background_color: None,
1037 underline: None,
1038 strikethrough: None,
1039 }],
1040 None,
1041 )
1042 .width
1043 })
1044 .fold(px(0.), Pixels::max);
1045 code_width(width, gutter_width, lane_width, window.rem_size(), mode)
1046}
1047
1048fn render_row(
1049 row: &DisplayRow,
1050 code: Rc<CodePresentation>,
1051 window: &mut Window,
1052 cx: &mut App,
1053) -> AnyElement {
1054 match row {
1055 DisplayRow::File(file) => render_file_header(*file, &code, window, cx),
1056 DisplayRow::Notice(file) => render_notice(&code.files[*file], cx),
1057 DisplayRow::Hunk { file, hunk } => render_hunk_separator(*file, *hunk, &code, cx),
1058 DisplayRow::Fold { file, pairs } => render_fold(*file, pairs.clone(), &code, cx),
1059 DisplayRow::Conflict {
1060 file,
1061 conflict,
1062 part,
1063 } => render_conflict(*file, *conflict, *part, &code, cx),
1064 DisplayRow::Code {
1065 file,
1066 original,
1067 modified,
1068 changed,
1069 } => {
1070 if code.mode == DiffMode::Split && !code.files[*file].is_single_column() {
1071 h_flex()
1072 .items_stretch()
1073 .w_full()
1074 .when_some(code.split_offset, |this, offset| {
1075 this.relative().left(offset)
1076 })
1077 .child(render_cell(
1078 *file,
1079 DiffSide::Original,
1080 *original,
1081 *modified,
1082 *changed,
1083 code.clone(),
1084 window,
1085 cx,
1086 ))
1087 .child(render_cell(
1088 *file,
1089 DiffSide::Modified,
1090 *modified,
1091 *original,
1092 *changed,
1093 code,
1094 window,
1095 cx,
1096 ))
1097 .into_any_element()
1098 } else {
1099 let (side, ix) = match (original, modified) {
1100 (_, Some(modified)) => (DiffSide::Modified, *modified),
1101 (Some(original), None) => (DiffSide::Original, *original),
1102 (None, None) => unreachable!("a code row shows at least one side"),
1103 };
1104 render_unified_cell(
1105 *file,
1106 side,
1107 ix,
1108 (*original, *modified),
1109 *changed,
1110 code,
1111 window,
1112 cx,
1113 )
1114 }
1115 }
1116 }
1117}
1118
1119fn render_hunk_separator(
1120 file: usize,
1121 hunk: usize,
1122 code: &CodePresentation,
1123 cx: &App,
1124) -> AnyElement {
1125 let hunks = code.files[file].hunks();
1126 let row = h_flex()
1127 .w_full()
1128 .px_3()
1129 .bg(cx.theme().muted.opacity(0.35))
1130 .text_xs()
1131 .text_color(cx.theme().muted_foreground);
1132 match code.hunk_separator {
1133 DiffHunkSeparator::Metadata => row
1134 .h_6()
1135 .child(hunks[hunk].label().clone())
1136 .into_any_element(),
1137 DiffHunkSeparator::LineInfo => {
1138 let hidden = hunks[hunk].hidden_lines_before(hunk.checked_sub(1).map(|ix| &hunks[ix]));
1139 if hidden == 0 {
1140 return div().into_any_element();
1141 }
1142 row.h_6()
1143 .child(t!("Diff.HiddenLines", count = hidden).to_string())
1144 .into_any_element()
1145 }
1146 DiffHunkSeparator::Simple => row.h_1().into_any_element(),
1147 }
1148}
1149
1150fn render_fold(
1151 file: usize,
1152 pairs: std::ops::Range<usize>,
1153 code: &CodePresentation,
1154 cx: &App,
1155) -> AnyElement {
1156 let document = &code.files[file];
1157 let hunk = document
1160 .hunks()
1161 .iter()
1162 .find(|hunk| hunk.pairs().contains(&pairs.start))
1163 .map_or(0..document.pairs().len(), |hunk| hunk.pairs());
1164 let lines = code.expansion_lines;
1165 let partial = pairs.len() > lines;
1166 let expand = |id: (&'static str, usize), expansion: FoldExpansion| {
1167 let state = code.state.clone();
1168 let pairs = pairs.clone();
1169 Button::new(id)
1170 .ghost()
1171 .xsmall()
1172 .w_auto()
1173 .text_color(cx.theme().muted_foreground)
1174 .on_click(move |_, _, cx| {
1175 state.update(cx, |state, cx| {
1176 state.expand_fold(file, pairs.clone(), expansion, cx)
1177 })
1178 })
1179 };
1180 h_flex()
1181 .w_full()
1182 .h_6()
1183 .px_2()
1184 .gap_1()
1185 .bg(cx.theme().muted.opacity(0.35))
1186 .when(partial && pairs.start > hunk.start, |this| {
1187 this.child(
1188 expand(("expand-down", pairs.start), FoldExpansion::Down)
1189 .icon(IconName::ArrowDown)
1190 .accessibility_label(t!("Diff.ExpandBelow", count = lines).to_string()),
1191 )
1192 })
1193 .when(partial && pairs.end < hunk.end, |this| {
1194 this.child(
1195 expand(("expand-up", pairs.start), FoldExpansion::Up)
1196 .icon(IconName::ArrowUp)
1197 .accessibility_label(t!("Diff.ExpandAbove", count = lines).to_string()),
1198 )
1199 })
1200 .child(
1201 expand(("expand", pairs.start), FoldExpansion::All)
1202 .icon(if partial {
1203 IconName::ChevronsUpDown
1204 } else {
1205 IconName::ChevronDown
1206 })
1207 .label(t!("Diff.UnchangedLines", count = pairs.len()).to_string())
1208 .accessibility_label(t!("Diff.ExpandLines", count = pairs.len()).to_string()),
1209 )
1210 .into_any_element()
1211}
1212
1213fn render_conflict(
1216 file: usize,
1217 ix: usize,
1218 part: ConflictPart,
1219 code: &CodePresentation,
1220 cx: &App,
1221) -> AnyElement {
1222 let document = &code.files[file];
1223 let conflict = &document.conflicts()[ix];
1224 let resolution = code.state.read(cx).conflict_resolution(document.path(), ix);
1225 let choose = |id: &'static str, label: String, resolution: Option<DiffConflictResolution>| {
1226 let state = code.state.clone();
1227 Button::new((id, ix))
1228 .ghost()
1229 .xsmall()
1230 .w_auto()
1231 .label(label)
1232 .on_click(move |_, _, cx| {
1233 state.update(cx, |state, cx| {
1234 state.choose_conflict(file, ix, resolution, cx)
1235 })
1236 })
1237 };
1238 let row = h_flex()
1239 .w_full()
1240 .h_6()
1241 .px_3()
1242 .gap_2()
1243 .text_xs()
1244 .text_color(cx.theme().muted_foreground)
1245 .bg(conflict_tint(Some(part), cx).opacity(0.25));
1246 if let Some(resolution) = resolution {
1247 let label = match resolution {
1248 DiffConflictResolution::Current => t!("Diff.AcceptedCurrent"),
1249 DiffConflictResolution::Incoming => t!("Diff.AcceptedIncoming"),
1250 _ => t!("Diff.AcceptedBoth"),
1251 };
1252 return row
1253 .bg(cx.theme().muted.opacity(0.35))
1254 .child(label.to_string())
1255 .child(choose(
1256 "undo-resolution",
1257 t!("Diff.UndoResolution").to_string(),
1258 None,
1259 ))
1260 .into_any_element();
1261 }
1262 let title = match part {
1263 ConflictPart::Current => t!("Diff.CurrentChange"),
1264 ConflictPart::Base => t!("Diff.BaseChange"),
1265 ConflictPart::Incoming => t!("Diff.IncomingChange"),
1266 };
1267 let label = conflict.label(part).clone();
1268 row.child(div().font_medium().child(title.to_string()))
1269 .when(!label.is_empty(), |this| this.child(label))
1270 .when(part == ConflictPart::Current, |this| {
1271 this.child(div().flex_1())
1272 .child(choose(
1273 "accept-current",
1274 t!("Diff.AcceptCurrent").to_string(),
1275 Some(DiffConflictResolution::Current),
1276 ))
1277 .child(choose(
1278 "accept-incoming",
1279 t!("Diff.AcceptIncoming").to_string(),
1280 Some(DiffConflictResolution::Incoming),
1281 ))
1282 .child(choose(
1283 "accept-both",
1284 t!("Diff.AcceptBoth").to_string(),
1285 Some(DiffConflictResolution::Both),
1286 ))
1287 })
1288 .into_any_element()
1289}
1290
1291fn conflict_tint(part: Option<ConflictPart>, cx: &App) -> Hsla {
1293 match part {
1294 Some(ConflictPart::Current) => cx.theme().success,
1295 Some(ConflictPart::Incoming) => cx.theme().info,
1296 _ => cx.theme().muted_foreground,
1297 }
1298}
1299
1300fn render_file_header(
1301 file: usize,
1302 code: &CodePresentation,
1303 window: &mut Window,
1304 cx: &mut App,
1305) -> AnyElement {
1306 if !code.header_visible {
1307 return div()
1308 .children(file_annotations(file, code, window, cx))
1309 .into_any_element();
1310 }
1311 let document = &code.files[file];
1312 let foreground = cx.theme().muted_foreground;
1313 let border = cx.theme().border;
1314 let collapsed = code.state.read(cx).is_file_collapsed(document.path());
1315 let content = if let Some(render) = &code.header.content {
1316 render(document, window, cx)
1317 } else {
1318 let name: SharedString = match (document.original_path(), document.modified_path()) {
1319 (Some(old), Some(new)) if old != new => format!("{old} → {new}").into(),
1320 _ => document.path().clone(),
1321 };
1322 let slot = |render: &Option<FileRenderer>, window: &mut Window, cx: &mut App| {
1323 render.as_ref().map(|render| render(document, window, cx))
1324 };
1325 let prefix = slot(&code.header.prefix, window, cx);
1326 let title_suffix = slot(&code.header.title_suffix, window, cx);
1327 let suffix = slot(&code.header.suffix, window, cx);
1328 let status = match document.status() {
1329 DiffFileStatus::Added => Some(t!("Diff.AddedFile")),
1330 DiffFileStatus::Deleted => Some(t!("Diff.DeletedFile")),
1331 DiffFileStatus::Renamed => Some(t!("Diff.RenamedFile")),
1332 DiffFileStatus::Copied => Some(t!("Diff.CopiedFile")),
1333 DiffFileStatus::Conflicted => Some(t!("Diff.ConflictedFile")),
1334 _ => None,
1335 };
1336 let statistics = !document.is_single_column();
1337 h_flex()
1338 .w_full()
1339 .min_w_0()
1340 .gap_2()
1341 .children(prefix)
1342 .child(
1343 h_flex()
1344 .min_w_0()
1345 .flex_1()
1346 .gap_2()
1347 .child(div().min_w_0().truncate().font_medium().child(name))
1348 .when_some(title_suffix, |this, suffix| {
1349 this.child(div().flex_shrink_0().child(suffix))
1350 }),
1351 )
1352 .when(statistics, |this| {
1353 this.child(div().text_xs().text_color(foreground).child(format!(
1354 "+{} −{}",
1355 document.additions(),
1356 document.deletions()
1357 )))
1358 })
1359 .when_some(status, |this, status| {
1360 this.child(
1361 div()
1362 .text_xs()
1363 .text_color(foreground)
1364 .child(status.to_string()),
1365 )
1366 })
1367 .children(suffix)
1368 .into_any_element()
1369 };
1370 let state = code.state.clone();
1371 let name = document.path().clone();
1372 let scrolled = code.state.read(cx);
1377 let pin = -scrolled.horizontal_scroll().offset().x;
1378 let viewport = scrolled.viewport().width;
1379 v_flex()
1380 .id("file-header")
1381 .test_support()
1382 .map(|this| {
1383 if viewport > px(0.) {
1384 this.w(viewport).ml(pin)
1385 } else {
1386 this.w_full()
1387 }
1388 })
1389 .when(file > 0, |this| this.border_t_1())
1390 .border_b_1()
1391 .border_color(border)
1392 .child(
1393 h_flex()
1394 .w_full()
1395 .min_w_0()
1396 .pl_1()
1397 .pr_3()
1398 .py_1()
1399 .gap_1()
1400 .child(
1401 Button::new("collapse-file")
1402 .ghost()
1403 .xsmall()
1404 .icon(if collapsed {
1405 IconName::ChevronRight
1406 } else {
1407 IconName::ChevronDown
1408 })
1409 .accessibility_label(
1410 if collapsed {
1411 t!("Diff.ExpandFile", name = name.as_str())
1412 } else {
1413 t!("Diff.CollapseFile", name = name.as_str())
1414 }
1415 .to_string(),
1416 )
1417 .on_click(move |_, _, cx| {
1418 state.update(cx, |state, cx| state.toggle_file_collapsed(file, cx))
1419 }),
1420 )
1421 .child(div().flex_1().min_w_0().child(content)),
1422 )
1423 .children(file_annotations(file, code, window, cx))
1424 .into_any_element()
1425}
1426
1427fn file_annotations(
1428 file: usize,
1429 code: &CodePresentation,
1430 window: &mut Window,
1431 cx: &mut App,
1432) -> Vec<AnyElement> {
1433 let path = code.files[file].path();
1434 let ixs = code
1435 .annotations
1436 .files
1437 .get(path)
1438 .cloned()
1439 .unwrap_or_default();
1440 annotation_elements(&ixs, code, None, window, cx)
1443}
1444
1445fn render_notice(file: &DiffFile, cx: &App) -> AnyElement {
1447 let message = if !file.has_changes() {
1448 t!("Diff.NoChanges")
1449 } else if file.is_binary() {
1450 t!("Diff.BinaryChanges")
1451 } else if !file.extended_headers().is_empty() {
1452 t!("Diff.NoTextChanges")
1453 } else {
1454 t!("Diff.EmptyFile")
1455 };
1456 v_flex()
1457 .w_full()
1458 .px_3()
1459 .py_2()
1460 .gap_1()
1461 .text_xs()
1462 .text_color(cx.theme().muted_foreground)
1463 .children(
1464 file.extended_headers()
1465 .iter()
1466 .cloned()
1467 .map(|line| div().child(line)),
1468 )
1469 .child(div().text_sm().child(message.to_string()))
1470 .into_any_element()
1471}
1472
1473fn render_gutter(
1474 file: usize,
1475 side: DiffSide,
1476 ix: Option<usize>,
1477 code: &CodePresentation,
1478 cx: &App,
1479) -> AnyElement {
1480 let hover = matches!(
1481 code.hover_highlight,
1482 DiffHoverHighlight::LineNumber | DiffHoverHighlight::Both
1483 );
1484 div()
1485 .id(if side == DiffSide::Original {
1486 "old-gutter"
1487 } else {
1488 "new-gutter"
1489 })
1490 .flex_shrink_0()
1491 .w(code.gutter_width)
1492 .pr_1()
1493 .when(hover, |this| {
1494 this.hover(|this| this.bg(cx.theme().list_hover))
1495 })
1496 .when_some(ix, |this, ix| {
1497 let position = code.position(file, side, ix);
1498 let down = code.state.clone();
1499 let moved = code.state.clone();
1500 let dragged = position.clone();
1501 this.child(
1503 div()
1504 .id(("line", ix))
1505 .test_support()
1506 .w_full()
1507 .h(code.row_height)
1508 .px_1()
1509 .flex()
1510 .items_center()
1511 .justify_end()
1512 .text_size(code.font_size)
1513 .text_color(cx.theme().muted_foreground)
1514 .hover(|this| this.text_color(cx.theme().foreground))
1515 .role(gpui::accesskit::Role::Button)
1516 .aria_label(
1517 t!(
1518 "Diff.SelectLine",
1519 side = side_label(side),
1520 line = position.line()
1521 )
1522 .to_string(),
1523 )
1524 .child(position.line().to_string())
1525 .on_mouse_down(MouseButton::Left, move |event, window, cx| {
1526 down.update(cx, |state, cx| {
1527 state.begin_line_selection(
1528 position.clone(),
1529 event.modifiers.shift,
1530 window,
1531 cx,
1532 )
1533 })
1534 })
1535 .on_mouse_move(move |event, _, cx| {
1536 if event.pressed_button == Some(MouseButton::Left) {
1537 moved.update(cx, |state, cx| {
1538 state.drag_line_selection(dragged.clone(), cx)
1539 })
1540 }
1541 }),
1542 )
1543 })
1544 .into_any_element()
1545}
1546
1547fn side_label(side: DiffSide) -> std::borrow::Cow<'static, str> {
1548 if side == DiffSide::Original {
1549 t!("Diff.Original")
1550 } else {
1551 t!("Diff.Modified")
1552 }
1553}
1554
1555#[allow(clippy::too_many_arguments)]
1556fn render_cell(
1557 file: usize,
1558 side: DiffSide,
1559 ix: Option<usize>,
1560 other_ix: Option<usize>,
1561 changed: bool,
1562 code: Rc<CodePresentation>,
1563 window: &mut Window,
1564 cx: &mut App,
1565) -> AnyElement {
1566 let cell = v_flex()
1567 .w(if side == DiffSide::Original {
1568 code.column_width
1569 } else {
1570 code.modified_width
1571 })
1572 .min_w_0()
1573 .flex_shrink_0()
1574 .when(side == DiffSide::Original, |this| {
1575 this.border_r_1().border_color(cx.theme().border)
1576 })
1577 .when(ix.is_none(), |this| {
1578 this.bg(cx.theme().muted.opacity(0.3))
1579 .child(div().h(code.row_height))
1580 });
1581 let Some(ix) = ix else {
1582 return cell.into_any_element();
1583 };
1584 cell.id((
1585 if side == DiffSide::Original {
1586 "old"
1587 } else {
1588 "new"
1589 },
1590 ix,
1591 ))
1592 .child(code_line(
1593 file,
1594 side,
1595 ix,
1596 changed,
1597 code.clone(),
1598 [Some((side, Some(ix))), None],
1599 window,
1600 cx,
1601 ))
1602 .children(line_extras(
1603 file, side, ix, other_ix, changed, &code, window, cx,
1604 ))
1605 .into_any_element()
1606}
1607
1608#[allow(clippy::too_many_arguments)]
1609fn render_unified_cell(
1610 file: usize,
1611 side: DiffSide,
1612 ix: usize,
1613 pair: (Option<usize>, Option<usize>),
1614 changed: bool,
1615 code: Rc<CodePresentation>,
1616 window: &mut Window,
1617 cx: &mut App,
1618) -> AnyElement {
1619 let (original, modified) = pair;
1620 let single_column = code.files[file].is_single_column();
1621 let counterpart = code.files[file].lines(side)[ix].counterpart();
1622 let other_ix = if side == DiffSide::Original {
1623 modified
1624 } else {
1625 original
1626 };
1627 let mut extras = line_extras(file, side, ix, counterpart, changed, &code, window, cx);
1628 if !changed && let Some(other_ix) = other_ix {
1629 extras.extend(line_annotations(
1630 file,
1631 side.other(),
1632 other_ix,
1633 &code,
1634 window,
1635 cx,
1636 ));
1637 }
1638 let gutters = if single_column {
1639 [Some((DiffSide::Modified, modified)), None]
1640 } else {
1641 [
1642 Some((DiffSide::Original, original)),
1643 Some((DiffSide::Modified, modified)),
1644 ]
1645 };
1646 v_flex()
1647 .w(if single_column {
1648 code.content_width
1649 } else {
1650 code.column_width
1651 })
1652 .id((
1653 if side == DiffSide::Original {
1654 "old"
1655 } else {
1656 "new"
1657 },
1658 ix,
1659 ))
1660 .child(code_line(
1661 file,
1662 side,
1663 ix,
1664 changed,
1665 code.clone(),
1666 gutters,
1667 window,
1668 cx,
1669 ))
1670 .children(extras)
1671 .into_any_element()
1672}
1673
1674#[allow(clippy::too_many_arguments)]
1676fn line_highlights(
1677 file: usize,
1678 side: DiffSide,
1679 ix: usize,
1680 changed: bool,
1681 selected: bool,
1682 status: Hsla,
1683 code: &CodePresentation,
1684 cx: &App,
1685) -> Vec<(std::ops::Range<usize>, HighlightStyle)> {
1686 let line = &code.files[file].lines(side)[ix];
1687 let presentation = code.presentations.get(file).and_then(Option::as_ref);
1688 let mut highlights = match presentation {
1689 Some(presentation) if code.syntax_highlight => {
1690 presentation.syntax_highlights(line, side, ix, cx.theme().highlight_theme.as_ref())
1691 }
1692 _ => Vec::new(),
1693 };
1694 if changed && let Some(presentation) = presentation {
1695 highlights.extend(presentation.inline_changes(line, side, ix).map(|range| {
1696 (
1697 range,
1698 HighlightStyle {
1699 background_color: Some(status.opacity(0.3)),
1700 ..Default::default()
1701 },
1702 )
1703 }));
1704 }
1705 if selected {
1706 highlights.push((
1707 0..line.display().len(),
1708 HighlightStyle {
1709 background_color: Some(cx.theme().selection),
1710 ..Default::default()
1711 },
1712 ));
1713 }
1714 if let Some(spans) = code.span_highlights.at(&code.position(file, side, ix)) {
1718 for span in spans {
1719 let range = line.display_range(span.span());
1720 if range.is_empty() {
1721 continue;
1722 }
1723 highlights.push((
1724 range,
1725 HighlightStyle {
1726 background_color: Some(
1727 span.background()
1728 .unwrap_or_else(|| cx.theme().warning.opacity(0.5)),
1729 ),
1730 color: span.foreground(),
1731 underline: span.is_underlined().then(|| gpui::UnderlineStyle {
1732 thickness: px(1.),
1733 color: span.foreground(),
1734 wavy: false,
1735 }),
1736 ..Default::default()
1737 },
1738 ));
1739 }
1740 }
1741 highlights
1742}
1743
1744fn add_annotation_button(
1746 file: usize,
1747 side: DiffSide,
1748 ix: usize,
1749 left: Pixels,
1750 code: &CodePresentation,
1751 cx: &App,
1752) -> Option<AnyElement> {
1753 let handler = code.on_add_annotation.clone()?;
1754 let position = code.position(file, side, ix);
1755 let range = code
1756 .selected_lines
1757 .clone()
1758 .filter(|_| code.is_selected(file, side, ix))
1759 .unwrap_or_else(|| {
1760 DiffLineRange::new(
1761 position.path().clone(),
1762 side,
1763 position.line(),
1764 position.line(),
1765 )
1766 });
1767 let at_selection_end = code
1768 .selected
1769 .as_ref()
1770 .is_some_and(|selected| selected.is_last(&code.files, file, side, ix));
1771 Some(
1772 div()
1773 .id(("add-annotation", ix))
1774 .test_support()
1775 .absolute()
1776 .top_0()
1777 .left(left)
1778 .size(code.row_height)
1779 .flex()
1780 .items_center()
1781 .justify_center()
1782 .rounded(cx.theme().radius)
1783 .bg(cx.theme().primary)
1784 .text_color(cx.theme().primary_foreground)
1785 .when(!at_selection_end, |this| {
1786 this.opacity(0.)
1787 .group_hover("diff-line", |this| this.opacity(1.))
1788 })
1789 .role(gpui::accesskit::Role::Button)
1790 .aria_label(t!("Diff.AddAnnotation", line = position.line()).to_string())
1791 .child(Icon::new(IconName::Plus).xsmall())
1792 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1793 .on_click(move |_, window, cx| handler(&range, window, cx))
1794 .into_any_element(),
1795 )
1796}
1797
1798#[allow(clippy::too_many_arguments)]
1799fn code_line(
1800 file: usize,
1801 side: DiffSide,
1802 ix: usize,
1803 changed: bool,
1804 code: Rc<CodePresentation>,
1805 gutters: [Option<(DiffSide, Option<usize>)>; 2],
1806 window: &mut Window,
1807 cx: &mut App,
1808) -> AnyElement {
1809 let document = &code.files[file];
1810 let line = &document.lines(side)[ix];
1811 let conflict_part = (document.status() == DiffFileStatus::Conflicted && changed)
1812 .then(|| {
1813 document
1814 .conflicts()
1815 .iter()
1816 .find(|conflict| conflict.source_lines().contains(&ix))
1817 .and_then(|conflict| conflict.part_of(ix))
1818 })
1819 .flatten();
1820 let status = if conflict_part.is_some() {
1821 conflict_tint(conflict_part, cx)
1822 } else if side == DiffSide::Original {
1823 cx.theme().danger
1824 } else {
1825 cx.theme().success
1826 };
1827 let selected = code.is_selected(file, side, ix)
1828 || (code.mode == DiffMode::Unified
1829 && !changed
1830 && gutters
1831 .iter()
1832 .flatten()
1833 .any(|(side, ix)| ix.is_some_and(|ix| code.is_selected(file, *side, ix))));
1834 let highlights = line_highlights(file, side, ix, changed, selected, status, &code, cx);
1835 let (text_side, text_ix) = if code.mode == DiffMode::Unified
1838 && !changed
1839 && let Some((selected_file, selected_side, _)) =
1840 selection::selected_source_range(&code.selection, cx)
1841 && selected_file == file
1842 && selected_side != side
1843 && let Some(other_ix) = line.counterpart()
1844 {
1845 (selected_side, other_ix)
1846 } else {
1847 (side, ix)
1848 };
1849 let position = code.position(file, text_side, text_ix);
1850 let source_line = &document.lines(text_side)[text_ix];
1851 let ranges: Vec<_> = if code.soft_wrap {
1854 vec![0..source_line.display().len()]
1855 } else {
1856 source_line.chunk_ranges().collect()
1857 };
1858 let split_offset = code
1859 .split_offset
1860 .filter(|_| code.mode == DiffMode::Split && !document.is_single_column());
1861 let text = div()
1863 .map(|this| {
1864 if code.soft_wrap {
1865 this.w_full()
1866 } else {
1867 this.flex().flex_row().flex_shrink_0()
1868 }
1869 })
1870 .children(ranges.into_iter().enumerate().map(|(chunk_ix, range)| {
1871 CodeText::new(
1872 ("code", chunk_ix).into(),
1873 document.clone(),
1874 file,
1875 text_side,
1876 text_ix,
1877 range,
1878 highlights.clone(),
1879 code.selection.clone(),
1880 code.geometry.clone(),
1881 )
1882 }));
1883 let gutters_width = if code.line_number {
1884 code.gutter_width * gutters.iter().flatten().count() as f32
1885 } else {
1886 px(0.)
1887 };
1888 let indicator = match code.change_indicator {
1889 DiffChangeIndicator::Signs => div()
1890 .w_4()
1891 .flex_shrink_0()
1892 .text_color(if changed {
1893 status
1894 } else {
1895 cx.theme().muted_foreground
1896 })
1897 .child(match (changed && conflict_part.is_none(), side) {
1898 (false, _) => " ",
1899 (true, DiffSide::Original) => "−",
1900 (true, DiffSide::Modified) => "+",
1901 }),
1902 DiffChangeIndicator::Bars => div().w_4().h_full().flex_shrink_0().when(changed, |this| {
1903 this.child(div().w(px(3.)).h_full().bg(status))
1904 }),
1905 DiffChangeIndicator::None => div().w_2().flex_shrink_0(),
1906 };
1907 let hover_line = matches!(
1908 code.hover_highlight,
1909 DiffHoverHighlight::Line | DiffHoverHighlight::Both
1910 );
1911 let add_button = add_annotation_button(
1912 file,
1913 side,
1914 ix,
1915 gutters_width + code.lane_width + code.rem / 2.,
1916 &code,
1917 cx,
1918 );
1919 let positions: Vec<_> = gutters
1921 .iter()
1922 .flatten()
1923 .filter_map(|(side, ix)| ix.map(|ix| code.position(file, *side, ix)))
1924 .collect();
1925 let decoration = positions
1926 .iter()
1927 .find_map(|position| code.decorations.at(position))
1928 .filter(|_| !selected)
1929 .map(|decoration| {
1930 decoration
1931 .background()
1932 .unwrap_or_else(|| cx.theme().warning.opacity(0.2))
1933 });
1934 let marker_lane = code.gutter_marker_content.clone().map(|render| {
1935 let marker = positions
1936 .iter()
1937 .find_map(|position| code.gutter_markers.at(position));
1938 div()
1939 .id("marker-lane")
1940 .flex_shrink_0()
1941 .size(code.row_height)
1942 .flex()
1943 .items_center()
1944 .justify_center()
1945 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1947 .when_some(marker, |this, marker| {
1948 this.child(render(marker, window, cx))
1949 })
1950 });
1951 let source = div()
1952 .id("source")
1953 .test_support()
1954 .map(|this| {
1955 if code.soft_wrap {
1956 this.flex_1().min_w_0()
1957 } else {
1958 this.flex_shrink_0()
1959 }
1960 })
1961 .when_some(split_offset, |this, offset| this.relative().left(-offset))
1962 .role(gpui::accesskit::Role::Label)
1963 .aria_label(source_line.text().clone())
1964 .aria_description(
1965 t!(
1966 if changed {
1967 if side == DiffSide::Original {
1968 "Diff.RemovedLine"
1969 } else {
1970 "Diff.AddedLine"
1971 }
1972 } else {
1973 "Diff.SourceLine"
1974 },
1975 side = side_label(text_side),
1976 line = position.line()
1977 )
1978 .to_string(),
1979 )
1980 .when_some(code.text_cursor, |this, cursor| this.cursor(cursor))
1981 .when(
1982 code.on_line_click.is_some() || code.on_text_click.is_some(),
1983 |this| {
1984 let position = position.clone();
1985 let line_click = code.on_line_click.clone();
1986 let text_click = code.on_text_click.clone();
1987 let geometry = code.geometry.clone();
1988 this.on_click(move |event, window, cx| {
1989 if let ClickEvent::Mouse(mouse) = event {
1991 let moved = mouse.up.position - mouse.down.position;
1992 if moved.x.abs() > px(3.) || moved.y.abs() > px(3.) {
1993 return;
1994 }
1995 let hit = geometry.borrow().text_at(mouse.up.position);
1998 if let (Some(handler), Some(hit)) = (&text_click, hit)
1999 && handler(&hit, event, window, cx)
2000 {
2001 return;
2002 }
2003 }
2004 if let Some(handler) = &line_click {
2005 handler(&position, event, window, cx)
2006 }
2007 })
2008 },
2009 )
2010 .child(text);
2011 h_flex()
2012 .id("line-row")
2013 .group("diff-line")
2014 .relative()
2015 .w_full()
2016 .px_2()
2017 .map(|this| {
2018 if code.soft_wrap {
2019 this.min_h(code.row_height)
2020 .items_start()
2021 .whitespace_normal()
2022 } else {
2023 this.h(code.row_height).whitespace_nowrap()
2024 }
2025 })
2026 .font_family(cx.theme().mono_font_family.clone())
2027 .text_size(code.font_size)
2028 .line_height(code.row_height)
2029 .when(changed && code.change_background, |this| {
2030 this.bg(status.opacity(0.12))
2031 })
2032 .when_some(decoration, |this, background| {
2034 this.child(div().absolute().inset_0().bg(background))
2035 })
2036 .when(selected, |this| this.bg(cx.theme().selection))
2037 .when(hover_line && !selected, |this| {
2038 this.hover(|this| this.bg(cx.theme().list_hover))
2039 })
2040 .when_some(code.on_line_hover.clone(), |this, handler| {
2041 let position = position.clone();
2042 this.on_hover(move |hovered, window, cx| {
2043 handler(hovered.then_some(&position), window, cx)
2044 })
2045 })
2046 .when(code.line_number, |this| {
2047 this.children(
2048 gutters
2049 .into_iter()
2050 .flatten()
2051 .map(|(side, ix)| render_gutter(file, side, ix, &code, cx)),
2052 )
2053 })
2054 .children(marker_lane)
2055 .child(indicator)
2056 .map(|this| {
2057 if split_offset.is_some() {
2058 this.child(
2059 div()
2060 .flex()
2061 .flex_1()
2062 .min_w_0()
2063 .overflow_hidden()
2064 .child(source),
2065 )
2066 } else {
2067 this.child(source)
2068 }
2069 })
2070 .children(add_button)
2071 .into_any_element()
2072}
2073
2074#[allow(clippy::too_many_arguments)]
2075fn line_extras(
2076 file: usize,
2077 side: DiffSide,
2078 ix: usize,
2079 other_ix: Option<usize>,
2080 changed: bool,
2081 code: &CodePresentation,
2082 window: &mut Window,
2083 cx: &mut App,
2084) -> Vec<AnyElement> {
2085 let mut extras = Vec::new();
2086 let document = &code.files[file];
2087 let line = &document.lines(side)[ix];
2088 let ending = &document.source(side)[line.content_end()..line.source().end];
2089 let ending_only = changed && has_line_ending_change(document, side, ix, other_ix);
2090 if ending.is_empty() || ending_only {
2091 let label = if ending.is_empty() {
2092 t!("Diff.NoNewline").to_string()
2093 } else {
2094 format!("\\ {}", if ending == "\r\n" { "CRLF" } else { "LF" })
2095 };
2096 extras.push(
2097 div()
2098 .h_6()
2099 .px_3()
2100 .text_xs()
2101 .text_color(cx.theme().muted_foreground)
2102 .child(label)
2103 .into_any_element(),
2104 );
2105 }
2106 extras.extend(line_annotations(file, side, ix, code, window, cx));
2107 extras
2108}
2109
2110fn line_annotations(
2111 file: usize,
2112 side: DiffSide,
2113 ix: usize,
2114 code: &CodePresentation,
2115 window: &mut Window,
2116 cx: &mut App,
2117) -> Vec<AnyElement> {
2118 let position = code.position(file, side, ix);
2119 let ixs = code
2120 .annotations
2121 .lines
2122 .get(&position)
2123 .cloned()
2124 .unwrap_or_default();
2125 annotation_elements(&ixs, code, CardPlacement::resolve(code, cx), window, cx)
2126}
2127
2128#[derive(Clone, Copy)]
2134struct CardPlacement {
2135 pin: Pixels,
2137 viewport: Pixels,
2138}
2139
2140impl CardPlacement {
2141 fn resolve(code: &CodePresentation, cx: &App) -> Option<Self> {
2142 if code.mode != DiffMode::Unified || code.soft_wrap {
2143 return None;
2144 }
2145 let state = code.state.read(cx);
2146 let viewport = state.viewport().width;
2147 (viewport > px(0.)).then(|| Self {
2148 pin: -state.horizontal_scroll().offset().x,
2149 viewport,
2150 })
2151 }
2152}
2153
2154fn annotation_elements(
2155 ixs: &[usize],
2156 code: &CodePresentation,
2157 placement: Option<CardPlacement>,
2158 window: &mut Window,
2159 cx: &mut App,
2160) -> Vec<AnyElement> {
2161 let Some(render) = &code.annotation_content else {
2162 return Vec::new();
2163 };
2164 ixs.iter()
2165 .map(|ix| {
2166 let annotation = &code.annotations.items[*ix];
2167 div()
2168 .id(annotation.id.clone())
2169 .map(|this| match placement {
2170 Some(placement) => this.w(placement.viewport).ml(placement.pin),
2171 None => this.w_full(),
2172 })
2173 .px_3()
2174 .py_3()
2175 .border_t_1()
2176 .border_b_1()
2177 .border_color(cx.theme().border)
2178 .bg(cx.theme().muted.opacity(0.18))
2179 .child(render(annotation, window, cx))
2180 .into_any_element()
2181 })
2182 .collect()
2183}
2184
2185fn has_line_ending_change(
2186 file: &DiffFile,
2187 side: DiffSide,
2188 ix: usize,
2189 counterpart: Option<usize>,
2190) -> bool {
2191 counterpart.is_some_and(|counterpart| {
2192 let other_side = side.other();
2193 let line = &file.lines(side)[ix];
2194 let other = &file.lines(other_side)[counterpart];
2195 line.text() == other.text()
2196 && file.source(side)[line.content_end()..line.source().end]
2197 != file.source(other_side)[other.content_end()..other.source().end]
2198 })
2199}
2200
2201#[cfg(test)]
2202mod copy_tests;
2203#[cfg(test)]
2204mod decoration_tests;
2205#[cfg(test)]
2206mod header_tests;
2207#[cfg(test)]
2208mod newline_tests;
2209#[cfg(test)]
2210mod pointer_tests;
2211#[cfg(test)]
2212mod review_tests;
2213#[cfg(test)]
2214mod scroll_tests;
2215#[cfg(test)]
2216mod selection_tests;
2217#[cfg(test)]
2218mod tests;