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