diff: Derive colors from theme

19f8c16de7b4c62270369a249fadb40e3836c2f9
Uses the loaded theme color map to choose rustik-diff addition and deletion
chrome.
Alexis Sellier committed ago 1 parent 6c3731c1
crates/diff/src/bin/rustik-diff.rs +8 -3
133 133
        io::stdout().write_all(input)?;
134 134
        return Ok(());
135 135
    }
136 136
    let text = std::str::from_utf8(input).map_err(|error| Error::Input(error.to_string()))?;
137 137
    let document = DiffDocument::decode_str(text)?;
138 +
    let raw_theme = BUILTIN_THEME.parse::<syntax::RawTheme>()?;
139 +
    let options = DiffOptions {
140 +
        diff_palette: (&raw_theme).into(),
141 +
        ..DiffOptions::default()
142 +
    };
138 143
139 144
    if !io::stdout().is_terminal() {
140 -
        let mut viewer = DiffViewer::new(document, DiffOptions::default());
145 +
        let mut viewer = DiffViewer::new(document, options);
141 146
        let rows = viewer.content_rows(STATIC_COLS).min(STATIC_MAX_ROWS);
142 147
        let constraints = tui::Constraint::max(tui::Size::new(STATIC_COLS, rows));
143 148
144 149
        tui_termion::term::write_to_stdout(&mut viewer, constraints)?;
145 150
        return Ok(());
146 151
    }
147 152
    let backend = tui_termion::term::screen()?;
148 153
    let mut terminal = Terminal::new(backend)?;
149 154
    let mut registry = syntax::Registry::default();
150 -
    let theme = BUILTIN_THEME.parse()?;
155 +
    let theme = syntax::Theme::compile(&raw_theme);
151 156
    registry.add_theme(theme);
152 157
153 158
    for syntax in COMMON_SYNTAXES
154 159
        .iter()
155 160
        .filter(|syntax| syntax.matches_document(&document))
156 161
    {
157 162
        registry.add_grammar(syntax.grammar()?);
158 163
    }
159 164
    let highlighter = BuiltinHighlighter::new(registry, BUILTIN_THEME_NAME);
160 -
    let mut viewer = DiffViewer::new(document, DiffOptions::default());
165 +
    let mut viewer = DiffViewer::new(document, options);
161 166
162 167
    terminal.clear()?;
163 168
    terminal.set_cursor_visible(false)?;
164 169
165 170
    let result = terminal_loop(&mut terminal, &mut viewer, header, highlighter);
+0 -0
+0 -0
a.rs +0 -0
crates/diff/src/lib.rs +3 -1
23 23
pub use encode::Encode;
24 24
pub use highlight::{
25 25
    BuiltinHighlighter, DiffSide, HighlightKey, HighlightKeyInput, HighlightRequest,
26 26
    HighlightResult, HighlightSource,
27 27
};
28 -
pub use renderer::{DiffAction, DiffFocus, DiffOptions, DiffState, DiffViewer, ViewChange};
28 +
pub use renderer::{
29 +
    DiffAction, DiffFocus, DiffOptions, DiffPalette, DiffState, DiffViewer, ViewChange,
30 +
};
crates/diff/src/renderer.rs +97 -24
1 1
//! Read-only diff viewer state and buffer renderer.
2 2
3 3
use std::collections::{BTreeMap, BTreeSet};
4 4
use std::path::PathBuf;
5 5
6 +
use rustik_highlight as syntax;
6 7
use rustik_tui as tui;
7 8
use tui::{
8 9
    Buffer, Cell, Color, Constraint, HStack, Label, Line, Placement, Rect, Scroll, ScrollView,
9 10
    ScrollbarStyle, Size, Style, Text, View, Viewport, Widget, colors,
10 11
};
103 104
    pub highlight_lookahead: usize,
104 105
    /// Optional syntax override stored in highlight requests.
105 106
    pub syntax: Option<String>,
106 107
    /// Theme name stored in highlight requests.
107 108
    pub theme: String,
109 +
    /// Positive and negative colors used for diff chrome.
110 +
    pub diff_palette: DiffPalette,
111 +
}
112 +
113 +
/// Positive and negative colors used for diff chrome.
114 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
115 +
pub struct DiffPalette {
116 +
    /// Background color for removed line-number cells.
117 +
    pub negative_gutter_bg: Color,
118 +
    /// Background color for added line-number cells.
119 +
    pub positive_gutter_bg: Color,
120 +
    /// Background color for removed source rows.
121 +
    pub negative_row_bg: Color,
122 +
    /// Background color for added source rows.
123 +
    pub positive_row_bg: Color,
124 +
    /// Foreground color for removed stats, markers, and labels.
125 +
    pub negative_fg: Color,
126 +
    /// Foreground color for added stats, markers, and labels.
127 +
    pub positive_fg: Color,
108 128
}
109 129
110 130
/// Pure diff viewer that renders into a caller-owned buffer.
111 131
#[derive(Clone, Debug)]
112 132
pub struct DiffViewer {
167 187
    fn default() -> Self {
168 188
        Self {
169 189
            highlight_lookahead: DEFAULT_HIGHLIGHT_LOOKAHEAD,
170 190
            syntax: None,
171 191
            theme: DEFAULT_THEME.to_owned(),
192 +
            diff_palette: DiffPalette::default(),
193 +
        }
194 +
    }
195 +
}
196 +
197 +
impl Default for DiffPalette {
198 +
    fn default() -> Self {
199 +
        Self {
200 +
            negative_gutter_bg: colors::rgb::NEGATIVE,
201 +
            positive_gutter_bg: colors::rgb::POSITIVE,
202 +
            negative_row_bg: colors::rgb::NEGATIVE_DARK,
203 +
            positive_row_bg: colors::rgb::POSITIVE_DARK,
204 +
            negative_fg: colors::rgb::NEGATIVE_LIGHT,
205 +
            positive_fg: colors::rgb::POSITIVE_LIGHT,
172 206
        }
173 207
    }
174 208
}
175 209
210 +
impl From<&syntax::RawTheme> for DiffPalette {
211 +
    fn from(theme: &syntax::RawTheme) -> Self {
212 +
        let mut palette = Self::default();
213 +
        if theme.colors.is_empty() {
214 +
            return palette;
215 +
        };
216 +
        palette.positive_fg =
217 +
            Self::theme_color(&theme.colors, "gitDecoration.addedResourceForeground")
218 +
                .or_else(|| Self::theme_color(&theme.colors, "editorGutter.addedBackground"))
219 +
                .unwrap_or(palette.positive_fg);
220 +
        palette.negative_fg =
221 +
            Self::theme_color(&theme.colors, "gitDecoration.deletedResourceForeground")
222 +
                .or_else(|| Self::theme_color(&theme.colors, "editorGutter.deletedBackground"))
223 +
                .unwrap_or(palette.negative_fg);
224 +
        palette.positive_gutter_bg =
225 +
            Self::theme_color(&theme.colors, "diffEditor.insertedTextBackground")
226 +
                .unwrap_or(palette.positive_gutter_bg);
227 +
        palette.negative_gutter_bg =
228 +
            Self::theme_color(&theme.colors, "diffEditor.removedTextBackground")
229 +
                .unwrap_or(palette.negative_gutter_bg);
230 +
        palette.positive_row_bg =
231 +
            Self::theme_color(&theme.colors, "diffEditor.insertedLineBackground")
232 +
                .unwrap_or(palette.positive_row_bg);
233 +
        palette.negative_row_bg =
234 +
            Self::theme_color(&theme.colors, "diffEditor.removedLineBackground")
235 +
                .unwrap_or(palette.negative_row_bg);
236 +
        palette
237 +
    }
238 +
}
239 +
240 +
impl DiffPalette {
241 +
    /// Returns one RGB color from a theme color map.
242 +
    fn theme_color(colors: &BTreeMap<String, String>, key: &str) -> Option<Color> {
243 +
        let color = colors.get(key)?.parse::<syntax::Rgb>().ok()?;
244 +
        Some(Color::RGB(color.r, color.g, color.b))
245 +
    }
246 +
}
247 +
176 248
impl DiffViewer {
177 249
    /// Creates a viewer with plain initial rendering state.
178 250
    pub fn new(document: DiffDocument, options: DiffOptions) -> Self {
179 251
        Self {
180 252
            document,
397 469
                diff: None,
398 470
            };
399 471
        }
400 472
        if local == 1 {
401 473
            return RenderRow {
402 -
                line: wrap(file.header_line(child_cols)),
474 +
                line: wrap(file.header_line(child_cols, self.options.diff_palette)),
403 475
                diff: None,
404 476
            };
405 477
        }
406 478
        if local == bottom {
407 479
            return RenderRow {
597 669
                    });
598 670
                }
599 671
            }
600 672
            row += file.rendered_rows(collapsed);
601 673
        }
602 -
603 674
        targets
604 675
    }
605 676
606 677
    /// Toggles the file containing the current focus.
607 678
    fn toggle_focused_file(&mut self) {
678 749
        source_cols: usize,
679 750
    ) -> RenderRow {
680 751
        let (cells, source, style) = match line.kind {
681 752
            DiffLineKind::Addition => (
682 753
                [
683 -
                    Self::blank_number(colors::rgb::POSITIVE),
754 +
                    Self::blank_number(self.options.diff_palette.positive_gutter_bg),
684 755
                    Self::number_cell(
685 756
                        meta.source_line,
686 -
                        colors::rgb::POSITIVE_LIGHT,
687 -
                        colors::rgb::POSITIVE,
757 +
                        self.options.diff_palette.positive_fg,
758 +
                        self.options.diff_palette.positive_gutter_bg,
688 759
                    ),
689 -
                    Self::marker_cell(" + ", colors::rgb::POSITIVE_LIGHT),
760 +
                    Self::marker_cell(" + ", self.options.diff_palette.positive_fg),
690 761
                ],
691 762
                self.highlighted_or_plain(&meta, source_cols),
692 -
                Style::default().bg(colors::rgb::POSITIVE_DARK),
763 +
                Style::default().bg(self.options.diff_palette.positive_row_bg),
693 764
            ),
694 765
            DiffLineKind::Deletion => (
695 766
                [
696 767
                    Self::number_cell(
697 768
                        meta.source_line,
698 -
                        colors::rgb::NEGATIVE_LIGHT,
699 -
                        colors::rgb::NEGATIVE,
769 +
                        self.options.diff_palette.negative_fg,
770 +
                        self.options.diff_palette.negative_gutter_bg,
700 771
                    ),
701 -
                    Self::blank_number(colors::rgb::NEGATIVE),
702 -
                    Self::marker_cell(" - ", colors::rgb::NEGATIVE_LIGHT),
772 +
                    Self::blank_number(self.options.diff_palette.negative_gutter_bg),
773 +
                    Self::marker_cell(" - ", self.options.diff_palette.negative_fg),
703 774
                ],
704 775
                self.highlighted_or_plain(&meta, source_cols),
705 -
                Style::default().bg(colors::rgb::NEGATIVE_DARK).dim(),
776 +
                Style::default()
777 +
                    .bg(self.options.diff_palette.negative_row_bg)
778 +
                    .dim(),
706 779
            ),
707 780
            DiffLineKind::Context => (
708 781
                [
709 782
                    Self::number_cell(old_line, colors::rgb::DIM, colors::rgb::FAINT),
710 783
                    Self::number_cell(meta.source_line, colors::rgb::DIM, colors::rgb::FAINT),
722 795
                Line::new(NO_NEWLINE_MARKER).style(Style::default().fg(colors::rgb::DIM)),
723 796
                Style::default(),
724 797
            ),
725 798
        };
726 799
        let rendered = self.hunk_line(cells, source, source_cols, style);
800 +
727 801
        RenderRow {
728 802
            line: rendered,
729 803
            diff: Some(meta),
730 804
        }
731 805
    }
934 1008
                    text.push('\n');
935 1009
                    line_no += 1;
936 1010
                }
937 1011
            }
938 1012
        }
939 -
940 1013
        HighlightSource::new(text, head)
941 1014
    }
942 1015
943 1016
    /// Returns a file header line.
944 -
    fn header_line(&self, cols: usize) -> Line {
1017 +
    fn header_line(&self, cols: usize, palette: DiffPalette) -> Line {
945 1018
        let mut left = Line::blank();
946 1019
        left.push(Label::from_char(FILE_MARKER).fg(colors::fixed::DIM));
947 1020
        left.push(Label::space());
948 1021
        left = left.extend(self.path_line());
949 1022
950 -
        if let Some(badge) = self.badge() {
1023 +
        if let Some(badge) = self.badge(palette) {
951 1024
            left.push(Label::space());
952 1025
            left.push(badge);
953 1026
        }
954 1027
        let mut header = HStack::default().child(left).spacer();
955 1028
        let stats = self.stats();
956 1029
957 -
        if let Some(side) = Self::diffstat_line(stats.additions, stats.deletions) {
1030 +
        if let Some(side) = Self::diffstat_line(stats.additions, stats.deletions, palette) {
958 1031
            header = header.child(side);
959 1032
        }
960 1033
        header.to_line(Constraint::tight(cols))
961 1034
    }
962 1035
971 1044
            _ => Line::new(Self::display_path(self.header.display_path())),
972 1045
        }
973 1046
    }
974 1047
975 1048
    /// Returns an additions-first diffstat line.
976 -
    fn diffstat_line(additions: usize, deletions: usize) -> Option<Line> {
1049 +
    fn diffstat_line(additions: usize, deletions: usize, palette: DiffPalette) -> Option<Line> {
977 1050
        if additions == 0 && deletions == 0 {
978 1051
            return None;
979 1052
        }
980 1053
        let mut line = Line::blank();
981 1054
        if additions > 0 {
982 -
            line.push(Label::new(&format!("+{additions}")).fg(colors::rgb::POSITIVE_LIGHT));
1055 +
            line.push(Label::new(&format!("+{additions}")).fg(palette.positive_fg));
983 1056
        }
984 1057
        if deletions > 0 {
985 1058
            if additions > 0 {
986 1059
                line.push(Label::space());
987 1060
            }
988 -
            line.push(Label::new(&format!("-{deletions}")).fg(colors::rgb::NEGATIVE_LIGHT));
1061 +
            line.push(Label::new(&format!("-{deletions}")).fg(palette.negative_fg));
989 1062
        }
990 1063
        Some(line)
991 1064
    }
992 1065
993 1066
    /// Returns a file-kind badge.
994 -
    fn badge(&self) -> Option<Label> {
1067 +
    fn badge(&self, palette: DiffPalette) -> Option<Label> {
995 1068
        match self.header.kind {
996 1069
            FileKind::Added => Some(Self::change_badge(
997 1070
                "created",
998 -
                colors::rgb::POSITIVE_LIGHT,
999 -
                colors::rgb::POSITIVE_DARK,
1071 +
                palette.positive_fg,
1072 +
                palette.positive_row_bg,
1000 1073
            )),
1001 1074
            FileKind::Deleted => Some(Self::change_badge(
1002 1075
                "deleted",
1003 -
                colors::rgb::NEGATIVE_LIGHT,
1004 -
                colors::rgb::NEGATIVE_DARK,
1076 +
                palette.negative_fg,
1077 +
                palette.negative_row_bg,
1005 1078
            )),
1006 1079
            FileKind::Renamed => Some(Self::change_badge("moved", Color::Blue, Color::Fixed(236))),
1007 1080
            FileKind::Copied => Some(Self::change_badge("copied", Color::Blue, Color::Fixed(236))),
1008 1081
            FileKind::ModeChanged => Some(Self::change_badge(
1009 1082
                "mode changed",
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs +0 -0
crates/highlight/src/raw.rs +3 -1
71 71
/// A parsed, uncompiled TextMate theme.
72 72
#[derive(Clone, Debug, Deserialize)]
73 73
pub struct RawTheme {
74 74
    /// Theme name.
75 75
    pub name: String,
76 +
    /// Editor UI color keys.
77 +
    pub colors: BTreeMap<String, String>,
76 78
    /// TextMate theme settings.
77 79
    pub settings: Option<Vec<RawThemeRule>>,
78 -
    /// VS Code token color rules.
80 +
    /// TextMate token color rules.
79 81
    #[serde(rename = "tokenColors")]
80 82
    pub token_colors: Option<Vec<RawThemeRule>>,
81 83
}
82 84
83 85
/// One parsed TextMate theme rule.