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