1use gpui_kit::component::highlighter::{Diagnostic, DiagnosticSeverity};
5use gpui_kit::component::input::{Editor, EditorState, GutterDecoration, GutterDecorationCollection, InputEvent, Position};
6use gpui_kit::assets::IconName;
7use gpui_kit::component::{ActiveTheme as _, Icon, h_flex, v_flex};
8use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::{
10 AppContext as _, Context, Entity, EventEmitter, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Render, SharedString,
11 StatefulInteractiveElement as _, Styled as _, Subscription, TestSupportExt as _, Window, div, px,
12};
13
14use crate::diff::{ChangeMark, LineChange};
15use crate::theme::{self, color};
16
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
19pub enum CodeLanguage {
20 Rust,
22 Python,
24 Json,
26 #[default]
28 Plain,
29}
30
31impl CodeLanguage {
32 pub fn name(self) -> &'static str {
34 match self {
35 CodeLanguage::Rust => "rust",
36 CodeLanguage::Python => "python",
37 CodeLanguage::Json => "json",
38 CodeLanguage::Plain => "text",
39 }
40 }
41
42 pub fn from_name(name: &str) -> Self {
45 match name.trim().to_ascii_lowercase().as_str() {
46 "rust" | "rs" => CodeLanguage::Rust,
47 "python" | "py" | "pyi" => CodeLanguage::Python,
48 "json" | "jsonc" => CodeLanguage::Json,
49 _ => CodeLanguage::Plain,
50 }
51 }
52}
53
54#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct CodeChanged(pub String);
57
58pub struct CodeView {
72 editor: Entity<EditorState>,
73 language: CodeLanguage,
74 errors: Vec<(usize, String)>,
75 editable: bool,
76 max_lines: Option<usize>,
77 marks: GutterDecorationCollection,
78 changes: Vec<ChangeMark>,
80 change_marks: GutterDecorationCollection,
81 pending: bool,
83 _subs: Vec<Subscription>,
84}
85
86impl EventEmitter<CodeChanged> for CodeView {}
87
88impl CodeView {
89 pub fn new(language: CodeLanguage, text: impl Into<SharedString>, window: &mut Window, cx: &mut Context<Self>) -> Self {
91 let text: SharedString = text.into();
92 let editor = cx.new(|cx| {
93 let mut state = EditorState::new(window, cx).language(language.name()).default_value(text).gutter_decorations_width(px(4.));
94 state.set_readonly(true, cx);
95 state
96 });
97 let marks = editor.update(cx, |state, cx| state.create_gutter_decorations_collection(Vec::new(), cx));
98 let change_marks = editor.update(cx, |state, cx| state.create_gutter_decorations_collection(Vec::new(), cx));
99 let sub = cx.subscribe(&editor, |this: &mut Self, editor, e: &InputEvent, cx| {
100 if matches!(e, InputEvent::Change) && this.editable {
101 let text = editor.read(cx).value().to_string();
102 cx.emit(CodeChanged(text));
104 }
105 });
106 Self {
107 editor,
108 language,
109 errors: Vec::new(),
110 editable: false,
111 max_lines: None,
112 marks,
113 changes: Vec::new(),
114 change_marks,
115 pending: false,
116 _subs: vec![sub],
117 }
118 }
119
120 pub fn errors(mut self, errors: Vec<(usize, String)>) -> Self {
122 self.errors = errors;
123 self.pending = true;
124 self
125 }
126
127 pub fn editable(mut self, editable: bool) -> Self {
129 self.editable = editable;
130 self.pending = true;
131 self
132 }
133
134 pub fn max_lines(mut self, lines: usize) -> Self {
137 self.max_lines = Some(lines.max(1));
138 self
139 }
140
141 pub fn set_errors(&mut self, errors: Vec<(usize, String)>, cx: &mut Context<Self>) {
143 self.errors = errors;
144 self.apply_errors(cx);
145 cx.notify();
146 }
147
148 pub fn error_list(&self) -> &[(usize, String)] {
150 &self.errors
151 }
152
153 pub fn set_changes(&mut self, changes: Vec<ChangeMark>, cx: &mut Context<Self>) {
157 self.changes = changes;
158 self.apply_changes(cx);
159 cx.notify();
160 }
161
162 pub fn changes(&self) -> &[ChangeMark] {
164 &self.changes
165 }
166
167 pub fn set_editable(&mut self, editable: bool, cx: &mut Context<Self>) {
169 self.editable = editable;
170 self.editor.update(cx, |state, cx| state.set_readonly(!editable, cx));
171 cx.notify();
172 }
173
174 pub fn is_editable(&self) -> bool {
176 self.editable
177 }
178
179 pub fn set_text(&mut self, text: impl Into<SharedString>, window: &mut Window, cx: &mut Context<Self>) {
181 let text: SharedString = text.into();
182 self.editor.update(cx, |state, cx| state.set_value(text, window, cx));
183 self.apply_errors(cx);
184 self.apply_changes(cx);
185 cx.notify();
186 }
187
188 pub fn text(&self, cx: &gpui_kit::App) -> String {
190 self.editor.read(cx).value().to_string()
191 }
192
193 pub fn set_language(&mut self, language: CodeLanguage, cx: &mut Context<Self>) {
195 self.language = language;
196 self.editor.update(cx, |state, cx| state.set_highlighter(language.name(), cx));
197 cx.notify();
198 }
199
200 pub fn language(&self) -> CodeLanguage {
202 self.language
203 }
204
205 pub fn editor(&self) -> &Entity<EditorState> {
207 &self.editor
208 }
209
210 pub fn go_to_line(&mut self, line: usize, window: &mut Window, cx: &mut Context<Self>) {
212 let row = line.saturating_sub(1) as u32;
213 self.editor.update(cx, |state, cx| {
214 state.set_cursor_position(Position::new(row, 0), window, cx);
215 state.focus(window, cx);
216 });
217 }
218
219 fn apply_errors(&mut self, cx: &mut Context<Self>) {
221 let danger = color::danger();
222 let errors = self.errors.clone();
223 let marks = self.editor.update(cx, |state, cx| {
224 let text = state.value().to_string();
225 let starts: Vec<usize> = std::iter::once(0).chain(text.match_indices('\n').map(|(i, _)| i + 1)).collect();
226 let mut marks = Vec::new();
227 if let Some(set) = state.diagnostics_mut() {
228 set.clear();
229 for (line, message) in &errors {
230 let Some(&start) = starts.get(line.saturating_sub(1)) else { continue };
231 let end = text[start..].find('\n').map_or(text.len(), |i| start + i);
232 let row = line.saturating_sub(1) as u32;
233 let chars = text[start..end].encode_utf16().count() as u32;
234 set.push(Diagnostic::new(Position::new(row, 0)..Position::new(row, chars.max(1)), message.clone()).with_severity(DiagnosticSeverity::Error));
235 let range = if end > start { start..end } else { start..(start + 1).min(text.len()) };
237 marks.push(GutterDecoration::new(range).with_color(danger));
238 }
239 }
240 cx.notify();
241 marks
242 });
243 self.marks.set(marks, cx);
244 }
245
246 fn apply_changes(&mut self, cx: &mut Context<Self>) {
248 let (added, modified, removed) = (color::diff_added(), color::accent_mark(), color::diff_removed());
249 let changes = self.changes.clone();
250 let text = self.editor.read(cx).value().to_string();
251 let starts: Vec<usize> = std::iter::once(0).chain(text.match_indices('\n').map(|(i, _)| i + 1)).collect();
252 let line_end = |line: usize| starts.get(line).map_or(text.len(), |&s| s.saturating_sub(1));
253 let mut marks = Vec::new();
254 for c in &changes {
255 let first = c.line.saturating_sub(1);
256 match c.change {
257 LineChange::Removed => {
258 let at = starts.get(first).copied().unwrap_or_else(|| starts.last().copied().unwrap_or(0));
260 marks.push(GutterDecoration::new(at..(at + 1).min(text.len().max(1))).with_color(removed));
261 }
262 LineChange::Added | LineChange::Modified => {
263 let Some(&start) = starts.get(first) else { continue };
264 let end = line_end(first + c.lines.max(1)).max(start + 1).min(text.len().max(start + 1));
265 let colour = if c.change == LineChange::Added { added } else { modified };
266 marks.push(GutterDecoration::new(start..end).with_color(colour));
267 }
268 }
269 }
270 self.change_marks.set(marks, cx);
271 }
272
273 fn height(&self, cx: &gpui_kit::App) -> Option<Pixels> {
274 let max = self.max_lines?;
275 let lines = (self.editor.read(cx).value().matches('\n').count() + 1).clamp(1, max);
276 let row = cx.theme().mono_font_size * 1.5;
277 Some(row * lines as f32 + px(theme::MD + 2.))
278 }
279}
280
281impl Render for CodeView {
282 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
283 if std::mem::take(&mut self.pending) {
284 let editable = self.editable;
285 self.editor.update(cx, |state, cx| state.set_readonly(!editable, cx));
286 self.apply_errors(cx);
287 }
288 let height = self.height(cx);
289 let editor = Editor::new(&self.editor).readonly(!self.editable).when_some(height, |e, h| e.h(h)).when(height.is_none(), |e| e.h_full());
290 let id = cx.entity_id();
291 let list = self.errors.iter().enumerate().map(|(i, (line, message))| {
292 let line = *line;
293 h_flex()
294 .id(SharedString::from(format!("code-{id}-error-{i}")))
295 .w_full()
296 .min_h(px(theme::TARGET_MIN))
297 .px(px(theme::SM))
298 .gap(px(theme::SM))
299 .items_start()
300 .rounded(px(theme::RADIUS))
301 .cursor_pointer()
302 .hover(|d| d.bg(color::hover()))
303 .child(div().flex_none().mt(px(5.)).w(px(3.)).h(px(14.)).rounded(px(1.)).bg(color::danger()))
304 .child(div().flex_none().py(px(3.)).text_sm().font_weight(FontWeight::SEMIBOLD).text_color(color::danger()).child(format!("Line {line}")))
305 .child(div().flex_1().min_w_0().py(px(3.)).text_sm().child(message.clone()))
306 .on_click(cx.listener(move |this, _, window, cx| this.go_to_line(line, window, cx)))
307 .test_support()
308 });
309 let has_errors = !self.errors.is_empty();
310 v_flex()
311 .w_full()
312 .when(height.is_none(), |d| d.h_full())
313 .gap(px(theme::XS))
314 .child(div().w_full().min_h_0().when(height.is_none(), |d| d.flex_1()).child(editor))
315 .when(has_errors, |d| {
316 d.child(
317 v_flex()
318 .flex_none()
319 .w_full()
320 .child(
321 h_flex()
322 .gap(px(theme::XS))
323 .px(px(theme::SM))
324 .text_xs()
325 .text_color(color::text_muted())
326 .child(Icon::new(IconName::CircleAlert).size(px(12.)).text_color(color::danger()))
327 .child(if self.errors.len() == 1 { "1 error".to_string() } else { format!("{} errors", self.errors.len()) }),
328 )
329 .children(list),
330 )
331 })
332 }
333}