1use 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
22pub enum CodeLanguage {
23 Rust,
25 Python,
27 Json,
29 #[default]
31 Plain,
32}
33
34impl CodeLanguage {
35 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 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#[derive(Clone, Debug, PartialEq, Eq)]
59pub struct CodeChanged(pub String);
60
61pub 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 changes: Vec<ChangeMark>,
83 change_marks: GutterDecorationCollection,
84 pending: bool,
86 _subs: Vec<Subscription>,
87}
88
89impl EventEmitter<CodeChanged> for CodeView {}
90
91impl CodeView {
92 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 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 pub fn errors(mut self, errors: Vec<(usize, String)>) -> Self {
133 self.errors = errors;
134 self.pending = true;
135 self
136 }
137
138 pub fn editable(mut self, editable: bool) -> Self {
140 self.editable = editable;
141 self.pending = true;
142 self
143 }
144
145 pub fn max_lines(mut self, lines: usize) -> Self {
148 self.max_lines = Some(lines.max(1));
149 self
150 }
151
152 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 pub fn error_list(&self) -> &[(usize, String)] {
161 &self.errors
162 }
163
164 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 pub fn changes(&self) -> &[ChangeMark] {
175 &self.changes
176 }
177
178 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 pub fn is_editable(&self) -> bool {
187 self.editable
188 }
189
190 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 pub fn text(&self, cx: &gpui_kit::App) -> String {
201 self.editor.read(cx).value().to_string()
202 }
203
204 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 pub fn language(&self) -> CodeLanguage {
213 self.language
214 }
215
216 pub fn editor(&self) -> &Entity<EditorState> {
218 &self.editor
219 }
220
221 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 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 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 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 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}