1use super::{pane, Pane, PaneGroup, SplitDirection, Workspace};
2use crate::{settings::Settings, watch};
3use futures_core::future::LocalBoxFuture;
4use gpui::{
5 color::rgbu, elements::*, json::to_string_pretty, keymap::Binding, AnyViewHandle, AppContext,
6 ClipboardItem, Entity, ModelHandle, MutableAppContext, View, ViewContext, ViewHandle,
7};
8use log::error;
9use std::{collections::HashSet, path::PathBuf};
10
11pub fn init(app: &mut MutableAppContext) {
12 app.add_action("workspace:save", WorkspaceView::save_active_item);
13 app.add_action("workspace:debug_elements", WorkspaceView::debug_elements);
14 app.add_bindings(vec![
15 Binding::new("cmd-s", "workspace:save", None),
16 Binding::new("cmd-alt-i", "workspace:debug_elements", None),
17 ]);
18}
19
20pub trait ItemView: View {
21 fn title(&self, app: &AppContext) -> String;
22 fn entry_id(&self, app: &AppContext) -> Option<(usize, u64)>;
23 fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
24 where
25 Self: Sized,
26 {
27 None
28 }
29 fn is_dirty(&self, _: &AppContext) -> bool {
30 false
31 }
32 fn save(&self, _: &mut ViewContext<Self>) -> LocalBoxFuture<'static, anyhow::Result<()>> {
33 Box::pin(async { Ok(()) })
34 }
35 fn should_activate_item_on_event(_: &Self::Event) -> bool {
36 false
37 }
38 fn should_update_tab_on_event(_: &Self::Event) -> bool {
39 false
40 }
41}
42
43pub trait ItemViewHandle: Send + Sync {
44 fn title(&self, app: &AppContext) -> String;
45 fn entry_id(&self, app: &AppContext) -> Option<(usize, u64)>;
46 fn boxed_clone(&self) -> Box<dyn ItemViewHandle>;
47 fn clone_on_split(&self, app: &mut MutableAppContext) -> Option<Box<dyn ItemViewHandle>>;
48 fn set_parent_pane(&self, pane: &ViewHandle<Pane>, app: &mut MutableAppContext);
49 fn id(&self) -> usize;
50 fn to_any(&self) -> AnyViewHandle;
51 fn is_dirty(&self, ctx: &AppContext) -> bool;
52 fn save(&self, ctx: &mut MutableAppContext) -> LocalBoxFuture<'static, anyhow::Result<()>>;
53}
54
55impl<T: ItemView> ItemViewHandle for ViewHandle<T> {
56 fn title(&self, app: &AppContext) -> String {
57 self.read(app).title(app)
58 }
59
60 fn entry_id(&self, app: &AppContext) -> Option<(usize, u64)> {
61 self.read(app).entry_id(app)
62 }
63
64 fn boxed_clone(&self) -> Box<dyn ItemViewHandle> {
65 Box::new(self.clone())
66 }
67
68 fn clone_on_split(&self, app: &mut MutableAppContext) -> Option<Box<dyn ItemViewHandle>> {
69 self.update(app, |item, ctx| {
70 ctx.add_option_view(|ctx| item.clone_on_split(ctx))
71 })
72 .map(|handle| Box::new(handle) as Box<dyn ItemViewHandle>)
73 }
74
75 fn set_parent_pane(&self, pane: &ViewHandle<Pane>, app: &mut MutableAppContext) {
76 pane.update(app, |_, ctx| {
77 ctx.subscribe_to_view(self, |pane, item, event, ctx| {
78 if T::should_activate_item_on_event(event) {
79 if let Some(ix) = pane.item_index(&item) {
80 pane.activate_item(ix, ctx);
81 pane.activate(ctx);
82 }
83 }
84 if T::should_update_tab_on_event(event) {
85 ctx.notify()
86 }
87 })
88 })
89 }
90
91 fn save(&self, ctx: &mut MutableAppContext) -> LocalBoxFuture<'static, anyhow::Result<()>> {
92 self.update(ctx, |item, ctx| item.save(ctx))
93 }
94
95 fn is_dirty(&self, ctx: &AppContext) -> bool {
96 self.read(ctx).is_dirty(ctx)
97 }
98
99 fn id(&self) -> usize {
100 self.id()
101 }
102
103 fn to_any(&self) -> AnyViewHandle {
104 self.into()
105 }
106}
107
108impl Clone for Box<dyn ItemViewHandle> {
109 fn clone(&self) -> Box<dyn ItemViewHandle> {
110 self.boxed_clone()
111 }
112}
113
114#[derive(Debug)]
115pub struct State {
116 pub modal: Option<usize>,
117 pub center: PaneGroup,
118}
119
120pub struct WorkspaceView {
121 pub workspace: ModelHandle<Workspace>,
122 pub settings: watch::Receiver<Settings>,
123 modal: Option<AnyViewHandle>,
124 center: PaneGroup,
125 panes: Vec<ViewHandle<Pane>>,
126 active_pane: ViewHandle<Pane>,
127 loading_entries: HashSet<(usize, u64)>,
128}
129
130impl WorkspaceView {
131 pub fn new(
132 workspace: ModelHandle<Workspace>,
133 settings: watch::Receiver<Settings>,
134 ctx: &mut ViewContext<Self>,
135 ) -> Self {
136 ctx.observe(&workspace, Self::workspace_updated);
137
138 let pane = ctx.add_view(|_| Pane::new(settings.clone()));
139 let pane_id = pane.id();
140 ctx.subscribe_to_view(&pane, move |me, _, event, ctx| {
141 me.handle_pane_event(pane_id, event, ctx)
142 });
143 ctx.focus(&pane);
144
145 WorkspaceView {
146 workspace,
147 modal: None,
148 center: PaneGroup::new(pane.id()),
149 panes: vec![pane.clone()],
150 active_pane: pane.clone(),
151 loading_entries: HashSet::new(),
152 settings,
153 }
154 }
155
156 pub fn contains_paths(&self, paths: &[PathBuf], app: &AppContext) -> bool {
157 self.workspace.read(app).contains_paths(paths, app)
158 }
159
160 pub fn open_paths(&self, paths: &[PathBuf], app: &mut MutableAppContext) {
161 self.workspace
162 .update(app, |workspace, ctx| workspace.open_paths(paths, ctx));
163 }
164
165 pub fn toggle_modal<V, F>(&mut self, ctx: &mut ViewContext<Self>, add_view: F)
166 where
167 V: 'static + View,
168 F: FnOnce(&mut ViewContext<Self>, &mut Self) -> ViewHandle<V>,
169 {
170 if self.modal.as_ref().map_or(false, |modal| modal.is::<V>()) {
171 self.modal.take();
172 ctx.focus_self();
173 } else {
174 let modal = add_view(ctx, self);
175 ctx.focus(&modal);
176 self.modal = Some(modal.into());
177 }
178 ctx.notify();
179 }
180
181 pub fn modal(&self) -> Option<&AnyViewHandle> {
182 self.modal.as_ref()
183 }
184
185 pub fn dismiss_modal(&mut self, ctx: &mut ViewContext<Self>) {
186 if self.modal.take().is_some() {
187 ctx.focus(&self.active_pane);
188 ctx.notify();
189 }
190 }
191
192 pub fn open_entry(&mut self, entry: (usize, u64), ctx: &mut ViewContext<Self>) {
193 if self.loading_entries.contains(&entry) {
194 return;
195 }
196
197 if self
198 .active_pane()
199 .update(ctx, |pane, ctx| pane.activate_entry(entry, ctx))
200 {
201 return;
202 }
203
204 self.loading_entries.insert(entry);
205
206 match self
207 .workspace
208 .update(ctx, |workspace, ctx| workspace.open_entry(entry, ctx))
209 {
210 Err(error) => error!("{}", error),
211 Ok(item) => {
212 let settings = self.settings.clone();
213 ctx.spawn(item, move |me, item, ctx| {
214 me.loading_entries.remove(&entry);
215 match item {
216 Ok(item) => {
217 let item_view = item.add_view(ctx.window_id(), settings, ctx.as_mut());
218 me.add_item(item_view, ctx);
219 }
220 Err(error) => {
221 error!("{}", error);
222 }
223 }
224 })
225 .detach();
226 }
227 }
228 }
229
230 pub fn save_active_item(&mut self, _: &(), ctx: &mut ViewContext<Self>) {
231 self.active_pane.update(ctx, |pane, ctx| {
232 if let Some(item) = pane.active_item() {
233 let task = item.save(ctx.as_mut());
234 ctx.spawn(task, |_, result, _| {
235 if let Err(e) = result {
236 // TODO - present this error to the user
237 error!("failed to save item: {:?}, ", e);
238 }
239 })
240 .detach()
241 }
242 });
243 }
244
245 pub fn debug_elements(&mut self, _: &(), ctx: &mut ViewContext<Self>) {
246 match to_string_pretty(&ctx.debug_elements()) {
247 Ok(json) => {
248 let kib = json.len() as f32 / 1024.;
249 ctx.as_mut().write_to_clipboard(ClipboardItem::new(json));
250 log::info!(
251 "copied {:.1} KiB of element debug JSON to the clipboard",
252 kib
253 );
254 }
255 Err(error) => {
256 log::error!("error debugging elements: {}", error);
257 }
258 };
259 }
260
261 fn workspace_updated(&mut self, _: ModelHandle<Workspace>, ctx: &mut ViewContext<Self>) {
262 ctx.notify();
263 }
264
265 fn add_pane(&mut self, ctx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
266 let pane = ctx.add_view(|_| Pane::new(self.settings.clone()));
267 let pane_id = pane.id();
268 ctx.subscribe_to_view(&pane, move |me, _, event, ctx| {
269 me.handle_pane_event(pane_id, event, ctx)
270 });
271 self.panes.push(pane.clone());
272 self.activate_pane(pane.clone(), ctx);
273 pane
274 }
275
276 fn activate_pane(&mut self, pane: ViewHandle<Pane>, ctx: &mut ViewContext<Self>) {
277 self.active_pane = pane;
278 ctx.focus(&self.active_pane);
279 ctx.notify();
280 }
281
282 fn handle_pane_event(
283 &mut self,
284 pane_id: usize,
285 event: &pane::Event,
286 ctx: &mut ViewContext<Self>,
287 ) {
288 if let Some(pane) = self.pane(pane_id) {
289 match event {
290 pane::Event::Split(direction) => {
291 self.split_pane(pane, *direction, ctx);
292 }
293 pane::Event::Remove => {
294 self.remove_pane(pane, ctx);
295 }
296 pane::Event::Activate => {
297 self.activate_pane(pane, ctx);
298 }
299 }
300 } else {
301 error!("pane {} not found", pane_id);
302 }
303 }
304
305 fn split_pane(
306 &mut self,
307 pane: ViewHandle<Pane>,
308 direction: SplitDirection,
309 ctx: &mut ViewContext<Self>,
310 ) -> ViewHandle<Pane> {
311 let new_pane = self.add_pane(ctx);
312 self.activate_pane(new_pane.clone(), ctx);
313 if let Some(item) = pane.read(ctx).active_item() {
314 if let Some(clone) = item.clone_on_split(ctx.as_mut()) {
315 self.add_item(clone, ctx);
316 }
317 }
318 self.center
319 .split(pane.id(), new_pane.id(), direction)
320 .unwrap();
321 ctx.notify();
322 new_pane
323 }
324
325 fn remove_pane(&mut self, pane: ViewHandle<Pane>, ctx: &mut ViewContext<Self>) {
326 if self.center.remove(pane.id()).unwrap() {
327 self.panes.retain(|p| p != &pane);
328 self.activate_pane(self.panes.last().unwrap().clone(), ctx);
329 }
330 }
331
332 fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
333 self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
334 }
335
336 pub fn active_pane(&self) -> &ViewHandle<Pane> {
337 &self.active_pane
338 }
339
340 fn add_item(&self, item: Box<dyn ItemViewHandle>, ctx: &mut ViewContext<Self>) {
341 let active_pane = self.active_pane();
342 item.set_parent_pane(&active_pane, ctx.as_mut());
343 active_pane.update(ctx, |pane, ctx| {
344 let item_idx = pane.add_item(item, ctx);
345 pane.activate_item(item_idx, ctx);
346 });
347 }
348}
349
350impl Entity for WorkspaceView {
351 type Event = ();
352}
353
354impl View for WorkspaceView {
355 fn ui_name() -> &'static str {
356 "Workspace"
357 }
358
359 fn render(&self, _: &AppContext) -> ElementBox {
360 Container::new(
361 // self.center.render(bump)
362 Stack::new()
363 .with_child(self.center.render())
364 .with_children(self.modal.as_ref().map(|m| ChildView::new(m.id()).boxed()))
365 .boxed(),
366 )
367 .with_background_color(rgbu(0xea, 0xea, 0xeb))
368 .named("workspace")
369 }
370
371 fn on_focus(&mut self, ctx: &mut ViewContext<Self>) {
372 ctx.focus(&self.active_pane);
373 }
374}
375
376#[cfg(test)]
377mod tests {
378 use super::{pane, Workspace, WorkspaceView};
379 use crate::{settings, test::temp_tree, workspace::WorkspaceHandle as _};
380 use gpui::App;
381 use serde_json::json;
382
383 #[test]
384 fn test_open_entry() {
385 App::test_async((), |mut app| async move {
386 let dir = temp_tree(json!({
387 "a": {
388 "aa": "aa contents",
389 "ab": "ab contents",
390 "ac": "ab contents",
391 },
392 }));
393
394 let settings = settings::channel(&app.font_cache()).unwrap().1;
395 let workspace = app.add_model(|ctx| Workspace::new(vec![dir.path().into()], ctx));
396 app.read(|ctx| workspace.read(ctx).worktree_scans_complete(ctx))
397 .await;
398 let entries = app.read(|ctx| workspace.file_entries(ctx));
399
400 let (_, workspace_view) =
401 app.add_window(|ctx| WorkspaceView::new(workspace.clone(), settings, ctx));
402
403 // Open the first entry
404 workspace_view.update(&mut app, |w, ctx| w.open_entry(entries[0], ctx));
405
406 workspace_view
407 .condition(&app, |workspace_view, ctx| {
408 workspace_view.active_pane().read(ctx).items().len() == 1
409 })
410 .await;
411
412 // Open the second entry
413 workspace_view.update(&mut app, |w, ctx| w.open_entry(entries[1], ctx));
414
415 workspace_view
416 .condition(&app, |workspace_view, ctx| {
417 workspace_view.active_pane().read(ctx).items().len() == 2
418 })
419 .await;
420
421 app.read(|ctx| {
422 assert_eq!(
423 workspace_view
424 .read(ctx)
425 .active_pane()
426 .read(ctx)
427 .active_item()
428 .unwrap()
429 .entry_id(ctx),
430 Some(entries[1])
431 );
432 });
433
434 // Open the first entry again
435 workspace_view.update(&mut app, |w, ctx| w.open_entry(entries[0], ctx));
436
437 {
438 let entries = entries.clone();
439 workspace_view
440 .condition(&app, move |workspace_view, ctx| {
441 workspace_view
442 .active_pane()
443 .read(ctx)
444 .active_item()
445 .unwrap()
446 .entry_id(ctx)
447 == Some(entries[0])
448 })
449 .await;
450 }
451
452 app.read(|ctx| {
453 let active_pane = workspace_view.read(ctx).active_pane().read(ctx);
454 assert_eq!(active_pane.items().len(), 2);
455 });
456
457 // Open the third entry twice concurrently
458 workspace_view.update(&mut app, |w, ctx| {
459 w.open_entry(entries[2], ctx);
460 w.open_entry(entries[2], ctx);
461 });
462
463 workspace_view
464 .condition(&app, |workspace_view, ctx| {
465 workspace_view.active_pane().read(ctx).items().len() == 3
466 })
467 .await;
468 });
469 }
470
471 #[test]
472 fn test_pane_actions() {
473 App::test_async((), |mut app| async move {
474 app.update(|ctx| pane::init(ctx));
475
476 let dir = temp_tree(json!({
477 "a": {
478 "aa": "aa contents",
479 "ab": "ab contents",
480 "ac": "ab contents",
481 },
482 }));
483
484 let settings = settings::channel(&app.font_cache()).unwrap().1;
485 let workspace = app.add_model(|ctx| Workspace::new(vec![dir.path().into()], ctx));
486 app.finish_pending_tasks().await; // Open and populate worktree.
487 let entries = app.read(|ctx| workspace.file_entries(ctx));
488
489 let (window_id, workspace_view) =
490 app.add_window(|ctx| WorkspaceView::new(workspace.clone(), settings, ctx));
491
492 workspace_view.update(&mut app, |w, ctx| w.open_entry(entries[0], ctx));
493 app.finish_pending_tasks().await;
494
495 let pane_1 = app.read(|ctx| workspace_view.read(ctx).active_pane().clone());
496
497 app.dispatch_action(window_id, vec![pane_1.id()], "pane:split_right", ());
498 app.update(|ctx| {
499 let pane_2 = workspace_view.read(ctx).active_pane().clone();
500 assert_ne!(pane_1, pane_2);
501
502 assert_eq!(
503 pane_2
504 .read(ctx)
505 .active_item()
506 .unwrap()
507 .entry_id(ctx.as_ref()),
508 Some(entries[0])
509 );
510
511 ctx.dispatch_action(window_id, vec![pane_2.id()], "pane:close_active_item", ());
512
513 let w = workspace_view.read(ctx);
514 assert_eq!(w.panes.len(), 1);
515 assert_eq!(w.active_pane(), &pane_1);
516 });
517 });
518 }
519}