1mod dragged_item_receiver;
2
3use super::{ItemHandle, SplitDirection};
4use crate::{
5 dock::{icon_for_dock_anchor, AnchorDockBottom, AnchorDockRight, ExpandDock, HideDock},
6 item::WeakItemHandle,
7 toolbar::Toolbar,
8 Item, NewFile, NewSearch, NewTerminal, Workspace,
9};
10use anyhow::Result;
11use collections::{HashMap, HashSet, VecDeque};
12use context_menu::{ContextMenu, ContextMenuItem};
13use drag_and_drop::Draggable;
14pub use dragged_item_receiver::{dragged_item_receiver, handle_dropped_item};
15use futures::StreamExt;
16use gpui::{
17 actions,
18 elements::*,
19 geometry::{
20 rect::RectF,
21 vector::{vec2f, Vector2F},
22 },
23 impl_actions, impl_internal_actions,
24 keymap_matcher::KeymapContext,
25 platform::{CursorStyle, MouseButton, NavigationDirection, PromptLevel},
26 Action, AnyViewHandle, AnyWeakViewHandle, AppContext, AsyncAppContext, Entity, ModelHandle,
27 MouseRegion, Quad, Task, View, ViewContext, ViewHandle, WeakViewHandle,
28};
29use project::{Project, ProjectEntryId, ProjectPath};
30use serde::Deserialize;
31use settings::{Autosave, DockAnchor, Settings};
32use std::{any::Any, cell::RefCell, cmp, mem, path::Path, rc::Rc};
33use theme::Theme;
34use util::ResultExt;
35
36#[derive(Clone, Deserialize, PartialEq)]
37pub struct ActivateItem(pub usize);
38
39#[derive(Clone, PartialEq)]
40pub struct CloseItemById {
41 pub item_id: usize,
42 pub pane: WeakViewHandle<Pane>,
43}
44
45#[derive(Clone, PartialEq)]
46pub struct CloseItemsToTheLeftById {
47 pub item_id: usize,
48 pub pane: WeakViewHandle<Pane>,
49}
50
51#[derive(Clone, PartialEq)]
52pub struct CloseItemsToTheRightById {
53 pub item_id: usize,
54 pub pane: WeakViewHandle<Pane>,
55}
56
57actions!(
58 pane,
59 [
60 ActivatePrevItem,
61 ActivateNextItem,
62 ActivateLastItem,
63 CloseActiveItem,
64 CloseInactiveItems,
65 CloseCleanItems,
66 CloseItemsToTheLeft,
67 CloseItemsToTheRight,
68 CloseAllItems,
69 ReopenClosedItem,
70 SplitLeft,
71 SplitUp,
72 SplitRight,
73 SplitDown,
74 ]
75);
76
77#[derive(Clone, PartialEq)]
78pub struct MoveItem {
79 pub item_id: usize,
80 pub from: WeakViewHandle<Pane>,
81 pub to: WeakViewHandle<Pane>,
82 pub destination_index: usize,
83}
84
85#[derive(Clone, Deserialize, PartialEq)]
86pub struct GoBack {
87 #[serde(skip_deserializing)]
88 pub pane: Option<WeakViewHandle<Pane>>,
89}
90
91#[derive(Clone, Deserialize, PartialEq)]
92pub struct GoForward {
93 #[serde(skip_deserializing)]
94 pub pane: Option<WeakViewHandle<Pane>>,
95}
96
97#[derive(Clone, PartialEq)]
98pub struct DeploySplitMenu;
99
100#[derive(Clone, PartialEq)]
101pub struct DeployDockMenu;
102
103#[derive(Clone, PartialEq)]
104pub struct DeployNewMenu;
105
106#[derive(Clone, PartialEq)]
107pub struct DeployTabContextMenu {
108 pub position: Vector2F,
109 pub item_id: usize,
110 pub pane: WeakViewHandle<Pane>,
111}
112
113impl_actions!(pane, [GoBack, GoForward, ActivateItem]);
114impl_internal_actions!(
115 pane,
116 [
117 CloseItemById,
118 CloseItemsToTheLeftById,
119 CloseItemsToTheRightById,
120 DeployTabContextMenu,
121 DeploySplitMenu,
122 DeployNewMenu,
123 DeployDockMenu,
124 MoveItem
125 ]
126);
127
128const MAX_NAVIGATION_HISTORY_LEN: usize = 1024;
129
130pub type BackgroundActions = fn() -> &'static [(&'static str, &'static dyn Action)];
131
132pub fn init(cx: &mut AppContext) {
133 cx.add_action(|pane: &mut Pane, action: &ActivateItem, cx| {
134 pane.activate_item(action.0, true, true, cx);
135 });
136 cx.add_action(|pane: &mut Pane, _: &ActivateLastItem, cx| {
137 pane.activate_item(pane.items.len() - 1, true, true, cx);
138 });
139 cx.add_action(|pane: &mut Pane, _: &ActivatePrevItem, cx| {
140 pane.activate_prev_item(true, cx);
141 });
142 cx.add_action(|pane: &mut Pane, _: &ActivateNextItem, cx| {
143 pane.activate_next_item(true, cx);
144 });
145 cx.add_async_action(Pane::close_active_item);
146 cx.add_async_action(Pane::close_inactive_items);
147 cx.add_async_action(Pane::close_clean_items);
148 cx.add_async_action(Pane::close_items_to_the_left);
149 cx.add_async_action(Pane::close_items_to_the_right);
150 cx.add_async_action(Pane::close_all_items);
151 cx.add_async_action(|workspace: &mut Workspace, action: &CloseItemById, cx| {
152 let pane = action.pane.upgrade(cx)?;
153 let task = Pane::close_item_by_id(workspace, pane, action.item_id, cx);
154 Some(cx.foreground().spawn(async move {
155 task.await?;
156 Ok(())
157 }))
158 });
159 cx.add_async_action(
160 |workspace: &mut Workspace, action: &CloseItemsToTheLeftById, cx| {
161 let pane = action.pane.upgrade(cx)?;
162 let task = Pane::close_items_to_the_left_by_id(workspace, pane, action.item_id, cx);
163 Some(cx.foreground().spawn(async move {
164 task.await?;
165 Ok(())
166 }))
167 },
168 );
169 cx.add_async_action(
170 |workspace: &mut Workspace, action: &CloseItemsToTheRightById, cx| {
171 let pane = action.pane.upgrade(cx)?;
172 let task = Pane::close_items_to_the_right_by_id(workspace, pane, action.item_id, cx);
173 Some(cx.foreground().spawn(async move {
174 task.await?;
175 Ok(())
176 }))
177 },
178 );
179 cx.add_action(
180 |workspace,
181 MoveItem {
182 from,
183 to,
184 item_id,
185 destination_index,
186 },
187 cx| {
188 // Get item handle to move
189 let from = if let Some(from) = from.upgrade(cx) {
190 from
191 } else {
192 return;
193 };
194
195 // Add item to new pane at given index
196 let to = if let Some(to) = to.upgrade(cx) {
197 to
198 } else {
199 return;
200 };
201
202 Pane::move_item(workspace, from, to, *item_id, *destination_index, cx)
203 },
204 );
205 cx.add_action(|pane: &mut Pane, _: &SplitLeft, cx| pane.split(SplitDirection::Left, cx));
206 cx.add_action(|pane: &mut Pane, _: &SplitUp, cx| pane.split(SplitDirection::Up, cx));
207 cx.add_action(|pane: &mut Pane, _: &SplitRight, cx| pane.split(SplitDirection::Right, cx));
208 cx.add_action(|pane: &mut Pane, _: &SplitDown, cx| pane.split(SplitDirection::Down, cx));
209 cx.add_action(Pane::deploy_split_menu);
210 cx.add_action(Pane::deploy_dock_menu);
211 cx.add_action(Pane::deploy_new_menu);
212 cx.add_action(Pane::deploy_tab_context_menu);
213 cx.add_action(|workspace: &mut Workspace, _: &ReopenClosedItem, cx| {
214 Pane::reopen_closed_item(workspace, cx).detach();
215 });
216 cx.add_action(|workspace: &mut Workspace, action: &GoBack, cx| {
217 Pane::go_back(
218 workspace,
219 action
220 .pane
221 .as_ref()
222 .and_then(|weak_handle| weak_handle.upgrade(cx)),
223 cx,
224 )
225 .detach();
226 });
227 cx.add_action(|workspace: &mut Workspace, action: &GoForward, cx| {
228 Pane::go_forward(
229 workspace,
230 action
231 .pane
232 .as_ref()
233 .and_then(|weak_handle| weak_handle.upgrade(cx)),
234 cx,
235 )
236 .detach();
237 });
238}
239
240#[derive(Debug)]
241pub enum Event {
242 ActivateItem { local: bool },
243 Remove,
244 RemoveItem { item_id: usize },
245 Split(SplitDirection),
246 ChangeItemTitle,
247}
248
249pub struct Pane {
250 items: Vec<Box<dyn ItemHandle>>,
251 activation_history: Vec<usize>,
252 is_active: bool,
253 active_item_index: usize,
254 last_focused_view_by_item: HashMap<usize, AnyWeakViewHandle>,
255 autoscroll: bool,
256 nav_history: Rc<RefCell<NavHistory>>,
257 toolbar: ViewHandle<Toolbar>,
258 tab_bar_context_menu: TabBarContextMenu,
259 tab_context_menu: ViewHandle<ContextMenu>,
260 docked: Option<DockAnchor>,
261 _background_actions: BackgroundActions,
262 _workspace_id: usize,
263}
264
265pub struct ItemNavHistory {
266 history: Rc<RefCell<NavHistory>>,
267 item: Rc<dyn WeakItemHandle>,
268}
269
270struct NavHistory {
271 mode: NavigationMode,
272 backward_stack: VecDeque<NavigationEntry>,
273 forward_stack: VecDeque<NavigationEntry>,
274 closed_stack: VecDeque<NavigationEntry>,
275 paths_by_item: HashMap<usize, ProjectPath>,
276 pane: WeakViewHandle<Pane>,
277}
278
279#[derive(Copy, Clone)]
280enum NavigationMode {
281 Normal,
282 GoingBack,
283 GoingForward,
284 ClosingItem,
285 ReopeningClosedItem,
286 Disabled,
287}
288
289impl Default for NavigationMode {
290 fn default() -> Self {
291 Self::Normal
292 }
293}
294
295pub struct NavigationEntry {
296 pub item: Rc<dyn WeakItemHandle>,
297 pub data: Option<Box<dyn Any>>,
298}
299
300struct DraggedItem {
301 item: Box<dyn ItemHandle>,
302 pane: WeakViewHandle<Pane>,
303}
304
305pub enum ReorderBehavior {
306 None,
307 MoveAfterActive,
308 MoveToIndex(usize),
309}
310
311#[derive(Debug, Clone, Copy, PartialEq, Eq)]
312enum TabBarContextMenuKind {
313 New,
314 Split,
315 Dock,
316}
317
318struct TabBarContextMenu {
319 kind: TabBarContextMenuKind,
320 handle: ViewHandle<ContextMenu>,
321}
322
323impl TabBarContextMenu {
324 fn handle_if_kind(&self, kind: TabBarContextMenuKind) -> Option<ViewHandle<ContextMenu>> {
325 if self.kind == kind {
326 return Some(self.handle.clone());
327 }
328 None
329 }
330}
331
332impl Pane {
333 pub fn new(
334 workspace_id: usize,
335 docked: Option<DockAnchor>,
336 background_actions: BackgroundActions,
337 cx: &mut ViewContext<Self>,
338 ) -> Self {
339 let handle = cx.weak_handle();
340 let context_menu = cx.add_view(ContextMenu::new);
341 context_menu.update(cx, |menu, _| {
342 menu.set_position_mode(OverlayPositionMode::Local)
343 });
344
345 Self {
346 items: Vec::new(),
347 activation_history: Vec::new(),
348 is_active: true,
349 active_item_index: 0,
350 last_focused_view_by_item: Default::default(),
351 autoscroll: false,
352 nav_history: Rc::new(RefCell::new(NavHistory {
353 mode: NavigationMode::Normal,
354 backward_stack: Default::default(),
355 forward_stack: Default::default(),
356 closed_stack: Default::default(),
357 paths_by_item: Default::default(),
358 pane: handle.clone(),
359 })),
360 toolbar: cx.add_view(|_| Toolbar::new(handle)),
361 tab_bar_context_menu: TabBarContextMenu {
362 kind: TabBarContextMenuKind::New,
363 handle: context_menu,
364 },
365 tab_context_menu: cx.add_view(ContextMenu::new),
366 docked,
367 _background_actions: background_actions,
368 _workspace_id: workspace_id,
369 }
370 }
371
372 pub fn is_active(&self) -> bool {
373 self.is_active
374 }
375
376 pub fn set_active(&mut self, is_active: bool, cx: &mut ViewContext<Self>) {
377 self.is_active = is_active;
378 cx.notify();
379 }
380
381 pub fn set_docked(&mut self, docked: Option<DockAnchor>, cx: &mut ViewContext<Self>) {
382 self.docked = docked;
383 cx.notify();
384 }
385
386 pub fn nav_history_for_item<T: Item>(&self, item: &ViewHandle<T>) -> ItemNavHistory {
387 ItemNavHistory {
388 history: self.nav_history.clone(),
389 item: Rc::new(item.downgrade()),
390 }
391 }
392
393 pub fn go_back(
394 workspace: &mut Workspace,
395 pane: Option<ViewHandle<Pane>>,
396 cx: &mut ViewContext<Workspace>,
397 ) -> Task<()> {
398 Self::navigate_history(
399 workspace,
400 pane.unwrap_or_else(|| workspace.active_pane().clone()),
401 NavigationMode::GoingBack,
402 cx,
403 )
404 }
405
406 pub fn go_forward(
407 workspace: &mut Workspace,
408 pane: Option<ViewHandle<Pane>>,
409 cx: &mut ViewContext<Workspace>,
410 ) -> Task<()> {
411 Self::navigate_history(
412 workspace,
413 pane.unwrap_or_else(|| workspace.active_pane().clone()),
414 NavigationMode::GoingForward,
415 cx,
416 )
417 }
418
419 pub fn reopen_closed_item(
420 workspace: &mut Workspace,
421 cx: &mut ViewContext<Workspace>,
422 ) -> Task<()> {
423 Self::navigate_history(
424 workspace,
425 workspace.active_pane().clone(),
426 NavigationMode::ReopeningClosedItem,
427 cx,
428 )
429 }
430
431 pub fn disable_history(&mut self) {
432 self.nav_history.borrow_mut().disable();
433 }
434
435 pub fn enable_history(&mut self) {
436 self.nav_history.borrow_mut().enable();
437 }
438
439 pub fn can_navigate_backward(&self) -> bool {
440 !self.nav_history.borrow().backward_stack.is_empty()
441 }
442
443 pub fn can_navigate_forward(&self) -> bool {
444 !self.nav_history.borrow().forward_stack.is_empty()
445 }
446
447 fn history_updated(&mut self, cx: &mut ViewContext<Self>) {
448 self.toolbar.update(cx, |_, cx| cx.notify());
449 }
450
451 fn navigate_history(
452 workspace: &mut Workspace,
453 pane: ViewHandle<Pane>,
454 mode: NavigationMode,
455 cx: &mut ViewContext<Workspace>,
456 ) -> Task<()> {
457 cx.focus(&pane);
458
459 let to_load = pane.update(cx, |pane, cx| {
460 loop {
461 // Retrieve the weak item handle from the history.
462 let entry = pane.nav_history.borrow_mut().pop(mode, cx)?;
463
464 // If the item is still present in this pane, then activate it.
465 if let Some(index) = entry
466 .item
467 .upgrade(cx)
468 .and_then(|v| pane.index_for_item(v.as_ref()))
469 {
470 let prev_active_item_index = pane.active_item_index;
471 pane.nav_history.borrow_mut().set_mode(mode);
472 pane.activate_item(index, true, true, cx);
473 pane.nav_history
474 .borrow_mut()
475 .set_mode(NavigationMode::Normal);
476
477 let mut navigated = prev_active_item_index != pane.active_item_index;
478 if let Some(data) = entry.data {
479 navigated |= pane.active_item()?.navigate(data, cx);
480 }
481
482 if navigated {
483 break None;
484 }
485 }
486 // If the item is no longer present in this pane, then retrieve its
487 // project path in order to reopen it.
488 else {
489 break pane
490 .nav_history
491 .borrow()
492 .paths_by_item
493 .get(&entry.item.id())
494 .cloned()
495 .map(|project_path| (project_path, entry));
496 }
497 }
498 });
499
500 if let Some((project_path, entry)) = to_load {
501 // If the item was no longer present, then load it again from its previous path.
502 let pane = pane.downgrade();
503 let task = workspace.load_path(project_path, cx);
504 cx.spawn(|workspace, mut cx| async move {
505 let task = task.await;
506 if let Some(pane) = pane.upgrade(&cx) {
507 let mut navigated = false;
508 if let Some((project_entry_id, build_item)) = task.log_err() {
509 let prev_active_item_id = pane.update(&mut cx, |pane, _| {
510 pane.nav_history.borrow_mut().set_mode(mode);
511 pane.active_item().map(|p| p.id())
512 });
513
514 let item = workspace.update(&mut cx, |workspace, cx| {
515 Self::open_item(
516 workspace,
517 pane.clone(),
518 project_entry_id,
519 true,
520 cx,
521 build_item,
522 )
523 });
524
525 pane.update(&mut cx, |pane, cx| {
526 navigated |= Some(item.id()) != prev_active_item_id;
527 pane.nav_history
528 .borrow_mut()
529 .set_mode(NavigationMode::Normal);
530 if let Some(data) = entry.data {
531 navigated |= item.navigate(data, cx);
532 }
533 });
534 }
535
536 if !navigated {
537 workspace
538 .update(&mut cx, |workspace, cx| {
539 Self::navigate_history(workspace, pane, mode, cx)
540 })
541 .await;
542 }
543 }
544 })
545 } else {
546 Task::ready(())
547 }
548 }
549
550 pub(crate) fn open_item(
551 workspace: &mut Workspace,
552 pane: ViewHandle<Pane>,
553 project_entry_id: ProjectEntryId,
554 focus_item: bool,
555 cx: &mut ViewContext<Workspace>,
556 build_item: impl FnOnce(&mut ViewContext<Pane>) -> Box<dyn ItemHandle>,
557 ) -> Box<dyn ItemHandle> {
558 let existing_item = pane.update(cx, |pane, cx| {
559 for (index, item) in pane.items.iter().enumerate() {
560 if item.is_singleton(cx)
561 && item.project_entry_ids(cx).as_slice() == [project_entry_id]
562 {
563 let item = item.boxed_clone();
564 return Some((index, item));
565 }
566 }
567 None
568 });
569
570 if let Some((index, existing_item)) = existing_item {
571 pane.update(cx, |pane, cx| {
572 pane.activate_item(index, focus_item, focus_item, cx);
573 });
574 existing_item
575 } else {
576 let new_item = pane.update(cx, |_, cx| build_item(cx));
577 Pane::add_item(
578 workspace,
579 &pane,
580 new_item.clone(),
581 true,
582 focus_item,
583 None,
584 cx,
585 );
586 new_item
587 }
588 }
589
590 pub(crate) fn add_item(
591 workspace: &mut Workspace,
592 pane: &ViewHandle<Pane>,
593 item: Box<dyn ItemHandle>,
594 activate_pane: bool,
595 focus_item: bool,
596 destination_index: Option<usize>,
597 cx: &mut ViewContext<Workspace>,
598 ) {
599 // If no destination index is specified, add or move the item after the active item.
600 let mut insertion_index = {
601 let pane = pane.read(cx);
602 cmp::min(
603 if let Some(destination_index) = destination_index {
604 destination_index
605 } else {
606 pane.active_item_index + 1
607 },
608 pane.items.len(),
609 )
610 };
611
612 item.added_to_pane(workspace, pane.clone(), cx);
613
614 // Does the item already exist?
615 let project_entry_id = if item.is_singleton(cx) {
616 item.project_entry_ids(cx).get(0).copied()
617 } else {
618 None
619 };
620
621 let existing_item_index = pane.read(cx).items.iter().position(|existing_item| {
622 if existing_item.id() == item.id() {
623 true
624 } else if existing_item.is_singleton(cx) {
625 existing_item
626 .project_entry_ids(cx)
627 .get(0)
628 .map_or(false, |existing_entry_id| {
629 Some(existing_entry_id) == project_entry_id.as_ref()
630 })
631 } else {
632 false
633 }
634 });
635
636 if let Some(existing_item_index) = existing_item_index {
637 // If the item already exists, move it to the desired destination and activate it
638 pane.update(cx, |pane, cx| {
639 if existing_item_index != insertion_index {
640 cx.reparent(item.as_any());
641 let existing_item_is_active = existing_item_index == pane.active_item_index;
642
643 // If the caller didn't specify a destination and the added item is already
644 // the active one, don't move it
645 if existing_item_is_active && destination_index.is_none() {
646 insertion_index = existing_item_index;
647 } else {
648 pane.items.remove(existing_item_index);
649 if existing_item_index < pane.active_item_index {
650 pane.active_item_index -= 1;
651 }
652 insertion_index = insertion_index.min(pane.items.len());
653
654 pane.items.insert(insertion_index, item.clone());
655
656 if existing_item_is_active {
657 pane.active_item_index = insertion_index;
658 } else if insertion_index <= pane.active_item_index {
659 pane.active_item_index += 1;
660 }
661 }
662
663 cx.notify();
664 }
665
666 pane.activate_item(insertion_index, activate_pane, focus_item, cx);
667 });
668 } else {
669 pane.update(cx, |pane, cx| {
670 cx.reparent(item.as_any());
671 pane.items.insert(insertion_index, item);
672 if insertion_index <= pane.active_item_index {
673 pane.active_item_index += 1;
674 }
675
676 pane.activate_item(insertion_index, activate_pane, focus_item, cx);
677 cx.notify();
678 });
679 }
680 }
681
682 pub fn items_len(&self) -> usize {
683 self.items.len()
684 }
685
686 pub fn items(&self) -> impl Iterator<Item = &Box<dyn ItemHandle>> + DoubleEndedIterator {
687 self.items.iter()
688 }
689
690 pub fn items_of_type<T: View>(&self) -> impl '_ + Iterator<Item = ViewHandle<T>> {
691 self.items
692 .iter()
693 .filter_map(|item| item.as_any().clone().downcast())
694 }
695
696 pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
697 self.items.get(self.active_item_index).cloned()
698 }
699
700 pub fn item_for_entry(
701 &self,
702 entry_id: ProjectEntryId,
703 cx: &AppContext,
704 ) -> Option<Box<dyn ItemHandle>> {
705 self.items.iter().find_map(|item| {
706 if item.is_singleton(cx) && item.project_entry_ids(cx).as_slice() == [entry_id] {
707 Some(item.boxed_clone())
708 } else {
709 None
710 }
711 })
712 }
713
714 pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
715 self.items.iter().position(|i| i.id() == item.id())
716 }
717
718 pub fn activate_item(
719 &mut self,
720 index: usize,
721 activate_pane: bool,
722 focus_item: bool,
723 cx: &mut ViewContext<Self>,
724 ) {
725 use NavigationMode::{GoingBack, GoingForward};
726
727 if index < self.items.len() {
728 let prev_active_item_ix = mem::replace(&mut self.active_item_index, index);
729 if prev_active_item_ix != self.active_item_index
730 || matches!(self.nav_history.borrow().mode, GoingBack | GoingForward)
731 {
732 if let Some(prev_item) = self.items.get(prev_active_item_ix) {
733 prev_item.deactivated(cx);
734 }
735
736 cx.emit(Event::ActivateItem {
737 local: activate_pane,
738 });
739 }
740
741 if let Some(newly_active_item) = self.items.get(index) {
742 self.activation_history
743 .retain(|&previously_active_item_id| {
744 previously_active_item_id != newly_active_item.id()
745 });
746 self.activation_history.push(newly_active_item.id());
747 }
748
749 self.update_toolbar(cx);
750
751 if focus_item {
752 self.focus_active_item(cx);
753 }
754
755 self.autoscroll = true;
756 cx.notify();
757 }
758 }
759
760 pub fn activate_prev_item(&mut self, activate_pane: bool, cx: &mut ViewContext<Self>) {
761 let mut index = self.active_item_index;
762 if index > 0 {
763 index -= 1;
764 } else if !self.items.is_empty() {
765 index = self.items.len() - 1;
766 }
767 self.activate_item(index, activate_pane, activate_pane, cx);
768 }
769
770 pub fn activate_next_item(&mut self, activate_pane: bool, cx: &mut ViewContext<Self>) {
771 let mut index = self.active_item_index;
772 if index + 1 < self.items.len() {
773 index += 1;
774 } else {
775 index = 0;
776 }
777 self.activate_item(index, activate_pane, activate_pane, cx);
778 }
779
780 pub fn close_active_item(
781 workspace: &mut Workspace,
782 _: &CloseActiveItem,
783 cx: &mut ViewContext<Workspace>,
784 ) -> Option<Task<Result<()>>> {
785 let pane_handle = workspace.active_pane().clone();
786 let pane = pane_handle.read(cx);
787 let active_item_id = pane.items[pane.active_item_index].id();
788
789 let task = Self::close_item_by_id(workspace, pane_handle, active_item_id, cx);
790
791 Some(cx.foreground().spawn(async move {
792 task.await?;
793 Ok(())
794 }))
795 }
796
797 pub fn close_item_by_id(
798 workspace: &mut Workspace,
799 pane: ViewHandle<Pane>,
800 item_id_to_close: usize,
801 cx: &mut ViewContext<Workspace>,
802 ) -> Task<Result<()>> {
803 Self::close_items(workspace, pane, cx, move |view_id| {
804 view_id == item_id_to_close
805 })
806 }
807
808 pub fn close_inactive_items(
809 workspace: &mut Workspace,
810 _: &CloseInactiveItems,
811 cx: &mut ViewContext<Workspace>,
812 ) -> Option<Task<Result<()>>> {
813 let pane_handle = workspace.active_pane().clone();
814 let pane = pane_handle.read(cx);
815 let active_item_id = pane.items[pane.active_item_index].id();
816
817 let task = Self::close_items(workspace, pane_handle, cx, move |item_id| {
818 item_id != active_item_id
819 });
820
821 Some(cx.foreground().spawn(async move {
822 task.await?;
823 Ok(())
824 }))
825 }
826
827 pub fn close_clean_items(
828 workspace: &mut Workspace,
829 _: &CloseCleanItems,
830 cx: &mut ViewContext<Workspace>,
831 ) -> Option<Task<Result<()>>> {
832 let pane_handle = workspace.active_pane().clone();
833 let pane = pane_handle.read(cx);
834
835 let item_ids: Vec<_> = pane
836 .items()
837 .filter(|item| !item.is_dirty(cx))
838 .map(|item| item.id())
839 .collect();
840
841 let task = Self::close_items(workspace, pane_handle, cx, move |item_id| {
842 item_ids.contains(&item_id)
843 });
844
845 Some(cx.foreground().spawn(async move {
846 task.await?;
847 Ok(())
848 }))
849 }
850
851 pub fn close_items_to_the_left(
852 workspace: &mut Workspace,
853 _: &CloseItemsToTheLeft,
854 cx: &mut ViewContext<Workspace>,
855 ) -> Option<Task<Result<()>>> {
856 let pane_handle = workspace.active_pane().clone();
857 let pane = pane_handle.read(cx);
858 let active_item_id = pane.items[pane.active_item_index].id();
859
860 let task = Self::close_items_to_the_left_by_id(workspace, pane_handle, active_item_id, cx);
861
862 Some(cx.foreground().spawn(async move {
863 task.await?;
864 Ok(())
865 }))
866 }
867
868 pub fn close_items_to_the_left_by_id(
869 workspace: &mut Workspace,
870 pane: ViewHandle<Pane>,
871 item_id: usize,
872 cx: &mut ViewContext<Workspace>,
873 ) -> Task<Result<()>> {
874 let item_ids: Vec<_> = pane
875 .read(cx)
876 .items()
877 .take_while(|item| item.id() != item_id)
878 .map(|item| item.id())
879 .collect();
880
881 let task = Self::close_items(workspace, pane, cx, move |item_id| {
882 item_ids.contains(&item_id)
883 });
884
885 cx.foreground().spawn(async move {
886 task.await?;
887 Ok(())
888 })
889 }
890
891 pub fn close_items_to_the_right(
892 workspace: &mut Workspace,
893 _: &CloseItemsToTheRight,
894 cx: &mut ViewContext<Workspace>,
895 ) -> Option<Task<Result<()>>> {
896 let pane_handle = workspace.active_pane().clone();
897 let pane = pane_handle.read(cx);
898 let active_item_id = pane.items[pane.active_item_index].id();
899
900 let task = Self::close_items_to_the_right_by_id(workspace, pane_handle, active_item_id, cx);
901
902 Some(cx.foreground().spawn(async move {
903 task.await?;
904 Ok(())
905 }))
906 }
907
908 pub fn close_items_to_the_right_by_id(
909 workspace: &mut Workspace,
910 pane: ViewHandle<Pane>,
911 item_id: usize,
912 cx: &mut ViewContext<Workspace>,
913 ) -> Task<Result<()>> {
914 let item_ids: Vec<_> = pane
915 .read(cx)
916 .items()
917 .rev()
918 .take_while(|item| item.id() != item_id)
919 .map(|item| item.id())
920 .collect();
921
922 let task = Self::close_items(workspace, pane, cx, move |item_id| {
923 item_ids.contains(&item_id)
924 });
925
926 cx.foreground().spawn(async move {
927 task.await?;
928 Ok(())
929 })
930 }
931
932 pub fn close_all_items(
933 workspace: &mut Workspace,
934 _: &CloseAllItems,
935 cx: &mut ViewContext<Workspace>,
936 ) -> Option<Task<Result<()>>> {
937 let pane_handle = workspace.active_pane().clone();
938
939 let task = Self::close_items(workspace, pane_handle, cx, move |_| true);
940
941 Some(cx.foreground().spawn(async move {
942 task.await?;
943 Ok(())
944 }))
945 }
946
947 pub fn close_items(
948 workspace: &mut Workspace,
949 pane: ViewHandle<Pane>,
950 cx: &mut ViewContext<Workspace>,
951 should_close: impl 'static + Fn(usize) -> bool,
952 ) -> Task<Result<()>> {
953 let project = workspace.project().clone();
954
955 // Find the items to close.
956 let mut items_to_close = Vec::new();
957 for item in &pane.read(cx).items {
958 if should_close(item.id()) {
959 items_to_close.push(item.boxed_clone());
960 }
961 }
962
963 // If a buffer is open both in a singleton editor and in a multibuffer, make sure
964 // to focus the singleton buffer when prompting to save that buffer, as opposed
965 // to focusing the multibuffer, because this gives the user a more clear idea
966 // of what content they would be saving.
967 items_to_close.sort_by_key(|item| !item.is_singleton(cx));
968
969 cx.spawn(|workspace, mut cx| async move {
970 let mut saved_project_items_ids = HashSet::default();
971 for item in items_to_close.clone() {
972 // Find the item's current index and its set of project item models. Avoid
973 // storing these in advance, in case they have changed since this task
974 // was started.
975 let (item_ix, mut project_item_ids) = pane.read_with(&cx, |pane, cx| {
976 (pane.index_for_item(&*item), item.project_item_model_ids(cx))
977 });
978 let item_ix = if let Some(ix) = item_ix {
979 ix
980 } else {
981 continue;
982 };
983
984 // Check if this view has any project items that are not open anywhere else
985 // in the workspace, AND that the user has not already been prompted to save.
986 // If there are any such project entries, prompt the user to save this item.
987 workspace.read_with(&cx, |workspace, cx| {
988 for item in workspace.items(cx) {
989 if !items_to_close
990 .iter()
991 .any(|item_to_close| item_to_close.id() == item.id())
992 {
993 let other_project_item_ids = item.project_item_model_ids(cx);
994 project_item_ids.retain(|id| !other_project_item_ids.contains(id));
995 }
996 }
997 });
998 let should_save = project_item_ids
999 .iter()
1000 .any(|id| saved_project_items_ids.insert(*id));
1001
1002 if should_save
1003 && !Self::save_item(project.clone(), &pane, item_ix, &*item, true, &mut cx)
1004 .await?
1005 {
1006 break;
1007 }
1008
1009 // Remove the item from the pane.
1010 pane.update(&mut cx, |pane, cx| {
1011 if let Some(item_ix) = pane.items.iter().position(|i| i.id() == item.id()) {
1012 pane.remove_item(item_ix, false, cx);
1013 }
1014 });
1015 }
1016
1017 pane.update(&mut cx, |_, cx| cx.notify());
1018 Ok(())
1019 })
1020 }
1021
1022 fn remove_item(&mut self, item_index: usize, activate_pane: bool, cx: &mut ViewContext<Self>) {
1023 self.activation_history
1024 .retain(|&history_entry| history_entry != self.items[item_index].id());
1025
1026 if item_index == self.active_item_index {
1027 let index_to_activate = self
1028 .activation_history
1029 .pop()
1030 .and_then(|last_activated_item| {
1031 self.items.iter().enumerate().find_map(|(index, item)| {
1032 (item.id() == last_activated_item).then_some(index)
1033 })
1034 })
1035 // We didn't have a valid activation history entry, so fallback
1036 // to activating the item to the left
1037 .unwrap_or_else(|| item_index.min(self.items.len()).saturating_sub(1));
1038
1039 self.activate_item(index_to_activate, activate_pane, activate_pane, cx);
1040 }
1041
1042 let item = self.items.remove(item_index);
1043
1044 cx.emit(Event::RemoveItem { item_id: item.id() });
1045 if self.items.is_empty() {
1046 item.deactivated(cx);
1047 self.update_toolbar(cx);
1048 cx.emit(Event::Remove);
1049 }
1050
1051 if item_index < self.active_item_index {
1052 self.active_item_index -= 1;
1053 }
1054
1055 self.nav_history
1056 .borrow_mut()
1057 .set_mode(NavigationMode::ClosingItem);
1058 item.deactivated(cx);
1059 self.nav_history
1060 .borrow_mut()
1061 .set_mode(NavigationMode::Normal);
1062
1063 if let Some(path) = item.project_path(cx) {
1064 self.nav_history
1065 .borrow_mut()
1066 .paths_by_item
1067 .insert(item.id(), path);
1068 } else {
1069 self.nav_history
1070 .borrow_mut()
1071 .paths_by_item
1072 .remove(&item.id());
1073 }
1074
1075 cx.notify();
1076 }
1077
1078 pub async fn save_item(
1079 project: ModelHandle<Project>,
1080 pane: &ViewHandle<Pane>,
1081 item_ix: usize,
1082 item: &dyn ItemHandle,
1083 should_prompt_for_save: bool,
1084 cx: &mut AsyncAppContext,
1085 ) -> Result<bool> {
1086 const CONFLICT_MESSAGE: &str =
1087 "This file has changed on disk since you started editing it. Do you want to overwrite it?";
1088 const DIRTY_MESSAGE: &str = "This file contains unsaved edits. Do you want to save it?";
1089
1090 let (has_conflict, is_dirty, can_save, is_singleton) = cx.read(|cx| {
1091 (
1092 item.has_conflict(cx),
1093 item.is_dirty(cx),
1094 item.can_save(cx),
1095 item.is_singleton(cx),
1096 )
1097 });
1098
1099 if has_conflict && can_save {
1100 let mut answer = pane.update(cx, |pane, cx| {
1101 pane.activate_item(item_ix, true, true, cx);
1102 cx.prompt(
1103 PromptLevel::Warning,
1104 CONFLICT_MESSAGE,
1105 &["Overwrite", "Discard", "Cancel"],
1106 )
1107 });
1108 match answer.next().await {
1109 Some(0) => cx.update(|cx| item.save(project, cx)).await?,
1110 Some(1) => cx.update(|cx| item.reload(project, cx)).await?,
1111 _ => return Ok(false),
1112 }
1113 } else if is_dirty && (can_save || is_singleton) {
1114 let will_autosave = cx.read(|cx| {
1115 matches!(
1116 cx.global::<Settings>().autosave,
1117 Autosave::OnFocusChange | Autosave::OnWindowChange
1118 ) && Self::can_autosave_item(&*item, cx)
1119 });
1120 let should_save = if should_prompt_for_save && !will_autosave {
1121 let mut answer = pane.update(cx, |pane, cx| {
1122 pane.activate_item(item_ix, true, true, cx);
1123 cx.prompt(
1124 PromptLevel::Warning,
1125 DIRTY_MESSAGE,
1126 &["Save", "Don't Save", "Cancel"],
1127 )
1128 });
1129 match answer.next().await {
1130 Some(0) => true,
1131 Some(1) => false,
1132 _ => return Ok(false),
1133 }
1134 } else {
1135 true
1136 };
1137
1138 if should_save {
1139 if can_save {
1140 cx.update(|cx| item.save(project, cx)).await?;
1141 } else if is_singleton {
1142 let start_abs_path = project
1143 .read_with(cx, |project, cx| {
1144 let worktree = project.visible_worktrees(cx).next()?;
1145 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
1146 })
1147 .unwrap_or_else(|| Path::new("").into());
1148
1149 let mut abs_path = cx.update(|cx| cx.prompt_for_new_path(&start_abs_path));
1150 if let Some(abs_path) = abs_path.next().await.flatten() {
1151 cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
1152 } else {
1153 return Ok(false);
1154 }
1155 }
1156 }
1157 }
1158 Ok(true)
1159 }
1160
1161 fn can_autosave_item(item: &dyn ItemHandle, cx: &AppContext) -> bool {
1162 let is_deleted = item.project_entry_ids(cx).is_empty();
1163 item.is_dirty(cx) && !item.has_conflict(cx) && item.can_save(cx) && !is_deleted
1164 }
1165
1166 pub fn autosave_item(
1167 item: &dyn ItemHandle,
1168 project: ModelHandle<Project>,
1169 cx: &mut AppContext,
1170 ) -> Task<Result<()>> {
1171 if Self::can_autosave_item(item, cx) {
1172 item.save(project, cx)
1173 } else {
1174 Task::ready(Ok(()))
1175 }
1176 }
1177
1178 pub fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
1179 if let Some(active_item) = self.active_item() {
1180 cx.focus(active_item.as_any());
1181 }
1182 }
1183
1184 pub fn move_item(
1185 workspace: &mut Workspace,
1186 from: ViewHandle<Pane>,
1187 to: ViewHandle<Pane>,
1188 item_id_to_move: usize,
1189 destination_index: usize,
1190 cx: &mut ViewContext<Workspace>,
1191 ) {
1192 let item_to_move = from
1193 .read(cx)
1194 .items()
1195 .enumerate()
1196 .find(|(_, item_handle)| item_handle.id() == item_id_to_move);
1197
1198 if item_to_move.is_none() {
1199 log::warn!("Tried to move item handle which was not in `from` pane. Maybe tab was closed during drop");
1200 return;
1201 }
1202 let (item_ix, item_handle) = item_to_move.unwrap();
1203 let item_handle = item_handle.clone();
1204
1205 if from != to {
1206 // Close item from previous pane
1207 from.update(cx, |from, cx| {
1208 from.remove_item(item_ix, false, cx);
1209 });
1210 }
1211
1212 // This automatically removes duplicate items in the pane
1213 Pane::add_item(
1214 workspace,
1215 &to,
1216 item_handle,
1217 true,
1218 true,
1219 Some(destination_index),
1220 cx,
1221 );
1222
1223 cx.focus(&to);
1224 }
1225
1226 pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
1227 cx.emit(Event::Split(direction));
1228 }
1229
1230 fn deploy_split_menu(&mut self, _: &DeploySplitMenu, cx: &mut ViewContext<Self>) {
1231 self.tab_bar_context_menu.handle.update(cx, |menu, cx| {
1232 menu.show(
1233 Default::default(),
1234 AnchorCorner::TopRight,
1235 vec![
1236 ContextMenuItem::item("Split Right", SplitRight),
1237 ContextMenuItem::item("Split Left", SplitLeft),
1238 ContextMenuItem::item("Split Up", SplitUp),
1239 ContextMenuItem::item("Split Down", SplitDown),
1240 ],
1241 cx,
1242 );
1243 });
1244
1245 self.tab_bar_context_menu.kind = TabBarContextMenuKind::Split;
1246 }
1247
1248 fn deploy_dock_menu(&mut self, _: &DeployDockMenu, cx: &mut ViewContext<Self>) {
1249 self.tab_bar_context_menu.handle.update(cx, |menu, cx| {
1250 menu.show(
1251 Default::default(),
1252 AnchorCorner::TopRight,
1253 vec![
1254 ContextMenuItem::item("Anchor Dock Right", AnchorDockRight),
1255 ContextMenuItem::item("Anchor Dock Bottom", AnchorDockBottom),
1256 ContextMenuItem::item("Expand Dock", ExpandDock),
1257 ],
1258 cx,
1259 );
1260 });
1261
1262 self.tab_bar_context_menu.kind = TabBarContextMenuKind::Dock;
1263 }
1264
1265 fn deploy_new_menu(&mut self, _: &DeployNewMenu, cx: &mut ViewContext<Self>) {
1266 self.tab_bar_context_menu.handle.update(cx, |menu, cx| {
1267 menu.show(
1268 Default::default(),
1269 AnchorCorner::TopRight,
1270 vec![
1271 ContextMenuItem::item("New File", NewFile),
1272 ContextMenuItem::item("New Terminal", NewTerminal),
1273 ContextMenuItem::item("New Search", NewSearch),
1274 ],
1275 cx,
1276 );
1277 });
1278
1279 self.tab_bar_context_menu.kind = TabBarContextMenuKind::New;
1280 }
1281
1282 fn deploy_tab_context_menu(
1283 &mut self,
1284 action: &DeployTabContextMenu,
1285 cx: &mut ViewContext<Self>,
1286 ) {
1287 let target_item_id = action.item_id;
1288 let target_pane = action.pane.clone();
1289 let active_item_id = self.items[self.active_item_index].id();
1290 let is_active_item = target_item_id == active_item_id;
1291
1292 // The `CloseInactiveItems` action should really be called "CloseOthers" and the behaviour should be dynamically based on the tab the action is ran on. Currenlty, this is a weird action because you can run it on a non-active tab and it will close everything by the actual active tab
1293
1294 self.tab_context_menu.update(cx, |menu, cx| {
1295 menu.show(
1296 action.position,
1297 AnchorCorner::TopLeft,
1298 if is_active_item {
1299 vec![
1300 ContextMenuItem::item("Close Active Item", CloseActiveItem),
1301 ContextMenuItem::item("Close Inactive Items", CloseInactiveItems),
1302 ContextMenuItem::item("Close Clean Items", CloseCleanItems),
1303 ContextMenuItem::item("Close Items To The Left", CloseItemsToTheLeft),
1304 ContextMenuItem::item("Close Items To The Right", CloseItemsToTheRight),
1305 ContextMenuItem::item("Close All Items", CloseAllItems),
1306 ]
1307 } else {
1308 // In the case of the user right clicking on a non-active tab, for some item-closing commands, we need to provide the id of the tab, for the others, we can reuse the existing command.
1309 vec![
1310 ContextMenuItem::item(
1311 "Close Inactive Item",
1312 CloseItemById {
1313 item_id: target_item_id,
1314 pane: target_pane.clone(),
1315 },
1316 ),
1317 ContextMenuItem::item("Close Inactive Items", CloseInactiveItems),
1318 ContextMenuItem::item("Close Clean Items", CloseCleanItems),
1319 ContextMenuItem::item(
1320 "Close Items To The Left",
1321 CloseItemsToTheLeftById {
1322 item_id: target_item_id,
1323 pane: target_pane.clone(),
1324 },
1325 ),
1326 ContextMenuItem::item(
1327 "Close Items To The Right",
1328 CloseItemsToTheRightById {
1329 item_id: target_item_id,
1330 pane: target_pane.clone(),
1331 },
1332 ),
1333 ContextMenuItem::item("Close All Items", CloseAllItems),
1334 ]
1335 },
1336 cx,
1337 );
1338 });
1339 }
1340
1341 pub fn toolbar(&self) -> &ViewHandle<Toolbar> {
1342 &self.toolbar
1343 }
1344
1345 fn update_toolbar(&mut self, cx: &mut ViewContext<Self>) {
1346 let active_item = self
1347 .items
1348 .get(self.active_item_index)
1349 .map(|item| item.as_ref());
1350 self.toolbar.update(cx, |toolbar, cx| {
1351 toolbar.set_active_pane_item(active_item, cx);
1352 });
1353 }
1354
1355 fn render_tabs(&mut self, cx: &mut ViewContext<Self>) -> impl Drawable<Self> {
1356 let theme = cx.global::<Settings>().theme.clone();
1357
1358 let pane = cx.handle().downgrade();
1359 let autoscroll = if mem::take(&mut self.autoscroll) {
1360 Some(self.active_item_index)
1361 } else {
1362 None
1363 };
1364
1365 let pane_active = self.is_active;
1366
1367 enum Tabs {}
1368 let mut row = Flex::row().scrollable::<Tabs>(1, autoscroll, cx);
1369 for (ix, (item, detail)) in self
1370 .items
1371 .iter()
1372 .cloned()
1373 .zip(self.tab_details(cx))
1374 .enumerate()
1375 {
1376 let detail = if detail == 0 { None } else { Some(detail) };
1377 let tab_active = ix == self.active_item_index;
1378
1379 row.add_child({
1380 enum TabDragReceiver {}
1381 let mut receiver =
1382 dragged_item_receiver::<TabDragReceiver, _>(ix, ix, true, None, cx, {
1383 let item = item.clone();
1384 let pane = pane.clone();
1385 let detail = detail.clone();
1386
1387 let theme = cx.global::<Settings>().theme.clone();
1388
1389 move |mouse_state, cx| {
1390 let tab_style =
1391 theme.workspace.tab_bar.tab_style(pane_active, tab_active);
1392 let hovered = mouse_state.hovered();
1393
1394 enum Tab {}
1395 MouseEventHandler::<Tab, Pane>::new(ix, cx, |_, cx| {
1396 Self::render_tab::<Pane>(
1397 &item,
1398 pane.clone(),
1399 ix == 0,
1400 detail,
1401 hovered,
1402 tab_style,
1403 cx,
1404 )
1405 })
1406 .on_down(MouseButton::Left, move |_, _, cx| {
1407 cx.dispatch_action(ActivateItem(ix));
1408 })
1409 .on_click(MouseButton::Middle, {
1410 let item = item.clone();
1411 let pane = pane.clone();
1412 move |_, _, cx| {
1413 cx.dispatch_action(CloseItemById {
1414 item_id: item.id(),
1415 pane: pane.clone(),
1416 })
1417 }
1418 })
1419 .on_down(MouseButton::Right, move |e, _, cx| {
1420 let item = item.clone();
1421 cx.dispatch_action(DeployTabContextMenu {
1422 position: e.position,
1423 item_id: item.id(),
1424 pane: pane.clone(),
1425 });
1426 })
1427 .boxed()
1428 }
1429 });
1430
1431 if !pane_active || !tab_active {
1432 receiver = receiver.with_cursor_style(CursorStyle::PointingHand);
1433 }
1434
1435 receiver
1436 .as_draggable(
1437 DraggedItem {
1438 item,
1439 pane: pane.clone(),
1440 },
1441 {
1442 let theme = cx.global::<Settings>().theme.clone();
1443
1444 let detail = detail.clone();
1445 move |dragged_item: &DraggedItem, cx: &mut ViewContext<Pane>| {
1446 let tab_style = &theme.workspace.tab_bar.dragged_tab;
1447 Self::render_tab::<Pane>(
1448 &dragged_item.item,
1449 dragged_item.pane.clone(),
1450 false,
1451 detail,
1452 false,
1453 &tab_style,
1454 cx,
1455 )
1456 }
1457 },
1458 )
1459 .boxed()
1460 })
1461 }
1462
1463 // Use the inactive tab style along with the current pane's active status to decide how to render
1464 // the filler
1465 let filler_index = self.items.len();
1466 let filler_style = theme.workspace.tab_bar.tab_style(pane_active, false);
1467 enum Filler {}
1468 row.add_child(
1469 dragged_item_receiver::<Filler, _>(0, filler_index, true, None, cx, |_, _| {
1470 Empty::new()
1471 .contained()
1472 .with_style(filler_style.container)
1473 .with_border(filler_style.container.border)
1474 .boxed()
1475 })
1476 .flex(1., true)
1477 .named("filler"),
1478 );
1479
1480 row
1481 }
1482
1483 fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1484 let mut tab_details = (0..self.items.len()).map(|_| 0).collect::<Vec<_>>();
1485
1486 let mut tab_descriptions = HashMap::default();
1487 let mut done = false;
1488 while !done {
1489 done = true;
1490
1491 // Store item indices by their tab description.
1492 for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1493 if let Some(description) = item.tab_description(*detail, cx) {
1494 if *detail == 0
1495 || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1496 {
1497 tab_descriptions
1498 .entry(description)
1499 .or_insert(Vec::new())
1500 .push(ix);
1501 }
1502 }
1503 }
1504
1505 // If two or more items have the same tab description, increase their level
1506 // of detail and try again.
1507 for (_, item_ixs) in tab_descriptions.drain() {
1508 if item_ixs.len() > 1 {
1509 done = false;
1510 for ix in item_ixs {
1511 tab_details[ix] += 1;
1512 }
1513 }
1514 }
1515 }
1516
1517 tab_details
1518 }
1519
1520 fn render_tab<V: View>(
1521 item: &Box<dyn ItemHandle>,
1522 pane: WeakViewHandle<Pane>,
1523 first: bool,
1524 detail: Option<usize>,
1525 hovered: bool,
1526 tab_style: &theme::Tab,
1527 cx: &mut ViewContext<Self>,
1528 ) -> Element<Self> {
1529 let title = item.tab_content(detail, &tab_style, cx);
1530 let mut container = tab_style.container.clone();
1531 if first {
1532 container.border.left = false;
1533 }
1534
1535 Flex::row()
1536 .with_child(
1537 Align::new({
1538 let diameter = 7.0;
1539 let icon_color = if item.has_conflict(cx) {
1540 Some(tab_style.icon_conflict)
1541 } else if item.is_dirty(cx) {
1542 Some(tab_style.icon_dirty)
1543 } else {
1544 None
1545 };
1546
1547 ConstrainedBox::new(
1548 Canvas::new(move |scene, bounds, _, _, _| {
1549 if let Some(color) = icon_color {
1550 let square = RectF::new(bounds.origin(), vec2f(diameter, diameter));
1551 scene.push_quad(Quad {
1552 bounds: square,
1553 background: Some(color),
1554 border: Default::default(),
1555 corner_radius: diameter / 2.,
1556 });
1557 }
1558 })
1559 .boxed(),
1560 )
1561 .with_width(diameter)
1562 .with_height(diameter)
1563 .boxed()
1564 })
1565 .boxed(),
1566 )
1567 .with_child(
1568 Container::new(Align::new(title).boxed())
1569 .with_style(ContainerStyle {
1570 margin: Margin {
1571 left: tab_style.spacing,
1572 right: tab_style.spacing,
1573 ..Default::default()
1574 },
1575 ..Default::default()
1576 })
1577 .boxed(),
1578 )
1579 .with_child(
1580 Align::new(
1581 ConstrainedBox::new(if hovered {
1582 let item_id = item.id();
1583 enum TabCloseButton {}
1584 let icon = Svg::new("icons/x_mark_8.svg");
1585 MouseEventHandler::<TabCloseButton, _>::new(
1586 item_id,
1587 cx,
1588 |mouse_state, _| {
1589 if mouse_state.hovered() {
1590 icon.with_color(tab_style.icon_close_active).boxed()
1591 } else {
1592 icon.with_color(tab_style.icon_close).boxed()
1593 }
1594 },
1595 )
1596 .with_padding(Padding::uniform(4.))
1597 .with_cursor_style(CursorStyle::PointingHand)
1598 .on_click(MouseButton::Left, {
1599 let pane = pane.clone();
1600 move |_, _, cx| {
1601 cx.dispatch_action(CloseItemById {
1602 item_id,
1603 pane: pane.clone(),
1604 })
1605 }
1606 })
1607 .named("close-tab-icon")
1608 } else {
1609 Empty::new().boxed()
1610 })
1611 .with_width(tab_style.close_icon_width)
1612 .boxed(),
1613 )
1614 .boxed(),
1615 )
1616 .contained()
1617 .with_style(container)
1618 .constrained()
1619 .with_height(tab_style.height)
1620 .boxed()
1621 }
1622
1623 fn render_tab_bar_buttons(
1624 &mut self,
1625 theme: &Theme,
1626 cx: &mut ViewContext<Self>,
1627 ) -> Element<Self> {
1628 Flex::row()
1629 // New menu
1630 .with_child(render_tab_bar_button(
1631 0,
1632 "icons/plus_12.svg",
1633 cx,
1634 DeployNewMenu,
1635 self.tab_bar_context_menu
1636 .handle_if_kind(TabBarContextMenuKind::New),
1637 ))
1638 .with_child(
1639 self.docked
1640 .map(|anchor| {
1641 // Add the dock menu button if this pane is a dock
1642 let dock_icon = icon_for_dock_anchor(anchor);
1643
1644 render_tab_bar_button(
1645 1,
1646 dock_icon,
1647 cx,
1648 DeployDockMenu,
1649 self.tab_bar_context_menu
1650 .handle_if_kind(TabBarContextMenuKind::Dock),
1651 )
1652 })
1653 .unwrap_or_else(|| {
1654 // Add the split menu if this pane is not a dock
1655 render_tab_bar_button(
1656 2,
1657 "icons/split_12.svg",
1658 cx,
1659 DeploySplitMenu,
1660 self.tab_bar_context_menu
1661 .handle_if_kind(TabBarContextMenuKind::Split),
1662 )
1663 }),
1664 )
1665 // Add the close dock button if this pane is a dock
1666 .with_children(
1667 self.docked
1668 .map(|_| render_tab_bar_button(3, "icons/x_mark_8.svg", cx, HideDock, None)),
1669 )
1670 .contained()
1671 .with_style(theme.workspace.tab_bar.pane_button_container)
1672 .flex(1., false)
1673 .boxed()
1674 }
1675
1676 fn render_blank_pane(&mut self, theme: &Theme, _cx: &mut ViewContext<Self>) -> Element<Self> {
1677 let background = theme.workspace.background;
1678 Empty::new()
1679 .contained()
1680 .with_background_color(background)
1681 .boxed()
1682 }
1683}
1684
1685impl Entity for Pane {
1686 type Event = Event;
1687}
1688
1689impl View for Pane {
1690 fn ui_name() -> &'static str {
1691 "Pane"
1692 }
1693
1694 fn render(&mut self, cx: &mut ViewContext<Self>) -> Element<Self> {
1695 let this = cx.handle().downgrade();
1696
1697 enum MouseNavigationHandler {}
1698
1699 Stack::new()
1700 .with_child(
1701 MouseEventHandler::<MouseNavigationHandler, _>::new(0, cx, |_, cx| {
1702 let active_item_index = self.active_item_index;
1703
1704 if let Some(active_item) = self.active_item() {
1705 Flex::column()
1706 .with_child({
1707 let theme = cx.global::<Settings>().theme.clone();
1708
1709 let mut stack = Stack::new();
1710
1711 enum TabBarEventHandler {}
1712 stack.add_child(
1713 MouseEventHandler::<TabBarEventHandler, _>::new(
1714 0,
1715 cx,
1716 |_, _| {
1717 Empty::new()
1718 .contained()
1719 .with_style(theme.workspace.tab_bar.container)
1720 .boxed()
1721 },
1722 )
1723 .on_down(MouseButton::Left, move |_, _, cx| {
1724 cx.dispatch_action(ActivateItem(active_item_index));
1725 })
1726 .boxed(),
1727 );
1728
1729 let mut tab_row = Flex::row()
1730 .with_child(self.render_tabs(cx).flex(1., true).named("tabs"));
1731
1732 if self.is_active {
1733 tab_row.add_child(self.render_tab_bar_buttons(&theme, cx))
1734 }
1735
1736 stack.add_child(tab_row.boxed());
1737 stack
1738 .constrained()
1739 .with_height(theme.workspace.tab_bar.height)
1740 .flex(1., false)
1741 .named("tab bar")
1742 })
1743 .with_child({
1744 enum PaneContentTabDropTarget {}
1745 dragged_item_receiver::<PaneContentTabDropTarget, _>(
1746 0,
1747 self.active_item_index + 1,
1748 false,
1749 if self.docked.is_some() {
1750 None
1751 } else {
1752 Some(100.)
1753 },
1754 cx,
1755 {
1756 let toolbar = self.toolbar.clone();
1757 let toolbar_hidden = toolbar.read(cx).hidden();
1758 move |_, cx| {
1759 Flex::column()
1760 .with_children((!toolbar_hidden).then(|| {
1761 ChildView::new(&toolbar, cx).expanded().boxed()
1762 }))
1763 .with_child(
1764 ChildView::new(active_item.as_any(), cx)
1765 .flex(1., true)
1766 .boxed(),
1767 )
1768 .boxed()
1769 }
1770 },
1771 )
1772 .flex(1., true)
1773 .boxed()
1774 })
1775 .with_child(ChildView::new(&self.tab_context_menu, cx).boxed())
1776 .boxed()
1777 } else {
1778 enum EmptyPane {}
1779 let theme = cx.global::<Settings>().theme.clone();
1780
1781 dragged_item_receiver::<EmptyPane, _>(0, 0, false, None, cx, |_, cx| {
1782 self.render_blank_pane(&theme, cx)
1783 })
1784 .on_down(MouseButton::Left, |_, _, cx| {
1785 cx.focus_parent_view();
1786 })
1787 .boxed()
1788 }
1789 })
1790 .on_down(MouseButton::Navigate(NavigationDirection::Back), {
1791 let this = this.clone();
1792 move |_, _, cx| {
1793 cx.dispatch_action(GoBack {
1794 pane: Some(this.clone()),
1795 });
1796 }
1797 })
1798 .on_down(MouseButton::Navigate(NavigationDirection::Forward), {
1799 let this = this.clone();
1800 move |_, _, cx| {
1801 cx.dispatch_action(GoForward {
1802 pane: Some(this.clone()),
1803 })
1804 }
1805 })
1806 .boxed(),
1807 )
1808 .named("pane")
1809 }
1810
1811 fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
1812 self.toolbar.update(cx, |toolbar, cx| {
1813 toolbar.pane_focus_update(true, cx);
1814 });
1815
1816 if let Some(active_item) = self.active_item() {
1817 if cx.is_self_focused() {
1818 // Pane was focused directly. We need to either focus a view inside the active item,
1819 // or focus the active item itself
1820 if let Some(weak_last_focused_view) =
1821 self.last_focused_view_by_item.get(&active_item.id())
1822 {
1823 if let Some(last_focused_view) = weak_last_focused_view.upgrade(cx) {
1824 cx.focus(&last_focused_view);
1825 return;
1826 } else {
1827 self.last_focused_view_by_item.remove(&active_item.id());
1828 }
1829 }
1830
1831 cx.focus(active_item.as_any());
1832 } else if focused != self.tab_bar_context_menu.handle {
1833 self.last_focused_view_by_item
1834 .insert(active_item.id(), focused.downgrade());
1835 }
1836 }
1837 }
1838
1839 fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
1840 self.toolbar.update(cx, |toolbar, cx| {
1841 toolbar.pane_focus_update(false, cx);
1842 });
1843 }
1844
1845 fn keymap_context(&self, _: &AppContext) -> KeymapContext {
1846 let mut keymap = Self::default_keymap_context();
1847 if self.docked.is_some() {
1848 keymap.add_identifier("docked");
1849 }
1850 keymap
1851 }
1852}
1853
1854fn render_tab_bar_button<A: Action + Clone>(
1855 index: usize,
1856 icon: &'static str,
1857 cx: &mut ViewContext<Pane>,
1858 action: A,
1859 context_menu: Option<ViewHandle<ContextMenu>>,
1860) -> Element<Pane> {
1861 enum TabBarButton {}
1862
1863 Stack::new()
1864 .with_child(
1865 MouseEventHandler::<TabBarButton, _>::new(index, cx, |mouse_state, cx| {
1866 let theme = &cx.global::<Settings>().theme.workspace.tab_bar;
1867 let style = theme.pane_button.style_for(mouse_state, false);
1868 Svg::new(icon)
1869 .with_color(style.color)
1870 .constrained()
1871 .with_width(style.icon_width)
1872 .aligned()
1873 .constrained()
1874 .with_width(style.button_width)
1875 .with_height(style.button_width)
1876 .boxed()
1877 })
1878 .with_cursor_style(CursorStyle::PointingHand)
1879 .on_click(MouseButton::Left, move |_, _, cx| {
1880 cx.dispatch_action(action.clone());
1881 })
1882 .boxed(),
1883 )
1884 .with_children(
1885 context_menu.map(|menu| ChildView::new(&menu, cx).aligned().bottom().right().boxed()),
1886 )
1887 .flex(1., false)
1888 .boxed()
1889}
1890
1891impl ItemNavHistory {
1892 pub fn push<D: 'static + Any>(&self, data: Option<D>, cx: &mut AppContext) {
1893 self.history.borrow_mut().push(data, self.item.clone(), cx);
1894 }
1895
1896 pub fn pop_backward(&self, cx: &mut AppContext) -> Option<NavigationEntry> {
1897 self.history.borrow_mut().pop(NavigationMode::GoingBack, cx)
1898 }
1899
1900 pub fn pop_forward(&self, cx: &mut AppContext) -> Option<NavigationEntry> {
1901 self.history
1902 .borrow_mut()
1903 .pop(NavigationMode::GoingForward, cx)
1904 }
1905}
1906
1907impl NavHistory {
1908 fn set_mode(&mut self, mode: NavigationMode) {
1909 self.mode = mode;
1910 }
1911
1912 fn disable(&mut self) {
1913 self.mode = NavigationMode::Disabled;
1914 }
1915
1916 fn enable(&mut self) {
1917 self.mode = NavigationMode::Normal;
1918 }
1919
1920 fn pop(&mut self, mode: NavigationMode, cx: &mut AppContext) -> Option<NavigationEntry> {
1921 let entry = match mode {
1922 NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
1923 return None
1924 }
1925 NavigationMode::GoingBack => &mut self.backward_stack,
1926 NavigationMode::GoingForward => &mut self.forward_stack,
1927 NavigationMode::ReopeningClosedItem => &mut self.closed_stack,
1928 }
1929 .pop_back();
1930 if entry.is_some() {
1931 self.did_update(cx);
1932 }
1933 entry
1934 }
1935
1936 fn push<D: 'static + Any>(
1937 &mut self,
1938 data: Option<D>,
1939 item: Rc<dyn WeakItemHandle>,
1940 cx: &mut AppContext,
1941 ) {
1942 match self.mode {
1943 NavigationMode::Disabled => {}
1944 NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
1945 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1946 self.backward_stack.pop_front();
1947 }
1948 self.backward_stack.push_back(NavigationEntry {
1949 item,
1950 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1951 });
1952 self.forward_stack.clear();
1953 }
1954 NavigationMode::GoingBack => {
1955 if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1956 self.forward_stack.pop_front();
1957 }
1958 self.forward_stack.push_back(NavigationEntry {
1959 item,
1960 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1961 });
1962 }
1963 NavigationMode::GoingForward => {
1964 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1965 self.backward_stack.pop_front();
1966 }
1967 self.backward_stack.push_back(NavigationEntry {
1968 item,
1969 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1970 });
1971 }
1972 NavigationMode::ClosingItem => {
1973 if self.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1974 self.closed_stack.pop_front();
1975 }
1976 self.closed_stack.push_back(NavigationEntry {
1977 item,
1978 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1979 });
1980 }
1981 }
1982 self.did_update(cx);
1983 }
1984
1985 fn did_update(&self, cx: &mut AppContext) {
1986 if let Some(pane) = self.pane.upgrade(cx) {
1987 cx.defer(move |cx| pane.update(cx, |pane, cx| pane.history_updated(cx)));
1988 }
1989 }
1990}
1991
1992pub struct PaneBackdrop<V: View> {
1993 child_view: usize,
1994 child: Element<V>,
1995}
1996
1997impl<V: View> PaneBackdrop<V> {
1998 pub fn new(pane_item_view: usize, child: Element<V>) -> Self {
1999 PaneBackdrop {
2000 child,
2001 child_view: pane_item_view,
2002 }
2003 }
2004}
2005
2006impl<V: View> Drawable<V> for PaneBackdrop<V> {
2007 type LayoutState = ();
2008
2009 type PaintState = ();
2010
2011 fn layout(
2012 &mut self,
2013 constraint: gpui::SizeConstraint,
2014 view: &mut V,
2015 cx: &mut ViewContext<V>,
2016 ) -> (Vector2F, Self::LayoutState) {
2017 let size = self.child.layout(constraint, view, cx);
2018 (size, ())
2019 }
2020
2021 fn paint(
2022 &mut self,
2023 scene: &mut gpui::SceneBuilder,
2024 bounds: RectF,
2025 visible_bounds: RectF,
2026 _: &mut Self::LayoutState,
2027 view: &mut V,
2028 cx: &mut ViewContext<V>,
2029 ) -> Self::PaintState {
2030 let background = cx.global::<Settings>().theme.editor.background;
2031
2032 let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2033
2034 scene.push_quad(gpui::Quad {
2035 bounds: RectF::new(bounds.origin(), bounds.size()),
2036 background: Some(background),
2037 ..Default::default()
2038 });
2039
2040 let child_view_id = self.child_view;
2041 scene.push_mouse_region(
2042 MouseRegion::new::<Self>(child_view_id, 0, visible_bounds).on_down(
2043 gpui::platform::MouseButton::Left,
2044 move |_, _: &mut V, cx| {
2045 let window_id = cx.window_id();
2046 cx.app_context().focus(window_id, Some(child_view_id))
2047 },
2048 ),
2049 );
2050
2051 scene.paint_layer(Some(bounds), |scene| {
2052 self.child
2053 .paint(scene, bounds.origin(), visible_bounds, view, cx)
2054 })
2055 }
2056
2057 fn rect_for_text_range(
2058 &self,
2059 range_utf16: std::ops::Range<usize>,
2060 _bounds: RectF,
2061 _visible_bounds: RectF,
2062 _layout: &Self::LayoutState,
2063 _paint: &Self::PaintState,
2064 view: &V,
2065 cx: &gpui::ViewContext<V>,
2066 ) -> Option<RectF> {
2067 self.child.rect_for_text_range(range_utf16, view, cx)
2068 }
2069
2070 fn debug(
2071 &self,
2072 _bounds: RectF,
2073 _layout: &Self::LayoutState,
2074 _paint: &Self::PaintState,
2075 view: &V,
2076 cx: &gpui::ViewContext<V>,
2077 ) -> serde_json::Value {
2078 gpui::json::json!({
2079 "type": "Pane Back Drop",
2080 "view": self.child_view,
2081 "child": self.child.debug(view, cx),
2082 })
2083 }
2084}
2085
2086#[cfg(test)]
2087mod tests {
2088 use std::sync::Arc;
2089
2090 use super::*;
2091 use crate::item::test::{TestItem, TestProjectItem};
2092 use gpui::{executor::Deterministic, TestAppContext};
2093 use project::FakeFs;
2094
2095 #[gpui::test]
2096 async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
2097 cx.foreground().forbid_parking();
2098 Settings::test_async(cx);
2099 let fs = FakeFs::new(cx.background());
2100
2101 let project = Project::test(fs, None, cx).await;
2102 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2103 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2104
2105 // 1. Add with a destination index
2106 // a. Add before the active item
2107 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2108 workspace.update(cx, |workspace, cx| {
2109 Pane::add_item(
2110 workspace,
2111 &pane,
2112 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2113 false,
2114 false,
2115 Some(0),
2116 cx,
2117 );
2118 });
2119 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2120
2121 // b. Add after the active item
2122 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2123 workspace.update(cx, |workspace, cx| {
2124 Pane::add_item(
2125 workspace,
2126 &pane,
2127 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2128 false,
2129 false,
2130 Some(2),
2131 cx,
2132 );
2133 });
2134 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2135
2136 // c. Add at the end of the item list (including off the length)
2137 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2138 workspace.update(cx, |workspace, cx| {
2139 Pane::add_item(
2140 workspace,
2141 &pane,
2142 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2143 false,
2144 false,
2145 Some(5),
2146 cx,
2147 );
2148 });
2149 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2150
2151 // 2. Add without a destination index
2152 // a. Add with active item at the start of the item list
2153 set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
2154 workspace.update(cx, |workspace, cx| {
2155 Pane::add_item(
2156 workspace,
2157 &pane,
2158 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2159 false,
2160 false,
2161 None,
2162 cx,
2163 );
2164 });
2165 set_labeled_items(&workspace, &pane, ["A", "D*", "B", "C"], cx);
2166
2167 // b. Add with active item at the end of the item list
2168 set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
2169 workspace.update(cx, |workspace, cx| {
2170 Pane::add_item(
2171 workspace,
2172 &pane,
2173 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2174 false,
2175 false,
2176 None,
2177 cx,
2178 );
2179 });
2180 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2181 }
2182
2183 #[gpui::test]
2184 async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
2185 cx.foreground().forbid_parking();
2186 Settings::test_async(cx);
2187 let fs = FakeFs::new(cx.background());
2188
2189 let project = Project::test(fs, None, cx).await;
2190 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2191 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2192
2193 // 1. Add with a destination index
2194 // 1a. Add before the active item
2195 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
2196 workspace.update(cx, |workspace, cx| {
2197 Pane::add_item(workspace, &pane, d, false, false, Some(0), cx);
2198 });
2199 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2200
2201 // 1b. Add after the active item
2202 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
2203 workspace.update(cx, |workspace, cx| {
2204 Pane::add_item(workspace, &pane, d, false, false, Some(2), cx);
2205 });
2206 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2207
2208 // 1c. Add at the end of the item list (including off the length)
2209 let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
2210 workspace.update(cx, |workspace, cx| {
2211 Pane::add_item(workspace, &pane, a, false, false, Some(5), cx);
2212 });
2213 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2214
2215 // 1d. Add same item to active index
2216 let [_, b, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2217 workspace.update(cx, |workspace, cx| {
2218 Pane::add_item(workspace, &pane, b, false, false, Some(1), cx);
2219 });
2220 assert_item_labels(&pane, ["A", "B*", "C"], cx);
2221
2222 // 1e. Add item to index after same item in last position
2223 let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2224 workspace.update(cx, |workspace, cx| {
2225 Pane::add_item(workspace, &pane, c, false, false, Some(2), cx);
2226 });
2227 assert_item_labels(&pane, ["A", "B", "C*"], cx);
2228
2229 // 2. Add without a destination index
2230 // 2a. Add with active item at the start of the item list
2231 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A*", "B", "C", "D"], cx);
2232 workspace.update(cx, |workspace, cx| {
2233 Pane::add_item(workspace, &pane, d, false, false, None, cx);
2234 });
2235 assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
2236
2237 // 2b. Add with active item at the end of the item list
2238 let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B", "C", "D*"], cx);
2239 workspace.update(cx, |workspace, cx| {
2240 Pane::add_item(workspace, &pane, a, false, false, None, cx);
2241 });
2242 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2243
2244 // 2c. Add active item to active item at end of list
2245 let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
2246 workspace.update(cx, |workspace, cx| {
2247 Pane::add_item(workspace, &pane, c, false, false, None, cx);
2248 });
2249 assert_item_labels(&pane, ["A", "B", "C*"], cx);
2250
2251 // 2d. Add active item to active item at start of list
2252 let [a, _, _] = set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
2253 workspace.update(cx, |workspace, cx| {
2254 Pane::add_item(workspace, &pane, a, false, false, None, cx);
2255 });
2256 assert_item_labels(&pane, ["A*", "B", "C"], cx);
2257 }
2258
2259 #[gpui::test]
2260 async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
2261 cx.foreground().forbid_parking();
2262 Settings::test_async(cx);
2263 let fs = FakeFs::new(cx.background());
2264
2265 let project = Project::test(fs, None, cx).await;
2266 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2267 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2268
2269 // singleton view
2270 workspace.update(cx, |workspace, cx| {
2271 let item = TestItem::new()
2272 .with_singleton(true)
2273 .with_label("buffer 1")
2274 .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)]);
2275
2276 Pane::add_item(
2277 workspace,
2278 &pane,
2279 Box::new(cx.add_view(|_| item)),
2280 false,
2281 false,
2282 None,
2283 cx,
2284 );
2285 });
2286 assert_item_labels(&pane, ["buffer 1*"], cx);
2287
2288 // new singleton view with the same project entry
2289 workspace.update(cx, |workspace, cx| {
2290 let item = TestItem::new()
2291 .with_singleton(true)
2292 .with_label("buffer 1")
2293 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2294
2295 Pane::add_item(
2296 workspace,
2297 &pane,
2298 Box::new(cx.add_view(|_| item)),
2299 false,
2300 false,
2301 None,
2302 cx,
2303 );
2304 });
2305 assert_item_labels(&pane, ["buffer 1*"], cx);
2306
2307 // new singleton view with different project entry
2308 workspace.update(cx, |workspace, cx| {
2309 let item = TestItem::new()
2310 .with_singleton(true)
2311 .with_label("buffer 2")
2312 .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)]);
2313
2314 Pane::add_item(
2315 workspace,
2316 &pane,
2317 Box::new(cx.add_view(|_| item)),
2318 false,
2319 false,
2320 None,
2321 cx,
2322 );
2323 });
2324 assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
2325
2326 // new multibuffer view with the same project entry
2327 workspace.update(cx, |workspace, cx| {
2328 let item = TestItem::new()
2329 .with_singleton(false)
2330 .with_label("multibuffer 1")
2331 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2332
2333 Pane::add_item(
2334 workspace,
2335 &pane,
2336 Box::new(cx.add_view(|_| item)),
2337 false,
2338 false,
2339 None,
2340 cx,
2341 );
2342 });
2343 assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
2344
2345 // another multibuffer view with the same project entry
2346 workspace.update(cx, |workspace, cx| {
2347 let item = TestItem::new()
2348 .with_singleton(false)
2349 .with_label("multibuffer 1b")
2350 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2351
2352 Pane::add_item(
2353 workspace,
2354 &pane,
2355 Box::new(cx.add_view(|_| item)),
2356 false,
2357 false,
2358 None,
2359 cx,
2360 );
2361 });
2362 assert_item_labels(
2363 &pane,
2364 ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
2365 cx,
2366 );
2367 }
2368
2369 #[gpui::test]
2370 async fn test_remove_item_ordering(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2371 Settings::test_async(cx);
2372 let fs = FakeFs::new(cx.background());
2373
2374 let project = Project::test(fs, None, cx).await;
2375 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2376 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2377
2378 add_labeled_item(&workspace, &pane, "A", false, cx);
2379 add_labeled_item(&workspace, &pane, "B", false, cx);
2380 add_labeled_item(&workspace, &pane, "C", false, cx);
2381 add_labeled_item(&workspace, &pane, "D", false, cx);
2382 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2383
2384 pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2385 add_labeled_item(&workspace, &pane, "1", false, cx);
2386 assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2387
2388 workspace.update(cx, |workspace, cx| {
2389 Pane::close_active_item(workspace, &CloseActiveItem, cx);
2390 });
2391 deterministic.run_until_parked();
2392 assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2393
2394 pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2395 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2396
2397 workspace.update(cx, |workspace, cx| {
2398 Pane::close_active_item(workspace, &CloseActiveItem, cx);
2399 });
2400 deterministic.run_until_parked();
2401 assert_item_labels(&pane, ["A", "B*", "C"], cx);
2402
2403 workspace.update(cx, |workspace, cx| {
2404 Pane::close_active_item(workspace, &CloseActiveItem, cx);
2405 });
2406 deterministic.run_until_parked();
2407 assert_item_labels(&pane, ["A", "C*"], cx);
2408
2409 workspace.update(cx, |workspace, cx| {
2410 Pane::close_active_item(workspace, &CloseActiveItem, cx);
2411 });
2412 deterministic.run_until_parked();
2413 assert_item_labels(&pane, ["A*"], cx);
2414 }
2415
2416 #[gpui::test]
2417 async fn test_close_inactive_items(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2418 Settings::test_async(cx);
2419 let fs = FakeFs::new(cx.background());
2420
2421 let project = Project::test(fs, None, cx).await;
2422 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2423 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2424
2425 set_labeled_items(&workspace, &pane, ["A", "B", "C*", "D", "E"], cx);
2426
2427 workspace.update(cx, |workspace, cx| {
2428 Pane::close_inactive_items(workspace, &CloseInactiveItems, cx);
2429 });
2430
2431 deterministic.run_until_parked();
2432 assert_item_labels(&pane, ["C*"], cx);
2433 }
2434
2435 #[gpui::test]
2436 async fn test_close_clean_items(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2437 Settings::test_async(cx);
2438 let fs = FakeFs::new(cx.background());
2439
2440 let project = Project::test(fs, None, cx).await;
2441 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2442 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2443
2444 add_labeled_item(&workspace, &pane, "A", true, cx);
2445 add_labeled_item(&workspace, &pane, "B", false, cx);
2446 add_labeled_item(&workspace, &pane, "C", true, cx);
2447 add_labeled_item(&workspace, &pane, "D", false, cx);
2448 add_labeled_item(&workspace, &pane, "E", false, cx);
2449 assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
2450
2451 workspace.update(cx, |workspace, cx| {
2452 Pane::close_clean_items(workspace, &CloseCleanItems, cx);
2453 });
2454
2455 deterministic.run_until_parked();
2456 assert_item_labels(&pane, ["A^", "C*^"], cx);
2457 }
2458
2459 #[gpui::test]
2460 async fn test_close_items_to_the_left(
2461 deterministic: Arc<Deterministic>,
2462 cx: &mut TestAppContext,
2463 ) {
2464 Settings::test_async(cx);
2465 let fs = FakeFs::new(cx.background());
2466
2467 let project = Project::test(fs, None, cx).await;
2468 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2469 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2470
2471 set_labeled_items(&workspace, &pane, ["A", "B", "C*", "D", "E"], cx);
2472
2473 workspace.update(cx, |workspace, cx| {
2474 Pane::close_items_to_the_left(workspace, &CloseItemsToTheLeft, cx);
2475 });
2476
2477 deterministic.run_until_parked();
2478 assert_item_labels(&pane, ["C*", "D", "E"], cx);
2479 }
2480
2481 #[gpui::test]
2482 async fn test_close_items_to_the_right(
2483 deterministic: Arc<Deterministic>,
2484 cx: &mut TestAppContext,
2485 ) {
2486 Settings::test_async(cx);
2487 let fs = FakeFs::new(cx.background());
2488
2489 let project = Project::test(fs, None, cx).await;
2490 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2491 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2492
2493 set_labeled_items(&workspace, &pane, ["A", "B", "C*", "D", "E"], cx);
2494
2495 workspace.update(cx, |workspace, cx| {
2496 Pane::close_items_to_the_right(workspace, &CloseItemsToTheRight, cx);
2497 });
2498
2499 deterministic.run_until_parked();
2500 assert_item_labels(&pane, ["A", "B", "C*"], cx);
2501 }
2502
2503 #[gpui::test]
2504 async fn test_close_all_items(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2505 Settings::test_async(cx);
2506 let fs = FakeFs::new(cx.background());
2507
2508 let project = Project::test(fs, None, cx).await;
2509 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2510 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2511
2512 add_labeled_item(&workspace, &pane, "A", false, cx);
2513 add_labeled_item(&workspace, &pane, "B", false, cx);
2514 add_labeled_item(&workspace, &pane, "C", false, cx);
2515 assert_item_labels(&pane, ["A", "B", "C*"], cx);
2516
2517 workspace.update(cx, |workspace, cx| {
2518 Pane::close_all_items(workspace, &CloseAllItems, cx);
2519 });
2520
2521 deterministic.run_until_parked();
2522 assert_item_labels(&pane, [], cx);
2523 }
2524
2525 fn add_labeled_item(
2526 workspace: &ViewHandle<Workspace>,
2527 pane: &ViewHandle<Pane>,
2528 label: &str,
2529 is_dirty: bool,
2530 cx: &mut TestAppContext,
2531 ) -> Box<ViewHandle<TestItem>> {
2532 workspace.update(cx, |workspace, cx| {
2533 let labeled_item =
2534 Box::new(cx.add_view(|_| TestItem::new().with_label(label).with_dirty(is_dirty)));
2535
2536 Pane::add_item(
2537 workspace,
2538 pane,
2539 labeled_item.clone(),
2540 false,
2541 false,
2542 None,
2543 cx,
2544 );
2545
2546 labeled_item
2547 })
2548 }
2549
2550 fn set_labeled_items<const COUNT: usize>(
2551 workspace: &ViewHandle<Workspace>,
2552 pane: &ViewHandle<Pane>,
2553 labels: [&str; COUNT],
2554 cx: &mut TestAppContext,
2555 ) -> [Box<ViewHandle<TestItem>>; COUNT] {
2556 pane.update(cx, |pane, _| {
2557 pane.items.clear();
2558 });
2559
2560 workspace.update(cx, |workspace, cx| {
2561 let mut active_item_index = 0;
2562
2563 let mut index = 0;
2564 let items = labels.map(|mut label| {
2565 if label.ends_with("*") {
2566 label = label.trim_end_matches("*");
2567 active_item_index = index;
2568 }
2569
2570 let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
2571 Pane::add_item(
2572 workspace,
2573 pane,
2574 labeled_item.clone(),
2575 false,
2576 false,
2577 None,
2578 cx,
2579 );
2580 index += 1;
2581 labeled_item
2582 });
2583
2584 pane.update(cx, |pane, cx| {
2585 pane.activate_item(active_item_index, false, false, cx)
2586 });
2587
2588 items
2589 })
2590 }
2591
2592 // Assert the item label, with the active item label suffixed with a '*'
2593 fn assert_item_labels<const COUNT: usize>(
2594 pane: &ViewHandle<Pane>,
2595 expected_states: [&str; COUNT],
2596 cx: &mut TestAppContext,
2597 ) {
2598 pane.read_with(cx, |pane, cx| {
2599 let actual_states = pane
2600 .items
2601 .iter()
2602 .enumerate()
2603 .map(|(ix, item)| {
2604 let mut state = item
2605 .as_any()
2606 .downcast_ref::<TestItem>()
2607 .unwrap()
2608 .read(cx)
2609 .label
2610 .clone();
2611 if ix == pane.active_item_index {
2612 state.push('*');
2613 }
2614 if item.is_dirty(cx) {
2615 state.push('^');
2616 }
2617 state
2618 })
2619 .collect::<Vec<_>>();
2620
2621 assert_eq!(
2622 actual_states, expected_states,
2623 "pane items do not match expectation"
2624 );
2625 })
2626 }
2627}