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 tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
125 let title = self.title(cx);
126 Label::new(title, style.label.clone()).boxed()
127 }
128
129 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
130 File::from_dyn(self.buffer().read(cx).file(cx)).map(|file| ProjectPath {
131 worktree_id: file.worktree_id(cx),
132 path: file.path().clone(),
133 })
134 }
135
136 fn clone_on_split(&self, cx: &mut ViewContext<Self>) -> Option<Self>
137 where
138 Self: Sized,
139 {
140 Some(self.clone(cx))
141 }
142
143 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
144 if let Some(selection) = self.newest_anchor_selection() {
145 self.push_to_nav_history(selection.head(), None, cx);
146 }
147 }
148
149 fn is_dirty(&self, cx: &AppContext) -> bool {
150 self.buffer().read(cx).read(cx).is_dirty()
151 }
152
153 fn has_conflict(&self, cx: &AppContext) -> bool {
154 self.buffer().read(cx).read(cx).has_conflict()
155 }
156
157 fn can_save(&self, cx: &AppContext) -> bool {
158 self.project_path(cx).is_some()
159 }
160
161 fn save(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
162 let buffer = self.buffer().clone();
163 cx.spawn(|editor, mut cx| async move {
164 buffer
165 .update(&mut cx, |buffer, cx| buffer.format(cx).log_err())
166 .await;
167 editor.update(&mut cx, |editor, cx| {
168 editor.request_autoscroll(Autoscroll::Fit, cx)
169 });
170 buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
171 Ok(())
172 })
173 }
174
175 fn can_save_as(&self, _: &AppContext) -> bool {
176 true
177 }
178
179 fn save_as(
180 &mut self,
181 project: ModelHandle<Project>,
182 abs_path: PathBuf,
183 cx: &mut ViewContext<Self>,
184 ) -> Task<Result<()>> {
185 let buffer = self
186 .buffer()
187 .read(cx)
188 .as_singleton()
189 .expect("cannot call save_as on an excerpt list")
190 .clone();
191
192 project.update(cx, |project, cx| {
193 project.save_buffer_as(buffer, abs_path, cx)
194 })
195 }
196
197 fn should_activate_item_on_event(event: &Event) -> bool {
198 matches!(event, Event::Activate)
199 }
200
201 fn should_close_item_on_event(event: &Event) -> bool {
202 matches!(event, Event::Closed)
203 }
204
205 fn should_update_tab_on_event(event: &Event) -> bool {
206 matches!(event, Event::Saved | Event::Dirtied | Event::TitleChanged)
207 }
208}
209
210pub struct CursorPosition {
211 position: Option<Point>,
212 selected_count: usize,
213 settings: watch::Receiver<Settings>,
214 _observe_active_editor: Option<Subscription>,
215}
216
217impl CursorPosition {
218 pub fn new(settings: watch::Receiver<Settings>) -> Self {
219 Self {
220 position: None,
221 selected_count: 0,
222 settings,
223 _observe_active_editor: None,
224 }
225 }
226
227 fn update_position(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
228 let editor = editor.read(cx);
229 let buffer = editor.buffer().read(cx).snapshot(cx);
230
231 self.selected_count = 0;
232 let mut last_selection: Option<Selection<usize>> = None;
233 for selection in editor.local_selections::<usize>(cx) {
234 self.selected_count += selection.end - selection.start;
235 if last_selection
236 .as_ref()
237 .map_or(true, |last_selection| selection.id > last_selection.id)
238 {
239 last_selection = Some(selection);
240 }
241 }
242 self.position = last_selection.map(|s| s.head().to_point(&buffer));
243
244 cx.notify();
245 }
246}
247
248impl Entity for CursorPosition {
249 type Event = ();
250}
251
252impl View for CursorPosition {
253 fn ui_name() -> &'static str {
254 "CursorPosition"
255 }
256
257 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
258 if let Some(position) = self.position {
259 let theme = &self.settings.borrow().theme.workspace.status_bar;
260 let mut text = format!("{},{}", position.row + 1, position.column + 1);
261 if self.selected_count > 0 {
262 write!(text, " ({} selected)", self.selected_count).unwrap();
263 }
264 Label::new(text, theme.cursor_position.clone()).boxed()
265 } else {
266 Empty::new().boxed()
267 }
268 }
269}
270
271impl StatusItemView for CursorPosition {
272 fn set_active_pane_item(
273 &mut self,
274 active_pane_item: Option<&dyn ItemViewHandle>,
275 cx: &mut ViewContext<Self>,
276 ) {
277 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
278 self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
279 self.update_position(editor, cx);
280 } else {
281 self.position = None;
282 self._observe_active_editor = None;
283 }
284
285 cx.notify();
286 }
287}
288
289pub struct DiagnosticMessage {
290 settings: watch::Receiver<Settings>,
291 diagnostic: Option<Diagnostic>,
292 _observe_active_editor: Option<Subscription>,
293}
294
295impl DiagnosticMessage {
296 pub fn new(settings: watch::Receiver<Settings>) -> Self {
297 Self {
298 diagnostic: None,
299 settings,
300 _observe_active_editor: None,
301 }
302 }
303
304 fn update(&mut self, editor: ViewHandle<Editor>, cx: &mut ViewContext<Self>) {
305 let editor = editor.read(cx);
306 let buffer = editor.buffer().read(cx);
307 let cursor_position = editor.newest_selection::<usize>(&buffer.read(cx)).head();
308 let new_diagnostic = buffer
309 .read(cx)
310 .diagnostics_in_range::<_, usize>(cursor_position..cursor_position)
311 .filter(|entry| !entry.range.is_empty())
312 .min_by_key(|entry| (entry.diagnostic.severity, entry.range.len()))
313 .map(|entry| entry.diagnostic);
314 if new_diagnostic != self.diagnostic {
315 self.diagnostic = new_diagnostic;
316 cx.notify();
317 }
318 }
319}
320
321impl Entity for DiagnosticMessage {
322 type Event = ();
323}
324
325impl View for DiagnosticMessage {
326 fn ui_name() -> &'static str {
327 "DiagnosticMessage"
328 }
329
330 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
331 if let Some(diagnostic) = &self.diagnostic {
332 let theme = &self.settings.borrow().theme.workspace.status_bar;
333 Label::new(
334 diagnostic.message.lines().next().unwrap().to_string(),
335 theme.diagnostic_message.clone(),
336 )
337 .contained()
338 .with_margin_left(theme.item_spacing)
339 .boxed()
340 } else {
341 Empty::new().boxed()
342 }
343 }
344}
345
346impl StatusItemView for DiagnosticMessage {
347 fn set_active_pane_item(
348 &mut self,
349 active_pane_item: Option<&dyn ItemViewHandle>,
350 cx: &mut ViewContext<Self>,
351 ) {
352 if let Some(editor) = active_pane_item.and_then(|item| item.downcast::<Editor>()) {
353 self._observe_active_editor = Some(cx.observe(&editor, Self::update));
354 self.update(editor, cx);
355 } else {
356 self.diagnostic = Default::default();
357 self._observe_active_editor = None;
358 }
359 cx.notify();
360 }
361}