1use super::{ItemHandle, SplitDirection};
2use crate::{toolbar::Toolbar, Item, Settings, WeakItemHandle, Workspace};
3use collections::{HashMap, VecDeque};
4use futures::StreamExt;
5use gpui::{
6 action,
7 elements::*,
8 geometry::{rect::RectF, vector::vec2f},
9 keymap::Binding,
10 platform::{CursorStyle, NavigationDirection},
11 AppContext, Entity, ModelHandle, MutableAppContext, PromptLevel, Quad, RenderContext, Task,
12 View, ViewContext, ViewHandle, WeakViewHandle,
13};
14use project::{Project, ProjectEntryId, ProjectPath};
15use std::{any::Any, cell::RefCell, cmp, mem, path::Path, rc::Rc};
16use util::ResultExt;
17
18action!(Split, SplitDirection);
19action!(ActivateItem, usize);
20action!(ActivatePrevItem);
21action!(ActivateNextItem);
22action!(CloseActiveItem);
23action!(CloseInactiveItems);
24action!(CloseItem, usize);
25action!(GoBack, Option<WeakViewHandle<Pane>>);
26action!(GoForward, Option<WeakViewHandle<Pane>>);
27
28const MAX_NAVIGATION_HISTORY_LEN: usize = 1024;
29
30pub fn init(cx: &mut MutableAppContext) {
31 cx.add_action(|pane: &mut Pane, action: &ActivateItem, cx| {
32 pane.activate_item(action.0, true, cx);
33 });
34 cx.add_action(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
35 pane.activate_prev_item(cx);
36 });
37 cx.add_action(|pane: &mut Pane, _: &ActivateNextItem, cx| {
38 pane.activate_next_item(cx);
39 });
40 cx.add_action(|pane: &mut Pane, _: &CloseActiveItem, cx| {
41 pane.close_active_item(cx).detach();
42 });
43 cx.add_action(|pane: &mut Pane, _: &CloseInactiveItems, cx| {
44 pane.close_inactive_items(cx).detach();
45 });
46 cx.add_action(|pane: &mut Pane, action: &CloseItem, cx| {
47 pane.close_item(action.0, cx).detach();
48 });
49 cx.add_action(|pane: &mut Pane, action: &Split, cx| {
50 pane.split(action.0, cx);
51 });
52 cx.add_action(|workspace: &mut Workspace, action: &GoBack, cx| {
53 Pane::go_back(
54 workspace,
55 action
56 .0
57 .as_ref()
58 .and_then(|weak_handle| weak_handle.upgrade(cx)),
59 cx,
60 )
61 .detach();
62 });
63 cx.add_action(|workspace: &mut Workspace, action: &GoForward, cx| {
64 Pane::go_forward(
65 workspace,
66 action
67 .0
68 .as_ref()
69 .and_then(|weak_handle| weak_handle.upgrade(cx)),
70 cx,
71 )
72 .detach();
73 });
74
75 cx.add_bindings(vec![
76 Binding::new("shift-cmd-{", ActivatePrevItem, Some("Pane")),
77 Binding::new("shift-cmd-}", ActivateNextItem, Some("Pane")),
78 Binding::new("cmd-w", CloseActiveItem, Some("Pane")),
79 Binding::new("alt-cmd-w", CloseInactiveItems, Some("Pane")),
80 Binding::new("cmd-k up", Split(SplitDirection::Up), Some("Pane")),
81 Binding::new("cmd-k down", Split(SplitDirection::Down), Some("Pane")),
82 Binding::new("cmd-k left", Split(SplitDirection::Left), Some("Pane")),
83 Binding::new("cmd-k right", Split(SplitDirection::Right), Some("Pane")),
84 Binding::new("ctrl--", GoBack(None), Some("Pane")),
85 Binding::new("shift-ctrl-_", GoForward(None), Some("Pane")),
86 ]);
87}
88
89pub enum Event {
90 Activate,
91 ActivateItem { local: bool },
92 Remove,
93 Split(SplitDirection),
94}
95
96pub struct Pane {
97 items: Vec<Box<dyn ItemHandle>>,
98 active_item_index: usize,
99 nav_history: Rc<RefCell<NavHistory>>,
100 toolbar: ViewHandle<Toolbar>,
101 project: ModelHandle<Project>,
102}
103
104pub struct ItemNavHistory {
105 history: Rc<RefCell<NavHistory>>,
106 item: Rc<dyn WeakItemHandle>,
107}
108
109#[derive(Default)]
110pub struct NavHistory {
111 mode: NavigationMode,
112 backward_stack: VecDeque<NavigationEntry>,
113 forward_stack: VecDeque<NavigationEntry>,
114 paths_by_item: HashMap<usize, ProjectPath>,
115}
116
117#[derive(Copy, Clone)]
118enum NavigationMode {
119 Normal,
120 GoingBack,
121 GoingForward,
122 Disabled,
123}
124
125impl Default for NavigationMode {
126 fn default() -> Self {
127 Self::Normal
128 }
129}
130
131pub struct NavigationEntry {
132 pub item: Rc<dyn WeakItemHandle>,
133 pub data: Option<Box<dyn Any>>,
134}
135
136impl Pane {
137 pub fn new(project: ModelHandle<Project>, cx: &mut ViewContext<Self>) -> Self {
138 Self {
139 items: Vec::new(),
140 active_item_index: 0,
141 nav_history: Default::default(),
142 toolbar: cx.add_view(|_| Toolbar::new()),
143 project,
144 }
145 }
146
147 pub fn nav_history(&self) -> &Rc<RefCell<NavHistory>> {
148 &self.nav_history
149 }
150
151 pub fn activate(&self, cx: &mut ViewContext<Self>) {
152 cx.emit(Event::Activate);
153 }
154
155 pub fn go_back(
156 workspace: &mut Workspace,
157 pane: Option<ViewHandle<Pane>>,
158 cx: &mut ViewContext<Workspace>,
159 ) -> Task<()> {
160 Self::navigate_history(
161 workspace,
162 pane.unwrap_or_else(|| workspace.active_pane().clone()),
163 NavigationMode::GoingBack,
164 cx,
165 )
166 }
167
168 pub fn go_forward(
169 workspace: &mut Workspace,
170 pane: Option<ViewHandle<Pane>>,
171 cx: &mut ViewContext<Workspace>,
172 ) -> Task<()> {
173 Self::navigate_history(
174 workspace,
175 pane.unwrap_or_else(|| workspace.active_pane().clone()),
176 NavigationMode::GoingForward,
177 cx,
178 )
179 }
180
181 fn navigate_history(
182 workspace: &mut Workspace,
183 pane: ViewHandle<Pane>,
184 mode: NavigationMode,
185 cx: &mut ViewContext<Workspace>,
186 ) -> Task<()> {
187 workspace.activate_pane(pane.clone(), cx);
188
189 let to_load = pane.update(cx, |pane, cx| {
190 loop {
191 // Retrieve the weak item handle from the history.
192 let entry = pane.nav_history.borrow_mut().pop(mode)?;
193
194 // If the item is still present in this pane, then activate it.
195 if let Some(index) = entry
196 .item
197 .upgrade(cx)
198 .and_then(|v| pane.index_for_item(v.as_ref()))
199 {
200 if let Some(item) = pane.active_item() {
201 pane.nav_history.borrow_mut().set_mode(mode);
202 item.deactivated(cx);
203 pane.nav_history
204 .borrow_mut()
205 .set_mode(NavigationMode::Normal);
206 }
207
208 let prev_active_index = mem::replace(&mut pane.active_item_index, index);
209
210 let mut navigated = prev_active_index != pane.active_item_index;
211 if let Some(data) = entry.data {
212 navigated |= pane.active_item()?.navigate(data, cx);
213 }
214
215 if navigated {
216 pane.focus_active_item(cx);
217 pane.update_toolbar(cx);
218 pane.activate(cx);
219 cx.emit(Event::ActivateItem { local: true });
220 cx.notify();
221 break None;
222 }
223 }
224 // If the item is no longer present in this pane, then retrieve its
225 // project path in order to reopen it.
226 else {
227 break pane
228 .nav_history
229 .borrow_mut()
230 .paths_by_item
231 .get(&entry.item.id())
232 .cloned()
233 .map(|project_path| (project_path, entry));
234 }
235 }
236 });
237
238 if let Some((project_path, entry)) = to_load {
239 // If the item was no longer present, then load it again from its previous path.
240 let pane = pane.downgrade();
241 let task = workspace.load_path(project_path, cx);
242 cx.spawn(|workspace, mut cx| async move {
243 let task = task.await;
244 if let Some(pane) = pane.upgrade(&cx) {
245 if let Some((project_entry_id, build_item)) = task.log_err() {
246 pane.update(&mut cx, |pane, _| {
247 pane.nav_history.borrow_mut().set_mode(mode);
248 });
249 let item = workspace.update(&mut cx, |workspace, cx| {
250 Self::open_item(
251 workspace,
252 pane.clone(),
253 project_entry_id,
254 cx,
255 build_item,
256 )
257 });
258 pane.update(&mut cx, |pane, cx| {
259 pane.nav_history
260 .borrow_mut()
261 .set_mode(NavigationMode::Normal);
262 if let Some(data) = entry.data {
263 item.navigate(data, cx);
264 }
265 });
266 } else {
267 workspace
268 .update(&mut cx, |workspace, cx| {
269 Self::navigate_history(workspace, pane, mode, cx)
270 })
271 .await;
272 }
273 }
274 })
275 } else {
276 Task::ready(())
277 }
278 }
279
280 pub(crate) fn open_item(
281 workspace: &mut Workspace,
282 pane: ViewHandle<Pane>,
283 project_entry_id: ProjectEntryId,
284 cx: &mut ViewContext<Workspace>,
285 build_item: impl FnOnce(&mut MutableAppContext) -> Box<dyn ItemHandle>,
286 ) -> Box<dyn ItemHandle> {
287 let existing_item = pane.update(cx, |pane, cx| {
288 for (ix, item) in pane.items.iter().enumerate() {
289 if item.project_entry_id(cx) == Some(project_entry_id) {
290 let item = item.boxed_clone();
291 pane.activate_item(ix, true, cx);
292 return Some(item);
293 }
294 }
295 None
296 });
297 if let Some(existing_item) = existing_item {
298 existing_item
299 } else {
300 let item = build_item(cx);
301 Self::add_item(workspace, pane, item.boxed_clone(), true, cx);
302 item
303 }
304 }
305
306 pub(crate) fn add_item(
307 workspace: &mut Workspace,
308 pane: ViewHandle<Pane>,
309 item: Box<dyn ItemHandle>,
310 local: bool,
311 cx: &mut ViewContext<Workspace>,
312 ) {
313 // Prevent adding the same item to the pane more than once.
314 if let Some(item_ix) = pane.read(cx).items.iter().position(|i| i.id() == item.id()) {
315 pane.update(cx, |pane, cx| pane.activate_item(item_ix, local, cx));
316 return;
317 }
318
319 item.set_nav_history(pane.read(cx).nav_history.clone(), cx);
320 item.added_to_pane(workspace, pane.clone(), cx);
321 pane.update(cx, |pane, cx| {
322 let item_idx = cmp::min(pane.active_item_index + 1, pane.items.len());
323 pane.items.insert(item_idx, item);
324 pane.activate_item(item_idx, local, cx);
325 cx.notify();
326 });
327 }
328
329 pub fn items(&self) -> impl Iterator<Item = &Box<dyn ItemHandle>> {
330 self.items.iter()
331 }
332
333 pub fn items_of_type<'a, T: View>(&'a self) -> impl 'a + Iterator<Item = ViewHandle<T>> {
334 self.items
335 .iter()
336 .filter_map(|item| item.to_any().downcast())
337 }
338
339 pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
340 self.items.get(self.active_item_index).cloned()
341 }
342
343 pub fn project_entry_id_for_item(
344 &self,
345 item: &dyn ItemHandle,
346 cx: &AppContext,
347 ) -> Option<ProjectEntryId> {
348 self.items.iter().find_map(|existing| {
349 if existing.id() == item.id() {
350 existing.project_entry_id(cx)
351 } else {
352 None
353 }
354 })
355 }
356
357 pub fn item_for_entry(
358 &self,
359 entry_id: ProjectEntryId,
360 cx: &AppContext,
361 ) -> Option<Box<dyn ItemHandle>> {
362 self.items.iter().find_map(|item| {
363 if item.project_entry_id(cx) == Some(entry_id) {
364 Some(item.boxed_clone())
365 } else {
366 None
367 }
368 })
369 }
370
371 pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
372 self.items.iter().position(|i| i.id() == item.id())
373 }
374
375 pub fn activate_item(&mut self, index: usize, local: bool, cx: &mut ViewContext<Self>) {
376 if index < self.items.len() {
377 let prev_active_item_ix = mem::replace(&mut self.active_item_index, index);
378 if prev_active_item_ix != self.active_item_index
379 && prev_active_item_ix < self.items.len()
380 {
381 self.items[prev_active_item_ix].deactivated(cx);
382 cx.emit(Event::ActivateItem { local });
383 }
384 self.update_toolbar(cx);
385 if local {
386 self.focus_active_item(cx);
387 self.activate(cx);
388 }
389 cx.notify();
390 }
391 }
392
393 pub fn activate_prev_item(&mut self, cx: &mut ViewContext<Self>) {
394 let mut index = self.active_item_index;
395 if index > 0 {
396 index -= 1;
397 } else if self.items.len() > 0 {
398 index = self.items.len() - 1;
399 }
400 self.activate_item(index, true, cx);
401 }
402
403 pub fn activate_next_item(&mut self, cx: &mut ViewContext<Self>) {
404 let mut index = self.active_item_index;
405 if index + 1 < self.items.len() {
406 index += 1;
407 } else {
408 index = 0;
409 }
410 self.activate_item(index, true, cx);
411 }
412
413 pub fn close_active_item(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
414 if self.items.is_empty() {
415 Task::ready(())
416 } else {
417 self.close_item(self.items[self.active_item_index].id(), cx)
418 }
419 }
420
421 pub fn close_inactive_items(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
422 if self.items.is_empty() {
423 Task::ready(())
424 } else {
425 let active_item_id = self.items[self.active_item_index].id();
426 self.close_items(cx, move |id| id != active_item_id)
427 }
428 }
429
430 pub fn close_item(&mut self, view_id_to_close: usize, cx: &mut ViewContext<Self>) -> Task<()> {
431 self.close_items(cx, move |view_id| view_id == view_id_to_close)
432 }
433
434 pub fn close_items(
435 &mut self,
436 cx: &mut ViewContext<Self>,
437 should_close: impl 'static + Fn(usize) -> bool,
438 ) -> Task<()> {
439 const CONFLICT_MESSAGE: &'static str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
440 const DIRTY_MESSAGE: &'static str =
441 "This file contains unsaved edits. Do you want to save it?";
442
443 let project = self.project.clone();
444 cx.spawn(|this, mut cx| async move {
445 while let Some(item_to_close_ix) = this.read_with(&cx, |this, _| {
446 this.items.iter().position(|item| should_close(item.id()))
447 }) {
448 let item =
449 this.read_with(&cx, |this, _| this.items[item_to_close_ix].boxed_clone());
450 if cx.read(|cx| item.is_dirty(cx)) {
451 if cx.read(|cx| item.can_save(cx)) {
452 let mut answer = this.update(&mut cx, |this, cx| {
453 this.activate_item(item_to_close_ix, true, cx);
454 cx.prompt(
455 PromptLevel::Warning,
456 DIRTY_MESSAGE,
457 &["Save", "Don't Save", "Cancel"],
458 )
459 });
460
461 match answer.next().await {
462 Some(0) => {
463 if cx
464 .update(|cx| item.save(project.clone(), cx))
465 .await
466 .log_err()
467 .is_none()
468 {
469 break;
470 }
471 }
472 Some(1) => {}
473 _ => break,
474 }
475 } else if cx.read(|cx| item.can_save_as(cx)) {
476 let mut answer = this.update(&mut cx, |this, cx| {
477 this.activate_item(item_to_close_ix, true, cx);
478 cx.prompt(
479 PromptLevel::Warning,
480 DIRTY_MESSAGE,
481 &["Save", "Don't Save", "Cancel"],
482 )
483 });
484
485 match answer.next().await {
486 Some(0) => {
487 let start_abs_path = project
488 .read_with(&cx, |project, cx| {
489 let worktree = project.visible_worktrees(cx).next()?;
490 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
491 })
492 .unwrap_or(Path::new("").into());
493
494 let mut abs_path =
495 cx.update(|cx| cx.prompt_for_new_path(&start_abs_path));
496 if let Some(abs_path) = abs_path.next().await.flatten() {
497 if cx
498 .update(|cx| item.save_as(project.clone(), abs_path, cx))
499 .await
500 .log_err()
501 .is_none()
502 {
503 break;
504 }
505 } else {
506 break;
507 }
508 }
509 Some(1) => {}
510 _ => break,
511 }
512 }
513 } else if cx.read(|cx| item.has_conflict(cx) && item.can_save(cx)) {
514 let mut answer = this.update(&mut cx, |this, cx| {
515 this.activate_item(item_to_close_ix, true, cx);
516 cx.prompt(
517 PromptLevel::Warning,
518 CONFLICT_MESSAGE,
519 &["Overwrite", "Discard", "Cancel"],
520 )
521 });
522
523 match answer.next().await {
524 Some(0) => {
525 if cx
526 .update(|cx| item.save(project.clone(), cx))
527 .await
528 .log_err()
529 .is_none()
530 {
531 break;
532 }
533 }
534 Some(1) => {
535 if cx
536 .update(|cx| item.reload(project.clone(), cx))
537 .await
538 .log_err()
539 .is_none()
540 {
541 break;
542 }
543 }
544 _ => break,
545 }
546 }
547
548 this.update(&mut cx, |this, cx| {
549 if let Some(item_ix) = this.items.iter().position(|i| i.id() == item.id()) {
550 if item_ix == this.active_item_index {
551 if item_ix + 1 < this.items.len() {
552 this.activate_next_item(cx);
553 } else if item_ix > 0 {
554 this.activate_prev_item(cx);
555 }
556 }
557
558 let item = this.items.remove(item_ix);
559 if this.items.is_empty() {
560 item.deactivated(cx);
561 cx.emit(Event::Remove);
562 }
563
564 if item_ix < this.active_item_index {
565 this.active_item_index -= 1;
566 }
567
568 let mut nav_history = this.nav_history.borrow_mut();
569 if let Some(path) = item.project_path(cx) {
570 nav_history.paths_by_item.insert(item.id(), path);
571 } else {
572 nav_history.paths_by_item.remove(&item.id());
573 }
574 }
575 });
576 }
577
578 this.update(&mut cx, |_, cx| cx.notify());
579 })
580 }
581
582 pub fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
583 if let Some(active_item) = self.active_item() {
584 cx.focus(active_item);
585 }
586 }
587
588 pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
589 cx.emit(Event::Split(direction));
590 }
591
592 pub fn toolbar(&self) -> &ViewHandle<Toolbar> {
593 &self.toolbar
594 }
595
596 fn update_toolbar(&mut self, cx: &mut ViewContext<Self>) {
597 let active_item = self
598 .items
599 .get(self.active_item_index)
600 .map(|item| item.as_ref());
601 self.toolbar.update(cx, |toolbar, cx| {
602 toolbar.set_active_pane_item(active_item, cx);
603 });
604 }
605
606 fn render_tabs(&self, cx: &mut RenderContext<Self>) -> ElementBox {
607 let theme = cx.global::<Settings>().theme.clone();
608
609 enum Tabs {}
610 let tabs = MouseEventHandler::new::<Tabs, _, _>(0, cx, |mouse_state, cx| {
611 let mut row = Flex::row();
612 for (ix, item) in self.items.iter().enumerate() {
613 let is_active = ix == self.active_item_index;
614
615 row.add_child({
616 let tab_style = if is_active {
617 theme.workspace.active_tab.clone()
618 } else {
619 theme.workspace.tab.clone()
620 };
621 let title = item.tab_content(&tab_style, cx);
622
623 let mut style = if is_active {
624 theme.workspace.active_tab.clone()
625 } else {
626 theme.workspace.tab.clone()
627 };
628 if ix == 0 {
629 style.container.border.left = false;
630 }
631
632 EventHandler::new(
633 Container::new(
634 Flex::row()
635 .with_child(
636 Align::new({
637 let diameter = 7.0;
638 let icon_color = if item.has_conflict(cx) {
639 Some(style.icon_conflict)
640 } else if item.is_dirty(cx) {
641 Some(style.icon_dirty)
642 } else {
643 None
644 };
645
646 ConstrainedBox::new(
647 Canvas::new(move |bounds, _, cx| {
648 if let Some(color) = icon_color {
649 let square = RectF::new(
650 bounds.origin(),
651 vec2f(diameter, diameter),
652 );
653 cx.scene.push_quad(Quad {
654 bounds: square,
655 background: Some(color),
656 border: Default::default(),
657 corner_radius: diameter / 2.,
658 });
659 }
660 })
661 .boxed(),
662 )
663 .with_width(diameter)
664 .with_height(diameter)
665 .boxed()
666 })
667 .boxed(),
668 )
669 .with_child(
670 Container::new(Align::new(title).boxed())
671 .with_style(ContainerStyle {
672 margin: Margin {
673 left: style.spacing,
674 right: style.spacing,
675 ..Default::default()
676 },
677 ..Default::default()
678 })
679 .boxed(),
680 )
681 .with_child(
682 Align::new(
683 ConstrainedBox::new(if mouse_state.hovered {
684 let item_id = item.id();
685 enum TabCloseButton {}
686 let icon = Svg::new("icons/x.svg");
687 MouseEventHandler::new::<TabCloseButton, _, _>(
688 item_id,
689 cx,
690 |mouse_state, _| {
691 if mouse_state.hovered {
692 icon.with_color(style.icon_close_active)
693 .boxed()
694 } else {
695 icon.with_color(style.icon_close).boxed()
696 }
697 },
698 )
699 .with_padding(Padding::uniform(4.))
700 .with_cursor_style(CursorStyle::PointingHand)
701 .on_click(move |cx| {
702 cx.dispatch_action(CloseItem(item_id))
703 })
704 .named("close-tab-icon")
705 } else {
706 Empty::new().boxed()
707 })
708 .with_width(style.icon_width)
709 .boxed(),
710 )
711 .boxed(),
712 )
713 .boxed(),
714 )
715 .with_style(style.container)
716 .boxed(),
717 )
718 .on_mouse_down(move |cx| {
719 cx.dispatch_action(ActivateItem(ix));
720 true
721 })
722 .boxed()
723 })
724 }
725
726 row.add_child(
727 Empty::new()
728 .contained()
729 .with_border(theme.workspace.tab.container.border)
730 .flex(0., true)
731 .named("filler"),
732 );
733
734 row.boxed()
735 });
736
737 ConstrainedBox::new(tabs.boxed())
738 .with_height(theme.workspace.tab.height)
739 .named("tabs")
740 }
741}
742
743impl Entity for Pane {
744 type Event = Event;
745}
746
747impl View for Pane {
748 fn ui_name() -> &'static str {
749 "Pane"
750 }
751
752 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
753 let this = cx.handle();
754
755 EventHandler::new(if let Some(active_item) = self.active_item() {
756 Flex::column()
757 .with_child(self.render_tabs(cx))
758 .with_child(ChildView::new(&self.toolbar).boxed())
759 .with_child(ChildView::new(active_item).flex(1., true).boxed())
760 .boxed()
761 } else {
762 Empty::new().boxed()
763 })
764 .on_navigate_mouse_down(move |direction, cx| {
765 let this = this.clone();
766 match direction {
767 NavigationDirection::Back => cx.dispatch_action(GoBack(Some(this))),
768 NavigationDirection::Forward => cx.dispatch_action(GoForward(Some(this))),
769 }
770
771 true
772 })
773 .named("pane")
774 }
775
776 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
777 self.focus_active_item(cx);
778 }
779}
780
781impl ItemNavHistory {
782 pub fn new<T: Item>(history: Rc<RefCell<NavHistory>>, item: &ViewHandle<T>) -> Self {
783 Self {
784 history,
785 item: Rc::new(item.downgrade()),
786 }
787 }
788
789 pub fn history(&self) -> Rc<RefCell<NavHistory>> {
790 self.history.clone()
791 }
792
793 pub fn push<D: 'static + Any>(&self, data: Option<D>) {
794 self.history.borrow_mut().push(data, self.item.clone());
795 }
796}
797
798impl NavHistory {
799 pub fn disable(&mut self) {
800 self.mode = NavigationMode::Disabled;
801 }
802
803 pub fn enable(&mut self) {
804 self.mode = NavigationMode::Normal;
805 }
806
807 pub fn pop_backward(&mut self) -> Option<NavigationEntry> {
808 self.backward_stack.pop_back()
809 }
810
811 pub fn pop_forward(&mut self) -> Option<NavigationEntry> {
812 self.forward_stack.pop_back()
813 }
814
815 fn pop(&mut self, mode: NavigationMode) -> Option<NavigationEntry> {
816 match mode {
817 NavigationMode::Normal | NavigationMode::Disabled => None,
818 NavigationMode::GoingBack => self.pop_backward(),
819 NavigationMode::GoingForward => self.pop_forward(),
820 }
821 }
822
823 fn set_mode(&mut self, mode: NavigationMode) {
824 self.mode = mode;
825 }
826
827 pub fn push<D: 'static + Any>(&mut self, data: Option<D>, item: Rc<dyn WeakItemHandle>) {
828 match self.mode {
829 NavigationMode::Disabled => {}
830 NavigationMode::Normal => {
831 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
832 self.backward_stack.pop_front();
833 }
834 self.backward_stack.push_back(NavigationEntry {
835 item,
836 data: data.map(|data| Box::new(data) as Box<dyn Any>),
837 });
838 self.forward_stack.clear();
839 }
840 NavigationMode::GoingBack => {
841 if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
842 self.forward_stack.pop_front();
843 }
844 self.forward_stack.push_back(NavigationEntry {
845 item,
846 data: data.map(|data| Box::new(data) as Box<dyn Any>),
847 });
848 }
849 NavigationMode::GoingForward => {
850 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
851 self.backward_stack.pop_front();
852 }
853 self.backward_stack.push_back(NavigationEntry {
854 item,
855 data: data.map(|data| Box::new(data) as Box<dyn Any>),
856 });
857 }
858 }
859 }
860}
861
862#[cfg(test)]
863mod tests {
864 use crate::WorkspaceParams;
865
866 use super::*;
867 use gpui::TestAppContext;
868
869 #[gpui::test]
870 async fn test_close_items(cx: &mut TestAppContext) {
871 cx.foreground().forbid_parking();
872
873 let params = cx.update(WorkspaceParams::test);
874 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(¶ms, cx));
875 let item1 = cx.add_view(window_id, |_| {
876 let mut item = TestItem::new();
877 item.has_conflict = true;
878 item
879 });
880 let item2 = cx.add_view(window_id, |_| {
881 let mut item = TestItem::new();
882 item.is_dirty = true;
883 item.has_conflict = true;
884 item
885 });
886 let item3 = cx.add_view(window_id, |_| {
887 let mut item = TestItem::new();
888 item.has_conflict = true;
889 item
890 });
891 let item4 = cx.add_view(window_id, |_| {
892 let mut item = TestItem::new();
893 item.is_dirty = true;
894 item
895 });
896 let item5 = cx.add_view(window_id, |_| {
897 let mut item = TestItem::new();
898 item.is_dirty = true;
899 item.can_save = false;
900 item
901 });
902 let pane = workspace.update(cx, |workspace, cx| {
903 workspace.add_item(Box::new(item1.clone()), cx);
904 workspace.add_item(Box::new(item2.clone()), cx);
905 workspace.add_item(Box::new(item3.clone()), cx);
906 workspace.add_item(Box::new(item4.clone()), cx);
907 workspace.add_item(Box::new(item5.clone()), cx);
908 workspace.active_pane().clone()
909 });
910
911 let close_items = pane.update(cx, |pane, cx| {
912 pane.activate_item(1, true, cx);
913 assert_eq!(pane.active_item().unwrap().id(), item2.id());
914
915 let item1_id = item1.id();
916 let item3_id = item3.id();
917 let item4_id = item4.id();
918 let item5_id = item5.id();
919 pane.close_items(cx, move |id| {
920 [item1_id, item3_id, item4_id, item5_id].contains(&id)
921 })
922 });
923
924 cx.foreground().run_until_parked();
925 pane.read_with(cx, |pane, _| {
926 assert_eq!(pane.items.len(), 5);
927 assert_eq!(pane.active_item().unwrap().id(), item1.id());
928 });
929
930 cx.simulate_prompt_answer(window_id, 0);
931 cx.foreground().run_until_parked();
932 pane.read_with(cx, |pane, cx| {
933 assert_eq!(item1.read(cx).save_count, 1);
934 assert_eq!(item1.read(cx).save_as_count, 0);
935 assert_eq!(item1.read(cx).reload_count, 0);
936 assert_eq!(pane.items.len(), 4);
937 assert_eq!(pane.active_item().unwrap().id(), item3.id());
938 });
939
940 cx.simulate_prompt_answer(window_id, 1);
941 cx.foreground().run_until_parked();
942 pane.read_with(cx, |pane, cx| {
943 assert_eq!(item3.read(cx).save_count, 0);
944 assert_eq!(item3.read(cx).save_as_count, 0);
945 assert_eq!(item3.read(cx).reload_count, 1);
946 assert_eq!(pane.items.len(), 3);
947 assert_eq!(pane.active_item().unwrap().id(), item4.id());
948 });
949
950 cx.simulate_prompt_answer(window_id, 0);
951 cx.foreground().run_until_parked();
952 pane.read_with(cx, |pane, cx| {
953 assert_eq!(item4.read(cx).save_count, 1);
954 assert_eq!(item4.read(cx).save_as_count, 0);
955 assert_eq!(item4.read(cx).reload_count, 0);
956 assert_eq!(pane.items.len(), 2);
957 assert_eq!(pane.active_item().unwrap().id(), item5.id());
958 });
959
960 cx.simulate_prompt_answer(window_id, 0);
961 cx.foreground().run_until_parked();
962 cx.simulate_new_path_selection(|_| Some(Default::default()));
963 close_items.await;
964 pane.read_with(cx, |pane, cx| {
965 assert_eq!(item5.read(cx).save_count, 0);
966 assert_eq!(item5.read(cx).save_as_count, 1);
967 assert_eq!(item5.read(cx).reload_count, 0);
968 assert_eq!(pane.items.len(), 1);
969 assert_eq!(pane.active_item().unwrap().id(), item2.id());
970 });
971 }
972
973 struct TestItem {
974 save_count: usize,
975 save_as_count: usize,
976 reload_count: usize,
977 is_dirty: bool,
978 has_conflict: bool,
979 can_save: bool,
980 }
981
982 impl TestItem {
983 fn new() -> Self {
984 Self {
985 save_count: 0,
986 save_as_count: 0,
987 reload_count: 0,
988 is_dirty: false,
989 has_conflict: false,
990 can_save: true,
991 }
992 }
993 }
994
995 impl Entity for TestItem {
996 type Event = ();
997 }
998
999 impl View for TestItem {
1000 fn ui_name() -> &'static str {
1001 "TestItem"
1002 }
1003
1004 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
1005 Empty::new().boxed()
1006 }
1007 }
1008
1009 impl Item for TestItem {
1010 fn tab_content(&self, _: &theme::Tab, _: &AppContext) -> ElementBox {
1011 Empty::new().boxed()
1012 }
1013
1014 fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
1015 None
1016 }
1017
1018 fn project_entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
1019 None
1020 }
1021
1022 fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>) {}
1023
1024 fn is_dirty(&self, _: &AppContext) -> bool {
1025 self.is_dirty
1026 }
1027
1028 fn has_conflict(&self, _: &AppContext) -> bool {
1029 self.has_conflict
1030 }
1031
1032 fn can_save(&self, _: &AppContext) -> bool {
1033 self.can_save
1034 }
1035
1036 fn save(
1037 &mut self,
1038 _: ModelHandle<Project>,
1039 _: &mut ViewContext<Self>,
1040 ) -> Task<anyhow::Result<()>> {
1041 self.save_count += 1;
1042 Task::ready(Ok(()))
1043 }
1044
1045 fn can_save_as(&self, _: &AppContext) -> bool {
1046 true
1047 }
1048
1049 fn save_as(
1050 &mut self,
1051 _: ModelHandle<Project>,
1052 _: std::path::PathBuf,
1053 _: &mut ViewContext<Self>,
1054 ) -> Task<anyhow::Result<()>> {
1055 self.save_as_count += 1;
1056 Task::ready(Ok(()))
1057 }
1058
1059 fn reload(
1060 &mut self,
1061 _: ModelHandle<Project>,
1062 _: &mut ViewContext<Self>,
1063 ) -> Task<anyhow::Result<()>> {
1064 self.reload_count += 1;
1065 Task::ready(Ok(()))
1066 }
1067 }
1068}