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