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