1use crate::{Editor, EditorSettings, Event};
2use anyhow::Result;
3use gpui::{
4 elements::*, fonts::TextStyle, AppContext, Entity, ModelContext, ModelHandle,
5 MutableAppContext, RenderContext, Subscription, Task, View, ViewContext, ViewHandle,
6 WeakModelHandle,
7};
8use language::{
9 multi_buffer::{MultiBuffer, ToPoint as _},
10 Diagnostic, File as _,
11};
12use postage::watch;
13use project::{ProjectPath, Worktree};
14use std::fmt::Write;
15use std::path::Path;
16use text::{Point, Selection};
17use workspace::{
18 settings, EntryOpener, ItemHandle, ItemView, ItemViewHandle, Settings, StatusItemView,
19 WeakItemHandle,
20};
21
22pub struct BufferOpener;
23
24#[derive(Clone)]
25pub struct BufferItemHandle(pub ModelHandle<MultiBuffer>);
26
27#[derive(Clone)]
28struct WeakBufferItemHandle(WeakModelHandle<MultiBuffer>);
29
30impl EntryOpener for BufferOpener {
31 fn open(
32 &self,
33 worktree: &mut Worktree,
34 project_path: ProjectPath,
35 cx: &mut ModelContext<Worktree>,
36 ) -> Option<Task<Result<Box<dyn ItemHandle>>>> {
37 let buffer = worktree.open_buffer(project_path.path, cx);
38 let task = cx.spawn(|_, mut cx| async move {
39 let buffer = buffer.await?;
40 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
41 Ok(Box::new(BufferItemHandle(buffer)) as Box<dyn ItemHandle>)
42 });
43 Some(task)
44 }
45}
46
47impl ItemHandle for BufferItemHandle {
48 fn add_view(
49 &self,
50 window_id: usize,
51 settings: watch::Receiver<Settings>,
52 cx: &mut MutableAppContext,
53 ) -> Box<dyn ItemViewHandle> {
54 let buffer = self.0.downgrade();
55 Box::new(cx.add_view(window_id, |cx| {
56 Editor::for_buffer(
57 self.0.clone(),
58 move |cx| {
59 let settings = settings.borrow();
60 let font_cache = cx.font_cache();
61 let font_family_id = settings.buffer_font_family;
62 let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
63 let font_properties = Default::default();
64 let font_id = font_cache
65 .select_font(font_family_id, &font_properties)
66 .unwrap();
67 let font_size = settings.buffer_font_size;
68
69 let mut theme = settings.theme.editor.clone();
70 theme.text = TextStyle {
71 color: theme.text.color,
72 font_family_name,
73 font_family_id,
74 font_id,
75 font_size,
76 font_properties,
77 underline: None,
78 };
79 let language = buffer
80 .upgrade(cx)
81 .and_then(|buf| buf.read(cx).read(cx).language());
82 let soft_wrap = match settings.soft_wrap(language) {
83 settings::SoftWrap::None => crate::SoftWrap::None,
84 settings::SoftWrap::EditorWidth => crate::SoftWrap::EditorWidth,
85 settings::SoftWrap::PreferredLineLength => crate::SoftWrap::Column(
86 settings.preferred_line_length(language).saturating_sub(1),
87 ),
88 };
89
90 EditorSettings {
91 tab_size: settings.tab_size,
92 soft_wrap,
93 style: theme,
94 }
95 },
96 cx,
97 )
98 }))
99 }
100
101 fn boxed_clone(&self) -> Box<dyn ItemHandle> {
102 Box::new(self.clone())
103 }
104
105 fn downgrade(&self) -> Box<dyn workspace::WeakItemHandle> {
106 Box::new(WeakBufferItemHandle(self.0.downgrade()))
107 }
108
109 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
110 self.0.read(cx).file(cx).map(|f| ProjectPath {
111 worktree_id: f.worktree_id(),
112 path: f.path().clone(),
113 })
114 }
115}
116
117impl WeakItemHandle for WeakBufferItemHandle {
118 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
119 self.0
120 .upgrade(cx)
121 .map(|buffer| Box::new(BufferItemHandle(buffer)) as Box<dyn ItemHandle>)
122 }
123}
124
125impl ItemView for Editor {
126 fn should_activate_item_on_event(event: &Event) -> bool {
127 matches!(event, Event::Activate)
128 }
129
130 fn should_close_item_on_event(event: &Event) -> bool {
131 matches!(event, Event::Closed)
132 }
133
134 fn should_update_tab_on_event(event: &Event) -> bool {
135 matches!(
136 event,
137 Event::Saved | Event::Dirtied | Event::FileHandleChanged
138 )
139 }
140
141 fn title(&self, cx: &AppContext) -> String {
142 let filename = self
143 .buffer()
144 .read(cx)
145 .file(cx)
146 .and_then(|file| file.file_name());
147 if let Some(name) = filename {
148 name.to_string_lossy().into()
149 } else {
150 "untitled".into()
151 }
152 }
153
154 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
155 self.buffer().read(cx).file(cx).map(|file| ProjectPath {
156 worktree_id: file.worktree_id(),
157 path: file.path().clone(),
158 })
159 }
160
161 fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
162 where
163 Self: Sized,
164 {
165 Some(self.clone(cx))
166 }
167
168 fn save(&mut self, cx: &mut ViewContext<Self>) -> Result<Task<Result<()>>> {
169 let save = self.buffer().update(cx, |b, cx| b.save(cx))?;
170 Ok(cx.spawn(|_, _| async move {
171 save.await?;
172 Ok(())
173 }))
174 }
175
176 fn save_as(
177 &mut self,
178 worktree: ModelHandle<Worktree>,
179 path: &Path,
180 cx: &mut ViewContext<Self>,
181 ) -> Task<Result<()>> {
182 let buffer = self
183 .buffer()
184 .read(cx)
185 .as_singleton()
186 .expect("cannot call save_as on an excerpt list")
187 .clone();
188
189 buffer.update(cx, |buffer, cx| {
190 let handle = cx.handle();
191 let text = buffer.as_rope().clone();
192 let version = buffer.version();
193
194 let save_as = worktree.update(cx, |worktree, cx| {
195 worktree
196 .as_local_mut()
197 .unwrap()
198 .save_buffer_as(handle, path, text, cx)
199 });
200
201 cx.spawn(|buffer, mut cx| async move {
202 save_as.await.map(|new_file| {
203 let (language, language_server) = worktree.update(&mut cx, |worktree, cx| {
204 let worktree = worktree.as_local_mut().unwrap();
205 let language = worktree
206 .languages()
207 .select_language(new_file.full_path())
208 .cloned();
209 let language_server = language
210 .as_ref()
211 .and_then(|language| worktree.ensure_language_server(language, cx));
212 (language, language_server.clone())
213 });
214
215 buffer.update(&mut cx, |buffer, cx| {
216 buffer.did_save(version, new_file.mtime, Some(Box::new(new_file)), cx);
217 buffer.set_language(language, language_server, cx);
218 });
219 })
220 })
221 })
222 }
223
224 fn is_dirty(&self, cx: &AppContext) -> bool {
225 self.buffer().read(cx).is_dirty()
226 }
227
228 fn has_conflict(&self, cx: &AppContext) -> bool {
229 self.buffer().read(cx).has_conflict()
230 }
231}
232
233pub struct CursorPosition {
234 position: Option<Point>,
235 selected_count: usize,
236 settings: watch::Receiver<Settings>,
237 _observe_active_editor: Option<Subscription>,
238}
239
240impl CursorPosition {
241 pub fn new(settings: watch::Receiver<Settings>) -> Self {
242 Self {
243 position: None,
244 selected_count: 0,
245 settings,
246 _observe_active_editor: None,
247 }
248 }
249
250 fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
251 let editor = editor.read(cx);
252 let buffer = editor.buffer().read(cx).snapshot(cx);
253
254 self.selected_count = 0;
255 let mut last_selection: Option<Selection<usize>> = None;
256 for selection in editor.selections::<usize>(cx) {
257 self.selected_count += selection.end - selection.start;
258 if last_selection
259 .as_ref()
260 .map_or(true, |last_selection| selection.id > last_selection.id)
261 {
262 last_selection = Some(selection);
263 }
264 }
265 self.position = last_selection.map(|s| s.head().to_point(&buffer));
266
267 cx.notify();
268 }
269}
270
271impl Entity for CursorPosition {
272 type Event = ();
273}
274
275impl View for CursorPosition {
276 fn ui_name() -> &'static str {
277 "CursorPosition"
278 }
279
280 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
281 if let Some(position) = self.position {
282 let theme = &self.settings.borrow().theme.workspace.status_bar;
283 let mut text = format!("{},{}", position.row + 1, position.column + 1);
284 if self.selected_count > 0 {
285 write!(text, " ({} selected)", self.selected_count).unwrap();
286 }
287 Label::new(text, theme.cursor_position.clone()).boxed()
288 } else {
289 Empty::new().boxed()
290 }
291 }
292}
293
294impl StatusItemView for CursorPosition {
295 fn set_active_pane_item(
296 &mut self,
297 active_pane_item: Option<&dyn ItemViewHandle>,
298 cx: &mut ViewContext<Self>,
299 ) {
300 if let Some(editor) = active_pane_item.and_then(|item| item.to_any().downcast::<Editor>()) {
301 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
302 self.update_position(editor, cx);
303 } else {
304 self.position = None;
305 self._observe_active_editor = None;
306 }
307
308 cx.notify();
309 }
310}
311
312pub struct DiagnosticMessage {
313 settings: watch::Receiver<Settings>,
314 diagnostic: Option<Diagnostic>,
315 _observe_active_editor: Option<Subscription>,
316}
317
318impl DiagnosticMessage {
319 pub fn new(settings: watch::Receiver<Settings>) -> Self {
320 Self {
321 diagnostic: None,
322 settings,
323 _observe_active_editor: None,
324 }
325 }
326
327 fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
328 let editor = editor.read(cx);
329 let cursor_position = editor.newest_selection::<usize>(cx).head();
330 let buffer = editor.buffer().read(cx);
331 let new_diagnostic = buffer
332 .read(cx)
333 .diagnostics_in_range::<_, usize>(cursor_position..cursor_position)
334 .filter(|entry| !entry.range.is_empty())
335 .min_by_key(|entry| (entry.diagnostic.severity, entry.range.len()))
336 .map(|entry| entry.diagnostic);
337 if new_diagnostic != self.diagnostic {
338 self.diagnostic = new_diagnostic;
339 cx.notify();
340 }
341 }
342}
343
344impl Entity for DiagnosticMessage {
345 type Event = ();
346}
347
348impl View for DiagnosticMessage {
349 fn ui_name() -> &'static str {
350 "DiagnosticMessage"
351 }
352
353 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
354 if let Some(diagnostic) = &self.diagnostic {
355 let theme = &self.settings.borrow().theme.workspace.status_bar;
356 Flex::row()
357 .with_child(
358 Svg::new("icons/warning.svg")
359 .with_color(theme.diagnostic_icon_color)
360 .constrained()
361 .with_height(theme.diagnostic_icon_size)
362 .contained()
363 .with_margin_right(theme.diagnostic_icon_spacing)
364 .boxed(),
365 )
366 .with_child(
367 Label::new(
368 diagnostic.message.lines().next().unwrap().to_string(),
369 theme.diagnostic_message.clone(),
370 )
371 .boxed(),
372 )
373 .boxed()
374 } else {
375 Empty::new().boxed()
376 }
377 }
378}
379
380impl StatusItemView for DiagnosticMessage {
381 fn set_active_pane_item(
382 &mut self,
383 active_pane_item: Option<&dyn ItemViewHandle>,
384 cx: &mut ViewContext<Self>,
385 ) {
386 if let Some(editor) = active_pane_item.and_then(|item| item.to_any().downcast::<Editor>()) {
387 self._observe_active_editor = Some(cx.observe(&editor, Self::update));
388 self.update(editor, cx);
389 } else {
390 self.diagnostic = Default::default();
391 self._observe_active_editor = None;
392 }
393 cx.notify();
394 }
395}