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 Entity, ModelHandle, MutableAppContext, View, ViewContext, ViewHandle,
7};
8use log::{error, info};
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 open_example_entry(&mut self, ctx: &mut ViewContext<Self>) {
231 if let Some(tree) = self.workspace.read(ctx).worktrees().iter().next() {
232 if let Some(file) = tree.read(ctx).files().next() {
233 info!("open_entry ({}, {})", tree.id(), file.entry_id);
234 self.open_entry((tree.id(), file.entry_id), ctx);
235 } else {
236 error!("No example file found for worktree {}", tree.id());
237 }
238 } else {
239 error!("No worktree found while opening example entry");
240 }
241 }
242
243 pub fn save_active_item(&mut self, _: &(), ctx: &mut ViewContext<Self>) {
244 self.active_pane.update(ctx, |pane, ctx| {
245 if let Some(item) = pane.active_item() {
246 let task = item.save(ctx.as_mut());
247 ctx.spawn(task, |_, result, _| {
248 if let Err(e) = result {
249 // TODO - present this error to the user
250 error!("failed to save item: {:?}, ", e);
251 }
252 })
253 .detach()
254 }
255 });
256 }
257
258 pub fn debug_elements(&mut self, _: &(), ctx: &mut ViewContext<Self>) {
259 match to_string_pretty(&ctx.debug_elements()) {
260 Ok(json) => {
261 ctx.as_mut().copy(&json);
262 log::info!(
263 "copied {:.1} KiB of element debug JSON to the clipboard",
264 json.len() as f32 / 1024.
265 );
266 }
267 Err(error) => {
268 log::error!("error debugging elements: {}", error);
269 }
270 };
271 }
272
273 fn workspace_updated(&mut self, _: ModelHandle<Workspace>, ctx: &mut ViewContext<Self>) {
274 ctx.notify();
275 }
276
277 fn add_pane(&mut self, ctx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
278 let pane = ctx.add_view(|_| Pane::new(self.settings.clone()));
279 let pane_id = pane.id();
280 ctx.subscribe_to_view(&pane, move |me, _, event, ctx| {
281 me.handle_pane_event(pane_id, event, ctx)
282 });
283 self.panes.push(pane.clone());
284 self.activate_pane(pane.clone(), ctx);
285 pane
286 }
287
288 fn activate_pane(&mut self, pane: ViewHandle<Pane>, ctx: &mut ViewContext<Self>) {
289 self.active_pane = pane;
290 ctx.focus(&self.active_pane);
291 ctx.notify();
292 }
293
294 fn handle_pane_event(
295 &mut self,
296 pane_id: usize,
297 event: &pane::Event,
298 ctx: &mut ViewContext<Self>,
299 ) {
300 if let Some(pane) = self.pane(pane_id) {
301 match event {
302 pane::Event::Split(direction) => {
303 self.split_pane(pane, *direction, ctx);
304 }
305 pane::Event::Remove => {
306 self.remove_pane(pane, ctx);
307 }
308 pane::Event::Activate => {
309 self.activate_pane(pane, ctx);
310 }
311 }
312 } else {
313 error!("pane {} not found", pane_id);
314 }
315 }
316
317 fn split_pane(
318 &mut self,
319 pane: ViewHandle<Pane>,
320 direction: SplitDirection,
321 ctx: &mut ViewContext<Self>,
322 ) -> ViewHandle<Pane> {
323 let new_pane = self.add_pane(ctx);
324 self.activate_pane(new_pane.clone(), ctx);
325 if let Some(item) = pane.read(ctx).active_item() {
326 if let Some(clone) = item.clone_on_split(ctx.as_mut()) {
327 self.add_item(clone, ctx);
328 }
329 }
330 self.center
331 .split(pane.id(), new_pane.id(), direction)
332 .unwrap();
333 ctx.notify();
334 new_pane
335 }
336
337 fn remove_pane(&mut self, pane: ViewHandle<Pane>, ctx: &mut ViewContext<Self>) {
338 if self.center.remove(pane.id()).unwrap() {
339 self.panes.retain(|p| p != &pane);
340 self.activate_pane(self.panes.last().unwrap().clone(), ctx);
341 }
342 }
343
344 fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
345 self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
346 }
347
348 pub fn active_pane(&self) -> &ViewHandle<Pane> {
349 &self.active_pane
350 }
351
352 fn add_item(&self, item: Box<dyn ItemViewHandle>, ctx: &mut ViewContext<Self>) {
353 let active_pane = self.active_pane();
354 item.set_parent_pane(&active_pane, ctx.as_mut());
355 active_pane.update(ctx, |pane, ctx| {
356 let item_idx = pane.add_item(item, ctx);
357 pane.activate_item(item_idx, ctx);
358 });
359 }
360}
361
362impl Entity for WorkspaceView {
363 type Event = ();
364}
365
366impl View for WorkspaceView {
367 fn ui_name() -> &'static str {
368 "Workspace"
369 }
370
371 fn render(&self, _: &AppContext) -> ElementBox {
372 Container::new(
373 // self.center.render(bump)
374 Stack::new()
375 .with_child(self.center.render())
376 .with_children(self.modal.as_ref().map(|m| ChildView::new(m.id()).boxed()))
377 .boxed(),
378 )
379 .with_background_color(rgbu(0xea, 0xea, 0xeb))
380 .named("workspace")
381 }
382
383 fn on_focus(&mut self, ctx: &mut ViewContext<Self>) {
384 ctx.focus(&self.active_pane);
385 }
386}
387
388#[cfg(test)]
389mod tests {
390 use super::{pane, Workspace, WorkspaceView};
391 use crate::{settings, test::temp_tree, workspace::WorkspaceHandle as _};
392 use gpui::App;
393 use serde_json::json;
394
395 #[test]
396 fn test_open_entry() {
397 App::test_async((), |mut app| async move {
398 let dir = temp_tree(json!({
399 "a": {
400 "aa": "aa contents",
401 "ab": "ab contents",
402 "ac": "ab contents",
403 },
404 }));
405
406 let settings = settings::channel(&app.font_cache()).unwrap().1;
407 let workspace = app.add_model(|ctx| Workspace::new(vec![dir.path().into()], ctx));
408 app.finish_pending_tasks().await; // Open and populate worktree.
409 let entries = app.read(|ctx| workspace.file_entries(ctx));
410
411 let (_, workspace_view) =
412 app.add_window(|ctx| WorkspaceView::new(workspace.clone(), settings, ctx));
413
414 // Open the first entry
415 workspace_view.update(&mut app, |w, ctx| w.open_entry(entries[0], ctx));
416 app.finish_pending_tasks().await;
417
418 app.read(|ctx| {
419 assert_eq!(
420 workspace_view
421 .read(ctx)
422 .active_pane()
423 .read(ctx)
424 .items()
425 .len(),
426 1
427 )
428 });
429
430 // Open the second entry
431 workspace_view.update(&mut app, |w, ctx| w.open_entry(entries[1], ctx));
432 app.finish_pending_tasks().await;
433
434 app.read(|ctx| {
435 let active_pane = workspace_view.read(ctx).active_pane().read(ctx);
436 assert_eq!(active_pane.items().len(), 2);
437 assert_eq!(
438 active_pane.active_item().unwrap().entry_id(ctx),
439 Some(entries[1])
440 );
441 });
442
443 // Open the first entry again
444 workspace_view.update(&mut app, |w, ctx| w.open_entry(entries[0], ctx));
445 app.finish_pending_tasks().await;
446
447 app.read(|ctx| {
448 let active_pane = workspace_view.read(ctx).active_pane().read(ctx);
449 assert_eq!(active_pane.items().len(), 2);
450 assert_eq!(
451 active_pane.active_item().unwrap().entry_id(ctx),
452 Some(entries[0])
453 );
454 });
455
456 // Open the third entry twice concurrently
457 workspace_view.update(&mut app, |w, ctx| {
458 w.open_entry(entries[2], ctx);
459 w.open_entry(entries[2], ctx);
460 });
461 app.finish_pending_tasks().await;
462
463 app.read(|ctx| {
464 assert_eq!(
465 workspace_view
466 .read(ctx)
467 .active_pane()
468 .read(ctx)
469 .items()
470 .len(),
471 3
472 );
473 });
474 });
475 }
476
477 #[test]
478 fn test_pane_actions() {
479 App::test_async((), |mut app| async move {
480 app.update(|ctx| pane::init(ctx));
481
482 let dir = temp_tree(json!({
483 "a": {
484 "aa": "aa contents",
485 "ab": "ab contents",
486 "ac": "ab contents",
487 },
488 }));
489
490 let settings = settings::channel(&app.font_cache()).unwrap().1;
491 let workspace = app.add_model(|ctx| Workspace::new(vec![dir.path().into()], ctx));
492 app.finish_pending_tasks().await; // Open and populate worktree.
493 let entries = app.read(|ctx| workspace.file_entries(ctx));
494
495 let (window_id, workspace_view) =
496 app.add_window(|ctx| WorkspaceView::new(workspace.clone(), settings, ctx));
497
498 workspace_view.update(&mut app, |w, ctx| w.open_entry(entries[0], ctx));
499 app.finish_pending_tasks().await;
500
501 let pane_1 = app.read(|ctx| workspace_view.read(ctx).active_pane().clone());
502
503 app.dispatch_action(window_id, vec![pane_1.id()], "pane:split_right", ());
504 app.update(|ctx| {
505 let pane_2 = workspace_view.read(ctx).active_pane().clone();
506 assert_ne!(pane_1, pane_2);
507
508 assert_eq!(
509 pane_2
510 .read(ctx)
511 .active_item()
512 .unwrap()
513 .entry_id(ctx.as_ref()),
514 Some(entries[0])
515 );
516
517 ctx.dispatch_action(window_id, vec![pane_2.id()], "pane:close_active_item", ());
518
519 let w = workspace_view.read(ctx);
520 assert_eq!(w.panes.len(), 1);
521 assert_eq!(w.active_pane(), &pane_1);
522 });
523 });
524 }
525}