1use super::{ItemHandle, SplitDirection};
2use crate::{toolbar::Toolbar, Item, NewFile, NewSearch, NewTerminal, WeakItemHandle, Workspace};
3use anyhow::Result;
4use collections::{HashMap, HashSet, VecDeque};
5use context_menu::{ContextMenu, ContextMenuItem};
6use drag_and_drop::{DragAndDrop, Draggable};
7use futures::StreamExt;
8use gpui::{
9 actions,
10 color::Color,
11 elements::*,
12 geometry::{
13 rect::RectF,
14 vector::{vec2f, Vector2F},
15 },
16 impl_actions, impl_internal_actions,
17 platform::{CursorStyle, NavigationDirection},
18 AnyViewHandle, AnyWeakViewHandle, AppContext, AsyncAppContext, Entity, EventContext,
19 ModelHandle, MouseButton, MutableAppContext, PromptLevel, Quad, RenderContext, Task, View,
20 ViewContext, ViewHandle, WeakViewHandle,
21};
22use project::{Project, ProjectEntryId, ProjectPath};
23use serde::Deserialize;
24use settings::{Autosave, Settings};
25use std::{any::Any, cell::RefCell, cmp, mem, path::Path, rc::Rc};
26use theme::Theme;
27use util::ResultExt;
28
29#[derive(Clone, Deserialize, PartialEq)]
30pub struct ActivateItem(pub usize);
31
32actions!(
33 pane,
34 [
35 ActivatePrevItem,
36 ActivateNextItem,
37 ActivateLastItem,
38 CloseActiveItem,
39 CloseInactiveItems,
40 ReopenClosedItem,
41 SplitLeft,
42 SplitUp,
43 SplitRight,
44 SplitDown,
45 ]
46);
47
48#[derive(Clone, PartialEq)]
49pub struct CloseItem {
50 pub item_id: usize,
51 pub pane: WeakViewHandle<Pane>,
52}
53
54#[derive(Clone, PartialEq)]
55pub struct MoveItem {
56 pub item_id: usize,
57 pub from: WeakViewHandle<Pane>,
58 pub to: WeakViewHandle<Pane>,
59 pub destination_index: usize,
60}
61
62#[derive(Clone, Deserialize, PartialEq)]
63pub struct GoBack {
64 #[serde(skip_deserializing)]
65 pub pane: Option<WeakViewHandle<Pane>>,
66}
67
68#[derive(Clone, Deserialize, PartialEq)]
69pub struct GoForward {
70 #[serde(skip_deserializing)]
71 pub pane: Option<WeakViewHandle<Pane>>,
72}
73
74#[derive(Clone, PartialEq)]
75pub struct DeploySplitMenu {
76 position: Vector2F,
77}
78
79#[derive(Clone, PartialEq)]
80pub struct DeployNewMenu {
81 position: Vector2F,
82}
83
84impl_actions!(pane, [GoBack, GoForward, ActivateItem]);
85impl_internal_actions!(pane, [CloseItem, DeploySplitMenu, DeployNewMenu, MoveItem]);
86
87const MAX_NAVIGATION_HISTORY_LEN: usize = 1024;
88
89pub fn init(cx: &mut MutableAppContext) {
90 cx.add_action(|pane: &mut Pane, action: &ActivateItem, cx| {
91 pane.activate_item(action.0, true, true, cx);
92 });
93 cx.add_action(|pane: &mut Pane, _: &ActivateLastItem, cx| {
94 pane.activate_item(pane.items.len() - 1, true, true, cx);
95 });
96 cx.add_action(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
97 pane.activate_prev_item(cx);
98 });
99 cx.add_action(|pane: &mut Pane, _: &ActivateNextItem, cx| {
100 pane.activate_next_item(cx);
101 });
102 cx.add_async_action(Pane::close_active_item);
103 cx.add_async_action(Pane::close_inactive_items);
104 cx.add_async_action(|workspace: &mut Workspace, action: &CloseItem, cx| {
105 let pane = action.pane.upgrade(cx)?;
106 let task = Pane::close_item(workspace, pane, action.item_id, cx);
107 Some(cx.foreground().spawn(async move {
108 task.await?;
109 Ok(())
110 }))
111 });
112 cx.add_action(
113 |workspace,
114 MoveItem {
115 from,
116 to,
117 item_id,
118 destination_index,
119 },
120 cx| {
121 // Get item handle to move
122 let from = if let Some(from) = from.upgrade(cx) {
123 from
124 } else {
125 return;
126 };
127
128 // Add item to new pane at given index
129 let to = if let Some(to) = to.upgrade(cx) {
130 to
131 } else {
132 return;
133 };
134
135 Pane::move_item(workspace, from, to, *item_id, *destination_index, cx)
136 },
137 );
138 cx.add_action(|pane: &mut Pane, _: &SplitLeft, cx| pane.split(SplitDirection::Left, cx));
139 cx.add_action(|pane: &mut Pane, _: &SplitUp, cx| pane.split(SplitDirection::Up, cx));
140 cx.add_action(|pane: &mut Pane, _: &SplitRight, cx| pane.split(SplitDirection::Right, cx));
141 cx.add_action(|pane: &mut Pane, _: &SplitDown, cx| pane.split(SplitDirection::Down, cx));
142 cx.add_action(Pane::deploy_split_menu);
143 cx.add_action(Pane::deploy_new_menu);
144 cx.add_action(|workspace: &mut Workspace, _: &ReopenClosedItem, cx| {
145 Pane::reopen_closed_item(workspace, cx).detach();
146 });
147 cx.add_action(|workspace: &mut Workspace, action: &GoBack, cx| {
148 Pane::go_back(
149 workspace,
150 action
151 .pane
152 .as_ref()
153 .and_then(|weak_handle| weak_handle.upgrade(cx)),
154 cx,
155 )
156 .detach();
157 });
158 cx.add_action(|workspace: &mut Workspace, action: &GoForward, cx| {
159 Pane::go_forward(
160 workspace,
161 action
162 .pane
163 .as_ref()
164 .and_then(|weak_handle| weak_handle.upgrade(cx)),
165 cx,
166 )
167 .detach();
168 });
169}
170
171pub enum Event {
172 Focused,
173 ActivateItem { local: bool },
174 Remove,
175 RemoveItem { item_id: usize },
176 Split(SplitDirection),
177 ChangeItemTitle,
178}
179
180pub struct Pane {
181 items: Vec<Box<dyn ItemHandle>>,
182 is_active: bool,
183 active_item_index: usize,
184 last_focused_view: Option<AnyWeakViewHandle>,
185 autoscroll: bool,
186 nav_history: Rc<RefCell<NavHistory>>,
187 toolbar: ViewHandle<Toolbar>,
188 context_menu: ViewHandle<ContextMenu>,
189}
190
191pub struct ItemNavHistory {
192 history: Rc<RefCell<NavHistory>>,
193 item: Rc<dyn WeakItemHandle>,
194}
195
196struct NavHistory {
197 mode: NavigationMode,
198 backward_stack: VecDeque<NavigationEntry>,
199 forward_stack: VecDeque<NavigationEntry>,
200 closed_stack: VecDeque<NavigationEntry>,
201 paths_by_item: HashMap<usize, ProjectPath>,
202 pane: WeakViewHandle<Pane>,
203}
204
205#[derive(Copy, Clone)]
206enum NavigationMode {
207 Normal,
208 GoingBack,
209 GoingForward,
210 ClosingItem,
211 ReopeningClosedItem,
212 Disabled,
213}
214
215impl Default for NavigationMode {
216 fn default() -> Self {
217 Self::Normal
218 }
219}
220
221pub struct NavigationEntry {
222 pub item: Rc<dyn WeakItemHandle>,
223 pub data: Option<Box<dyn Any>>,
224}
225
226struct DraggedItem {
227 item: Box<dyn ItemHandle>,
228 pane: WeakViewHandle<Pane>,
229}
230
231pub enum ReorderBehavior {
232 None,
233 MoveAfterActive,
234 MoveToIndex(usize),
235}
236
237impl Pane {
238 pub fn new(cx: &mut ViewContext<Self>) -> Self {
239 let handle = cx.weak_handle();
240 let context_menu = cx.add_view(ContextMenu::new);
241 Self {
242 items: Vec::new(),
243 is_active: true,
244 active_item_index: 0,
245 last_focused_view: None,
246 autoscroll: false,
247 nav_history: Rc::new(RefCell::new(NavHistory {
248 mode: NavigationMode::Normal,
249 backward_stack: Default::default(),
250 forward_stack: Default::default(),
251 closed_stack: Default::default(),
252 paths_by_item: Default::default(),
253 pane: handle.clone(),
254 })),
255 toolbar: cx.add_view(|_| Toolbar::new(handle)),
256 context_menu,
257 }
258 }
259
260 pub fn set_active(&mut self, is_active: bool, cx: &mut ViewContext<Self>) {
261 self.is_active = is_active;
262 cx.notify();
263 }
264
265 pub fn nav_history_for_item<T: Item>(&self, item: &ViewHandle<T>) -> ItemNavHistory {
266 ItemNavHistory {
267 history: self.nav_history.clone(),
268 item: Rc::new(item.downgrade()),
269 }
270 }
271
272 pub fn go_back(
273 workspace: &mut Workspace,
274 pane: Option<ViewHandle<Pane>>,
275 cx: &mut ViewContext<Workspace>,
276 ) -> Task<()> {
277 Self::navigate_history(
278 workspace,
279 pane.unwrap_or_else(|| workspace.active_pane().clone()),
280 NavigationMode::GoingBack,
281 cx,
282 )
283 }
284
285 pub fn go_forward(
286 workspace: &mut Workspace,
287 pane: Option<ViewHandle<Pane>>,
288 cx: &mut ViewContext<Workspace>,
289 ) -> Task<()> {
290 Self::navigate_history(
291 workspace,
292 pane.unwrap_or_else(|| workspace.active_pane().clone()),
293 NavigationMode::GoingForward,
294 cx,
295 )
296 }
297
298 pub fn reopen_closed_item(
299 workspace: &mut Workspace,
300 cx: &mut ViewContext<Workspace>,
301 ) -> Task<()> {
302 Self::navigate_history(
303 workspace,
304 workspace.active_pane().clone(),
305 NavigationMode::ReopeningClosedItem,
306 cx,
307 )
308 }
309
310 pub fn disable_history(&mut self) {
311 self.nav_history.borrow_mut().disable();
312 }
313
314 pub fn enable_history(&mut self) {
315 self.nav_history.borrow_mut().enable();
316 }
317
318 pub fn can_navigate_backward(&self) -> bool {
319 !self.nav_history.borrow().backward_stack.is_empty()
320 }
321
322 pub fn can_navigate_forward(&self) -> bool {
323 !self.nav_history.borrow().forward_stack.is_empty()
324 }
325
326 fn history_updated(&mut self, cx: &mut ViewContext<Self>) {
327 self.toolbar.update(cx, |_, cx| cx.notify());
328 }
329
330 fn navigate_history(
331 workspace: &mut Workspace,
332 pane: ViewHandle<Pane>,
333 mode: NavigationMode,
334 cx: &mut ViewContext<Workspace>,
335 ) -> Task<()> {
336 cx.focus(pane.clone());
337
338 let to_load = pane.update(cx, |pane, cx| {
339 loop {
340 // Retrieve the weak item handle from the history.
341 let entry = pane.nav_history.borrow_mut().pop(mode, cx)?;
342
343 // If the item is still present in this pane, then activate it.
344 if let Some(index) = entry
345 .item
346 .upgrade(cx)
347 .and_then(|v| pane.index_for_item(v.as_ref()))
348 {
349 let prev_active_item_index = pane.active_item_index;
350 pane.nav_history.borrow_mut().set_mode(mode);
351 pane.activate_item(index, true, true, cx);
352 pane.nav_history
353 .borrow_mut()
354 .set_mode(NavigationMode::Normal);
355
356 let mut navigated = prev_active_item_index != pane.active_item_index;
357 if let Some(data) = entry.data {
358 navigated |= pane.active_item()?.navigate(data, cx);
359 }
360
361 if navigated {
362 break None;
363 }
364 }
365 // If the item is no longer present in this pane, then retrieve its
366 // project path in order to reopen it.
367 else {
368 break pane
369 .nav_history
370 .borrow()
371 .paths_by_item
372 .get(&entry.item.id())
373 .cloned()
374 .map(|project_path| (project_path, entry));
375 }
376 }
377 });
378
379 if let Some((project_path, entry)) = to_load {
380 // If the item was no longer present, then load it again from its previous path.
381 let pane = pane.downgrade();
382 let task = workspace.load_path(project_path, cx);
383 cx.spawn(|workspace, mut cx| async move {
384 let task = task.await;
385 if let Some(pane) = pane.upgrade(&cx) {
386 let mut navigated = false;
387 if let Some((project_entry_id, build_item)) = task.log_err() {
388 let prev_active_item_id = pane.update(&mut cx, |pane, _| {
389 pane.nav_history.borrow_mut().set_mode(mode);
390 pane.active_item().map(|p| p.id())
391 });
392
393 let item = workspace.update(&mut cx, |workspace, cx| {
394 Self::open_item(
395 workspace,
396 pane.clone(),
397 project_entry_id,
398 true,
399 cx,
400 build_item,
401 )
402 });
403
404 pane.update(&mut cx, |pane, cx| {
405 navigated |= Some(item.id()) != prev_active_item_id;
406 pane.nav_history
407 .borrow_mut()
408 .set_mode(NavigationMode::Normal);
409 if let Some(data) = entry.data {
410 navigated |= item.navigate(data, cx);
411 }
412 });
413 }
414
415 if !navigated {
416 workspace
417 .update(&mut cx, |workspace, cx| {
418 Self::navigate_history(workspace, pane, mode, cx)
419 })
420 .await;
421 }
422 }
423 })
424 } else {
425 Task::ready(())
426 }
427 }
428
429 pub(crate) fn open_item(
430 workspace: &mut Workspace,
431 pane: ViewHandle<Pane>,
432 project_entry_id: ProjectEntryId,
433 focus_item: bool,
434 cx: &mut ViewContext<Workspace>,
435 build_item: impl FnOnce(&mut ViewContext<Pane>) -> Box<dyn ItemHandle>,
436 ) -> Box<dyn ItemHandle> {
437 let existing_item = pane.update(cx, |pane, cx| {
438 for item in pane.items.iter() {
439 if item.project_path(cx).is_some()
440 && item.project_entry_ids(cx).as_slice() == [project_entry_id]
441 {
442 let item = item.boxed_clone();
443 return Some(item);
444 }
445 }
446 None
447 });
448
449 // Even if the item exists, we re-add it to reorder it after the active item.
450 // We may revisit this behavior after adding an "activation history" for pane items.
451 let item = existing_item.unwrap_or_else(|| pane.update(cx, |_, cx| build_item(cx)));
452 Pane::add_item(workspace, &pane, item.clone(), true, focus_item, None, cx);
453 item
454 }
455
456 pub(crate) fn add_item(
457 workspace: &mut Workspace,
458 pane: &ViewHandle<Pane>,
459 item: Box<dyn ItemHandle>,
460 activate_pane: bool,
461 focus_item: bool,
462 destination_index: Option<usize>,
463 cx: &mut ViewContext<Workspace>,
464 ) {
465 // If no destination index is specified, add or move the item after the active item.
466 let mut insertion_index = {
467 let pane = pane.read(cx);
468 cmp::min(
469 if let Some(destination_index) = destination_index {
470 destination_index
471 } else {
472 pane.active_item_index + 1
473 },
474 pane.items.len(),
475 )
476 };
477
478 item.added_to_pane(workspace, pane.clone(), cx);
479
480 // Does the item already exist?
481 if let Some(existing_item_index) = pane.read(cx).items.iter().position(|existing_item| {
482 let existing_item_entry_ids = existing_item.project_entry_ids(cx);
483 let added_item_entry_ids = item.project_entry_ids(cx);
484 let entries_match = !existing_item_entry_ids.is_empty()
485 && existing_item_entry_ids == added_item_entry_ids;
486
487 existing_item.id() == item.id() || entries_match
488 }) {
489 // If the item already exists, move it to the desired destination and activate it
490 pane.update(cx, |pane, cx| {
491 if existing_item_index != insertion_index {
492 cx.reparent(&item);
493 let existing_item_is_active = existing_item_index == pane.active_item_index;
494
495 // If the caller didn't specify a destination and the added item is already
496 // the active one, don't move it
497 if existing_item_is_active && destination_index.is_none() {
498 insertion_index = existing_item_index;
499 } else {
500 pane.items.remove(existing_item_index);
501 if existing_item_index < pane.active_item_index {
502 pane.active_item_index -= 1;
503 }
504 insertion_index = insertion_index.min(pane.items.len());
505
506 pane.items.insert(insertion_index, item.clone());
507
508 if existing_item_is_active {
509 pane.active_item_index = insertion_index;
510 } else if insertion_index <= pane.active_item_index {
511 pane.active_item_index += 1;
512 }
513 }
514
515 cx.notify();
516 }
517
518 pane.activate_item(insertion_index, activate_pane, focus_item, cx);
519 });
520 } else {
521 pane.update(cx, |pane, cx| {
522 cx.reparent(&item);
523 pane.items.insert(insertion_index, item);
524 if insertion_index <= pane.active_item_index {
525 pane.active_item_index += 1;
526 }
527
528 pane.activate_item(insertion_index, activate_pane, focus_item, cx);
529 cx.notify();
530 });
531 }
532 }
533
534 pub fn items(&self) -> impl Iterator<Item = &Box<dyn ItemHandle>> {
535 self.items.iter()
536 }
537
538 pub fn items_of_type<T: View>(&self) -> impl '_ + Iterator<Item = ViewHandle<T>> {
539 self.items
540 .iter()
541 .filter_map(|item| item.to_any().downcast())
542 }
543
544 pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
545 self.items.get(self.active_item_index).cloned()
546 }
547
548 pub fn item_for_entry(
549 &self,
550 entry_id: ProjectEntryId,
551 cx: &AppContext,
552 ) -> Option<Box<dyn ItemHandle>> {
553 self.items.iter().find_map(|item| {
554 if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [entry_id] {
555 Some(item.boxed_clone())
556 } else {
557 None
558 }
559 })
560 }
561
562 pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
563 self.items.iter().position(|i| i.id() == item.id())
564 }
565
566 pub fn activate_item(
567 &mut self,
568 index: usize,
569 activate_pane: bool,
570 focus_item: bool,
571 cx: &mut ViewContext<Self>,
572 ) {
573 use NavigationMode::{GoingBack, GoingForward};
574 if index < self.items.len() {
575 let prev_active_item_ix = mem::replace(&mut self.active_item_index, index);
576 if prev_active_item_ix != self.active_item_index
577 || matches!(self.nav_history.borrow().mode, GoingBack | GoingForward)
578 {
579 if let Some(prev_item) = self.items.get(prev_active_item_ix) {
580 prev_item.deactivated(cx);
581 }
582 cx.emit(Event::ActivateItem {
583 local: activate_pane,
584 });
585 }
586 self.update_toolbar(cx);
587 if focus_item {
588 self.focus_active_item(cx);
589 }
590 if activate_pane {
591 cx.emit(Event::Focused);
592 }
593 self.autoscroll = true;
594 cx.notify();
595 }
596 }
597
598 pub fn activate_prev_item(&mut self, cx: &mut ViewContext<Self>) {
599 let mut index = self.active_item_index;
600 if index > 0 {
601 index -= 1;
602 } else if !self.items.is_empty() {
603 index = self.items.len() - 1;
604 }
605 self.activate_item(index, true, true, cx);
606 }
607
608 pub fn activate_next_item(&mut self, cx: &mut ViewContext<Self>) {
609 let mut index = self.active_item_index;
610 if index + 1 < self.items.len() {
611 index += 1;
612 } else {
613 index = 0;
614 }
615 self.activate_item(index, true, true, cx);
616 }
617
618 pub fn close_active_item(
619 workspace: &mut Workspace,
620 _: &CloseActiveItem,
621 cx: &mut ViewContext<Workspace>,
622 ) -> Option<Task<Result<()>>> {
623 let pane_handle = workspace.active_pane().clone();
624 let pane = pane_handle.read(cx);
625 if pane.items.is_empty() {
626 None
627 } else {
628 let item_id_to_close = pane.items[pane.active_item_index].id();
629 let task = Self::close_items(workspace, pane_handle, cx, move |item_id| {
630 item_id == item_id_to_close
631 });
632 Some(cx.foreground().spawn(async move {
633 task.await?;
634 Ok(())
635 }))
636 }
637 }
638
639 pub fn close_inactive_items(
640 workspace: &mut Workspace,
641 _: &CloseInactiveItems,
642 cx: &mut ViewContext<Workspace>,
643 ) -> Option<Task<Result<()>>> {
644 let pane_handle = workspace.active_pane().clone();
645 let pane = pane_handle.read(cx);
646 if pane.items.is_empty() {
647 None
648 } else {
649 let active_item_id = pane.items[pane.active_item_index].id();
650 let task =
651 Self::close_items(workspace, pane_handle, cx, move |id| id != active_item_id);
652 Some(cx.foreground().spawn(async move {
653 task.await?;
654 Ok(())
655 }))
656 }
657 }
658
659 pub fn close_item(
660 workspace: &mut Workspace,
661 pane: ViewHandle<Pane>,
662 item_id_to_close: usize,
663 cx: &mut ViewContext<Workspace>,
664 ) -> Task<Result<bool>> {
665 Self::close_items(workspace, pane, cx, move |view_id| {
666 view_id == item_id_to_close
667 })
668 }
669
670 pub fn close_items(
671 workspace: &mut Workspace,
672 pane: ViewHandle<Pane>,
673 cx: &mut ViewContext<Workspace>,
674 should_close: impl 'static + Fn(usize) -> bool,
675 ) -> Task<Result<bool>> {
676 let project = workspace.project().clone();
677
678 // Find the items to close.
679 let mut items_to_close = Vec::new();
680 for item in &pane.read(cx).items {
681 if should_close(item.id()) {
682 items_to_close.push(item.boxed_clone());
683 }
684 }
685
686 // If a buffer is open both in a singleton editor and in a multibuffer, make sure
687 // to focus the singleton buffer when prompting to save that buffer, as opposed
688 // to focusing the multibuffer, because this gives the user a more clear idea
689 // of what content they would be saving.
690 items_to_close.sort_by_key(|item| !item.is_singleton(cx));
691
692 cx.spawn(|workspace, mut cx| async move {
693 let mut saved_project_entry_ids = HashSet::default();
694 for item in items_to_close.clone() {
695 // Find the item's current index and its set of project entries. Avoid
696 // storing these in advance, in case they have changed since this task
697 // was started.
698 let (item_ix, mut project_entry_ids) = pane.read_with(&cx, |pane, cx| {
699 (pane.index_for_item(&*item), item.project_entry_ids(cx))
700 });
701 let item_ix = if let Some(ix) = item_ix {
702 ix
703 } else {
704 continue;
705 };
706
707 // If an item hasn't yet been associated with a project entry, then always
708 // prompt to save it before closing it. Otherwise, check if the item has
709 // any project entries that are not open anywhere else in the workspace,
710 // AND that the user has not already been prompted to save. If there are
711 // any such project entries, prompt the user to save this item.
712 let should_save = if project_entry_ids.is_empty() {
713 true
714 } else {
715 workspace.read_with(&cx, |workspace, cx| {
716 for item in workspace.items(cx) {
717 if !items_to_close
718 .iter()
719 .any(|item_to_close| item_to_close.id() == item.id())
720 {
721 let other_project_entry_ids = item.project_entry_ids(cx);
722 project_entry_ids
723 .retain(|id| !other_project_entry_ids.contains(id));
724 }
725 }
726 });
727 project_entry_ids
728 .iter()
729 .any(|id| saved_project_entry_ids.insert(*id))
730 };
731
732 if should_save
733 && !Self::save_item(project.clone(), &pane, item_ix, &*item, true, &mut cx)
734 .await?
735 {
736 break;
737 }
738
739 // Remove the item from the pane.
740 pane.update(&mut cx, |pane, cx| {
741 if let Some(item_ix) = pane.items.iter().position(|i| i.id() == item.id()) {
742 pane.remove_item(item_ix, cx);
743 }
744 });
745 }
746
747 pane.update(&mut cx, |_, cx| cx.notify());
748 Ok(true)
749 })
750 }
751
752 fn remove_item(&mut self, item_ix: usize, cx: &mut ViewContext<Self>) {
753 if item_ix == self.active_item_index {
754 // Activate the previous item if possible.
755 // This returns the user to the previously opened tab if they closed
756 // a new item they just navigated to.
757 if item_ix > 0 {
758 self.activate_prev_item(cx);
759 } else if item_ix + 1 < self.items.len() {
760 self.activate_next_item(cx);
761 }
762 }
763
764 let item = self.items.remove(item_ix);
765 cx.emit(Event::RemoveItem { item_id: item.id() });
766 if self.items.is_empty() {
767 item.deactivated(cx);
768 self.update_toolbar(cx);
769 cx.emit(Event::Remove);
770 }
771
772 if item_ix < self.active_item_index {
773 self.active_item_index -= 1;
774 }
775
776 self.nav_history
777 .borrow_mut()
778 .set_mode(NavigationMode::ClosingItem);
779 item.deactivated(cx);
780 self.nav_history
781 .borrow_mut()
782 .set_mode(NavigationMode::Normal);
783
784 if let Some(path) = item.project_path(cx) {
785 self.nav_history
786 .borrow_mut()
787 .paths_by_item
788 .insert(item.id(), path);
789 } else {
790 self.nav_history
791 .borrow_mut()
792 .paths_by_item
793 .remove(&item.id());
794 }
795
796 cx.notify();
797 }
798
799 pub async fn save_item(
800 project: ModelHandle<Project>,
801 pane: &ViewHandle<Pane>,
802 item_ix: usize,
803 item: &dyn ItemHandle,
804 should_prompt_for_save: bool,
805 cx: &mut AsyncAppContext,
806 ) -> Result<bool> {
807 const CONFLICT_MESSAGE: &str =
808 "This file has changed on disk since you started editing it. Do you want to overwrite it?";
809 const DIRTY_MESSAGE: &str = "This file contains unsaved edits. Do you want to save it?";
810
811 let (has_conflict, is_dirty, can_save, is_singleton) = cx.read(|cx| {
812 (
813 item.has_conflict(cx),
814 item.is_dirty(cx),
815 item.can_save(cx),
816 item.is_singleton(cx),
817 )
818 });
819
820 if has_conflict && can_save {
821 let mut answer = pane.update(cx, |pane, cx| {
822 pane.activate_item(item_ix, true, true, cx);
823 cx.prompt(
824 PromptLevel::Warning,
825 CONFLICT_MESSAGE,
826 &["Overwrite", "Discard", "Cancel"],
827 )
828 });
829 match answer.next().await {
830 Some(0) => cx.update(|cx| item.save(project, cx)).await?,
831 Some(1) => cx.update(|cx| item.reload(project, cx)).await?,
832 _ => return Ok(false),
833 }
834 } else if is_dirty && (can_save || is_singleton) {
835 let will_autosave = cx.read(|cx| {
836 matches!(
837 cx.global::<Settings>().autosave,
838 Autosave::OnFocusChange | Autosave::OnWindowChange
839 ) && Self::can_autosave_item(&*item, cx)
840 });
841 let should_save = if should_prompt_for_save && !will_autosave {
842 let mut answer = pane.update(cx, |pane, cx| {
843 pane.activate_item(item_ix, true, true, cx);
844 cx.prompt(
845 PromptLevel::Warning,
846 DIRTY_MESSAGE,
847 &["Save", "Don't Save", "Cancel"],
848 )
849 });
850 match answer.next().await {
851 Some(0) => true,
852 Some(1) => false,
853 _ => return Ok(false),
854 }
855 } else {
856 true
857 };
858
859 if should_save {
860 if can_save {
861 cx.update(|cx| item.save(project, cx)).await?;
862 } else if is_singleton {
863 let start_abs_path = project
864 .read_with(cx, |project, cx| {
865 let worktree = project.visible_worktrees(cx).next()?;
866 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
867 })
868 .unwrap_or_else(|| Path::new("").into());
869
870 let mut abs_path = cx.update(|cx| cx.prompt_for_new_path(&start_abs_path));
871 if let Some(abs_path) = abs_path.next().await.flatten() {
872 cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
873 } else {
874 return Ok(false);
875 }
876 }
877 }
878 }
879 Ok(true)
880 }
881
882 fn can_autosave_item(item: &dyn ItemHandle, cx: &AppContext) -> bool {
883 let is_deleted = item.project_entry_ids(cx).is_empty();
884 item.is_dirty(cx) && !item.has_conflict(cx) && item.can_save(cx) && !is_deleted
885 }
886
887 pub fn autosave_item(
888 item: &dyn ItemHandle,
889 project: ModelHandle<Project>,
890 cx: &mut MutableAppContext,
891 ) -> Task<Result<()>> {
892 if Self::can_autosave_item(item, cx) {
893 item.save(project, cx)
894 } else {
895 Task::ready(Ok(()))
896 }
897 }
898
899 pub fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
900 if let Some(active_item) = self.active_item() {
901 cx.focus(active_item);
902 }
903 }
904
905 fn move_item(
906 workspace: &mut Workspace,
907 from: ViewHandle<Pane>,
908 to: ViewHandle<Pane>,
909 item_to_move: usize,
910 destination_index: usize,
911 cx: &mut ViewContext<Workspace>,
912 ) {
913 let item_to_move = from
914 .read(cx)
915 .items()
916 .enumerate()
917 .find(|(_, item_handle)| item_handle.id() == item_to_move);
918
919 if item_to_move.is_none() {
920 log::warn!("Tried to move item handle which was not in `from` pane. Maybe tab was closed during drop");
921 return;
922 }
923
924 let (item_ix, item_handle) = item_to_move.unwrap();
925 // This automatically removes duplicate items in the pane
926 Pane::add_item(
927 workspace,
928 &to,
929 item_handle.clone(),
930 true,
931 true,
932 Some(destination_index),
933 cx,
934 );
935
936 if from != to {
937 // Close item from previous pane
938 from.update(cx, |from, cx| {
939 from.remove_item(item_ix, cx);
940 });
941 }
942
943 cx.focus(to);
944 }
945
946 pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
947 cx.emit(Event::Split(direction));
948 }
949
950 fn deploy_split_menu(&mut self, action: &DeploySplitMenu, cx: &mut ViewContext<Self>) {
951 self.context_menu.update(cx, |menu, cx| {
952 menu.show(
953 action.position,
954 vec![
955 ContextMenuItem::item("Split Right", SplitRight),
956 ContextMenuItem::item("Split Left", SplitLeft),
957 ContextMenuItem::item("Split Up", SplitUp),
958 ContextMenuItem::item("Split Down", SplitDown),
959 ],
960 cx,
961 );
962 });
963 }
964
965 fn deploy_new_menu(&mut self, action: &DeployNewMenu, cx: &mut ViewContext<Self>) {
966 self.context_menu.update(cx, |menu, cx| {
967 menu.show(
968 action.position,
969 vec![
970 ContextMenuItem::item("New File", NewFile),
971 ContextMenuItem::item("New Terminal", NewTerminal),
972 ContextMenuItem::item("New Search", NewSearch),
973 ],
974 cx,
975 );
976 });
977 }
978
979 pub fn toolbar(&self) -> &ViewHandle<Toolbar> {
980 &self.toolbar
981 }
982
983 fn update_toolbar(&mut self, cx: &mut ViewContext<Self>) {
984 let active_item = self
985 .items
986 .get(self.active_item_index)
987 .map(|item| item.as_ref());
988 self.toolbar.update(cx, |toolbar, cx| {
989 toolbar.set_active_pane_item(active_item, cx);
990 });
991 }
992
993 fn render_tab_bar(&mut self, cx: &mut RenderContext<Self>) -> impl Element {
994 let theme = cx.global::<Settings>().theme.clone();
995 let filler_index = self.items.len();
996
997 enum Tabs {}
998 enum Tab {}
999 enum Filler {}
1000 let pane = cx.handle();
1001 MouseEventHandler::new::<Tabs, _, _>(0, cx, |_, cx| {
1002 let autoscroll = if mem::take(&mut self.autoscroll) {
1003 Some(self.active_item_index)
1004 } else {
1005 None
1006 };
1007
1008 let pane_active = self.is_active;
1009
1010 let mut row = Flex::row().scrollable::<Tabs, _>(1, autoscroll, cx);
1011 for (ix, (item, detail)) in self
1012 .items
1013 .iter()
1014 .cloned()
1015 .zip(self.tab_details(cx))
1016 .enumerate()
1017 {
1018 let detail = if detail == 0 { None } else { Some(detail) };
1019 let tab_active = ix == self.active_item_index;
1020
1021 row.add_child({
1022 MouseEventHandler::new::<Tab, _, _>(ix, cx, {
1023 let item = item.clone();
1024 let pane = pane.clone();
1025 let detail = detail.clone();
1026
1027 let theme = cx.global::<Settings>().theme.clone();
1028
1029 move |mouse_state, cx| {
1030 let tab_style =
1031 theme.workspace.tab_bar.tab_style(pane_active, tab_active);
1032 let hovered = mouse_state.hovered;
1033 Self::render_tab(
1034 &item,
1035 pane,
1036 detail,
1037 hovered,
1038 Self::tab_overlay_color(hovered, theme.as_ref(), cx),
1039 tab_style,
1040 cx,
1041 )
1042 }
1043 })
1044 .with_cursor_style(if pane_active && tab_active {
1045 CursorStyle::Arrow
1046 } else {
1047 CursorStyle::PointingHand
1048 })
1049 .on_down(MouseButton::Left, move |_, cx| {
1050 cx.dispatch_action(ActivateItem(ix));
1051 })
1052 .on_click(MouseButton::Middle, {
1053 let item = item.clone();
1054 let pane = pane.clone();
1055 move |_, cx: &mut EventContext| {
1056 cx.dispatch_action(CloseItem {
1057 item_id: item.id(),
1058 pane: pane.clone(),
1059 })
1060 }
1061 })
1062 .on_up(MouseButton::Left, {
1063 let pane = pane.clone();
1064 move |_, cx: &mut EventContext| Pane::handle_dropped_item(&pane, ix, cx)
1065 })
1066 .as_draggable(
1067 DraggedItem {
1068 item,
1069 pane: pane.clone(),
1070 },
1071 {
1072 let theme = cx.global::<Settings>().theme.clone();
1073
1074 let detail = detail.clone();
1075 move |dragged_item, cx: &mut RenderContext<Workspace>| {
1076 let tab_style = &theme.workspace.tab_bar.dragged_tab;
1077 Self::render_tab(
1078 &dragged_item.item,
1079 dragged_item.pane.clone(),
1080 detail,
1081 false,
1082 None,
1083 &tab_style,
1084 cx,
1085 )
1086 }
1087 },
1088 )
1089 .boxed()
1090 })
1091 }
1092
1093 // Use the inactive tab style along with the current pane's active status to decide how to render
1094 // the filler
1095 let filler_style = theme.workspace.tab_bar.tab_style(pane_active, false);
1096 row.add_child(
1097 MouseEventHandler::new::<Filler, _, _>(0, cx, |mouse_state, cx| {
1098 let mut filler = Empty::new()
1099 .contained()
1100 .with_style(filler_style.container)
1101 .with_border(filler_style.container.border);
1102
1103 if let Some(overlay) = Self::tab_overlay_color(mouse_state.hovered, &theme, cx)
1104 {
1105 filler = filler.with_overlay_color(overlay);
1106 }
1107
1108 filler.boxed()
1109 })
1110 .flex(1., true)
1111 .named("filler"),
1112 );
1113
1114 row.boxed()
1115 })
1116 .on_up(MouseButton::Left, move |_, cx| {
1117 Pane::handle_dropped_item(&pane, filler_index, cx)
1118 })
1119 }
1120
1121 fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1122 let mut tab_details = (0..self.items.len()).map(|_| 0).collect::<Vec<_>>();
1123
1124 let mut tab_descriptions = HashMap::default();
1125 let mut done = false;
1126 while !done {
1127 done = true;
1128
1129 // Store item indices by their tab description.
1130 for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1131 if let Some(description) = item.tab_description(*detail, cx) {
1132 if *detail == 0
1133 || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1134 {
1135 tab_descriptions
1136 .entry(description)
1137 .or_insert(Vec::new())
1138 .push(ix);
1139 }
1140 }
1141 }
1142
1143 // If two or more items have the same tab description, increase their level
1144 // of detail and try again.
1145 for (_, item_ixs) in tab_descriptions.drain() {
1146 if item_ixs.len() > 1 {
1147 done = false;
1148 for ix in item_ixs {
1149 tab_details[ix] += 1;
1150 }
1151 }
1152 }
1153 }
1154
1155 tab_details
1156 }
1157
1158 fn render_tab<V: View>(
1159 item: &Box<dyn ItemHandle>,
1160 pane: WeakViewHandle<Pane>,
1161 detail: Option<usize>,
1162 hovered: bool,
1163 overlay: Option<Color>,
1164 tab_style: &theme::Tab,
1165 cx: &mut RenderContext<V>,
1166 ) -> ElementBox {
1167 let title = item.tab_content(detail, &tab_style, cx);
1168
1169 let mut tab = Flex::row()
1170 .with_child(
1171 Align::new({
1172 let diameter = 7.0;
1173 let icon_color = if item.has_conflict(cx) {
1174 Some(tab_style.icon_conflict)
1175 } else if item.is_dirty(cx) {
1176 Some(tab_style.icon_dirty)
1177 } else {
1178 None
1179 };
1180
1181 ConstrainedBox::new(
1182 Canvas::new(move |bounds, _, cx| {
1183 if let Some(color) = icon_color {
1184 let square = RectF::new(bounds.origin(), vec2f(diameter, diameter));
1185 cx.scene.push_quad(Quad {
1186 bounds: square,
1187 background: Some(color),
1188 border: Default::default(),
1189 corner_radius: diameter / 2.,
1190 });
1191 }
1192 })
1193 .boxed(),
1194 )
1195 .with_width(diameter)
1196 .with_height(diameter)
1197 .boxed()
1198 })
1199 .boxed(),
1200 )
1201 .with_child(
1202 Container::new(Align::new(title).boxed())
1203 .with_style(ContainerStyle {
1204 margin: Margin {
1205 left: tab_style.spacing,
1206 right: tab_style.spacing,
1207 ..Default::default()
1208 },
1209 ..Default::default()
1210 })
1211 .boxed(),
1212 )
1213 .with_child(
1214 Align::new(
1215 ConstrainedBox::new(if hovered {
1216 let item_id = item.id();
1217 enum TabCloseButton {}
1218 let icon = Svg::new("icons/x_mark_thin_8.svg");
1219 MouseEventHandler::new::<TabCloseButton, _, _>(
1220 item_id,
1221 cx,
1222 |mouse_state, _| {
1223 if mouse_state.hovered {
1224 icon.with_color(tab_style.icon_close_active).boxed()
1225 } else {
1226 icon.with_color(tab_style.icon_close).boxed()
1227 }
1228 },
1229 )
1230 .with_padding(Padding::uniform(4.))
1231 .with_cursor_style(CursorStyle::PointingHand)
1232 .on_click(MouseButton::Left, {
1233 let pane = pane.clone();
1234 move |_, cx| {
1235 cx.dispatch_action(CloseItem {
1236 item_id,
1237 pane: pane.clone(),
1238 })
1239 }
1240 })
1241 .on_click(MouseButton::Middle, |_, cx| cx.propogate_event())
1242 .named("close-tab-icon")
1243 } else {
1244 Empty::new().boxed()
1245 })
1246 .with_width(tab_style.icon_width)
1247 .boxed(),
1248 )
1249 .boxed(),
1250 )
1251 .contained()
1252 .with_style(tab_style.container);
1253
1254 if let Some(overlay) = overlay {
1255 tab = tab.with_overlay_color(overlay);
1256 }
1257
1258 tab.constrained().with_height(tab_style.height).boxed()
1259 }
1260
1261 fn handle_dropped_item(pane: &WeakViewHandle<Pane>, index: usize, cx: &mut EventContext) {
1262 if let Some((_, dragged_item)) = cx
1263 .global::<DragAndDrop<Workspace>>()
1264 .currently_dragged::<DraggedItem>(cx.window_id)
1265 {
1266 cx.dispatch_action(MoveItem {
1267 item_id: dragged_item.item.id(),
1268 from: dragged_item.pane.clone(),
1269 to: pane.clone(),
1270 destination_index: index,
1271 })
1272 } else {
1273 cx.propogate_event();
1274 }
1275 }
1276
1277 fn tab_overlay_color(
1278 hovered: bool,
1279 theme: &Theme,
1280 cx: &mut RenderContext<Self>,
1281 ) -> Option<Color> {
1282 if hovered
1283 && cx
1284 .global::<DragAndDrop<Workspace>>()
1285 .currently_dragged::<DraggedItem>(cx.window_id())
1286 .is_some()
1287 {
1288 Some(theme.workspace.tab_bar.drop_target_overlay_color)
1289 } else {
1290 None
1291 }
1292 }
1293}
1294
1295impl Entity for Pane {
1296 type Event = Event;
1297}
1298
1299impl View for Pane {
1300 fn ui_name() -> &'static str {
1301 "Pane"
1302 }
1303
1304 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1305 enum SplitIcon {}
1306
1307 let this = cx.handle();
1308
1309 Stack::new()
1310 .with_child(
1311 EventHandler::new(if let Some(active_item) = self.active_item() {
1312 Flex::column()
1313 .with_child({
1314 let mut tab_row = Flex::row()
1315 .with_child(self.render_tab_bar(cx).flex(1., true).named("tabs"));
1316
1317 if self.is_active {
1318 tab_row.add_children([
1319 MouseEventHandler::new::<SplitIcon, _, _>(
1320 0,
1321 cx,
1322 |mouse_state, cx| {
1323 let theme =
1324 &cx.global::<Settings>().theme.workspace.tab_bar;
1325 let style =
1326 theme.pane_button.style_for(mouse_state, false);
1327 Svg::new("icons/plus_12.svg")
1328 .with_color(style.color)
1329 .constrained()
1330 .with_width(style.icon_width)
1331 .aligned()
1332 .contained()
1333 .with_style(style.container)
1334 .constrained()
1335 .with_width(style.button_width)
1336 .with_height(style.button_width)
1337 .aligned()
1338 .boxed()
1339 },
1340 )
1341 .with_cursor_style(CursorStyle::PointingHand)
1342 .on_down(MouseButton::Left, |e, cx| {
1343 cx.dispatch_action(DeployNewMenu {
1344 position: e.position,
1345 });
1346 })
1347 .boxed(),
1348 MouseEventHandler::new::<SplitIcon, _, _>(
1349 1,
1350 cx,
1351 |mouse_state, cx| {
1352 let theme =
1353 &cx.global::<Settings>().theme.workspace.tab_bar;
1354 let style =
1355 theme.pane_button.style_for(mouse_state, false);
1356 Svg::new("icons/split_12.svg")
1357 .with_color(style.color)
1358 .constrained()
1359 .with_width(style.icon_width)
1360 .aligned()
1361 .contained()
1362 .with_style(style.container)
1363 .constrained()
1364 .with_width(style.button_width)
1365 .with_height(style.button_width)
1366 .aligned()
1367 .boxed()
1368 },
1369 )
1370 .with_cursor_style(CursorStyle::PointingHand)
1371 .on_down(MouseButton::Left, |e, cx| {
1372 cx.dispatch_action(DeploySplitMenu {
1373 position: e.position,
1374 });
1375 })
1376 .boxed(),
1377 ])
1378 }
1379
1380 tab_row
1381 .constrained()
1382 .with_height(cx.global::<Settings>().theme.workspace.tab_bar.height)
1383 .named("tab bar")
1384 })
1385 .with_child(ChildView::new(&self.toolbar).boxed())
1386 .with_child(ChildView::new(active_item).flex(1., true).boxed())
1387 .boxed()
1388 } else {
1389 enum EmptyPane {}
1390 let theme = cx.global::<Settings>().theme.clone();
1391
1392 MouseEventHandler::new::<EmptyPane, _, _>(0, cx, |_, _| {
1393 Empty::new()
1394 .contained()
1395 .with_background_color(theme.workspace.background)
1396 .boxed()
1397 })
1398 .on_down(MouseButton::Left, |_, cx| {
1399 cx.focus_parent_view();
1400 })
1401 .boxed()
1402 })
1403 .on_navigate_mouse_down(move |direction, cx| {
1404 let this = this.clone();
1405 match direction {
1406 NavigationDirection::Back => {
1407 cx.dispatch_action(GoBack { pane: Some(this) })
1408 }
1409 NavigationDirection::Forward => {
1410 cx.dispatch_action(GoForward { pane: Some(this) })
1411 }
1412 }
1413
1414 true
1415 })
1416 .boxed(),
1417 )
1418 .with_child(ChildView::new(&self.context_menu).boxed())
1419 .named("pane")
1420 }
1421
1422 fn on_focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
1423 if cx.is_self_focused() {
1424 if let Some(last_focused_view) = self
1425 .last_focused_view
1426 .as_ref()
1427 .and_then(|handle| handle.upgrade(cx))
1428 {
1429 cx.focus(last_focused_view);
1430 } else {
1431 self.focus_active_item(cx);
1432 }
1433 } else {
1434 self.last_focused_view = Some(focused.downgrade());
1435 }
1436 cx.emit(Event::Focused);
1437 }
1438}
1439
1440impl ItemNavHistory {
1441 pub fn push<D: 'static + Any>(&self, data: Option<D>, cx: &mut MutableAppContext) {
1442 self.history.borrow_mut().push(data, self.item.clone(), cx);
1443 }
1444
1445 pub fn pop_backward(&self, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1446 self.history.borrow_mut().pop(NavigationMode::GoingBack, cx)
1447 }
1448
1449 pub fn pop_forward(&self, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1450 self.history
1451 .borrow_mut()
1452 .pop(NavigationMode::GoingForward, cx)
1453 }
1454}
1455
1456impl NavHistory {
1457 fn set_mode(&mut self, mode: NavigationMode) {
1458 self.mode = mode;
1459 }
1460
1461 fn disable(&mut self) {
1462 self.mode = NavigationMode::Disabled;
1463 }
1464
1465 fn enable(&mut self) {
1466 self.mode = NavigationMode::Normal;
1467 }
1468
1469 fn pop(&mut self, mode: NavigationMode, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1470 let entry = match mode {
1471 NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
1472 return None
1473 }
1474 NavigationMode::GoingBack => &mut self.backward_stack,
1475 NavigationMode::GoingForward => &mut self.forward_stack,
1476 NavigationMode::ReopeningClosedItem => &mut self.closed_stack,
1477 }
1478 .pop_back();
1479 if entry.is_some() {
1480 self.did_update(cx);
1481 }
1482 entry
1483 }
1484
1485 fn push<D: 'static + Any>(
1486 &mut self,
1487 data: Option<D>,
1488 item: Rc<dyn WeakItemHandle>,
1489 cx: &mut MutableAppContext,
1490 ) {
1491 match self.mode {
1492 NavigationMode::Disabled => {}
1493 NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
1494 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1495 self.backward_stack.pop_front();
1496 }
1497 self.backward_stack.push_back(NavigationEntry {
1498 item,
1499 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1500 });
1501 self.forward_stack.clear();
1502 }
1503 NavigationMode::GoingBack => {
1504 if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1505 self.forward_stack.pop_front();
1506 }
1507 self.forward_stack.push_back(NavigationEntry {
1508 item,
1509 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1510 });
1511 }
1512 NavigationMode::GoingForward => {
1513 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1514 self.backward_stack.pop_front();
1515 }
1516 self.backward_stack.push_back(NavigationEntry {
1517 item,
1518 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1519 });
1520 }
1521 NavigationMode::ClosingItem => {
1522 if self.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1523 self.closed_stack.pop_front();
1524 }
1525 self.closed_stack.push_back(NavigationEntry {
1526 item,
1527 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1528 });
1529 }
1530 }
1531 self.did_update(cx);
1532 }
1533
1534 fn did_update(&self, cx: &mut MutableAppContext) {
1535 if let Some(pane) = self.pane.upgrade(cx) {
1536 cx.defer(move |cx| pane.update(cx, |pane, cx| pane.history_updated(cx)));
1537 }
1538 }
1539}
1540
1541#[cfg(test)]
1542mod tests {
1543 use gpui::TestAppContext;
1544 use project::FakeFs;
1545
1546 use crate::tests::TestItem;
1547
1548 use super::*;
1549
1550 #[gpui::test]
1551 async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
1552 cx.foreground().forbid_parking();
1553 Settings::test_async(cx);
1554 let fs = FakeFs::new(cx.background());
1555
1556 let project = Project::test(fs, None, cx).await;
1557 let (_, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
1558 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
1559
1560 // 1. Add with a destination index
1561 // a. Add before the active item
1562 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1563 workspace.update(cx, |workspace, cx| {
1564 Pane::add_item(
1565 workspace,
1566 &pane,
1567 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1568 false,
1569 false,
1570 Some(0),
1571 cx,
1572 );
1573 });
1574 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
1575
1576 // b. Add after the active item
1577 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1578 workspace.update(cx, |workspace, cx| {
1579 Pane::add_item(
1580 workspace,
1581 &pane,
1582 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1583 false,
1584 false,
1585 Some(2),
1586 cx,
1587 );
1588 });
1589 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
1590
1591 // c. Add at the end of the item list (including off the length)
1592 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1593 workspace.update(cx, |workspace, cx| {
1594 Pane::add_item(
1595 workspace,
1596 &pane,
1597 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1598 false,
1599 false,
1600 Some(5),
1601 cx,
1602 );
1603 });
1604 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
1605
1606 // 2. Add without a destination index
1607 // a. Add with active item at the start of the item list
1608 set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
1609 workspace.update(cx, |workspace, cx| {
1610 Pane::add_item(
1611 workspace,
1612 &pane,
1613 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1614 false,
1615 false,
1616 None,
1617 cx,
1618 );
1619 });
1620 set_labeled_items(&workspace, &pane, ["A", "D*", "B", "C"], cx);
1621
1622 // b. Add with active item at the end of the item list
1623 set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
1624 workspace.update(cx, |workspace, cx| {
1625 Pane::add_item(
1626 workspace,
1627 &pane,
1628 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1629 false,
1630 false,
1631 None,
1632 cx,
1633 );
1634 });
1635 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
1636 }
1637
1638 #[gpui::test]
1639 async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
1640 cx.foreground().forbid_parking();
1641 Settings::test_async(cx);
1642 let fs = FakeFs::new(cx.background());
1643
1644 let project = Project::test(fs, None, cx).await;
1645 let (_, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
1646 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
1647
1648 // 1. Add with a destination index
1649 // 1a. Add before the active item
1650 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
1651 workspace.update(cx, |workspace, cx| {
1652 Pane::add_item(workspace, &pane, d, false, false, Some(0), cx);
1653 });
1654 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
1655
1656 // 1b. Add after the active item
1657 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
1658 workspace.update(cx, |workspace, cx| {
1659 Pane::add_item(workspace, &pane, d, false, false, Some(2), cx);
1660 });
1661 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
1662
1663 // 1c. Add at the end of the item list (including off the length)
1664 let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
1665 workspace.update(cx, |workspace, cx| {
1666 Pane::add_item(workspace, &pane, a, false, false, Some(5), cx);
1667 });
1668 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
1669
1670 // 1d. Add same item to active index
1671 let [_, b, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1672 workspace.update(cx, |workspace, cx| {
1673 Pane::add_item(workspace, &pane, b, false, false, Some(1), cx);
1674 });
1675 assert_item_labels(&pane, ["A", "B*", "C"], cx);
1676
1677 // 1e. Add item to index after same item in last position
1678 let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1679 workspace.update(cx, |workspace, cx| {
1680 Pane::add_item(workspace, &pane, c, false, false, Some(2), cx);
1681 });
1682 assert_item_labels(&pane, ["A", "B", "C*"], cx);
1683
1684 // 2. Add without a destination index
1685 // 2a. Add with active item at the start of the item list
1686 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A*", "B", "C", "D"], cx);
1687 workspace.update(cx, |workspace, cx| {
1688 Pane::add_item(workspace, &pane, d, false, false, None, cx);
1689 });
1690 assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
1691
1692 // 2b. Add with active item at the end of the item list
1693 let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B", "C", "D*"], cx);
1694 workspace.update(cx, |workspace, cx| {
1695 Pane::add_item(workspace, &pane, a, false, false, None, cx);
1696 });
1697 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
1698
1699 // 2c. Add active item to active item at end of list
1700 let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
1701 workspace.update(cx, |workspace, cx| {
1702 Pane::add_item(workspace, &pane, c, false, false, None, cx);
1703 });
1704 assert_item_labels(&pane, ["A", "B", "C*"], cx);
1705
1706 // 2d. Add active item to active item at start of list
1707 let [a, _, _] = set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
1708 workspace.update(cx, |workspace, cx| {
1709 Pane::add_item(workspace, &pane, a, false, false, None, cx);
1710 });
1711 assert_item_labels(&pane, ["A*", "B", "C"], cx);
1712 }
1713
1714 fn set_labeled_items<const COUNT: usize>(
1715 workspace: &ViewHandle<Workspace>,
1716 pane: &ViewHandle<Pane>,
1717 labels: [&str; COUNT],
1718 cx: &mut TestAppContext,
1719 ) -> [Box<ViewHandle<TestItem>>; COUNT] {
1720 pane.update(cx, |pane, _| {
1721 pane.items.clear();
1722 });
1723
1724 workspace.update(cx, |workspace, cx| {
1725 let mut active_item_index = 0;
1726
1727 let mut index = 0;
1728 let items = labels.map(|mut label| {
1729 if label.ends_with("*") {
1730 label = label.trim_end_matches("*");
1731 active_item_index = index;
1732 }
1733
1734 let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
1735 Pane::add_item(
1736 workspace,
1737 pane,
1738 labeled_item.clone(),
1739 false,
1740 false,
1741 None,
1742 cx,
1743 );
1744 index += 1;
1745 labeled_item
1746 });
1747
1748 pane.update(cx, |pane, cx| {
1749 pane.activate_item(active_item_index, false, false, cx)
1750 });
1751
1752 items
1753 })
1754 }
1755
1756 // Assert the item label, with the active item label suffixed with a '*'
1757 fn assert_item_labels<const COUNT: usize>(
1758 pane: &ViewHandle<Pane>,
1759 expected_states: [&str; COUNT],
1760 cx: &mut TestAppContext,
1761 ) {
1762 pane.read_with(cx, |pane, cx| {
1763 let actual_states = pane
1764 .items
1765 .iter()
1766 .enumerate()
1767 .map(|(ix, item)| {
1768 let mut state = item
1769 .to_any()
1770 .downcast::<TestItem>()
1771 .unwrap()
1772 .read(cx)
1773 .label
1774 .clone();
1775 if ix == pane.active_item_index {
1776 state.push('*');
1777 }
1778 state
1779 })
1780 .collect::<Vec<_>>();
1781
1782 assert_eq!(
1783 actual_states, expected_states,
1784 "pane items do not match expectation"
1785 );
1786 })
1787 }
1788}