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_ix, item_handle) = from
914 .read(cx)
915 .items()
916 .enumerate()
917 .find(|(_, item_handle)| item_handle.id() == item_to_move)
918 .expect("Tried to move item handle which was not in from pane");
919
920 // This automatically removes duplicate items in the pane
921 Pane::add_item(
922 workspace,
923 &to,
924 item_handle.clone(),
925 true,
926 true,
927 Some(destination_index),
928 cx,
929 );
930
931 if from != to {
932 // Close item from previous pane
933 from.update(cx, |from, cx| {
934 from.remove_item(item_ix, cx);
935 });
936 }
937
938 cx.focus(to);
939 }
940
941 pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
942 cx.emit(Event::Split(direction));
943 }
944
945 fn deploy_split_menu(&mut self, action: &DeploySplitMenu, cx: &mut ViewContext<Self>) {
946 self.context_menu.update(cx, |menu, cx| {
947 menu.show(
948 action.position,
949 vec![
950 ContextMenuItem::item("Split Right", SplitRight),
951 ContextMenuItem::item("Split Left", SplitLeft),
952 ContextMenuItem::item("Split Up", SplitUp),
953 ContextMenuItem::item("Split Down", SplitDown),
954 ],
955 cx,
956 );
957 });
958 }
959
960 fn deploy_new_menu(&mut self, action: &DeployNewMenu, cx: &mut ViewContext<Self>) {
961 self.context_menu.update(cx, |menu, cx| {
962 menu.show(
963 action.position,
964 vec![
965 ContextMenuItem::item("New File", NewFile),
966 ContextMenuItem::item("New Terminal", NewTerminal),
967 ContextMenuItem::item("New Search", NewSearch),
968 ],
969 cx,
970 );
971 });
972 }
973
974 pub fn toolbar(&self) -> &ViewHandle<Toolbar> {
975 &self.toolbar
976 }
977
978 fn update_toolbar(&mut self, cx: &mut ViewContext<Self>) {
979 let active_item = self
980 .items
981 .get(self.active_item_index)
982 .map(|item| item.as_ref());
983 self.toolbar.update(cx, |toolbar, cx| {
984 toolbar.set_active_pane_item(active_item, cx);
985 });
986 }
987
988 fn render_tab_bar(&mut self, cx: &mut RenderContext<Self>) -> impl Element {
989 let theme = cx.global::<Settings>().theme.clone();
990 let filler_index = self.items.len();
991
992 enum Tabs {}
993 enum Tab {}
994 enum Filler {}
995 let pane = cx.handle();
996 MouseEventHandler::new::<Tabs, _, _>(0, cx, |_, cx| {
997 let autoscroll = if mem::take(&mut self.autoscroll) {
998 Some(self.active_item_index)
999 } else {
1000 None
1001 };
1002
1003 let pane_active = self.is_active;
1004
1005 let mut row = Flex::row().scrollable::<Tabs, _>(1, autoscroll, cx);
1006 for (ix, (item, detail)) in self
1007 .items
1008 .iter()
1009 .cloned()
1010 .zip(self.tab_details(cx))
1011 .enumerate()
1012 {
1013 let detail = if detail == 0 { None } else { Some(detail) };
1014 let tab_active = ix == self.active_item_index;
1015
1016 row.add_child({
1017 MouseEventHandler::new::<Tab, _, _>(ix, cx, {
1018 let item = item.clone();
1019 let pane = pane.clone();
1020 let detail = detail.clone();
1021
1022 let theme = cx.global::<Settings>().theme.clone();
1023
1024 move |mouse_state, cx| {
1025 let tab_style =
1026 theme.workspace.tab_bar.tab_style(pane_active, tab_active);
1027 let hovered = mouse_state.hovered;
1028 Self::render_tab(
1029 &item,
1030 pane,
1031 detail,
1032 hovered,
1033 Self::tab_overlay_color(hovered, theme.as_ref(), cx),
1034 tab_style,
1035 cx,
1036 )
1037 }
1038 })
1039 .with_cursor_style(if pane_active && tab_active {
1040 CursorStyle::Arrow
1041 } else {
1042 CursorStyle::PointingHand
1043 })
1044 .on_down(MouseButton::Left, move |_, cx| {
1045 cx.dispatch_action(ActivateItem(ix));
1046 })
1047 .on_click(MouseButton::Middle, {
1048 let item = item.clone();
1049 let pane = pane.clone();
1050 move |_, cx: &mut EventContext| {
1051 cx.dispatch_action(CloseItem {
1052 item_id: item.id(),
1053 pane: pane.clone(),
1054 })
1055 }
1056 })
1057 .on_up(MouseButton::Left, {
1058 let pane = pane.clone();
1059 move |_, cx: &mut EventContext| Pane::handle_dropped_item(&pane, ix, cx)
1060 })
1061 .as_draggable(
1062 DraggedItem {
1063 item,
1064 pane: pane.clone(),
1065 },
1066 {
1067 let theme = cx.global::<Settings>().theme.clone();
1068
1069 let detail = detail.clone();
1070 move |dragged_item, cx: &mut RenderContext<Workspace>| {
1071 let tab_style = &theme.workspace.tab_bar.dragged_tab;
1072 Self::render_tab(
1073 &dragged_item.item,
1074 dragged_item.pane.clone(),
1075 detail,
1076 false,
1077 None,
1078 &tab_style,
1079 cx,
1080 )
1081 }
1082 },
1083 )
1084 .boxed()
1085 })
1086 }
1087
1088 // Use the inactive tab style along with the current pane's active status to decide how to render
1089 // the filler
1090 let filler_style = theme.workspace.tab_bar.tab_style(pane_active, false);
1091 row.add_child(
1092 MouseEventHandler::new::<Filler, _, _>(0, cx, |mouse_state, cx| {
1093 let mut filler = Empty::new()
1094 .contained()
1095 .with_style(filler_style.container)
1096 .with_border(filler_style.container.border);
1097
1098 if let Some(overlay) = Self::tab_overlay_color(mouse_state.hovered, &theme, cx)
1099 {
1100 filler = filler.with_overlay_color(overlay);
1101 }
1102
1103 filler.boxed()
1104 })
1105 .flex(1., true)
1106 .named("filler"),
1107 );
1108
1109 row.boxed()
1110 })
1111 .on_up(MouseButton::Left, move |_, cx| {
1112 Pane::handle_dropped_item(&pane, filler_index, cx)
1113 })
1114 }
1115
1116 fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1117 let mut tab_details = (0..self.items.len()).map(|_| 0).collect::<Vec<_>>();
1118
1119 let mut tab_descriptions = HashMap::default();
1120 let mut done = false;
1121 while !done {
1122 done = true;
1123
1124 // Store item indices by their tab description.
1125 for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1126 if let Some(description) = item.tab_description(*detail, cx) {
1127 if *detail == 0
1128 || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1129 {
1130 tab_descriptions
1131 .entry(description)
1132 .or_insert(Vec::new())
1133 .push(ix);
1134 }
1135 }
1136 }
1137
1138 // If two or more items have the same tab description, increase their level
1139 // of detail and try again.
1140 for (_, item_ixs) in tab_descriptions.drain() {
1141 if item_ixs.len() > 1 {
1142 done = false;
1143 for ix in item_ixs {
1144 tab_details[ix] += 1;
1145 }
1146 }
1147 }
1148 }
1149
1150 tab_details
1151 }
1152
1153 fn render_tab<V: View>(
1154 item: &Box<dyn ItemHandle>,
1155 pane: WeakViewHandle<Pane>,
1156 detail: Option<usize>,
1157 hovered: bool,
1158 overlay: Option<Color>,
1159 tab_style: &theme::Tab,
1160 cx: &mut RenderContext<V>,
1161 ) -> ElementBox {
1162 let title = item.tab_content(detail, &tab_style, cx);
1163
1164 let mut tab = Flex::row()
1165 .with_child(
1166 Align::new({
1167 let diameter = 7.0;
1168 let icon_color = if item.has_conflict(cx) {
1169 Some(tab_style.icon_conflict)
1170 } else if item.is_dirty(cx) {
1171 Some(tab_style.icon_dirty)
1172 } else {
1173 None
1174 };
1175
1176 ConstrainedBox::new(
1177 Canvas::new(move |bounds, _, cx| {
1178 if let Some(color) = icon_color {
1179 let square = RectF::new(bounds.origin(), vec2f(diameter, diameter));
1180 cx.scene.push_quad(Quad {
1181 bounds: square,
1182 background: Some(color),
1183 border: Default::default(),
1184 corner_radius: diameter / 2.,
1185 });
1186 }
1187 })
1188 .boxed(),
1189 )
1190 .with_width(diameter)
1191 .with_height(diameter)
1192 .boxed()
1193 })
1194 .boxed(),
1195 )
1196 .with_child(
1197 Container::new(Align::new(title).boxed())
1198 .with_style(ContainerStyle {
1199 margin: Margin {
1200 left: tab_style.spacing,
1201 right: tab_style.spacing,
1202 ..Default::default()
1203 },
1204 ..Default::default()
1205 })
1206 .boxed(),
1207 )
1208 .with_child(
1209 Align::new(
1210 ConstrainedBox::new(if hovered {
1211 let item_id = item.id();
1212 enum TabCloseButton {}
1213 let icon = Svg::new("icons/x_mark_thin_8.svg");
1214 MouseEventHandler::new::<TabCloseButton, _, _>(
1215 item_id,
1216 cx,
1217 |mouse_state, _| {
1218 if mouse_state.hovered {
1219 icon.with_color(tab_style.icon_close_active).boxed()
1220 } else {
1221 icon.with_color(tab_style.icon_close).boxed()
1222 }
1223 },
1224 )
1225 .with_padding(Padding::uniform(4.))
1226 .with_cursor_style(CursorStyle::PointingHand)
1227 .on_click(MouseButton::Left, {
1228 let pane = pane.clone();
1229 move |_, cx| {
1230 cx.dispatch_action(CloseItem {
1231 item_id,
1232 pane: pane.clone(),
1233 })
1234 }
1235 })
1236 .on_click(MouseButton::Middle, |_, cx| cx.propogate_event())
1237 .named("close-tab-icon")
1238 } else {
1239 Empty::new().boxed()
1240 })
1241 .with_width(tab_style.icon_width)
1242 .boxed(),
1243 )
1244 .boxed(),
1245 )
1246 .contained()
1247 .with_style(tab_style.container);
1248
1249 if let Some(overlay) = overlay {
1250 tab = tab.with_overlay_color(overlay);
1251 }
1252
1253 tab.constrained().with_height(tab_style.height).boxed()
1254 }
1255
1256 fn handle_dropped_item(pane: &WeakViewHandle<Pane>, index: usize, cx: &mut EventContext) {
1257 if let Some((_, dragged_item)) = cx
1258 .global::<DragAndDrop<Workspace>>()
1259 .currently_dragged::<DraggedItem>(cx.window_id)
1260 {
1261 cx.dispatch_action(MoveItem {
1262 item_id: dragged_item.item.id(),
1263 from: dragged_item.pane.clone(),
1264 to: pane.clone(),
1265 destination_index: index,
1266 })
1267 } else {
1268 cx.propogate_event();
1269 }
1270 }
1271
1272 fn tab_overlay_color(
1273 hovered: bool,
1274 theme: &Theme,
1275 cx: &mut RenderContext<Self>,
1276 ) -> Option<Color> {
1277 if hovered
1278 && cx
1279 .global::<DragAndDrop<Workspace>>()
1280 .currently_dragged::<DraggedItem>(cx.window_id())
1281 .is_some()
1282 {
1283 Some(theme.workspace.tab_bar.drop_target_overlay_color)
1284 } else {
1285 None
1286 }
1287 }
1288}
1289
1290impl Entity for Pane {
1291 type Event = Event;
1292}
1293
1294impl View for Pane {
1295 fn ui_name() -> &'static str {
1296 "Pane"
1297 }
1298
1299 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1300 enum SplitIcon {}
1301
1302 let this = cx.handle();
1303
1304 Stack::new()
1305 .with_child(
1306 EventHandler::new(if let Some(active_item) = self.active_item() {
1307 Flex::column()
1308 .with_child({
1309 let mut tab_row = Flex::row()
1310 .with_child(self.render_tab_bar(cx).flex(1., true).named("tabs"));
1311
1312 if self.is_active {
1313 tab_row.add_children([
1314 MouseEventHandler::new::<SplitIcon, _, _>(
1315 0,
1316 cx,
1317 |mouse_state, cx| {
1318 let theme =
1319 &cx.global::<Settings>().theme.workspace.tab_bar;
1320 let style =
1321 theme.pane_button.style_for(mouse_state, false);
1322 Svg::new("icons/plus_12.svg")
1323 .with_color(style.color)
1324 .constrained()
1325 .with_width(style.icon_width)
1326 .aligned()
1327 .contained()
1328 .with_style(style.container)
1329 .constrained()
1330 .with_width(style.button_width)
1331 .with_height(style.button_width)
1332 .aligned()
1333 .boxed()
1334 },
1335 )
1336 .with_cursor_style(CursorStyle::PointingHand)
1337 .on_down(MouseButton::Left, |e, cx| {
1338 cx.dispatch_action(DeployNewMenu {
1339 position: e.position,
1340 });
1341 })
1342 .boxed(),
1343 MouseEventHandler::new::<SplitIcon, _, _>(
1344 1,
1345 cx,
1346 |mouse_state, cx| {
1347 let theme =
1348 &cx.global::<Settings>().theme.workspace.tab_bar;
1349 let style =
1350 theme.pane_button.style_for(mouse_state, false);
1351 Svg::new("icons/split_12.svg")
1352 .with_color(style.color)
1353 .constrained()
1354 .with_width(style.icon_width)
1355 .aligned()
1356 .contained()
1357 .with_style(style.container)
1358 .constrained()
1359 .with_width(style.button_width)
1360 .with_height(style.button_width)
1361 .aligned()
1362 .boxed()
1363 },
1364 )
1365 .with_cursor_style(CursorStyle::PointingHand)
1366 .on_down(MouseButton::Left, |e, cx| {
1367 cx.dispatch_action(DeploySplitMenu {
1368 position: e.position,
1369 });
1370 })
1371 .boxed(),
1372 ])
1373 }
1374
1375 tab_row
1376 .constrained()
1377 .with_height(cx.global::<Settings>().theme.workspace.tab_bar.height)
1378 .named("tab bar")
1379 })
1380 .with_child(ChildView::new(&self.toolbar).boxed())
1381 .with_child(ChildView::new(active_item).flex(1., true).boxed())
1382 .boxed()
1383 } else {
1384 enum EmptyPane {}
1385 let theme = cx.global::<Settings>().theme.clone();
1386
1387 MouseEventHandler::new::<EmptyPane, _, _>(0, cx, |_, _| {
1388 Empty::new()
1389 .contained()
1390 .with_background_color(theme.workspace.background)
1391 .boxed()
1392 })
1393 .on_down(MouseButton::Left, |_, cx| {
1394 cx.focus_parent_view();
1395 })
1396 .boxed()
1397 })
1398 .on_navigate_mouse_down(move |direction, cx| {
1399 let this = this.clone();
1400 match direction {
1401 NavigationDirection::Back => {
1402 cx.dispatch_action(GoBack { pane: Some(this) })
1403 }
1404 NavigationDirection::Forward => {
1405 cx.dispatch_action(GoForward { pane: Some(this) })
1406 }
1407 }
1408
1409 true
1410 })
1411 .boxed(),
1412 )
1413 .with_child(ChildView::new(&self.context_menu).boxed())
1414 .named("pane")
1415 }
1416
1417 fn on_focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
1418 if cx.is_self_focused() {
1419 if let Some(last_focused_view) = self
1420 .last_focused_view
1421 .as_ref()
1422 .and_then(|handle| handle.upgrade(cx))
1423 {
1424 cx.focus(last_focused_view);
1425 } else {
1426 self.focus_active_item(cx);
1427 }
1428 } else {
1429 self.last_focused_view = Some(focused.downgrade());
1430 }
1431 cx.emit(Event::Focused);
1432 }
1433}
1434
1435impl ItemNavHistory {
1436 pub fn push<D: 'static + Any>(&self, data: Option<D>, cx: &mut MutableAppContext) {
1437 self.history.borrow_mut().push(data, self.item.clone(), cx);
1438 }
1439
1440 pub fn pop_backward(&self, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1441 self.history.borrow_mut().pop(NavigationMode::GoingBack, cx)
1442 }
1443
1444 pub fn pop_forward(&self, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1445 self.history
1446 .borrow_mut()
1447 .pop(NavigationMode::GoingForward, cx)
1448 }
1449}
1450
1451impl NavHistory {
1452 fn set_mode(&mut self, mode: NavigationMode) {
1453 self.mode = mode;
1454 }
1455
1456 fn disable(&mut self) {
1457 self.mode = NavigationMode::Disabled;
1458 }
1459
1460 fn enable(&mut self) {
1461 self.mode = NavigationMode::Normal;
1462 }
1463
1464 fn pop(&mut self, mode: NavigationMode, cx: &mut MutableAppContext) -> Option<NavigationEntry> {
1465 let entry = match mode {
1466 NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
1467 return None
1468 }
1469 NavigationMode::GoingBack => &mut self.backward_stack,
1470 NavigationMode::GoingForward => &mut self.forward_stack,
1471 NavigationMode::ReopeningClosedItem => &mut self.closed_stack,
1472 }
1473 .pop_back();
1474 if entry.is_some() {
1475 self.did_update(cx);
1476 }
1477 entry
1478 }
1479
1480 fn push<D: 'static + Any>(
1481 &mut self,
1482 data: Option<D>,
1483 item: Rc<dyn WeakItemHandle>,
1484 cx: &mut MutableAppContext,
1485 ) {
1486 match self.mode {
1487 NavigationMode::Disabled => {}
1488 NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
1489 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1490 self.backward_stack.pop_front();
1491 }
1492 self.backward_stack.push_back(NavigationEntry {
1493 item,
1494 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1495 });
1496 self.forward_stack.clear();
1497 }
1498 NavigationMode::GoingBack => {
1499 if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1500 self.forward_stack.pop_front();
1501 }
1502 self.forward_stack.push_back(NavigationEntry {
1503 item,
1504 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1505 });
1506 }
1507 NavigationMode::GoingForward => {
1508 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1509 self.backward_stack.pop_front();
1510 }
1511 self.backward_stack.push_back(NavigationEntry {
1512 item,
1513 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1514 });
1515 }
1516 NavigationMode::ClosingItem => {
1517 if self.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1518 self.closed_stack.pop_front();
1519 }
1520 self.closed_stack.push_back(NavigationEntry {
1521 item,
1522 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1523 });
1524 }
1525 }
1526 self.did_update(cx);
1527 }
1528
1529 fn did_update(&self, cx: &mut MutableAppContext) {
1530 if let Some(pane) = self.pane.upgrade(cx) {
1531 cx.defer(move |cx| pane.update(cx, |pane, cx| pane.history_updated(cx)));
1532 }
1533 }
1534}
1535
1536#[cfg(test)]
1537mod tests {
1538 use gpui::TestAppContext;
1539 use project::FakeFs;
1540
1541 use crate::tests::TestItem;
1542
1543 use super::*;
1544
1545 #[gpui::test]
1546 async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
1547 cx.foreground().forbid_parking();
1548 Settings::test_async(cx);
1549 let fs = FakeFs::new(cx.background());
1550
1551 let project = Project::test(fs, None, cx).await;
1552 let (_, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
1553 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
1554
1555 // 1. Add with a destination index
1556 // a. Add before the active item
1557 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1558 workspace.update(cx, |workspace, cx| {
1559 Pane::add_item(
1560 workspace,
1561 &pane,
1562 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1563 false,
1564 false,
1565 Some(0),
1566 cx,
1567 );
1568 });
1569 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
1570
1571 // b. Add after the active item
1572 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1573 workspace.update(cx, |workspace, cx| {
1574 Pane::add_item(
1575 workspace,
1576 &pane,
1577 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1578 false,
1579 false,
1580 Some(2),
1581 cx,
1582 );
1583 });
1584 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
1585
1586 // c. Add at the end of the item list (including off the length)
1587 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1588 workspace.update(cx, |workspace, cx| {
1589 Pane::add_item(
1590 workspace,
1591 &pane,
1592 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1593 false,
1594 false,
1595 Some(5),
1596 cx,
1597 );
1598 });
1599 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
1600
1601 // 2. Add without a destination index
1602 // a. Add with active item at the start of the item list
1603 set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
1604 workspace.update(cx, |workspace, cx| {
1605 Pane::add_item(
1606 workspace,
1607 &pane,
1608 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1609 false,
1610 false,
1611 None,
1612 cx,
1613 );
1614 });
1615 set_labeled_items(&workspace, &pane, ["A", "D*", "B", "C"], cx);
1616
1617 // b. Add with active item at the end of the item list
1618 set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
1619 workspace.update(cx, |workspace, cx| {
1620 Pane::add_item(
1621 workspace,
1622 &pane,
1623 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
1624 false,
1625 false,
1626 None,
1627 cx,
1628 );
1629 });
1630 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
1631 }
1632
1633 #[gpui::test]
1634 async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
1635 cx.foreground().forbid_parking();
1636 Settings::test_async(cx);
1637 let fs = FakeFs::new(cx.background());
1638
1639 let project = Project::test(fs, None, cx).await;
1640 let (_, workspace) = cx.add_window(|cx| Workspace::new(project, cx));
1641 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
1642
1643 // 1. Add with a destination index
1644 // 1a. Add before the active item
1645 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
1646 workspace.update(cx, |workspace, cx| {
1647 Pane::add_item(workspace, &pane, d, false, false, Some(0), cx);
1648 });
1649 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
1650
1651 // 1b. Add after the active item
1652 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
1653 workspace.update(cx, |workspace, cx| {
1654 Pane::add_item(workspace, &pane, d, false, false, Some(2), cx);
1655 });
1656 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
1657
1658 // 1c. Add at the end of the item list (including off the length)
1659 let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
1660 workspace.update(cx, |workspace, cx| {
1661 Pane::add_item(workspace, &pane, a, false, false, Some(5), cx);
1662 });
1663 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
1664
1665 // 1d. Add same item to active index
1666 let [_, b, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1667 workspace.update(cx, |workspace, cx| {
1668 Pane::add_item(workspace, &pane, b, false, false, Some(1), cx);
1669 });
1670 assert_item_labels(&pane, ["A", "B*", "C"], cx);
1671
1672 // 1e. Add item to index after same item in last position
1673 let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
1674 workspace.update(cx, |workspace, cx| {
1675 Pane::add_item(workspace, &pane, c, false, false, Some(2), cx);
1676 });
1677 assert_item_labels(&pane, ["A", "B", "C*"], cx);
1678
1679 // 2. Add without a destination index
1680 // 2a. Add with active item at the start of the item list
1681 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A*", "B", "C", "D"], cx);
1682 workspace.update(cx, |workspace, cx| {
1683 Pane::add_item(workspace, &pane, d, false, false, None, cx);
1684 });
1685 assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
1686
1687 // 2b. Add with active item at the end of the item list
1688 let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B", "C", "D*"], cx);
1689 workspace.update(cx, |workspace, cx| {
1690 Pane::add_item(workspace, &pane, a, false, false, None, cx);
1691 });
1692 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
1693
1694 // 2c. Add active item to active item at end of list
1695 let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
1696 workspace.update(cx, |workspace, cx| {
1697 Pane::add_item(workspace, &pane, c, false, false, None, cx);
1698 });
1699 assert_item_labels(&pane, ["A", "B", "C*"], cx);
1700
1701 // 2d. Add active item to active item at start of list
1702 let [a, _, _] = set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
1703 workspace.update(cx, |workspace, cx| {
1704 Pane::add_item(workspace, &pane, a, false, false, None, cx);
1705 });
1706 assert_item_labels(&pane, ["A*", "B", "C"], cx);
1707 }
1708
1709 fn set_labeled_items<const COUNT: usize>(
1710 workspace: &ViewHandle<Workspace>,
1711 pane: &ViewHandle<Pane>,
1712 labels: [&str; COUNT],
1713 cx: &mut TestAppContext,
1714 ) -> [Box<ViewHandle<TestItem>>; COUNT] {
1715 pane.update(cx, |pane, _| {
1716 pane.items.clear();
1717 });
1718
1719 workspace.update(cx, |workspace, cx| {
1720 let mut active_item_index = 0;
1721
1722 let mut index = 0;
1723 let items = labels.map(|mut label| {
1724 if label.ends_with("*") {
1725 label = label.trim_end_matches("*");
1726 active_item_index = index;
1727 }
1728
1729 let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
1730 Pane::add_item(
1731 workspace,
1732 pane,
1733 labeled_item.clone(),
1734 false,
1735 false,
1736 None,
1737 cx,
1738 );
1739 index += 1;
1740 labeled_item
1741 });
1742
1743 pane.update(cx, |pane, cx| {
1744 pane.activate_item(active_item_index, false, false, cx)
1745 });
1746
1747 items
1748 })
1749 }
1750
1751 // Assert the item label, with the active item label suffixed with a '*'
1752 fn assert_item_labels<const COUNT: usize>(
1753 pane: &ViewHandle<Pane>,
1754 expected_states: [&str; COUNT],
1755 cx: &mut TestAppContext,
1756 ) {
1757 pane.read_with(cx, |pane, cx| {
1758 let actual_states = pane
1759 .items
1760 .iter()
1761 .enumerate()
1762 .map(|(ix, item)| {
1763 let mut state = item
1764 .to_any()
1765 .downcast::<TestItem>()
1766 .unwrap()
1767 .read(cx)
1768 .label
1769 .clone();
1770 if ix == pane.active_item_index {
1771 state.push('*');
1772 }
1773 state
1774 })
1775 .collect::<Vec<_>>();
1776
1777 assert_eq!(
1778 actual_states, expected_states,
1779 "pane items do not match expectation"
1780 );
1781 })
1782 }
1783}