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
1390 move |mouse_state, cx| {
1391 let tab_style =
1392 theme.workspace.tab_bar.tab_style(pane_active, tab_active);
1393 let hovered = mouse_state.hovered();
1394
1395 enum Tab {}
1396 MouseEventHandler::<Tab>::new(ix, cx, |_, cx| {
1397 Self::render_tab(
1398 &item,
1399 pane.clone(),
1400 ix == 0,
1401 detail,
1402 hovered,
1403 tab_style,
1404 cx,
1405 )
1406 })
1407 .on_down(MouseButton::Left, move |_, cx| {
1408 cx.dispatch_action(ActivateItem(ix));
1409 })
1410 .on_click(MouseButton::Middle, {
1411 let item = item.clone();
1412 let pane = pane.clone();
1413 move |_, cx: &mut EventContext| {
1414 cx.dispatch_action(CloseItemById {
1415 item_id: item.id(),
1416 pane: pane.clone(),
1417 })
1418 }
1419 })
1420 .on_down(MouseButton::Right, move |e, cx| {
1421 let item = item.clone();
1422 cx.dispatch_action(DeployTabContextMenu {
1423 position: e.position,
1424 item_id: item.id(),
1425 pane: pane.clone(),
1426 });
1427 })
1428 .boxed()
1429 }
1430 });
1431
1432 if !pane_active || !tab_active {
1433 receiver = receiver.with_cursor_style(CursorStyle::PointingHand);
1434 }
1435
1436 receiver
1437 .as_draggable(
1438 DraggedItem {
1439 item,
1440 pane: pane.clone(),
1441 },
1442 {
1443 let theme = cx.global::<Settings>().theme.clone();
1444
1445 let detail = detail.clone();
1446 move |dragged_item, cx: &mut RenderContext<Workspace>| {
1447 let tab_style = &theme.workspace.tab_bar.dragged_tab;
1448 Self::render_tab(
1449 &dragged_item.item,
1450 dragged_item.pane.clone(),
1451 false,
1452 detail,
1453 false,
1454 &tab_style,
1455 cx,
1456 )
1457 }
1458 },
1459 )
1460 .boxed()
1461 })
1462 }
1463
1464 // Use the inactive tab style along with the current pane's active status to decide how to render
1465 // the filler
1466 let filler_index = self.items.len();
1467 let filler_style = theme.workspace.tab_bar.tab_style(pane_active, false);
1468 enum Filler {}
1469 row.add_child(
1470 dragged_item_receiver::<Filler, _>(0, filler_index, true, None, cx, |_, _| {
1471 Empty::new()
1472 .contained()
1473 .with_style(filler_style.container)
1474 .with_border(filler_style.container.border)
1475 .boxed()
1476 })
1477 .flex(1., true)
1478 .named("filler"),
1479 );
1480
1481 row
1482 }
1483
1484 fn tab_details(&self, cx: &AppContext) -> Vec<usize> {
1485 let mut tab_details = (0..self.items.len()).map(|_| 0).collect::<Vec<_>>();
1486
1487 let mut tab_descriptions = HashMap::default();
1488 let mut done = false;
1489 while !done {
1490 done = true;
1491
1492 // Store item indices by their tab description.
1493 for (ix, (item, detail)) in self.items.iter().zip(&tab_details).enumerate() {
1494 if let Some(description) = item.tab_description(*detail, cx) {
1495 if *detail == 0
1496 || Some(&description) != item.tab_description(detail - 1, cx).as_ref()
1497 {
1498 tab_descriptions
1499 .entry(description)
1500 .or_insert(Vec::new())
1501 .push(ix);
1502 }
1503 }
1504 }
1505
1506 // If two or more items have the same tab description, increase their level
1507 // of detail and try again.
1508 for (_, item_ixs) in tab_descriptions.drain() {
1509 if item_ixs.len() > 1 {
1510 done = false;
1511 for ix in item_ixs {
1512 tab_details[ix] += 1;
1513 }
1514 }
1515 }
1516 }
1517
1518 tab_details
1519 }
1520
1521 fn render_tab<V: View>(
1522 item: &Box<dyn ItemHandle>,
1523 pane: WeakViewHandle<Pane>,
1524 first: bool,
1525 detail: Option<usize>,
1526 hovered: bool,
1527 tab_style: &theme::Tab,
1528 cx: &mut RenderContext<V>,
1529 ) -> ElementBox {
1530 let title = item.tab_content(detail, &tab_style, cx);
1531 let mut container = tab_style.container.clone();
1532 if first {
1533 container.border.left = false;
1534 }
1535
1536 Flex::row()
1537 .with_child(
1538 Align::new({
1539 let diameter = 7.0;
1540 let icon_color = if item.has_conflict(cx) {
1541 Some(tab_style.icon_conflict)
1542 } else if item.is_dirty(cx) {
1543 Some(tab_style.icon_dirty)
1544 } else {
1545 None
1546 };
1547
1548 ConstrainedBox::new(
1549 Canvas::new(move |bounds, _, cx| {
1550 if let Some(color) = icon_color {
1551 let square = RectF::new(bounds.origin(), vec2f(diameter, diameter));
1552 cx.scene.push_quad(Quad {
1553 bounds: square,
1554 background: Some(color),
1555 border: Default::default(),
1556 corner_radius: diameter / 2.,
1557 });
1558 }
1559 })
1560 .boxed(),
1561 )
1562 .with_width(diameter)
1563 .with_height(diameter)
1564 .boxed()
1565 })
1566 .boxed(),
1567 )
1568 .with_child(
1569 Container::new(Align::new(title).boxed())
1570 .with_style(ContainerStyle {
1571 margin: Margin {
1572 left: tab_style.spacing,
1573 right: tab_style.spacing,
1574 ..Default::default()
1575 },
1576 ..Default::default()
1577 })
1578 .boxed(),
1579 )
1580 .with_child(
1581 Align::new(
1582 ConstrainedBox::new(if hovered {
1583 let item_id = item.id();
1584 enum TabCloseButton {}
1585 let icon = Svg::new("icons/x_mark_8.svg");
1586 MouseEventHandler::<TabCloseButton>::new(item_id, cx, |mouse_state, _| {
1587 if mouse_state.hovered() {
1588 icon.with_color(tab_style.icon_close_active).boxed()
1589 } else {
1590 icon.with_color(tab_style.icon_close).boxed()
1591 }
1592 })
1593 .with_padding(Padding::uniform(4.))
1594 .with_cursor_style(CursorStyle::PointingHand)
1595 .on_click(MouseButton::Left, {
1596 let pane = pane.clone();
1597 move |_, cx| {
1598 cx.dispatch_action(CloseItemById {
1599 item_id,
1600 pane: pane.clone(),
1601 })
1602 }
1603 })
1604 .named("close-tab-icon")
1605 } else {
1606 Empty::new().boxed()
1607 })
1608 .with_width(tab_style.close_icon_width)
1609 .boxed(),
1610 )
1611 .boxed(),
1612 )
1613 .contained()
1614 .with_style(container)
1615 .constrained()
1616 .with_height(tab_style.height)
1617 .boxed()
1618 }
1619
1620 fn render_tab_bar_buttons(
1621 &mut self,
1622 theme: &Theme,
1623 cx: &mut RenderContext<Self>,
1624 ) -> ElementBox {
1625 Flex::row()
1626 // New menu
1627 .with_child(render_tab_bar_button(
1628 0,
1629 "icons/plus_12.svg",
1630 cx,
1631 DeployNewMenu,
1632 self.tab_bar_context_menu
1633 .handle_if_kind(TabBarContextMenuKind::New),
1634 ))
1635 .with_child(
1636 self.docked
1637 .map(|anchor| {
1638 // Add the dock menu button if this pane is a dock
1639 let dock_icon = icon_for_dock_anchor(anchor);
1640
1641 render_tab_bar_button(
1642 1,
1643 dock_icon,
1644 cx,
1645 DeployDockMenu,
1646 self.tab_bar_context_menu
1647 .handle_if_kind(TabBarContextMenuKind::Dock),
1648 )
1649 })
1650 .unwrap_or_else(|| {
1651 // Add the split menu if this pane is not a dock
1652 render_tab_bar_button(
1653 2,
1654 "icons/split_12.svg",
1655 cx,
1656 DeploySplitMenu,
1657 self.tab_bar_context_menu
1658 .handle_if_kind(TabBarContextMenuKind::Split),
1659 )
1660 }),
1661 )
1662 // Add the close dock button if this pane is a dock
1663 .with_children(
1664 self.docked
1665 .map(|_| render_tab_bar_button(3, "icons/x_mark_8.svg", cx, HideDock, None)),
1666 )
1667 .contained()
1668 .with_style(theme.workspace.tab_bar.pane_button_container)
1669 .flex(1., false)
1670 .boxed()
1671 }
1672
1673 fn render_blank_pane(&mut self, theme: &Theme, _cx: &mut RenderContext<Self>) -> ElementBox {
1674 let background = theme.workspace.background;
1675 Empty::new()
1676 .contained()
1677 .with_background_color(background)
1678 .boxed()
1679 }
1680}
1681
1682impl Entity for Pane {
1683 type Event = Event;
1684}
1685
1686impl View for Pane {
1687 fn ui_name() -> &'static str {
1688 "Pane"
1689 }
1690
1691 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1692 let this = cx.handle();
1693
1694 enum MouseNavigationHandler {}
1695
1696 Stack::new()
1697 .with_child(
1698 MouseEventHandler::<MouseNavigationHandler>::new(0, cx, |_, cx| {
1699 let active_item_index = self.active_item_index;
1700
1701 if let Some(active_item) = self.active_item() {
1702 Flex::column()
1703 .with_child({
1704 let theme = cx.global::<Settings>().theme.clone();
1705
1706 let mut stack = Stack::new();
1707
1708 enum TabBarEventHandler {}
1709 stack.add_child(
1710 MouseEventHandler::<TabBarEventHandler>::new(0, cx, |_, _| {
1711 Empty::new()
1712 .contained()
1713 .with_style(theme.workspace.tab_bar.container)
1714 .boxed()
1715 })
1716 .on_down(MouseButton::Left, move |_, cx| {
1717 cx.dispatch_action(ActivateItem(active_item_index));
1718 })
1719 .boxed(),
1720 );
1721
1722 let mut tab_row = Flex::row()
1723 .with_child(self.render_tabs(cx).flex(1., true).named("tabs"));
1724
1725 if self.is_active {
1726 tab_row.add_child(self.render_tab_bar_buttons(&theme, cx))
1727 }
1728
1729 stack.add_child(tab_row.boxed());
1730 stack
1731 .constrained()
1732 .with_height(theme.workspace.tab_bar.height)
1733 .flex(1., false)
1734 .named("tab bar")
1735 })
1736 .with_child({
1737 enum PaneContentTabDropTarget {}
1738 dragged_item_receiver::<PaneContentTabDropTarget, _>(
1739 0,
1740 self.active_item_index + 1,
1741 false,
1742 if self.docked.is_some() {
1743 None
1744 } else {
1745 Some(100.)
1746 },
1747 cx,
1748 {
1749 let toolbar = self.toolbar.clone();
1750 let toolbar_hidden = toolbar.read(cx).hidden();
1751 move |_, cx| {
1752 Flex::column()
1753 .with_children((!toolbar_hidden).then(|| {
1754 ChildView::new(&toolbar, cx).expanded().boxed()
1755 }))
1756 .with_child(
1757 ChildView::new(active_item.as_any(), cx)
1758 .flex(1., true)
1759 .boxed(),
1760 )
1761 .boxed()
1762 }
1763 },
1764 )
1765 .flex(1., true)
1766 .boxed()
1767 })
1768 .with_child(ChildView::new(&self.tab_context_menu, cx).boxed())
1769 .boxed()
1770 } else {
1771 enum EmptyPane {}
1772 let theme = cx.global::<Settings>().theme.clone();
1773
1774 dragged_item_receiver::<EmptyPane, _>(0, 0, false, None, cx, |_, cx| {
1775 self.render_blank_pane(&theme, cx)
1776 })
1777 .on_down(MouseButton::Left, |_, cx| {
1778 cx.focus_parent_view();
1779 })
1780 .boxed()
1781 }
1782 })
1783 .on_down(MouseButton::Navigate(NavigationDirection::Back), {
1784 let this = this.clone();
1785 move |_, cx| {
1786 cx.dispatch_action(GoBack {
1787 pane: Some(this.clone()),
1788 });
1789 }
1790 })
1791 .on_down(MouseButton::Navigate(NavigationDirection::Forward), {
1792 let this = this.clone();
1793 move |_, cx| {
1794 cx.dispatch_action(GoForward {
1795 pane: Some(this.clone()),
1796 })
1797 }
1798 })
1799 .boxed(),
1800 )
1801 .named("pane")
1802 }
1803
1804 fn focus_in(&mut self, focused: AnyViewHandle, cx: &mut ViewContext<Self>) {
1805 self.toolbar.update(cx, |toolbar, cx| {
1806 toolbar.pane_focus_update(true, cx);
1807 });
1808
1809 if let Some(active_item) = self.active_item() {
1810 if cx.is_self_focused() {
1811 // Pane was focused directly. We need to either focus a view inside the active item,
1812 // or focus the active item itself
1813 if let Some(weak_last_focused_view) =
1814 self.last_focused_view_by_item.get(&active_item.id())
1815 {
1816 if let Some(last_focused_view) = weak_last_focused_view.upgrade(cx) {
1817 cx.focus(&last_focused_view);
1818 return;
1819 } else {
1820 self.last_focused_view_by_item.remove(&active_item.id());
1821 }
1822 }
1823
1824 cx.focus(active_item.as_any());
1825 } else if focused != self.tab_bar_context_menu.handle {
1826 self.last_focused_view_by_item
1827 .insert(active_item.id(), focused.downgrade());
1828 }
1829 }
1830 }
1831
1832 fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
1833 self.toolbar.update(cx, |toolbar, cx| {
1834 toolbar.pane_focus_update(false, cx);
1835 });
1836 }
1837
1838 fn keymap_context(&self, _: &AppContext) -> KeymapContext {
1839 let mut keymap = Self::default_keymap_context();
1840 if self.docked.is_some() {
1841 keymap.add_identifier("docked");
1842 }
1843 keymap
1844 }
1845}
1846
1847fn render_tab_bar_button<A: Action + Clone>(
1848 index: usize,
1849 icon: &'static str,
1850 cx: &mut RenderContext<Pane>,
1851 action: A,
1852 context_menu: Option<ViewHandle<ContextMenu>>,
1853) -> ElementBox {
1854 enum TabBarButton {}
1855
1856 Stack::new()
1857 .with_child(
1858 MouseEventHandler::<TabBarButton>::new(index, cx, |mouse_state, cx| {
1859 let theme = &cx.global::<Settings>().theme.workspace.tab_bar;
1860 let style = theme.pane_button.style_for(mouse_state, false);
1861 Svg::new(icon)
1862 .with_color(style.color)
1863 .constrained()
1864 .with_width(style.icon_width)
1865 .aligned()
1866 .constrained()
1867 .with_width(style.button_width)
1868 .with_height(style.button_width)
1869 .boxed()
1870 })
1871 .with_cursor_style(CursorStyle::PointingHand)
1872 .on_click(MouseButton::Left, move |_, cx| {
1873 cx.dispatch_action(action.clone());
1874 })
1875 .boxed(),
1876 )
1877 .with_children(
1878 context_menu.map(|menu| ChildView::new(&menu, cx).aligned().bottom().right().boxed()),
1879 )
1880 .flex(1., false)
1881 .boxed()
1882}
1883
1884impl ItemNavHistory {
1885 pub fn push<D: 'static + Any>(&self, data: Option<D>, cx: &mut AppContext) {
1886 self.history.borrow_mut().push(data, self.item.clone(), cx);
1887 }
1888
1889 pub fn pop_backward(&self, cx: &mut AppContext) -> Option<NavigationEntry> {
1890 self.history.borrow_mut().pop(NavigationMode::GoingBack, cx)
1891 }
1892
1893 pub fn pop_forward(&self, cx: &mut AppContext) -> Option<NavigationEntry> {
1894 self.history
1895 .borrow_mut()
1896 .pop(NavigationMode::GoingForward, cx)
1897 }
1898}
1899
1900impl NavHistory {
1901 fn set_mode(&mut self, mode: NavigationMode) {
1902 self.mode = mode;
1903 }
1904
1905 fn disable(&mut self) {
1906 self.mode = NavigationMode::Disabled;
1907 }
1908
1909 fn enable(&mut self) {
1910 self.mode = NavigationMode::Normal;
1911 }
1912
1913 fn pop(&mut self, mode: NavigationMode, cx: &mut AppContext) -> Option<NavigationEntry> {
1914 let entry = match mode {
1915 NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
1916 return None
1917 }
1918 NavigationMode::GoingBack => &mut self.backward_stack,
1919 NavigationMode::GoingForward => &mut self.forward_stack,
1920 NavigationMode::ReopeningClosedItem => &mut self.closed_stack,
1921 }
1922 .pop_back();
1923 if entry.is_some() {
1924 self.did_update(cx);
1925 }
1926 entry
1927 }
1928
1929 fn push<D: 'static + Any>(
1930 &mut self,
1931 data: Option<D>,
1932 item: Rc<dyn WeakItemHandle>,
1933 cx: &mut AppContext,
1934 ) {
1935 match self.mode {
1936 NavigationMode::Disabled => {}
1937 NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
1938 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1939 self.backward_stack.pop_front();
1940 }
1941 self.backward_stack.push_back(NavigationEntry {
1942 item,
1943 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1944 });
1945 self.forward_stack.clear();
1946 }
1947 NavigationMode::GoingBack => {
1948 if self.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1949 self.forward_stack.pop_front();
1950 }
1951 self.forward_stack.push_back(NavigationEntry {
1952 item,
1953 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1954 });
1955 }
1956 NavigationMode::GoingForward => {
1957 if self.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1958 self.backward_stack.pop_front();
1959 }
1960 self.backward_stack.push_back(NavigationEntry {
1961 item,
1962 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1963 });
1964 }
1965 NavigationMode::ClosingItem => {
1966 if self.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
1967 self.closed_stack.pop_front();
1968 }
1969 self.closed_stack.push_back(NavigationEntry {
1970 item,
1971 data: data.map(|data| Box::new(data) as Box<dyn Any>),
1972 });
1973 }
1974 }
1975 self.did_update(cx);
1976 }
1977
1978 fn did_update(&self, cx: &mut AppContext) {
1979 if let Some(pane) = self.pane.upgrade(cx) {
1980 cx.defer(move |cx| pane.update(cx, |pane, cx| pane.history_updated(cx)));
1981 }
1982 }
1983}
1984
1985pub struct PaneBackdrop {
1986 child_view: usize,
1987 child: ElementBox,
1988}
1989impl PaneBackdrop {
1990 pub fn new(pane_item_view: usize, child: ElementBox) -> Self {
1991 PaneBackdrop {
1992 child,
1993 child_view: pane_item_view,
1994 }
1995 }
1996}
1997
1998impl Element for PaneBackdrop {
1999 type LayoutState = ();
2000
2001 type PaintState = ();
2002
2003 fn layout(
2004 &mut self,
2005 constraint: gpui::SizeConstraint,
2006 cx: &mut gpui::LayoutContext,
2007 ) -> (Vector2F, Self::LayoutState) {
2008 let size = self.child.layout(constraint, cx);
2009 (size, ())
2010 }
2011
2012 fn paint(
2013 &mut self,
2014 bounds: RectF,
2015 visible_bounds: RectF,
2016 _: &mut Self::LayoutState,
2017 cx: &mut gpui::PaintContext,
2018 ) -> Self::PaintState {
2019 let background = cx.global::<Settings>().theme.editor.background;
2020
2021 let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2022
2023 cx.scene.push_quad(gpui::Quad {
2024 bounds: RectF::new(bounds.origin(), bounds.size()),
2025 background: Some(background),
2026 ..Default::default()
2027 });
2028
2029 let child_view_id = self.child_view;
2030 cx.scene.push_mouse_region(
2031 MouseRegion::new::<Self>(child_view_id, 0, visible_bounds).on_down(
2032 gpui::platform::MouseButton::Left,
2033 move |_, cx| {
2034 let window_id = cx.window_id;
2035 cx.focus(window_id, Some(child_view_id))
2036 },
2037 ),
2038 );
2039
2040 cx.paint_layer(Some(bounds), |cx| {
2041 self.child.paint(bounds.origin(), visible_bounds, cx)
2042 })
2043 }
2044
2045 fn rect_for_text_range(
2046 &self,
2047 range_utf16: std::ops::Range<usize>,
2048 _bounds: RectF,
2049 _visible_bounds: RectF,
2050 _layout: &Self::LayoutState,
2051 _paint: &Self::PaintState,
2052 cx: &gpui::MeasurementContext,
2053 ) -> Option<RectF> {
2054 self.child.rect_for_text_range(range_utf16, cx)
2055 }
2056
2057 fn debug(
2058 &self,
2059 _bounds: RectF,
2060 _layout: &Self::LayoutState,
2061 _paint: &Self::PaintState,
2062 cx: &gpui::DebugContext,
2063 ) -> serde_json::Value {
2064 gpui::json::json!({
2065 "type": "Pane Back Drop",
2066 "view": self.child_view,
2067 "child": self.child.debug(cx),
2068 })
2069 }
2070}
2071
2072#[cfg(test)]
2073mod tests {
2074 use std::sync::Arc;
2075
2076 use super::*;
2077 use crate::item::test::{TestItem, TestProjectItem};
2078 use gpui::{executor::Deterministic, TestAppContext};
2079 use project::FakeFs;
2080
2081 #[gpui::test]
2082 async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
2083 cx.foreground().forbid_parking();
2084 Settings::test_async(cx);
2085 let fs = FakeFs::new(cx.background());
2086
2087 let project = Project::test(fs, None, cx).await;
2088 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2089 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2090
2091 // 1. Add with a destination index
2092 // a. Add before the active item
2093 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2094 workspace.update(cx, |workspace, cx| {
2095 Pane::add_item(
2096 workspace,
2097 &pane,
2098 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2099 false,
2100 false,
2101 Some(0),
2102 cx,
2103 );
2104 });
2105 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2106
2107 // b. Add after the active item
2108 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2109 workspace.update(cx, |workspace, cx| {
2110 Pane::add_item(
2111 workspace,
2112 &pane,
2113 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2114 false,
2115 false,
2116 Some(2),
2117 cx,
2118 );
2119 });
2120 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2121
2122 // c. Add at the end of the item list (including off the length)
2123 set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2124 workspace.update(cx, |workspace, cx| {
2125 Pane::add_item(
2126 workspace,
2127 &pane,
2128 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2129 false,
2130 false,
2131 Some(5),
2132 cx,
2133 );
2134 });
2135 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2136
2137 // 2. Add without a destination index
2138 // a. Add with active item at the start of the item list
2139 set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
2140 workspace.update(cx, |workspace, cx| {
2141 Pane::add_item(
2142 workspace,
2143 &pane,
2144 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2145 false,
2146 false,
2147 None,
2148 cx,
2149 );
2150 });
2151 set_labeled_items(&workspace, &pane, ["A", "D*", "B", "C"], cx);
2152
2153 // b. Add with active item at the end of the item list
2154 set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
2155 workspace.update(cx, |workspace, cx| {
2156 Pane::add_item(
2157 workspace,
2158 &pane,
2159 Box::new(cx.add_view(|_| TestItem::new().with_label("D"))),
2160 false,
2161 false,
2162 None,
2163 cx,
2164 );
2165 });
2166 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2167 }
2168
2169 #[gpui::test]
2170 async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
2171 cx.foreground().forbid_parking();
2172 Settings::test_async(cx);
2173 let fs = FakeFs::new(cx.background());
2174
2175 let project = Project::test(fs, None, cx).await;
2176 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2177 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2178
2179 // 1. Add with a destination index
2180 // 1a. Add before the active item
2181 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
2182 workspace.update(cx, |workspace, cx| {
2183 Pane::add_item(workspace, &pane, d, false, false, Some(0), cx);
2184 });
2185 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
2186
2187 // 1b. Add after the active item
2188 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
2189 workspace.update(cx, |workspace, cx| {
2190 Pane::add_item(workspace, &pane, d, false, false, Some(2), cx);
2191 });
2192 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
2193
2194 // 1c. Add at the end of the item list (including off the length)
2195 let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C", "D"], cx);
2196 workspace.update(cx, |workspace, cx| {
2197 Pane::add_item(workspace, &pane, a, false, false, Some(5), cx);
2198 });
2199 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2200
2201 // 1d. Add same item to active index
2202 let [_, b, _] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2203 workspace.update(cx, |workspace, cx| {
2204 Pane::add_item(workspace, &pane, b, false, false, Some(1), cx);
2205 });
2206 assert_item_labels(&pane, ["A", "B*", "C"], cx);
2207
2208 // 1e. Add item to index after same item in last position
2209 let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B*", "C"], cx);
2210 workspace.update(cx, |workspace, cx| {
2211 Pane::add_item(workspace, &pane, c, false, false, Some(2), cx);
2212 });
2213 assert_item_labels(&pane, ["A", "B", "C*"], cx);
2214
2215 // 2. Add without a destination index
2216 // 2a. Add with active item at the start of the item list
2217 let [_, _, _, d] = set_labeled_items(&workspace, &pane, ["A*", "B", "C", "D"], cx);
2218 workspace.update(cx, |workspace, cx| {
2219 Pane::add_item(workspace, &pane, d, false, false, None, cx);
2220 });
2221 assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
2222
2223 // 2b. Add with active item at the end of the item list
2224 let [a, _, _, _] = set_labeled_items(&workspace, &pane, ["A", "B", "C", "D*"], cx);
2225 workspace.update(cx, |workspace, cx| {
2226 Pane::add_item(workspace, &pane, a, false, false, None, cx);
2227 });
2228 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
2229
2230 // 2c. Add active item to active item at end of list
2231 let [_, _, c] = set_labeled_items(&workspace, &pane, ["A", "B", "C*"], cx);
2232 workspace.update(cx, |workspace, cx| {
2233 Pane::add_item(workspace, &pane, c, false, false, None, cx);
2234 });
2235 assert_item_labels(&pane, ["A", "B", "C*"], cx);
2236
2237 // 2d. Add active item to active item at start of list
2238 let [a, _, _] = set_labeled_items(&workspace, &pane, ["A*", "B", "C"], cx);
2239 workspace.update(cx, |workspace, cx| {
2240 Pane::add_item(workspace, &pane, a, false, false, None, cx);
2241 });
2242 assert_item_labels(&pane, ["A*", "B", "C"], cx);
2243 }
2244
2245 #[gpui::test]
2246 async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
2247 cx.foreground().forbid_parking();
2248 Settings::test_async(cx);
2249 let fs = FakeFs::new(cx.background());
2250
2251 let project = Project::test(fs, None, cx).await;
2252 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2253 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2254
2255 // singleton view
2256 workspace.update(cx, |workspace, cx| {
2257 let item = TestItem::new()
2258 .with_singleton(true)
2259 .with_label("buffer 1")
2260 .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)]);
2261
2262 Pane::add_item(
2263 workspace,
2264 &pane,
2265 Box::new(cx.add_view(|_| item)),
2266 false,
2267 false,
2268 None,
2269 cx,
2270 );
2271 });
2272 assert_item_labels(&pane, ["buffer 1*"], cx);
2273
2274 // new singleton view with the same project entry
2275 workspace.update(cx, |workspace, cx| {
2276 let item = TestItem::new()
2277 .with_singleton(true)
2278 .with_label("buffer 1")
2279 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2280
2281 Pane::add_item(
2282 workspace,
2283 &pane,
2284 Box::new(cx.add_view(|_| item)),
2285 false,
2286 false,
2287 None,
2288 cx,
2289 );
2290 });
2291 assert_item_labels(&pane, ["buffer 1*"], cx);
2292
2293 // new singleton view with different project entry
2294 workspace.update(cx, |workspace, cx| {
2295 let item = TestItem::new()
2296 .with_singleton(true)
2297 .with_label("buffer 2")
2298 .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)]);
2299
2300 Pane::add_item(
2301 workspace,
2302 &pane,
2303 Box::new(cx.add_view(|_| item)),
2304 false,
2305 false,
2306 None,
2307 cx,
2308 );
2309 });
2310 assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
2311
2312 // new multibuffer view with the same project entry
2313 workspace.update(cx, |workspace, cx| {
2314 let item = TestItem::new()
2315 .with_singleton(false)
2316 .with_label("multibuffer 1")
2317 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2318
2319 Pane::add_item(
2320 workspace,
2321 &pane,
2322 Box::new(cx.add_view(|_| item)),
2323 false,
2324 false,
2325 None,
2326 cx,
2327 );
2328 });
2329 assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
2330
2331 // another multibuffer view with the same project entry
2332 workspace.update(cx, |workspace, cx| {
2333 let item = TestItem::new()
2334 .with_singleton(false)
2335 .with_label("multibuffer 1b")
2336 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)]);
2337
2338 Pane::add_item(
2339 workspace,
2340 &pane,
2341 Box::new(cx.add_view(|_| item)),
2342 false,
2343 false,
2344 None,
2345 cx,
2346 );
2347 });
2348 assert_item_labels(
2349 &pane,
2350 ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
2351 cx,
2352 );
2353 }
2354
2355 #[gpui::test]
2356 async fn test_remove_item_ordering(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2357 Settings::test_async(cx);
2358 let fs = FakeFs::new(cx.background());
2359
2360 let project = Project::test(fs, None, cx).await;
2361 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2362 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2363
2364 add_labeled_item(&workspace, &pane, "A", false, cx);
2365 add_labeled_item(&workspace, &pane, "B", false, cx);
2366 add_labeled_item(&workspace, &pane, "C", false, cx);
2367 add_labeled_item(&workspace, &pane, "D", false, cx);
2368 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2369
2370 pane.update(cx, |pane, cx| pane.activate_item(1, false, false, cx));
2371 add_labeled_item(&workspace, &pane, "1", false, cx);
2372 assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
2373
2374 workspace.update(cx, |workspace, cx| {
2375 Pane::close_active_item(workspace, &CloseActiveItem, cx);
2376 });
2377 deterministic.run_until_parked();
2378 assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
2379
2380 pane.update(cx, |pane, cx| pane.activate_item(3, false, false, cx));
2381 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
2382
2383 workspace.update(cx, |workspace, cx| {
2384 Pane::close_active_item(workspace, &CloseActiveItem, cx);
2385 });
2386 deterministic.run_until_parked();
2387 assert_item_labels(&pane, ["A", "B*", "C"], cx);
2388
2389 workspace.update(cx, |workspace, cx| {
2390 Pane::close_active_item(workspace, &CloseActiveItem, cx);
2391 });
2392 deterministic.run_until_parked();
2393 assert_item_labels(&pane, ["A", "C*"], cx);
2394
2395 workspace.update(cx, |workspace, cx| {
2396 Pane::close_active_item(workspace, &CloseActiveItem, cx);
2397 });
2398 deterministic.run_until_parked();
2399 assert_item_labels(&pane, ["A*"], cx);
2400 }
2401
2402 #[gpui::test]
2403 async fn test_close_inactive_items(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2404 Settings::test_async(cx);
2405 let fs = FakeFs::new(cx.background());
2406
2407 let project = Project::test(fs, None, cx).await;
2408 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2409 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2410
2411 set_labeled_items(&workspace, &pane, ["A", "B", "C*", "D", "E"], cx);
2412
2413 workspace.update(cx, |workspace, cx| {
2414 Pane::close_inactive_items(workspace, &CloseInactiveItems, cx);
2415 });
2416
2417 deterministic.run_until_parked();
2418 assert_item_labels(&pane, ["C*"], cx);
2419 }
2420
2421 #[gpui::test]
2422 async fn test_close_clean_items(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2423 Settings::test_async(cx);
2424 let fs = FakeFs::new(cx.background());
2425
2426 let project = Project::test(fs, None, cx).await;
2427 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2428 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2429
2430 add_labeled_item(&workspace, &pane, "A", true, cx);
2431 add_labeled_item(&workspace, &pane, "B", false, cx);
2432 add_labeled_item(&workspace, &pane, "C", true, cx);
2433 add_labeled_item(&workspace, &pane, "D", false, cx);
2434 add_labeled_item(&workspace, &pane, "E", false, cx);
2435 assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
2436
2437 workspace.update(cx, |workspace, cx| {
2438 Pane::close_clean_items(workspace, &CloseCleanItems, cx);
2439 });
2440
2441 deterministic.run_until_parked();
2442 assert_item_labels(&pane, ["A^", "C*^"], cx);
2443 }
2444
2445 #[gpui::test]
2446 async fn test_close_items_to_the_left(
2447 deterministic: Arc<Deterministic>,
2448 cx: &mut TestAppContext,
2449 ) {
2450 Settings::test_async(cx);
2451 let fs = FakeFs::new(cx.background());
2452
2453 let project = Project::test(fs, None, cx).await;
2454 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2455 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2456
2457 set_labeled_items(&workspace, &pane, ["A", "B", "C*", "D", "E"], cx);
2458
2459 workspace.update(cx, |workspace, cx| {
2460 Pane::close_items_to_the_left(workspace, &CloseItemsToTheLeft, cx);
2461 });
2462
2463 deterministic.run_until_parked();
2464 assert_item_labels(&pane, ["C*", "D", "E"], cx);
2465 }
2466
2467 #[gpui::test]
2468 async fn test_close_items_to_the_right(
2469 deterministic: Arc<Deterministic>,
2470 cx: &mut TestAppContext,
2471 ) {
2472 Settings::test_async(cx);
2473 let fs = FakeFs::new(cx.background());
2474
2475 let project = Project::test(fs, None, cx).await;
2476 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2477 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2478
2479 set_labeled_items(&workspace, &pane, ["A", "B", "C*", "D", "E"], cx);
2480
2481 workspace.update(cx, |workspace, cx| {
2482 Pane::close_items_to_the_right(workspace, &CloseItemsToTheRight, cx);
2483 });
2484
2485 deterministic.run_until_parked();
2486 assert_item_labels(&pane, ["A", "B", "C*"], cx);
2487 }
2488
2489 #[gpui::test]
2490 async fn test_close_all_items(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
2491 Settings::test_async(cx);
2492 let fs = FakeFs::new(cx.background());
2493
2494 let project = Project::test(fs, None, cx).await;
2495 let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
2496 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
2497
2498 add_labeled_item(&workspace, &pane, "A", false, cx);
2499 add_labeled_item(&workspace, &pane, "B", false, cx);
2500 add_labeled_item(&workspace, &pane, "C", false, cx);
2501 assert_item_labels(&pane, ["A", "B", "C*"], cx);
2502
2503 workspace.update(cx, |workspace, cx| {
2504 Pane::close_all_items(workspace, &CloseAllItems, cx);
2505 });
2506
2507 deterministic.run_until_parked();
2508 assert_item_labels(&pane, [], cx);
2509 }
2510
2511 fn add_labeled_item(
2512 workspace: &ViewHandle<Workspace>,
2513 pane: &ViewHandle<Pane>,
2514 label: &str,
2515 is_dirty: bool,
2516 cx: &mut TestAppContext,
2517 ) -> Box<ViewHandle<TestItem>> {
2518 workspace.update(cx, |workspace, cx| {
2519 let labeled_item =
2520 Box::new(cx.add_view(|_| TestItem::new().with_label(label).with_dirty(is_dirty)));
2521
2522 Pane::add_item(
2523 workspace,
2524 pane,
2525 labeled_item.clone(),
2526 false,
2527 false,
2528 None,
2529 cx,
2530 );
2531
2532 labeled_item
2533 })
2534 }
2535
2536 fn set_labeled_items<const COUNT: usize>(
2537 workspace: &ViewHandle<Workspace>,
2538 pane: &ViewHandle<Pane>,
2539 labels: [&str; COUNT],
2540 cx: &mut TestAppContext,
2541 ) -> [Box<ViewHandle<TestItem>>; COUNT] {
2542 pane.update(cx, |pane, _| {
2543 pane.items.clear();
2544 });
2545
2546 workspace.update(cx, |workspace, cx| {
2547 let mut active_item_index = 0;
2548
2549 let mut index = 0;
2550 let items = labels.map(|mut label| {
2551 if label.ends_with("*") {
2552 label = label.trim_end_matches("*");
2553 active_item_index = index;
2554 }
2555
2556 let labeled_item = Box::new(cx.add_view(|_| TestItem::new().with_label(label)));
2557 Pane::add_item(
2558 workspace,
2559 pane,
2560 labeled_item.clone(),
2561 false,
2562 false,
2563 None,
2564 cx,
2565 );
2566 index += 1;
2567 labeled_item
2568 });
2569
2570 pane.update(cx, |pane, cx| {
2571 pane.activate_item(active_item_index, false, false, cx)
2572 });
2573
2574 items
2575 })
2576 }
2577
2578 // Assert the item label, with the active item label suffixed with a '*'
2579 fn assert_item_labels<const COUNT: usize>(
2580 pane: &ViewHandle<Pane>,
2581 expected_states: [&str; COUNT],
2582 cx: &mut TestAppContext,
2583 ) {
2584 pane.read_with(cx, |pane, cx| {
2585 let actual_states = pane
2586 .items
2587 .iter()
2588 .enumerate()
2589 .map(|(ix, item)| {
2590 let mut state = item
2591 .as_any()
2592 .downcast_ref::<TestItem>()
2593 .unwrap()
2594 .read(cx)
2595 .label
2596 .clone();
2597 if ix == pane.active_item_index {
2598 state.push('*');
2599 }
2600 if item.is_dirty(cx) {
2601 state.push('^');
2602 }
2603 state
2604 })
2605 .collect::<Vec<_>>();
2606
2607 assert_eq!(
2608 actual_states, expected_states,
2609 "pane items do not match expectation"
2610 );
2611 })
2612 }
2613}