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