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 let active_item_id = pane.items[pane.active_item_index].id();
789
790 let task = Self::close_item_by_id(workspace, pane_handle, active_item_id, cx);
791
792 Some(cx.foreground().spawn(async move {
793 task.await?;
794 Ok(())
795 }))
796 }
797
798 pub fn close_item_by_id(
799 workspace: &mut Workspace,
800 pane: ViewHandle<Pane>,
801 item_id_to_close: usize,
802 cx: &mut ViewContext<Workspace>,
803 ) -> Task<Result<()>> {
804 Self::close_items(workspace, pane, cx, move |view_id| {
805 view_id == item_id_to_close
806 })
807 }
808
809 pub fn close_inactive_items(
810 workspace: &mut Workspace,
811 _: &CloseInactiveItems,
812 cx: &mut ViewContext<Workspace>,
813 ) -> Option<Task<Result<()>>> {
814 let pane_handle = workspace.active_pane().clone();
815 let pane = pane_handle.read(cx);
816 let active_item_id = pane.items[pane.active_item_index].id();
817
818 let task = Self::close_items(workspace, pane_handle, cx, move |item_id| {
819 item_id != active_item_id
820 });
821
822 Some(cx.foreground().spawn(async move {
823 task.await?;
824 Ok(())
825 }))
826 }
827
828 pub fn close_clean_items(
829 workspace: &mut Workspace,
830 _: &CloseCleanItems,
831 cx: &mut ViewContext<Workspace>,
832 ) -> Option<Task<Result<()>>> {
833 let pane_handle = workspace.active_pane().clone();
834 let pane = pane_handle.read(cx);
835
836 let item_ids: Vec<_> = pane
837 .items()
838 .filter(|item| !item.is_dirty(cx))
839 .map(|item| item.id())
840 .collect();
841
842 let task = Self::close_items(workspace, pane_handle, cx, move |item_id| {
843 item_ids.contains(&item_id)
844 });
845
846 Some(cx.foreground().spawn(async move {
847 task.await?;
848 Ok(())
849 }))
850 }
851
852 pub fn close_items_to_the_left(
853 workspace: &mut Workspace,
854 _: &CloseItemsToTheLeft,
855 cx: &mut ViewContext<Workspace>,
856 ) -> Option<Task<Result<()>>> {
857 let pane_handle = workspace.active_pane().clone();
858 let pane = pane_handle.read(cx);
859 let active_item_id = pane.items[pane.active_item_index].id();
860
861 let task = Self::close_items_to_the_left_by_id(workspace, pane_handle, active_item_id, cx);
862
863 Some(cx.foreground().spawn(async move {
864 task.await?;
865 Ok(())
866 }))
867 }
868
869 pub fn close_items_to_the_left_by_id(
870 workspace: &mut Workspace,
871 pane: ViewHandle<Pane>,
872 item_id: usize,
873 cx: &mut ViewContext<Workspace>,
874 ) -> Task<Result<()>> {
875 let item_ids: Vec<_> = pane
876 .read(cx)
877 .items()
878 .take_while(|item| item.id() != item_id)
879 .map(|item| item.id())
880 .collect();
881
882 let task = Self::close_items(workspace, pane, cx, move |item_id| {
883 item_ids.contains(&item_id)
884 });
885
886 cx.foreground().spawn(async move {
887 task.await?;
888 Ok(())
889 })
890 }
891
892 pub fn close_items_to_the_right(
893 workspace: &mut Workspace,
894 _: &CloseItemsToTheRight,
895 cx: &mut ViewContext<Workspace>,
896 ) -> Option<Task<Result<()>>> {
897 let pane_handle = workspace.active_pane().clone();
898 let pane = pane_handle.read(cx);
899 let active_item_id = pane.items[pane.active_item_index].id();
900
901 let task = Self::close_items_to_the_right_by_id(workspace, pane_handle, active_item_id, cx);
902
903 Some(cx.foreground().spawn(async move {
904 task.await?;
905 Ok(())
906 }))
907 }
908
909 pub fn close_items_to_the_right_by_id(
910 workspace: &mut Workspace,
911 pane: ViewHandle<Pane>,
912 item_id: usize,
913 cx: &mut ViewContext<Workspace>,
914 ) -> Task<Result<()>> {
915 let item_ids: Vec<_> = pane
916 .read(cx)
917 .items()
918 .rev()
919 .take_while(|item| item.id() != item_id)
920 .map(|item| item.id())
921 .collect();
922
923 let task = Self::close_items(workspace, pane, cx, move |item_id| {
924 item_ids.contains(&item_id)
925 });
926
927 cx.foreground().spawn(async move {
928 task.await?;
929 Ok(())
930 })
931 }
932
933 pub fn close_all_items(
934 workspace: &mut Workspace,
935 _: &CloseAllItems,
936 cx: &mut ViewContext<Workspace>,
937 ) -> Option<Task<Result<()>>> {
938 let pane_handle = workspace.active_pane().clone();
939
940 let task = Self::close_items(workspace, pane_handle, cx, move |_| true);
941
942 Some(cx.foreground().spawn(async move {
943 task.await?;
944 Ok(())
945 }))
946 }
947
948 pub fn close_items(
949 workspace: &mut Workspace,
950 pane: ViewHandle<Pane>,
951 cx: &mut ViewContext<Workspace>,
952 should_close: impl 'static + Fn(usize) -> bool,
953 ) -> Task<Result<()>> {
954 let project = workspace.project().clone();
955
956 // Find the items to close.
957 let mut items_to_close = Vec::new();
958 for item in &pane.read(cx).items {
959 if should_close(item.id()) {
960 items_to_close.push(item.boxed_clone());
961 }
962 }
963
964 // If a buffer is open both in a singleton editor and in a multibuffer, make sure
965 // to focus the singleton buffer when prompting to save that buffer, as opposed
966 // to focusing the multibuffer, because this gives the user a more clear idea
967 // of what content they would be saving.
968 items_to_close.sort_by_key(|item| !item.is_singleton(cx));
969
970 cx.spawn(|workspace, mut cx| async move {
971 let mut saved_project_items_ids = HashSet::default();
972 for item in items_to_close.clone() {
973 // Find the item's current index and its set of project item models. Avoid
974 // storing these in advance, in case they have changed since this task
975 // was started.
976 let (item_ix, mut project_item_ids) = pane.read_with(&cx, |pane, cx| {
977 (pane.index_for_item(&*item), item.project_item_model_ids(cx))
978 });
979 let item_ix = if let Some(ix) = item_ix {
980 ix
981 } else {
982 continue;
983 };
984
985 // Check if this view has any project items that are not open anywhere else
986 // in the workspace, AND that the user has not already been prompted to save.
987 // If there are any such project entries, prompt the user to save this item.
988 workspace.read_with(&cx, |workspace, cx| {
989 for item in workspace.items(cx) {
990 if !items_to_close
991 .iter()
992 .any(|item_to_close| item_to_close.id() == item.id())
993 {
994 let other_project_item_ids = item.project_item_model_ids(cx);
995 project_item_ids.retain(|id| !other_project_item_ids.contains(id));
996 }
997 }
998 });
999 let should_save = project_item_ids
1000 .iter()
1001 .any(|id| saved_project_items_ids.insert(*id));
1002
1003 if should_save
1004 && !Self::save_item(project.clone(), &pane, item_ix, &*item, true, &mut cx)
1005 .await?
1006 {
1007 break;
1008 }
1009
1010 // Remove the item from the pane.
1011 pane.update(&mut cx, |pane, cx| {
1012 if let Some(item_ix) = pane.items.iter().position(|i| i.id() == item.id()) {
1013 pane.remove_item(item_ix, false, cx);
1014 }
1015 });
1016 }
1017
1018 pane.update(&mut cx, |_, cx| cx.notify());
1019 Ok(())
1020 })
1021 }
1022
1023 fn remove_item(&mut self, item_index: usize, activate_pane: bool, cx: &mut ViewContext<Self>) {
1024 self.activation_history
1025 .retain(|&history_entry| history_entry != self.items[item_index].id());
1026
1027 if item_index == self.active_item_index {
1028 let index_to_activate = self
1029 .activation_history
1030 .pop()
1031 .and_then(|last_activated_item| {
1032 self.items.iter().enumerate().find_map(|(index, item)| {
1033 (item.id() == last_activated_item).then_some(index)
1034 })
1035 })
1036 // We didn't have a valid activation history entry, so fallback
1037 // to activating the item to the left
1038 .unwrap_or_else(|| item_index.min(self.items.len()).saturating_sub(1));
1039
1040 self.activate_item(index_to_activate, activate_pane, activate_pane, cx);
1041 }
1042
1043 let item = self.items.remove(item_index);
1044
1045 cx.emit(Event::RemoveItem { item_id: item.id() });
1046 if self.items.is_empty() {
1047 item.deactivated(cx);
1048 self.update_toolbar(cx);
1049 cx.emit(Event::Remove);
1050 }
1051
1052 if item_index < self.active_item_index {
1053 self.active_item_index -= 1;
1054 }
1055
1056 self.nav_history
1057 .borrow_mut()
1058 .set_mode(NavigationMode::ClosingItem);
1059 item.deactivated(cx);
1060 self.nav_history
1061 .borrow_mut()
1062 .set_mode(NavigationMode::Normal);
1063
1064 if let Some(path) = item.project_path(cx) {
1065 self.nav_history
1066 .borrow_mut()
1067 .paths_by_item
1068 .insert(item.id(), path);
1069 } else {
1070 self.nav_history
1071 .borrow_mut()
1072 .paths_by_item
1073 .remove(&item.id());
1074 }
1075
1076 cx.notify();
1077 }
1078
1079 pub async fn save_item(
1080 project: ModelHandle<Project>,
1081 pane: &ViewHandle<Pane>,
1082 item_ix: usize,
1083 item: &dyn ItemHandle,
1084 should_prompt_for_save: bool,
1085 cx: &mut AsyncAppContext,
1086 ) -> Result<bool> {
1087 const CONFLICT_MESSAGE: &str =
1088 "This file has changed on disk since you started editing it. Do you want to overwrite it?";
1089 const DIRTY_MESSAGE: &str = "This file contains unsaved edits. Do you want to save it?";
1090
1091 let (has_conflict, is_dirty, can_save, is_singleton) = cx.read(|cx| {
1092 (
1093 item.has_conflict(cx),
1094 item.is_dirty(cx),
1095 item.can_save(cx),
1096 item.is_singleton(cx),
1097 )
1098 });
1099
1100 if has_conflict && can_save {
1101 let mut answer = pane.update(cx, |pane, cx| {
1102 pane.activate_item(item_ix, true, true, cx);
1103 cx.prompt(
1104 PromptLevel::Warning,
1105 CONFLICT_MESSAGE,
1106 &["Overwrite", "Discard", "Cancel"],
1107 )
1108 });
1109 match answer.next().await {
1110 Some(0) => cx.update(|cx| item.save(project, cx)).await?,
1111 Some(1) => cx.update(|cx| item.reload(project, cx)).await?,
1112 _ => return Ok(false),
1113 }
1114 } else if is_dirty && (can_save || is_singleton) {
1115 let will_autosave = cx.read(|cx| {
1116 matches!(
1117 cx.global::<Settings>().autosave,
1118 Autosave::OnFocusChange | Autosave::OnWindowChange
1119 ) && Self::can_autosave_item(&*item, cx)
1120 });
1121 let should_save = if should_prompt_for_save && !will_autosave {
1122 let mut answer = pane.update(cx, |pane, cx| {
1123 pane.activate_item(item_ix, true, true, cx);
1124 cx.prompt(
1125 PromptLevel::Warning,
1126 DIRTY_MESSAGE,
1127 &["Save", "Don't Save", "Cancel"],
1128 )
1129 });
1130 match answer.next().await {
1131 Some(0) => true,
1132 Some(1) => false,
1133 _ => return Ok(false),
1134 }
1135 } else {
1136 true
1137 };
1138
1139 if should_save {
1140 if can_save {
1141 cx.update(|cx| item.save(project, cx)).await?;
1142 } else if is_singleton {
1143 let start_abs_path = project
1144 .read_with(cx, |project, cx| {
1145 let worktree = project.visible_worktrees(cx).next()?;
1146 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
1147 })
1148 .unwrap_or_else(|| Path::new("").into());
1149
1150 let mut abs_path = cx.update(|cx| cx.prompt_for_new_path(&start_abs_path));
1151 if let Some(abs_path) = abs_path.next().await.flatten() {
1152 cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
1153 } else {
1154 return Ok(false);
1155 }
1156 }
1157 }
1158 }
1159 Ok(true)
1160 }
1161
1162 fn can_autosave_item(item: &dyn ItemHandle, cx: &AppContext) -> bool {
1163 let is_deleted = item.project_entry_ids(cx).is_empty();
1164 item.is_dirty(cx) && !item.has_conflict(cx) && item.can_save(cx) && !is_deleted
1165 }
1166
1167 pub fn autosave_item(
1168 item: &dyn ItemHandle,
1169 project: ModelHandle<Project>,
1170 cx: &mut AppContext,
1171 ) -> Task<Result<()>> {
1172 if Self::can_autosave_item(item, cx) {
1173 item.save(project, cx)
1174 } else {
1175 Task::ready(Ok(()))
1176 }
1177 }
1178
1179 pub fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
1180 if let Some(active_item) = self.active_item() {
1181 cx.focus(active_item.as_any());
1182 }
1183 }
1184
1185 pub fn move_item(
1186 workspace: &mut Workspace,
1187 from: ViewHandle<Pane>,
1188 to: ViewHandle<Pane>,
1189 item_id_to_move: usize,
1190 destination_index: usize,
1191 cx: &mut ViewContext<Workspace>,
1192 ) {
1193 let item_to_move = from
1194 .read(cx)
1195 .items()
1196 .enumerate()
1197 .find(|(_, item_handle)| item_handle.id() == item_id_to_move);
1198
1199 if item_to_move.is_none() {
1200 log::warn!("Tried to move item handle which was not in `from` pane. Maybe tab was closed during drop");
1201 return;
1202 }
1203 let (item_ix, item_handle) = item_to_move.unwrap();
1204 let item_handle = item_handle.clone();
1205
1206 if from != to {
1207 // Close item from previous pane
1208 from.update(cx, |from, cx| {
1209 from.remove_item(item_ix, false, cx);
1210 });
1211 }
1212
1213 // This automatically removes duplicate items in the pane
1214 Pane::add_item(
1215 workspace,
1216 &to,
1217 item_handle,
1218 true,
1219 true,
1220 Some(destination_index),
1221 cx,
1222 );
1223
1224 cx.focus(&to);
1225 }
1226
1227 pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
1228 cx.emit(Event::Split(direction));
1229 }
1230
1231 fn deploy_split_menu(&mut self, _: &DeploySplitMenu, cx: &mut ViewContext<Self>) {
1232 self.tab_bar_context_menu.handle.update(cx, |menu, cx| {
1233 menu.show(
1234 Default::default(),
1235 AnchorCorner::TopRight,
1236 vec![
1237 ContextMenuItem::item("Split Right", SplitRight),
1238 ContextMenuItem::item("Split Left", SplitLeft),
1239 ContextMenuItem::item("Split Up", SplitUp),
1240 ContextMenuItem::item("Split Down", SplitDown),
1241 ],
1242 cx,
1243 );
1244 });
1245
1246 self.tab_bar_context_menu.kind = TabBarContextMenuKind::Split;
1247 }
1248
1249 fn deploy_dock_menu(&mut self, _: &DeployDockMenu, cx: &mut ViewContext<Self>) {
1250 self.tab_bar_context_menu.handle.update(cx, |menu, cx| {
1251 menu.show(
1252 Default::default(),
1253 AnchorCorner::TopRight,
1254 vec![
1255 ContextMenuItem::item("Anchor Dock Right", AnchorDockRight),
1256 ContextMenuItem::item("Anchor Dock Bottom", AnchorDockBottom),
1257 ContextMenuItem::item("Expand Dock", ExpandDock),
1258 ],
1259 cx,
1260 );
1261 });
1262
1263 self.tab_bar_context_menu.kind = TabBarContextMenuKind::Dock;
1264 }
1265
1266 fn deploy_new_menu(&mut self, _: &DeployNewMenu, cx: &mut ViewContext<Self>) {
1267 self.tab_bar_context_menu.handle.update(cx, |menu, cx| {
1268 menu.show(
1269 Default::default(),
1270 AnchorCorner::TopRight,
1271 vec![
1272 ContextMenuItem::item("New File", NewFile),
1273 ContextMenuItem::item("New Terminal", NewTerminal),
1274 ContextMenuItem::item("New Search", NewSearch),
1275 ],
1276 cx,
1277 );
1278 });
1279
1280 self.tab_bar_context_menu.kind = TabBarContextMenuKind::New;
1281 }
1282
1283 fn deploy_tab_context_menu(
1284 &mut self,
1285 action: &DeployTabContextMenu,
1286 cx: &mut ViewContext<Self>,
1287 ) {
1288 let target_item_id = action.item_id;
1289 let target_pane = action.pane.clone();
1290 let active_item_id = self.items[self.active_item_index].id();
1291 let is_active_item = target_item_id == active_item_id;
1292
1293 // 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
1294
1295 self.tab_context_menu.update(cx, |menu, cx| {
1296 menu.show(
1297 action.position,
1298 AnchorCorner::TopLeft,
1299 if is_active_item {
1300 vec![
1301 ContextMenuItem::item("Close Active Item", CloseActiveItem),
1302 ContextMenuItem::item("Close Inactive Items", CloseInactiveItems),
1303 ContextMenuItem::item("Close Clean Items", CloseCleanItems),
1304 ContextMenuItem::item("Close Items To The Left", CloseItemsToTheLeft),
1305 ContextMenuItem::item("Close Items To The Right", CloseItemsToTheRight),
1306 ContextMenuItem::item("Close All Items", CloseAllItems),
1307 ]
1308 } else {
1309 // 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.
1310 vec![
1311 ContextMenuItem::item(
1312 "Close Inactive Item",
1313 CloseItemById {
1314 item_id: target_item_id,
1315 pane: target_pane.clone(),
1316 },
1317 ),
1318 ContextMenuItem::item("Close Inactive Items", CloseInactiveItems),
1319 ContextMenuItem::item("Close Clean Items", CloseCleanItems),
1320 ContextMenuItem::item(
1321 "Close Items To The Left",
1322 CloseItemsToTheLeftById {
1323 item_id: target_item_id,
1324 pane: target_pane.clone(),
1325 },
1326 ),
1327 ContextMenuItem::item(
1328 "Close Items To The Right",
1329 CloseItemsToTheRightById {
1330 item_id: target_item_id,
1331 pane: target_pane.clone(),
1332 },
1333 ),
1334 ContextMenuItem::item("Close All Items", CloseAllItems),
1335 ]
1336 },
1337 cx,
1338 );
1339 });
1340 }
1341
1342 pub fn toolbar(&self) -> &ViewHandle<Toolbar> {
1343 &self.toolbar
1344 }
1345
1346 fn update_toolbar(&mut self, cx: &mut ViewContext<Self>) {
1347 let active_item = self
1348 .items
1349 .get(self.active_item_index)
1350 .map(|item| item.as_ref());
1351 self.toolbar.update(cx, |toolbar, cx| {
1352 toolbar.set_active_pane_item(active_item, cx);
1353 });
1354 }
1355
1356 fn render_tabs(&mut self, cx: &mut RenderContext<Self>) -> impl Element {
1357 let theme = cx.global::<Settings>().theme.clone();
1358
1359 let pane = cx.handle();
1360 let autoscroll = if mem::take(&mut self.autoscroll) {
1361 Some(self.active_item_index)
1362 } else {
1363 None
1364 };
1365
1366 let pane_active = self.is_active;
1367
1368 enum Tabs {}
1369 let mut row = Flex::row().scrollable::<Tabs, _>(1, autoscroll, cx);
1370 for (ix, (item, detail)) in self
1371 .items
1372 .iter()
1373 .cloned()
1374 .zip(self.tab_details(cx))
1375 .enumerate()
1376 {
1377 let detail = if detail == 0 { None } else { Some(detail) };
1378 let tab_active = ix == self.active_item_index;
1379
1380 row.add_child({
1381 enum TabDragReceiver {}
1382 let mut receiver =
1383 dragged_item_receiver::<TabDragReceiver, _>(ix, ix, true, None, cx, {
1384 let item = item.clone();
1385 let pane = pane.clone();
1386 let detail = detail.clone();
1387
1388 let theme = cx.global::<Settings>().theme.clone();
1389 let mut tooltip_theme = theme.tooltip.clone();
1390 tooltip_theme.max_text_width = None;
1391 let tab_tooltip_text = item.tab_tooltip_text(cx).map(|a| a.to_string());
1392
1393 move |mouse_state, cx| {
1394 let tab_style =
1395 theme.workspace.tab_bar.tab_style(pane_active, tab_active);
1396 let hovered = mouse_state.hovered();
1397
1398 enum Tab {}
1399 let mouse_event_handler =
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(
1425 MouseButton::Right,
1426 move |e, cx| {
1427 let item = item.clone();
1428 cx.dispatch_action(DeployTabContextMenu {
1429 position: e.position,
1430 item_id: item.id(),
1431 pane: pane.clone(),
1432 });
1433 },
1434 );
1435
1436 if let Some(tab_tooltip_text) = tab_tooltip_text {
1437 return mouse_event_handler
1438 .with_tooltip::<Self, _>(
1439 ix,
1440 tab_tooltip_text,
1441 None,
1442 tooltip_theme,
1443 cx,
1444 )
1445 .boxed();
1446 }
1447
1448 mouse_event_handler.boxed()
1449 }
1450 });
1451
1452 if !pane_active || !tab_active {
1453 receiver = receiver.with_cursor_style(CursorStyle::PointingHand);
1454 }
1455
1456 receiver
1457 .as_draggable(
1458 DraggedItem {
1459 item,
1460 pane: pane.clone(),
1461 },
1462 {
1463 let theme = cx.global::<Settings>().theme.clone();
1464
1465 let detail = detail.clone();
1466 move |dragged_item, cx: &mut RenderContext<Workspace>| {
1467 let tab_style = &theme.workspace.tab_bar.dragged_tab;
1468 Self::render_tab(
1469 &dragged_item.item,
1470 dragged_item.pane.clone(),
1471 false,
1472 detail,
1473 false,
1474 &tab_style,
1475 cx,
1476 )
1477 }
1478 },
1479 )
1480 .boxed()
1481 })
1482 }
1483
1484 // Use the inactive tab style along with the current pane's active status to decide how to render
1485 // the filler
1486 let filler_index = self.items.len();
1487 let filler_style = theme.workspace.tab_bar.tab_style(pane_active, false);
1488 enum Filler {}
1489 row.add_child(
1490 dragged_item_receiver::<Filler, _>(0, filler_index, true, None, cx, |_, _| {
1491 Empty::new()
1492 .contained()
1493 .with_style(filler_style.container)
1494 .with_border(filler_style.container.border)
1495 .boxed()
1496 })
1497 .flex(1., true)
1498 .named("filler"),
1499 );
1500
1501 row
1502 }
1503
1504 fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1505 let mut tab_details = (0..self.items.len()).map(|_| 0).collect::<Vec<_>>();
1506
1507 let mut tab_descriptions = HashMap::default();
1508 let mut done = false;
1509 while !done {
1510 done = true;
1511
1512 // Store item indices by their tab description.
1513 for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1514 if let Some(description) = item.tab_description(*detail, cx) {
1515 if *detail == 0
1516 || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1517 {
1518 tab_descriptions
1519 .entry(description)
1520 .or_insert(Vec::new())
1521 .push(ix);
1522 }
1523 }
1524 }
1525
1526 // If two or more items have the same tab description, increase their level
1527 // of detail and try again.
1528 for (_, item_ixs) in tab_descriptions.drain() {
1529 if item_ixs.len() > 1 {
1530 done = false;
1531 for ix in item_ixs {
1532 tab_details[ix] += 1;
1533 }
1534 }
1535 }
1536 }
1537
1538 tab_details
1539 }
1540
1541 fn render_tab<V: View>(
1542 item: &Box<dyn ItemHandle>,
1543 pane: WeakViewHandle<Pane>,
1544 first: bool,
1545 detail: Option<usize>,
1546 hovered: bool,
1547 tab_style: &theme::Tab,
1548 cx: &mut RenderContext<V>,
1549 ) -> ElementBox {
1550 let title = item.tab_content(detail, &tab_style, cx);
1551 let mut container = tab_style.container.clone();
1552 if first {
1553 container.border.left = false;
1554 }
1555
1556 Flex::row()
1557 .with_child(
1558 Align::new({
1559 let diameter = 7.0;
1560 let icon_color = if item.has_conflict(cx) {
1561 Some(tab_style.icon_conflict)
1562 } else if item.is_dirty(cx) {
1563 Some(tab_style.icon_dirty)
1564 } else {
1565 None
1566 };
1567
1568 ConstrainedBox::new(
1569 Canvas::new(move |bounds, _, cx| {
1570 if let Some(color) = icon_color {
1571 let square = RectF::new(bounds.origin(), vec2f(diameter, diameter));
1572 cx.scene.push_quad(Quad {
1573 bounds: square,
1574 background: Some(color),
1575 border: Default::default(),
1576 corner_radius: diameter / 2.,
1577 });
1578 }
1579 })
1580 .boxed(),
1581 )
1582 .with_width(diameter)
1583 .with_height(diameter)
1584 .boxed()
1585 })
1586 .boxed(),
1587 )
1588 .with_child(
1589 Container::new(Align::new(title).boxed())
1590 .with_style(ContainerStyle {
1591 margin: Margin {
1592 left: tab_style.spacing,
1593 right: tab_style.spacing,
1594 ..Default::default()
1595 },
1596 ..Default::default()
1597 })
1598 .boxed(),
1599 )
1600 .with_child(
1601 Align::new(
1602 ConstrainedBox::new(if hovered {
1603 let item_id = item.id();
1604 enum TabCloseButton {}
1605 let icon = Svg::new("icons/x_mark_8.svg");
1606 MouseEventHandler::<TabCloseButton>::new(item_id, cx, |mouse_state, _| {
1607 if mouse_state.hovered() {
1608 icon.with_color(tab_style.icon_close_active).boxed()
1609 } else {
1610 icon.with_color(tab_style.icon_close).boxed()
1611 }
1612 })
1613 .with_padding(Padding::uniform(4.))
1614 .with_cursor_style(CursorStyle::PointingHand)
1615 .on_click(MouseButton::Left, {
1616 let pane = pane.clone();
1617 move |_, cx| {
1618 cx.dispatch_action(CloseItemById {
1619 item_id,
1620 pane: pane.clone(),
1621 })
1622 }
1623 })
1624 .named("close-tab-icon")
1625 } else {
1626 Empty::new().boxed()
1627 })
1628 .with_width(tab_style.close_icon_width)
1629 .boxed(),
1630 )
1631 .boxed(),
1632 )
1633 .contained()
1634 .with_style(container)
1635 .constrained()
1636 .with_height(tab_style.height)
1637 .boxed()
1638 }
1639
1640 fn render_tab_bar_buttons(
1641 &mut self,
1642 theme: &Theme,
1643 cx: &mut RenderContext<Self>,
1644 ) -> ElementBox {
1645 Flex::row()
1646 // New menu
1647 .with_child(render_tab_bar_button(
1648 0,
1649 "icons/plus_12.svg",
1650 cx,
1651 DeployNewMenu,
1652 self.tab_bar_context_menu
1653 .handle_if_kind(TabBarContextMenuKind::New),
1654 ))
1655 .with_child(
1656 self.docked
1657 .map(|anchor| {
1658 // Add the dock menu button if this pane is a dock
1659 let dock_icon = icon_for_dock_anchor(anchor);
1660
1661 render_tab_bar_button(
1662 1,
1663 dock_icon,
1664 cx,
1665 DeployDockMenu,
1666 self.tab_bar_context_menu
1667 .handle_if_kind(TabBarContextMenuKind::Dock),
1668 )
1669 })
1670 .unwrap_or_else(|| {
1671 // Add the split menu if this pane is not a dock
1672 render_tab_bar_button(
1673 2,
1674 "icons/split_12.svg",
1675 cx,
1676 DeploySplitMenu,
1677 self.tab_bar_context_menu
1678 .handle_if_kind(TabBarContextMenuKind::Split),
1679 )
1680 }),
1681 )
1682 // Add the close dock button if this pane is a dock
1683 .with_children(
1684 self.docked
1685 .map(|_| render_tab_bar_button(3, "icons/x_mark_8.svg", cx, HideDock, None)),
1686 )
1687 .contained()
1688 .with_style(theme.workspace.tab_bar.pane_button_container)
1689 .flex(1., false)
1690 .boxed()
1691 }
1692
1693 fn render_blank_pane(&mut self, theme: &Theme, _cx: &mut RenderContext<Self>) -> ElementBox {
1694 let background = theme.workspace.background;
1695 Empty::new()
1696 .contained()
1697 .with_background_color(background)
1698 .boxed()
1699 }
1700}
1701
1702impl Entity for Pane {
1703 type Event = Event;
1704}
1705
1706impl View for Pane {
1707 fn ui_name() -> &'static str {
1708 "Pane"
1709 }
1710
1711 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1712 let this = cx.handle();
1713
1714 enum MouseNavigationHandler {}
1715
1716 Stack::new()
1717 .with_child(
1718 MouseEventHandler::<MouseNavigationHandler>::new(0, cx, |_, cx| {
1719 let active_item_index = self.active_item_index;
1720
1721 if let Some(active_item) = self.active_item() {
1722 Flex::column()
1723 .with_child({
1724 let theme = cx.global::<Settings>().theme.clone();
1725
1726 let mut stack = Stack::new();
1727
1728 enum TabBarEventHandler {}
1729 stack.add_child(
1730 MouseEventHandler::<TabBarEventHandler>::new(0, cx, |_, _| {
1731 Empty::new()
1732 .contained()
1733 .with_style(theme.workspace.tab_bar.container)
1734 .boxed()
1735 })
1736 .on_down(MouseButton::Left, move |_, cx| {
1737 cx.dispatch_action(ActivateItem(active_item_index));
1738 })
1739 .boxed(),
1740 );
1741
1742 let mut tab_row = Flex::row()
1743 .with_child(self.render_tabs(cx).flex(1., true).named("tabs"));
1744
1745 if self.is_active {
1746 tab_row.add_child(self.render_tab_bar_buttons(&theme, cx))
1747 }
1748
1749 stack.add_child(tab_row.boxed());
1750 stack
1751 .constrained()
1752 .with_height(theme.workspace.tab_bar.height)
1753 .flex(1., false)
1754 .named("tab bar")
1755 })
1756 .with_child({
1757 enum PaneContentTabDropTarget {}
1758 dragged_item_receiver::<PaneContentTabDropTarget, _>(
1759 0,
1760 self.active_item_index + 1,
1761 false,
1762 if self.docked.is_some() {
1763 None
1764 } else {
1765 Some(100.)
1766 },
1767 cx,
1768 {
1769 let toolbar = self.toolbar.clone();
1770 let toolbar_hidden = toolbar.read(cx).hidden();
1771 move |_, cx| {
1772 Flex::column()
1773 .with_children((!toolbar_hidden).then(|| {
1774 ChildView::new(&toolbar, cx).expanded().boxed()
1775 }))
1776 .with_child(
1777 ChildView::new(active_item.as_any(), cx)
1778 .flex(1., true)
1779 .boxed(),
1780 )
1781 .boxed()
1782 }
1783 },
1784 )
1785 .flex(1., true)
1786 .boxed()
1787 })
1788 .with_child(ChildView::new(&self.tab_context_menu, cx).boxed())
1789 .boxed()
1790 } else {
1791 enum EmptyPane {}
1792 let theme = cx.global::<Settings>().theme.clone();
1793
1794 dragged_item_receiver::<EmptyPane, _>(0, 0, false, None, cx, |_, cx| {
1795 self.render_blank_pane(&theme, cx)
1796 })
1797 .on_down(MouseButton::Left, |_, cx| {
1798 cx.focus_parent_view();
1799 })
1800 .boxed()
1801 }
1802 })
1803 .on_down(MouseButton::Navigate(NavigationDirection::Back), {
1804 let this = this.clone();
1805 move |_, cx| {
1806 cx.dispatch_action(GoBack {
1807 pane: Some(this.clone()),
1808 });
1809 }
1810 })
1811 .on_down(MouseButton::Navigate(NavigationDirection::Forward), {
1812 let this = this.clone();
1813 move |_, cx| {
1814 cx.dispatch_action(GoForward {
1815 pane: Some(this.clone()),
1816 })
1817 }
1818 })
1819 .boxed(),
1820 )
1821 .named("pane")
1822 }
1823
1824 fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
1825 self.toolbar.update(cx, |toolbar, cx| {
1826 toolbar.pane_focus_update(true, cx);
1827 });
1828
1829 if let Some(active_item) = self.active_item() {
1830 if cx.is_self_focused() {
1831 // Pane was focused directly. We need to either focus a view inside the active item,
1832 // or focus the active item itself
1833 if let Some(weak_last_focused_view) =
1834 self.last_focused_view_by_item.get(&active_item.id())
1835 {
1836 if let Some(last_focused_view) = weak_last_focused_view.upgrade(cx) {
1837 cx.focus(&last_focused_view);
1838 return;
1839 } else {
1840 self.last_focused_view_by_item.remove(&active_item.id());
1841 }
1842 }
1843
1844 cx.focus(active_item.as_any());
1845 } else if focused != self.tab_bar_context_menu.handle {
1846 self.last_focused_view_by_item
1847 .insert(active_item.id(), focused.downgrade());
1848 }
1849 }
1850 }
1851
1852 fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
1853 self.toolbar.update(cx, |toolbar, cx| {
1854 toolbar.pane_focus_update(false, cx);
1855 });
1856 }
1857
1858 fn keymap_context(&self, _: &AppContext) -> KeymapContext {
1859 let mut keymap = Self::default_keymap_context();
1860 if self.docked.is_some() {
1861 keymap.add_identifier("docked");
1862 }
1863 keymap
1864 }
1865}
1866
1867fn render_tab_bar_button<A: Action + Clone>(
1868 index: usize,
1869 icon: &'static str,
1870 cx: &mut RenderContext<Pane>,
1871 action: A,
1872 context_menu: Option<ViewHandle<ContextMenu>>,
1873) -> ElementBox {
1874 enum TabBarButton {}
1875
1876 Stack::new()
1877 .with_child(
1878 MouseEventHandler::<TabBarButton>::new(index, cx, |mouse_state, cx| {
1879 let theme = &cx.global::<Settings>().theme.workspace.tab_bar;
1880 let style = theme.pane_button.style_for(mouse_state, false);
1881 Svg::new(icon)
1882 .with_color(style.color)
1883 .constrained()
1884 .with_width(style.icon_width)
1885 .aligned()
1886 .constrained()
1887 .with_width(style.button_width)
1888 .with_height(style.button_width)
1889 .boxed()
1890 })
1891 .with_cursor_style(CursorStyle::PointingHand)
1892 .on_click(MouseButton::Left, move |_, cx| {
1893 cx.dispatch_action(action.clone());
1894 })
1895 .boxed(),
1896 )
1897 .with_children(
1898 context_menu.map(|menu| ChildView::new(&menu, cx).aligned().bottom().right().boxed()),
1899 )
1900 .flex(1., false)
1901 .boxed()
1902}
1903
1904impl ItemNavHistory {
1905 pub fn push<D: 'static + Any>(&self, data: Option<D>, cx: &mut AppContext) {
1906 self.history.borrow_mut().push(data, self.item.clone(), cx);
1907 }
1908
1909 pub fn pop_backward(&self, cx: &mut AppContext) -> Option<NavigationEntry> {
1910 self.history.borrow_mut().pop(NavigationMode::GoingBack, cx)
1911 }
1912
1913 pub fn pop_forward(&self, cx: &mut AppContext) -> Option<NavigationEntry> {
1914 self.history
1915 .borrow_mut()
1916 .pop(NavigationMode::GoingForward, cx)
1917 }
1918}
1919
1920impl NavHistory {
1921 fn set_mode(&mut self, mode: NavigationMode) {
1922 self.mode = mode;
1923 }
1924
1925 fn disable(&mut self) {
1926 self.mode = NavigationMode::Disabled;
1927 }
1928
1929 fn enable(&mut self) {
1930 self.mode = NavigationMode::Normal;
1931 }
1932
1933 fn pop(&mut self, mode: NavigationMode, cx: &mut AppContext) -> Option<NavigationEntry> {
1934 let entry = match mode {
1935 NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
1936 return None
1937 }
1938 NavigationMode::GoingBack => &mut self.backward_stack,
1939 NavigationMode::GoingForward => &mut self.forward_stack,
1940 NavigationMode::ReopeningClosedItem => &mut self.closed_stack,
1941 }
1942 .pop_back();
1943 if entry.is_some() {
1944 self.did_update(cx);
1945 }
1946 entry
1947 }
1948
1949 fn push<D: 'static + Any>(
1950 &mut self,
1951 data: Option<D>,
1952 item: Rc<dyn WeakItemHandle>,
1953 cx: &mut AppContext,
1954 ) {
1955 match self.mode {
1956 NavigationMode::Disabled => {}
1957 NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
1958 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1959 self.backward_stack.pop_front();
1960 }
1961 self.backward_stack.push_back(NavigationEntry {
1962 item,
1963 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1964 });
1965 self.forward_stack.clear();
1966 }
1967 NavigationMode::GoingBack => {
1968 if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1969 self.forward_stack.pop_front();
1970 }
1971 self.forward_stack.push_back(NavigationEntry {
1972 item,
1973 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1974 });
1975 }
1976 NavigationMode::GoingForward => {
1977 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1978 self.backward_stack.pop_front();
1979 }
1980 self.backward_stack.push_back(NavigationEntry {
1981 item,
1982 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1983 });
1984 }
1985 NavigationMode::ClosingItem => {
1986 if self.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1987 self.closed_stack.pop_front();
1988 }
1989 self.closed_stack.push_back(NavigationEntry {
1990 item,
1991 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1992 });
1993 }
1994 }
1995 self.did_update(cx);
1996 }
1997
1998 fn did_update(&self, cx: &mut AppContext) {
1999 if let Some(pane) = self.pane.upgrade(cx) {
2000 cx.defer(move |cx| pane.update(cx, |pane, cx| pane.history_updated(cx)));
2001 }
2002 }
2003}
2004
2005pub struct PaneBackdrop {
2006 child_view: usize,
2007 child: ElementBox,
2008}
2009impl PaneBackdrop {
2010 pub fn new(pane_item_view: usize, child: ElementBox) -> Self {
2011 PaneBackdrop {
2012 child,
2013 child_view: pane_item_view,
2014 }
2015 }
2016}
2017
2018impl Element for PaneBackdrop {
2019 type LayoutState = ();
2020
2021 type PaintState = ();
2022
2023 fn layout(
2024 &mut self,
2025 constraint: gpui::SizeConstraint,
2026 cx: &mut gpui::LayoutContext,
2027 ) -> (Vector2F, Self::LayoutState) {
2028 let size = self.child.layout(constraint, cx);
2029 (size, ())
2030 }
2031
2032 fn paint(
2033 &mut self,
2034 bounds: RectF,
2035 visible_bounds: RectF,
2036 _: &mut Self::LayoutState,
2037 cx: &mut gpui::PaintContext,
2038 ) -> Self::PaintState {
2039 let background = cx.global::<Settings>().theme.editor.background;
2040
2041 let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2042
2043 cx.scene.push_quad(gpui::Quad {
2044 bounds: RectF::new(bounds.origin(), bounds.size()),
2045 background: Some(background),
2046 ..Default::default()
2047 });
2048
2049 let child_view_id = self.child_view;
2050 cx.scene.push_mouse_region(
2051 MouseRegion::new::<Self>(child_view_id, 0, visible_bounds).on_down(
2052 gpui::platform::MouseButton::Left,
2053 move |_, cx| {
2054 let window_id = cx.window_id;
2055 cx.focus(window_id, Some(child_view_id))
2056 },
2057 ),
2058 );
2059
2060 cx.paint_layer(Some(bounds), |cx| {
2061 self.child.paint(bounds.origin(), visible_bounds, cx)
2062 })
2063 }
2064
2065 fn rect_for_text_range(
2066 &self,
2067 range_utf16: std::ops::Range<usize>,
2068 _bounds: RectF,
2069 _visible_bounds: RectF,
2070 _layout: &Self::LayoutState,
2071 _paint: &Self::PaintState,
2072 cx: &gpui::MeasurementContext,
2073 ) -> Option<RectF> {
2074 self.child.rect_for_text_range(range_utf16, cx)
2075 }
2076
2077 fn debug(
2078 &self,
2079 _bounds: RectF,
2080 _layout: &Self::LayoutState,
2081 _paint: &Self::PaintState,
2082 cx: &gpui::DebugContext,
2083 ) -> serde_json::Value {
2084 gpui::json::json!({
2085 "type": "Pane Back Drop",
2086 "view": self.child_view,
2087 "child": self.child.debug(cx),
2088 })
2089 }
2090}
2091
2092#[cfg(test)]
2093mod tests {
2094 use std::sync::Arc;
2095
2096 use super::*;
2097 use crate::item::test::{TestItem, TestProjectItem};
2098 use gpui::{executor::Deterministic, TestAppContext};
2099 use project::FakeFs;
2100
2101 #[gpui::test]
2102 async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
2103 cx.foreground().forbid_parking();
2104 Settings::test_async(cx);
2105 let fs = FakeFs::new(cx.background());
2106
2107 let project = Project::test(fs, None, cx).await;
2108 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2109 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2110
2111 // 1. Add with a destination index
2112 // a. Add before the active item
2113 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2114 workspace.update(cx, |workspace, cx| {
2115 Pane::add_item(
2116 workspace,
2117 &pane,
2118 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2119 false,
2120 false,
2121 Some(0),
2122 cx,
2123 );
2124 });
2125 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2126
2127 // b. Add after the active item
2128 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2129 workspace.update(cx, |workspace, cx| {
2130 Pane::add_item(
2131 workspace,
2132 &pane,
2133 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2134 false,
2135 false,
2136 Some(2),
2137 cx,
2138 );
2139 });
2140 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2141
2142 // c. Add at the end of the item list (including off the length)
2143 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2144 workspace.update(cx, |workspace, cx| {
2145 Pane::add_item(
2146 workspace,
2147 &pane,
2148 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2149 false,
2150 false,
2151 Some(5),
2152 cx,
2153 );
2154 });
2155 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2156
2157 // 2. Add without a destination index
2158 // a. Add with active item at the start of the item list
2159 set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
2160 workspace.update(cx, |workspace, cx| {
2161 Pane::add_item(
2162 workspace,
2163 &pane,
2164 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2165 false,
2166 false,
2167 None,
2168 cx,
2169 );
2170 });
2171 set_labeled_items(&workspace, &pane, ["A", "D*", "B", "C"], cx);
2172
2173 // b. Add with active item at the end of the item list
2174 set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
2175 workspace.update(cx, |workspace, cx| {
2176 Pane::add_item(
2177 workspace,
2178 &pane,
2179 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2180 false,
2181 false,
2182 None,
2183 cx,
2184 );
2185 });
2186 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2187 }
2188
2189 #[gpui::test]
2190 async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
2191 cx.foreground().forbid_parking();
2192 Settings::test_async(cx);
2193 let fs = FakeFs::new(cx.background());
2194
2195 let project = Project::test(fs, None, cx).await;
2196 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2197 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2198
2199 // 1. Add with a destination index
2200 // 1a. Add before the active item
2201 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
2202 workspace.update(cx, |workspace, cx| {
2203 Pane::add_item(workspace, &pane, d, false, false, Some(0), cx);
2204 });
2205 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2206
2207 // 1b. Add after the active item
2208 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
2209 workspace.update(cx, |workspace, cx| {
2210 Pane::add_item(workspace, &pane, d, false, false, Some(2), cx);
2211 });
2212 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2213
2214 // 1c. Add at the end of the item list (including off the length)
2215 let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
2216 workspace.update(cx, |workspace, cx| {
2217 Pane::add_item(workspace, &pane, a, false, false, Some(5), cx);
2218 });
2219 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2220
2221 // 1d. Add same item to active index
2222 let [_, b, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2223 workspace.update(cx, |workspace, cx| {
2224 Pane::add_item(workspace, &pane, b, false, false, Some(1), cx);
2225 });
2226 assert_item_labels(&pane, ["A", "B*", "C"], cx);
2227
2228 // 1e. Add item to index after same item in last position
2229 let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2230 workspace.update(cx, |workspace, cx| {
2231 Pane::add_item(workspace, &pane, c, false, false, Some(2), cx);
2232 });
2233 assert_item_labels(&pane, ["A", "B", "C*"], cx);
2234
2235 // 2. Add without a destination index
2236 // 2a. Add with active item at the start of the item list
2237 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A*", "B", "C", "D"], cx);
2238 workspace.update(cx, |workspace, cx| {
2239 Pane::add_item(workspace, &pane, d, false, false, None, cx);
2240 });
2241 assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
2242
2243 // 2b. Add with active item at the end of the item list
2244 let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B", "C", "D*"], cx);
2245 workspace.update(cx, |workspace, cx| {
2246 Pane::add_item(workspace, &pane, a, false, false, None, cx);
2247 });
2248 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2249
2250 // 2c. Add active item to active item at end of list
2251 let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
2252 workspace.update(cx, |workspace, cx| {
2253 Pane::add_item(workspace, &pane, c, false, false, None, cx);
2254 });
2255 assert_item_labels(&pane, ["A", "B", "C*"], cx);
2256
2257 // 2d. Add active item to active item at start of list
2258 let [a, _, _] = set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
2259 workspace.update(cx, |workspace, cx| {
2260 Pane::add_item(workspace, &pane, a, false, false, None, cx);
2261 });
2262 assert_item_labels(&pane, ["A*", "B", "C"], cx);
2263 }
2264
2265 #[gpui::test]
2266 async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
2267 cx.foreground().forbid_parking();
2268 Settings::test_async(cx);
2269 let fs = FakeFs::new(cx.background());
2270
2271 let project = Project::test(fs, None, cx).await;
2272 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2273 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2274
2275 // singleton view
2276 workspace.update(cx, |workspace, cx| {
2277 let item = TestItem::new()
2278 .with_singleton(true)
2279 .with_label("buffer 1")
2280 .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)]);
2281
2282 Pane::add_item(
2283 workspace,
2284 &pane,
2285 Box::new(cx.add_view(|_| item)),
2286 false,
2287 false,
2288 None,
2289 cx,
2290 );
2291 });
2292 assert_item_labels(&pane, ["buffer 1*"], cx);
2293
2294 // new singleton view with the same project entry
2295 workspace.update(cx, |workspace, cx| {
2296 let item = TestItem::new()
2297 .with_singleton(true)
2298 .with_label("buffer 1")
2299 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2300
2301 Pane::add_item(
2302 workspace,
2303 &pane,
2304 Box::new(cx.add_view(|_| item)),
2305 false,
2306 false,
2307 None,
2308 cx,
2309 );
2310 });
2311 assert_item_labels(&pane, ["buffer 1*"], cx);
2312
2313 // new singleton view with different project entry
2314 workspace.update(cx, |workspace, cx| {
2315 let item = TestItem::new()
2316 .with_singleton(true)
2317 .with_label("buffer 2")
2318 .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)]);
2319
2320 Pane::add_item(
2321 workspace,
2322 &pane,
2323 Box::new(cx.add_view(|_| item)),
2324 false,
2325 false,
2326 None,
2327 cx,
2328 );
2329 });
2330 assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
2331
2332 // new multibuffer view with the same project entry
2333 workspace.update(cx, |workspace, cx| {
2334 let item = TestItem::new()
2335 .with_singleton(false)
2336 .with_label("multibuffer 1")
2337 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2338
2339 Pane::add_item(
2340 workspace,
2341 &pane,
2342 Box::new(cx.add_view(|_| item)),
2343 false,
2344 false,
2345 None,
2346 cx,
2347 );
2348 });
2349 assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
2350
2351 // another multibuffer view with the same project entry
2352 workspace.update(cx, |workspace, cx| {
2353 let item = TestItem::new()
2354 .with_singleton(false)
2355 .with_label("multibuffer 1b")
2356 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2357
2358 Pane::add_item(
2359 workspace,
2360 &pane,
2361 Box::new(cx.add_view(|_| item)),
2362 false,
2363 false,
2364 None,
2365 cx,
2366 );
2367 });
2368 assert_item_labels(
2369 &pane,
2370 ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
2371 cx,
2372 );
2373 }
2374
2375 #[gpui::test]
2376 async fn test_remove_item_ordering(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2377 Settings::test_async(cx);
2378 let fs = FakeFs::new(cx.background());
2379
2380 let project = Project::test(fs, None, cx).await;
2381 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2382 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2383
2384 add_labeled_item(&workspace, &pane, "A", false, cx);
2385 add_labeled_item(&workspace, &pane, "B", false, cx);
2386 add_labeled_item(&workspace, &pane, "C", false, cx);
2387 add_labeled_item(&workspace, &pane, "D", false, cx);
2388 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2389
2390 pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2391 add_labeled_item(&workspace, &pane, "1", false, cx);
2392 assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2393
2394 workspace.update(cx, |workspace, cx| {
2395 Pane::close_active_item(workspace, &CloseActiveItem, cx);
2396 });
2397 deterministic.run_until_parked();
2398 assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2399
2400 pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2401 assert_item_labels(&pane, ["A", "B", "C", "D*"], 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", "B*", "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", "C*"], cx);
2414
2415 workspace.update(cx, |workspace, cx| {
2416 Pane::close_active_item(workspace, &CloseActiveItem, cx);
2417 });
2418 deterministic.run_until_parked();
2419 assert_item_labels(&pane, ["A*"], cx);
2420 }
2421
2422 #[gpui::test]
2423 async fn test_close_inactive_items(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2424 Settings::test_async(cx);
2425 let fs = FakeFs::new(cx.background());
2426
2427 let project = Project::test(fs, None, cx).await;
2428 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2429 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2430
2431 set_labeled_items(&workspace, &pane, ["A", "B", "C*", "D", "E"], cx);
2432
2433 workspace.update(cx, |workspace, cx| {
2434 Pane::close_inactive_items(workspace, &CloseInactiveItems, cx);
2435 });
2436
2437 deterministic.run_until_parked();
2438 assert_item_labels(&pane, ["C*"], cx);
2439 }
2440
2441 #[gpui::test]
2442 async fn test_close_clean_items(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2443 Settings::test_async(cx);
2444 let fs = FakeFs::new(cx.background());
2445
2446 let project = Project::test(fs, None, cx).await;
2447 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2448 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2449
2450 add_labeled_item(&workspace, &pane, "A", true, cx);
2451 add_labeled_item(&workspace, &pane, "B", false, cx);
2452 add_labeled_item(&workspace, &pane, "C", true, cx);
2453 add_labeled_item(&workspace, &pane, "D", false, cx);
2454 add_labeled_item(&workspace, &pane, "E", false, cx);
2455 assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
2456
2457 workspace.update(cx, |workspace, cx| {
2458 Pane::close_clean_items(workspace, &CloseCleanItems, cx);
2459 });
2460
2461 deterministic.run_until_parked();
2462 assert_item_labels(&pane, ["A^", "C*^"], cx);
2463 }
2464
2465 #[gpui::test]
2466 async fn test_close_items_to_the_left(
2467 deterministic: Arc<Deterministic>,
2468 cx: &mut TestAppContext,
2469 ) {
2470 Settings::test_async(cx);
2471 let fs = FakeFs::new(cx.background());
2472
2473 let project = Project::test(fs, None, cx).await;
2474 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2475 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2476
2477 set_labeled_items(&workspace, &pane, ["A", "B", "C*", "D", "E"], cx);
2478
2479 workspace.update(cx, |workspace, cx| {
2480 Pane::close_items_to_the_left(workspace, &CloseItemsToTheLeft, cx);
2481 });
2482
2483 deterministic.run_until_parked();
2484 assert_item_labels(&pane, ["C*", "D", "E"], cx);
2485 }
2486
2487 #[gpui::test]
2488 async fn test_close_items_to_the_right(
2489 deterministic: Arc<Deterministic>,
2490 cx: &mut TestAppContext,
2491 ) {
2492 Settings::test_async(cx);
2493 let fs = FakeFs::new(cx.background());
2494
2495 let project = Project::test(fs, None, cx).await;
2496 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2497 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2498
2499 set_labeled_items(&workspace, &pane, ["A", "B", "C*", "D", "E"], cx);
2500
2501 workspace.update(cx, |workspace, cx| {
2502 Pane::close_items_to_the_right(workspace, &CloseItemsToTheRight, cx);
2503 });
2504
2505 deterministic.run_until_parked();
2506 assert_item_labels(&pane, ["A", "B", "C*"], cx);
2507 }
2508
2509 #[gpui::test]
2510 async fn test_close_all_items(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2511 Settings::test_async(cx);
2512 let fs = FakeFs::new(cx.background());
2513
2514 let project = Project::test(fs, None, cx).await;
2515 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2516 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2517
2518 add_labeled_item(&workspace, &pane, "A", false, cx);
2519 add_labeled_item(&workspace, &pane, "B", false, cx);
2520 add_labeled_item(&workspace, &pane, "C", false, cx);
2521 assert_item_labels(&pane, ["A", "B", "C*"], cx);
2522
2523 workspace.update(cx, |workspace, cx| {
2524 Pane::close_all_items(workspace, &CloseAllItems, cx);
2525 });
2526
2527 deterministic.run_until_parked();
2528 assert_item_labels(&pane, [], cx);
2529 }
2530
2531 fn add_labeled_item(
2532 workspace: &ViewHandle<Workspace>,
2533 pane: &ViewHandle<Pane>,
2534 label: &str,
2535 is_dirty: bool,
2536 cx: &mut TestAppContext,
2537 ) -> Box<ViewHandle<TestItem>> {
2538 workspace.update(cx, |workspace, cx| {
2539 let labeled_item =
2540 Box::new(cx.add_view(|_| TestItem::new().with_label(label).with_dirty(is_dirty)));
2541
2542 Pane::add_item(
2543 workspace,
2544 pane,
2545 labeled_item.clone(),
2546 false,
2547 false,
2548 None,
2549 cx,
2550 );
2551
2552 labeled_item
2553 })
2554 }
2555
2556 fn set_labeled_items<const COUNT: usize>(
2557 workspace: &ViewHandle<Workspace>,
2558 pane: &ViewHandle<Pane>,
2559 labels: [&str; COUNT],
2560 cx: &mut TestAppContext,
2561 ) -> [Box<ViewHandle<TestItem>>; COUNT] {
2562 pane.update(cx, |pane, _| {
2563 pane.items.clear();
2564 });
2565
2566 workspace.update(cx, |workspace, cx| {
2567 let mut active_item_index = 0;
2568
2569 let mut index = 0;
2570 let items = labels.map(|mut label| {
2571 if label.ends_with("*") {
2572 label = label.trim_end_matches("*");
2573 active_item_index = index;
2574 }
2575
2576 let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
2577 Pane::add_item(
2578 workspace,
2579 pane,
2580 labeled_item.clone(),
2581 false,
2582 false,
2583 None,
2584 cx,
2585 );
2586 index += 1;
2587 labeled_item
2588 });
2589
2590 pane.update(cx, |pane, cx| {
2591 pane.activate_item(active_item_index, false, false, cx)
2592 });
2593
2594 items
2595 })
2596 }
2597
2598 // Assert the item label, with the active item label suffixed with a '*'
2599 fn assert_item_labels<const COUNT: usize>(
2600 pane: &ViewHandle<Pane>,
2601 expected_states: [&str; COUNT],
2602 cx: &mut TestAppContext,
2603 ) {
2604 pane.read_with(cx, |pane, cx| {
2605 let actual_states = pane
2606 .items
2607 .iter()
2608 .enumerate()
2609 .map(|(ix, item)| {
2610 let mut state = item
2611 .as_any()
2612 .downcast_ref::<TestItem>()
2613 .unwrap()
2614 .read(cx)
2615 .label
2616 .clone();
2617 if ix == pane.active_item_index {
2618 state.push('*');
2619 }
2620 if item.is_dirty(cx) {
2621 state.push('^');
2622 }
2623 state
2624 })
2625 .collect::<Vec<_>>();
2626
2627 assert_eq!(
2628 actual_states, expected_states,
2629 "pane items do not match expectation"
2630 );
2631 })
2632 }
2633}