1use crate::{Autoscroll, Editor, Event, MultiBuffer, NavigationData, ToOffset, ToPoint as _};
2use anyhow::Result;
3use gpui::{
4 elements::*, AppContext, Entity, ModelHandle, RenderContext, Subscription, Task, View,
5 ViewContext, ViewHandle, WeakModelHandle,
6};
7use language::{Bias, Buffer, Diagnostic, File as _};
8use project::{File, Project, ProjectPath};
9use std::fmt::Write;
10use std::path::PathBuf;
11use text::{Point, Selection};
12use util::ResultExt;
13use workspace::{Item, ItemHandle, ItemNavHistory, Settings, StatusItemView};
14
15#[derive(Clone)]
16pub struct BufferItemHandle(pub ModelHandle<Buffer>);
17
18#[derive(Clone)]
19struct WeakBufferItemHandle(WeakModelHandle<Buffer>);
20
21#[derive(Clone)]
22pub struct MultiBufferItemHandle(pub ModelHandle<MultiBuffer>);
23
24#[derive(Clone)]
25struct WeakMultiBufferItemHandle(WeakModelHandle<MultiBuffer>);
26
27impl Item for Editor {
28 fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) {
29 if let Some(data) = data.downcast_ref::<NavigationData>() {
30 let buffer = self.buffer.read(cx).read(cx);
31 let offset = if buffer.can_resolve(&data.anchor) {
32 data.anchor.to_offset(&buffer)
33 } else {
34 buffer.clip_offset(data.offset, Bias::Left)
35 };
36
37 drop(buffer);
38 let nav_history = self.nav_history.take();
39 self.select_ranges([offset..offset], Some(Autoscroll::Fit), cx);
40 self.nav_history = nav_history;
41 }
42 }
43
44 fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
45 let title = self.title(cx);
46 Label::new(title, style.label.clone()).boxed()
47 }
48
49 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
50 File::from_dyn(self.buffer().read(cx).file(cx)).map(|file| ProjectPath {
51 worktree_id: file.worktree_id(cx),
52 path: file.path().clone(),
53 })
54 }
55
56 fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
57 where
58 Self: Sized,
59 {
60 Some(self.clone(cx))
61 }
62
63 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
64 self.nav_history = Some(history);
65 }
66
67 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
68 let selection = self.newest_anchor_selection();
69 self.push_to_nav_history(selection.head(), None, cx);
70 }
71
72 fn is_dirty(&self, cx: &AppContext) -> bool {
73 self.buffer().read(cx).read(cx).is_dirty()
74 }
75
76 fn has_conflict(&self, cx: &AppContext) -> bool {
77 self.buffer().read(cx).read(cx).has_conflict()
78 }
79
80 fn can_save(&self, cx: &AppContext) -> bool {
81 !self.buffer().read(cx).is_singleton() || self.project_path(cx).is_some()
82 }
83
84 fn save(
85 &mut self,
86 project: ModelHandle<Project>,
87 cx: &mut ViewContext<Self>,
88 ) -> Task<Result<()>> {
89 let buffer = self.buffer().clone();
90 let buffers = buffer.read(cx).all_buffers();
91 let transaction = project.update(cx, |project, cx| project.format(buffers, true, cx));
92 cx.spawn(|this, mut cx| async move {
93 let transaction = transaction.await.log_err();
94 this.update(&mut cx, |editor, cx| {
95 editor.request_autoscroll(Autoscroll::Fit, cx)
96 });
97 buffer
98 .update(&mut cx, |buffer, cx| {
99 if let Some(transaction) = transaction {
100 if !buffer.is_singleton() {
101 buffer.push_transaction(&transaction.0);
102 }
103 }
104
105 buffer.save(cx)
106 })
107 .await?;
108 Ok(())
109 })
110 }
111
112 fn can_save_as(&self, cx: &AppContext) -> bool {
113 self.buffer().read(cx).is_singleton()
114 }
115
116 fn save_as(
117 &mut self,
118 project: ModelHandle<Project>,
119 abs_path: PathBuf,
120 cx: &mut ViewContext<Self>,
121 ) -> Task<Result<()>> {
122 let buffer = self
123 .buffer()
124 .read(cx)
125 .as_singleton()
126 .expect("cannot call save_as on an excerpt list")
127 .clone();
128
129 project.update(cx, |project, cx| {
130 project.save_buffer_as(buffer, abs_path, cx)
131 })
132 }
133
134 fn should_activate_item_on_event(event: &Event) -> bool {
135 matches!(event, Event::Activate)
136 }
137
138 fn should_close_item_on_event(event: &Event) -> bool {
139 matches!(event, Event::Closed)
140 }
141
142 fn should_update_tab_on_event(event: &Event) -> bool {
143 matches!(event, Event::Saved | Event::Dirtied | Event::TitleChanged)
144 }
145}
146
147pub struct CursorPosition {
148 position: Option<Point>,
149 selected_count: usize,
150 _observe_active_editor: Option<Subscription>,
151}
152
153impl CursorPosition {
154 pub fn new() -> Self {
155 Self {
156 position: None,
157 selected_count: 0,
158 _observe_active_editor: None,
159 }
160 }
161
162 fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
163 let editor = editor.read(cx);
164 let buffer = editor.buffer().read(cx).snapshot(cx);
165
166 self.selected_count = 0;
167 let mut last_selection: Option<Selection<usize>> = None;
168 for selection in editor.local_selections::<usize>(cx) {
169 self.selected_count += selection.end - selection.start;
170 if last_selection
171 .as_ref()
172 .map_or(true, |last_selection| selection.id > last_selection.id)
173 {
174 last_selection = Some(selection);
175 }
176 }
177 self.position = last_selection.map(|s| s.head().to_point(&buffer));
178
179 cx.notify();
180 }
181}
182
183impl Entity for CursorPosition {
184 type Event = ();
185}
186
187impl View for CursorPosition {
188 fn ui_name() -> &'static str {
189 "CursorPosition"
190 }
191
192 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
193 if let Some(position) = self.position {
194 let theme = &cx.app_state::<Settings>().theme.workspace.status_bar;
195 let mut text = format!("{},{}", position.row + 1, position.column + 1);
196 if self.selected_count > 0 {
197 write!(text, " ({} selected)", self.selected_count).unwrap();
198 }
199 Label::new(text, theme.cursor_position.clone()).boxed()
200 } else {
201 Empty::new().boxed()
202 }
203 }
204}
205
206impl StatusItemView for CursorPosition {
207 fn set_active_pane_item(
208 &mut self,
209 active_pane_item: Option<&dyn ItemHandle>,
210 cx: &mut ViewContext<Self>,
211 ) {
212 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
213 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
214 self.update_position(editor, cx);
215 } else {
216 self.position = None;
217 self._observe_active_editor = None;
218 }
219
220 cx.notify();
221 }
222}
223
224pub struct DiagnosticMessage {
225 diagnostic: Option<Diagnostic>,
226 _observe_active_editor: Option<Subscription>,
227}
228
229impl DiagnosticMessage {
230 pub fn new() -> Self {
231 Self {
232 diagnostic: None,
233 _observe_active_editor: None,
234 }
235 }
236
237 fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
238 let editor = editor.read(cx);
239 let buffer = editor.buffer().read(cx);
240 let cursor_position = editor
241 .newest_selection_with_snapshot::<usize>(&buffer.read(cx))
242 .head();
243 let new_diagnostic = buffer
244 .read(cx)
245 .diagnostics_in_range::<_, usize>(cursor_position..cursor_position, false)
246 .filter(|entry| !entry.range.is_empty())
247 .min_by_key(|entry| (entry.diagnostic.severity, entry.range.len()))
248 .map(|entry| entry.diagnostic);
249 if new_diagnostic != self.diagnostic {
250 self.diagnostic = new_diagnostic;
251 cx.notify();
252 }
253 }
254}
255
256impl Entity for DiagnosticMessage {
257 type Event = ();
258}
259
260impl View for DiagnosticMessage {
261 fn ui_name() -> &'static str {
262 "DiagnosticMessage"
263 }
264
265 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
266 if let Some(diagnostic) = &self.diagnostic {
267 let theme = &cx.app_state::<Settings>().theme.workspace.status_bar;
268 Label::new(
269 diagnostic.message.split('\n').next().unwrap().to_string(),
270 theme.diagnostic_message.clone(),
271 )
272 .boxed()
273 } else {
274 Empty::new().boxed()
275 }
276 }
277}
278
279impl StatusItemView for DiagnosticMessage {
280 fn set_active_pane_item(
281 &mut self,
282 active_pane_item: Option<&dyn ItemHandle>,
283 cx: &mut ViewContext<Self>,
284 ) {
285 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
286 self._observe_active_editor = Some(cx.observe(&editor, Self::update));
287 self.update(editor, cx);
288 } else {
289 self.diagnostic = Default::default();
290 self._observe_active_editor = None;
291 }
292 cx.notify();
293 }
294}