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