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