Skip to main content

kitchen_ui/widgets/
code_view.rs

1//! The code view: gpui-kit's code editor (tree-sitter highlighting, line numbers, current line,
2//! selection and copy), read-only or editable, with errors and changed lines (git style) marked.
3
4use gpui_kit::assets::IconName;
5use gpui_kit::component::highlighter::{Diagnostic, DiagnosticSeverity};
6use gpui_kit::component::input::{
7    Editor, EditorState, GutterDecoration, GutterDecorationCollection, InputEvent, Position,
8};
9use gpui_kit::component::{ActiveTheme as _, Icon, h_flex, v_flex};
10use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::{
12    AppContext as _, Context, Entity, EventEmitter, FontWeight, InteractiveElement as _, IntoElement,
13    ParentElement as _, Pixels, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Subscription,
14    TestSupportExt as _, Window, div, px,
15};
16
17use crate::diff::{ChangeMark, LineChange};
18use crate::theme::{self, color};
19
20/// The languages a [`CodeView`] highlights.
21#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
22pub enum CodeLanguage {
23    /// Rust.
24    Rust,
25    /// Python.
26    Python,
27    /// JSON.
28    Json,
29    /// No highlighting.
30    #[default]
31    Plain,
32}
33
34impl CodeLanguage {
35    /// The grammar name gpui-kit knows it by.
36    pub fn name(self) -> &'static str {
37        match self {
38            CodeLanguage::Rust => "rust",
39            CodeLanguage::Python => "python",
40            CodeLanguage::Json => "json",
41            CodeLanguage::Plain => "text",
42        }
43    }
44
45    /// The language of a name or file extension (`"rs"`, `"py"`, `"json"`, …); anything else is
46    /// [`CodeLanguage::Plain`].
47    pub fn from_name(name: &str) -> Self {
48        match name.trim().to_ascii_lowercase().as_str() {
49            "rust" | "rs" => CodeLanguage::Rust,
50            "python" | "py" | "pyi" => CodeLanguage::Python,
51            "json" | "jsonc" => CodeLanguage::Json,
52            _ => CodeLanguage::Plain,
53        }
54    }
55}
56
57/// What an editable [`CodeView`] reports when the user changes the text: the whole text.
58#[derive(Clone, Debug, PartialEq, Eq)]
59pub struct CodeChanged(pub String);
60
61/// Code in a monospace editor: line numbers in a gutter, syntax highlighting (Rust, Python, JSON),
62/// the current line highlighted, selection and copy (read-only too). Errors ([`CodeView::errors`],
63/// 1-based line numbers as compilers report them) get a red mark in the gutter and a red
64/// underline on their line, their message on hover, and are listed under the code: each entry
65/// moves the cursor to its line.
66///
67/// Wraps gpui-kit's `EditorState` (its tree-sitter grammars), so the look follows the theme
68/// ([`theme::apply`] sets the code colours). An editable view emits [`CodeChanged`].
69///
70/// ```ignore
71/// let code = cx.new(|cx| CodeView::new(CodeLanguage::Rust, source, window, cx).errors(vec![(6, "mismatched types".into())]).editable(true));
72/// cx.subscribe(&code, |this, _, CodeChanged(text), cx| { /* … */ }).detach();
73/// ```
74pub struct CodeView {
75    editor: Entity<EditorState>,
76    language: CodeLanguage,
77    errors: Vec<(usize, String)>,
78    editable: bool,
79    max_lines: Option<usize>,
80    marks: GutterDecorationCollection,
81    /// Lines changed against a baseline (git-style gutter marks), shown while on.
82    changes: Vec<ChangeMark>,
83    change_marks: GutterDecorationCollection,
84    /// Errors or editability set by a builder, handed to the editor on the next draw.
85    pending: bool,
86    _subs: Vec<Subscription>,
87}
88
89impl EventEmitter<CodeChanged> for CodeView {}
90
91impl CodeView {
92    /// A read-only view of `text` highlighted as `language`.
93    pub fn new(
94        language: CodeLanguage,
95        text: impl Into<SharedString>,
96        window: &mut Window,
97        cx: &mut Context<Self>,
98    ) -> Self {
99        let text: SharedString = text.into();
100        let editor = cx.new(|cx| {
101            let mut state = EditorState::new(window, cx)
102                .language(language.name())
103                .default_value(text)
104                .gutter_decorations_width(px(4.));
105            state.set_readonly(true, cx);
106            state
107        });
108        let marks = editor.update(cx, |state, cx| state.create_gutter_decorations_collection(Vec::new(), cx));
109        let change_marks = editor.update(cx, |state, cx| state.create_gutter_decorations_collection(Vec::new(), cx));
110        let sub = cx.subscribe(&editor, |this: &mut Self, editor, e: &InputEvent, cx| {
111            if matches!(e, InputEvent::Change) && this.editable {
112                let text = editor.read(cx).value().to_string();
113                // Marks follow the lines they were on; the owner sends new errors when it has them
114                cx.emit(CodeChanged(text));
115            }
116        });
117        Self {
118            editor,
119            language,
120            errors: Vec::new(),
121            editable: false,
122            max_lines: None,
123            marks,
124            changes: Vec::new(),
125            change_marks,
126            pending: false,
127            _subs: vec![sub],
128        }
129    }
130
131    /// Marks these errors: `(line, message)`, lines 1-based.
132    pub fn errors(mut self, errors: Vec<(usize, String)>) -> Self {
133        self.errors = errors;
134        self.pending = true;
135        self
136    }
137
138    /// Editable (`true`) or read-only (the default).
139    pub fn editable(mut self, editable: bool) -> Self {
140        self.editable = editable;
141        self.pending = true;
142        self
143    }
144
145    /// As tall as its text up to `lines` lines, then it scrolls (by default it fills the height
146    /// its parent gives it).
147    pub fn max_lines(mut self, lines: usize) -> Self {
148        self.max_lines = Some(lines.max(1));
149        self
150    }
151
152    /// Marks these errors instead of the ones shown: `(line, message)`, lines 1-based.
153    pub fn set_errors(&mut self, errors: Vec<(usize, String)>, cx: &mut Context<Self>) {
154        self.errors = errors;
155        self.apply_errors(cx);
156        cx.notify();
157    }
158
159    /// The errors shown.
160    pub fn error_list(&self) -> &[(usize, String)] {
161        &self.errors
162    }
163
164    /// Marks these changed lines in the gutter, git style: added green, modified in the accent,
165    /// removed as a red notch where the lines were (`crate::diff::line_changes` computes them).
166    /// An empty list clears the marks: the owner turns them off that way.
167    pub fn set_changes(&mut self, changes: Vec<ChangeMark>, cx: &mut Context<Self>) {
168        self.changes = changes;
169        self.apply_changes(cx);
170        cx.notify();
171    }
172
173    /// The changed lines marked.
174    pub fn changes(&self) -> &[ChangeMark] {
175        &self.changes
176    }
177
178    /// Makes the view editable or read-only.
179    pub fn set_editable(&mut self, editable: bool, cx: &mut Context<Self>) {
180        self.editable = editable;
181        self.editor.update(cx, |state, cx| state.set_readonly(!editable, cx));
182        cx.notify();
183    }
184
185    /// Whether the user can edit the text.
186    pub fn is_editable(&self) -> bool {
187        self.editable
188    }
189
190    /// Replaces the text (no [`CodeChanged`]); the errors shown are kept on their line numbers.
191    pub fn set_text(&mut self, text: impl Into<SharedString>, window: &mut Window, cx: &mut Context<Self>) {
192        let text: SharedString = text.into();
193        self.editor.update(cx, |state, cx| state.set_value(text, window, cx));
194        self.apply_errors(cx);
195        self.apply_changes(cx);
196        cx.notify();
197    }
198
199    /// The text.
200    pub fn text(&self, cx: &gpui_kit::App) -> String {
201        self.editor.read(cx).value().to_string()
202    }
203
204    /// Highlights the text as `language`.
205    pub fn set_language(&mut self, language: CodeLanguage, cx: &mut Context<Self>) {
206        self.language = language;
207        self.editor.update(cx, |state, cx| state.set_highlighter(language.name(), cx));
208        cx.notify();
209    }
210
211    /// The language highlighted.
212    pub fn language(&self) -> CodeLanguage {
213        self.language
214    }
215
216    /// The editor underneath (for its focus handle, cursor, search).
217    pub fn editor(&self) -> &Entity<EditorState> {
218        &self.editor
219    }
220
221    /// Moves the cursor to the start of `line` (1-based) and focuses the code.
222    pub fn go_to_line(&mut self, line: usize, window: &mut Window, cx: &mut Context<Self>) {
223        let row = line.saturating_sub(1) as u32;
224        self.editor.update(cx, |state, cx| {
225            state.set_cursor_position(Position::new(row, 0), window, cx);
226            state.focus(window, cx);
227        });
228    }
229
230    /// Hands the errors to the editor: diagnostics (underline, hover) and gutter marks.
231    fn apply_errors(&mut self, cx: &mut Context<Self>) {
232        let danger = color::danger();
233        let errors = self.errors.clone();
234        let marks = self.editor.update(cx, |state, cx| {
235            let text = state.value().to_string();
236            let starts: Vec<usize> = std::iter::once(0).chain(text.match_indices('\n').map(|(i, _)| i + 1)).collect();
237            let mut marks = Vec::new();
238            if let Some(set) = state.diagnostics_mut() {
239                set.clear();
240                for (line, message) in &errors {
241                    let Some(&start) = starts.get(line.saturating_sub(1)) else { continue };
242                    let end = text[start..].find('\n').map_or(text.len(), |i| start + i);
243                    let row = line.saturating_sub(1) as u32;
244                    let chars = text[start..end].encode_utf16().count() as u32;
245                    set.push(
246                        Diagnostic::new(Position::new(row, 0)..Position::new(row, chars.max(1)), message.clone())
247                            .with_severity(DiagnosticSeverity::Error),
248                    );
249                    // A whole line; an empty line by its newline
250                    let range = if end > start { start..end } else { start..(start + 1).min(text.len()) };
251                    marks.push(GutterDecoration::new(range).with_color(danger));
252                }
253            }
254            cx.notify();
255            marks
256        });
257        self.marks.set(marks, cx);
258    }
259
260    /// Hands the change marks to the editor's gutter, on whole lines.
261    fn apply_changes(&mut self, cx: &mut Context<Self>) {
262        let (added, modified, removed) = (color::diff_added(), color::accent_mark(), color::diff_removed());
263        let changes = self.changes.clone();
264        let text = self.editor.read(cx).value().to_string();
265        let starts: Vec<usize> = std::iter::once(0).chain(text.match_indices('\n').map(|(i, _)| i + 1)).collect();
266        let line_end = |line: usize| starts.get(line).map_or(text.len(), |&s| s.saturating_sub(1));
267        let mut marks = Vec::new();
268        for c in &changes {
269            let first = c.line.saturating_sub(1);
270            match c.change {
271                LineChange::Removed => {
272                    // A notch at the start of the line after the removed ones (or the last line)
273                    let at = starts.get(first).copied().unwrap_or_else(|| starts.last().copied().unwrap_or(0));
274                    marks.push(GutterDecoration::new(at..(at + 1).min(text.len().max(1))).with_color(removed));
275                }
276                LineChange::Added | LineChange::Modified => {
277                    let Some(&start) = starts.get(first) else { continue };
278                    let end = line_end(first + c.lines.max(1)).max(start + 1).min(text.len().max(start + 1));
279                    let colour = if c.change == LineChange::Added { added } else { modified };
280                    marks.push(GutterDecoration::new(start..end).with_color(colour));
281                }
282            }
283        }
284        self.change_marks.set(marks, cx);
285    }
286
287    fn height(&self, cx: &gpui_kit::App) -> Option<Pixels> {
288        let max = self.max_lines?;
289        let lines = (self.editor.read(cx).value().matches('\n').count() + 1).clamp(1, max);
290        let row = cx.theme().mono_font_size * 1.5;
291        Some(row * lines as f32 + px(theme::MD + 2.))
292    }
293}
294
295impl Render for CodeView {
296    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
297        if std::mem::take(&mut self.pending) {
298            let editable = self.editable;
299            self.editor.update(cx, |state, cx| state.set_readonly(!editable, cx));
300            self.apply_errors(cx);
301        }
302        let height = self.height(cx);
303        let editor = Editor::new(&self.editor)
304            .readonly(!self.editable)
305            .when_some(height, |e, h| e.h(h))
306            .when(height.is_none(), |e| e.h_full());
307        let id = cx.entity_id();
308        let list = self.errors.iter().enumerate().map(|(i, (line, message))| {
309            let line = *line;
310            h_flex()
311                .id(SharedString::from(format!("code-{id}-error-{i}")))
312                .w_full()
313                .min_h(px(theme::TARGET_MIN))
314                .px(px(theme::SM))
315                .gap(px(theme::SM))
316                .items_start()
317                .rounded(px(theme::RADIUS))
318                .cursor_pointer()
319                .hover(|d| d.bg(color::hover()))
320                .child(div().flex_none().mt(px(5.)).w(px(3.)).h(px(14.)).rounded(px(1.)).bg(color::danger()))
321                .child(
322                    div()
323                        .flex_none()
324                        .py(px(3.))
325                        .text_sm()
326                        .font_weight(FontWeight::SEMIBOLD)
327                        .text_color(color::danger())
328                        .child(format!("Line {line}")),
329                )
330                .child(div().flex_1().min_w_0().py(px(3.)).text_sm().child(message.clone()))
331                .on_click(cx.listener(move |this, _, window, cx| this.go_to_line(line, window, cx)))
332                .test_support()
333        });
334        let has_errors = !self.errors.is_empty();
335        v_flex()
336            .w_full()
337            .when(height.is_none(), |d| d.h_full())
338            .gap(px(theme::XS))
339            .child(div().w_full().min_h_0().when(height.is_none(), |d| d.flex_1()).child(editor))
340            .when(has_errors, |d| {
341                d.child(
342                    v_flex()
343                        .flex_none()
344                        .w_full()
345                        .child(
346                            h_flex()
347                                .gap(px(theme::XS))
348                                .px(px(theme::SM))
349                                .text_xs()
350                                .text_color(color::text_muted())
351                                .child(Icon::new(IconName::CircleAlert).size(px(12.)).text_color(color::danger()))
352                                .child(if self.errors.len() == 1 {
353                                    "1 error".to_string()
354                                } else {
355                                    format!("{} errors", self.errors.len())
356                                }),
357                        )
358                        .children(list),
359                )
360            })
361    }
362}