1use crate::{
2 CloseWindow, NewFile, NewTerminal, OpenInTerminal, OpenOptions, OpenTerminal, OpenVisible,
3 SplitDirection, ToggleFileFinder, ToggleProjectSymbols, ToggleZoom, Workspace,
4 WorkspaceItemBuilder, ZoomIn, ZoomOut,
5 invalid_item_view::InvalidItemView,
6 item::{
7 ActivateOnClose, ClosePosition, Item, ItemBufferKind, ItemHandle, ItemSettings,
8 PreviewTabsSettings, ProjectItemKind, SaveOptions, ShowCloseButton, ShowDiagnostics,
9 TabContentParams, TabTooltipContent, WeakItemHandle,
10 },
11 move_item,
12 notifications::NotifyResultExt,
13 toolbar::Toolbar,
14 utility_pane::UtilityPaneSlot,
15 workspace_settings::{AutosaveSetting, TabBarSettings, WorkspaceSettings},
16};
17use anyhow::Result;
18use collections::{BTreeSet, HashMap, HashSet, VecDeque};
19use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt};
20use futures::{StreamExt, stream::FuturesUnordered};
21use gpui::{
22 Action, AnyElement, App, AsyncWindowContext, ClickEvent, ClipboardItem, Context, Corner, Div,
23 DragMoveEvent, Entity, EntityId, EventEmitter, ExternalPaths, FocusHandle, FocusOutEvent,
24 Focusable, KeyContext, MouseButton, MouseDownEvent, NavigationDirection, Pixels, Point,
25 PromptLevel, Render, ScrollHandle, Subscription, Task, WeakEntity, WeakFocusHandle, Window,
26 actions, anchored, deferred, prelude::*,
27};
28use itertools::Itertools;
29use language::DiagnosticSeverity;
30use parking_lot::Mutex;
31use project::{DirectoryLister, Project, ProjectEntryId, ProjectPath, WorktreeId};
32use schemars::JsonSchema;
33use serde::Deserialize;
34use settings::{Settings, SettingsStore};
35use std::{
36 any::Any,
37 cmp, fmt, mem,
38 num::NonZeroUsize,
39 ops::ControlFlow,
40 path::PathBuf,
41 rc::Rc,
42 sync::{
43 Arc,
44 atomic::{AtomicUsize, Ordering},
45 },
46 time::Duration,
47};
48use theme::ThemeSettings;
49use ui::{
50 ContextMenu, ContextMenuEntry, ContextMenuItem, DecoratedIcon, IconButtonShape, IconDecoration,
51 IconDecorationKind, Indicator, PopoverMenu, PopoverMenuHandle, Tab, TabBar, TabPosition,
52 Tooltip, prelude::*, right_click_menu,
53};
54use util::{ResultExt, debug_panic, maybe, paths::PathStyle, truncate_and_remove_front};
55
56/// A selected entry in e.g. project panel.
57#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
58pub struct SelectedEntry {
59 pub worktree_id: WorktreeId,
60 pub entry_id: ProjectEntryId,
61}
62
63/// A group of selected entries from project panel.
64#[derive(Debug)]
65pub struct DraggedSelection {
66 pub active_selection: SelectedEntry,
67 pub marked_selections: Arc<[SelectedEntry]>,
68}
69
70impl DraggedSelection {
71 pub fn items<'a>(&'a self) -> Box<dyn Iterator<Item = &'a SelectedEntry> + 'a> {
72 if self.marked_selections.contains(&self.active_selection) {
73 Box::new(self.marked_selections.iter())
74 } else {
75 Box::new(std::iter::once(&self.active_selection))
76 }
77 }
78}
79
80#[derive(Clone, Copy, PartialEq, Debug, Deserialize, JsonSchema)]
81#[serde(rename_all = "snake_case")]
82pub enum SaveIntent {
83 /// write all files (even if unchanged)
84 /// prompt before overwriting on-disk changes
85 Save,
86 /// same as Save, but without auto formatting
87 SaveWithoutFormat,
88 /// write any files that have local changes
89 /// prompt before overwriting on-disk changes
90 SaveAll,
91 /// always prompt for a new path
92 SaveAs,
93 /// prompt "you have unsaved changes" before writing
94 Close,
95 /// write all dirty files, don't prompt on conflict
96 Overwrite,
97 /// skip all save-related behavior
98 Skip,
99}
100
101/// Activates a specific item in the pane by its index.
102#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
103#[action(namespace = pane)]
104pub struct ActivateItem(pub usize);
105
106/// Closes the currently active item in the pane.
107#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
108#[action(namespace = pane)]
109#[serde(deny_unknown_fields)]
110pub struct CloseActiveItem {
111 #[serde(default)]
112 pub save_intent: Option<SaveIntent>,
113 #[serde(default)]
114 pub close_pinned: bool,
115}
116
117/// Closes all inactive items in the pane.
118#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
119#[action(namespace = pane)]
120#[serde(deny_unknown_fields)]
121#[action(deprecated_aliases = ["pane::CloseInactiveItems"])]
122pub struct CloseOtherItems {
123 #[serde(default)]
124 pub save_intent: Option<SaveIntent>,
125 #[serde(default)]
126 pub close_pinned: bool,
127}
128
129/// Closes all multibuffers in the pane.
130#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
131#[action(namespace = pane)]
132#[serde(deny_unknown_fields)]
133pub struct CloseMultibufferItems {
134 #[serde(default)]
135 pub save_intent: Option<SaveIntent>,
136 #[serde(default)]
137 pub close_pinned: bool,
138}
139
140/// Closes all items in the pane.
141#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
142#[action(namespace = pane)]
143#[serde(deny_unknown_fields)]
144pub struct CloseAllItems {
145 #[serde(default)]
146 pub save_intent: Option<SaveIntent>,
147 #[serde(default)]
148 pub close_pinned: bool,
149}
150
151/// Closes all items that have no unsaved changes.
152#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
153#[action(namespace = pane)]
154#[serde(deny_unknown_fields)]
155pub struct CloseCleanItems {
156 #[serde(default)]
157 pub close_pinned: bool,
158}
159
160/// Closes all items to the right of the current item.
161#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
162#[action(namespace = pane)]
163#[serde(deny_unknown_fields)]
164pub struct CloseItemsToTheRight {
165 #[serde(default)]
166 pub close_pinned: bool,
167}
168
169/// Closes all items to the left of the current item.
170#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
171#[action(namespace = pane)]
172#[serde(deny_unknown_fields)]
173pub struct CloseItemsToTheLeft {
174 #[serde(default)]
175 pub close_pinned: bool,
176}
177
178/// Reveals the current item in the project panel.
179#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
180#[action(namespace = pane)]
181#[serde(deny_unknown_fields)]
182pub struct RevealInProjectPanel {
183 #[serde(skip)]
184 pub entry_id: Option<u64>,
185}
186
187/// Opens the search interface with the specified configuration.
188#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
189#[action(namespace = pane)]
190#[serde(deny_unknown_fields)]
191pub struct DeploySearch {
192 #[serde(default)]
193 pub replace_enabled: bool,
194 #[serde(default)]
195 pub included_files: Option<String>,
196 #[serde(default)]
197 pub excluded_files: Option<String>,
198}
199
200#[derive(Clone, Copy, PartialEq, Debug, Deserialize, JsonSchema, Default)]
201#[serde(deny_unknown_fields)]
202pub enum SplitMode {
203 /// Clone the current pane.
204 #[default]
205 ClonePane,
206 /// Create an empty new pane.
207 EmptyPane,
208 /// Move the item into a new pane. This will map to nop if only one pane exists.
209 MovePane,
210}
211
212macro_rules! split_structs {
213 ($($name:ident => $doc:literal),* $(,)?) => {
214 $(
215 #[doc = $doc]
216 #[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
217 #[action(namespace = pane)]
218 #[serde(deny_unknown_fields, default)]
219 pub struct $name {
220 pub mode: SplitMode,
221 }
222 )*
223 };
224}
225
226split_structs!(
227 SplitLeft => "Splits the pane to the left.",
228 SplitRight => "Splits the pane to the right.",
229 SplitUp => "Splits the pane upward.",
230 SplitDown => "Splits the pane downward.",
231 SplitHorizontal => "Splits the pane horizontally.",
232 SplitVertical => "Splits the pane vertically."
233);
234
235actions!(
236 pane,
237 [
238 /// Activates the previous item in the pane.
239 ActivatePreviousItem,
240 /// Activates the next item in the pane.
241 ActivateNextItem,
242 /// Activates the last item in the pane.
243 ActivateLastItem,
244 /// Switches to the alternate file.
245 AlternateFile,
246 /// Navigates back in history.
247 GoBack,
248 /// Navigates forward in history.
249 GoForward,
250 /// Joins this pane into the next pane.
251 JoinIntoNext,
252 /// Joins all panes into one.
253 JoinAll,
254 /// Reopens the most recently closed item.
255 ReopenClosedItem,
256 /// Splits the pane to the left, moving the current item.
257 SplitAndMoveLeft,
258 /// Splits the pane upward, moving the current item.
259 SplitAndMoveUp,
260 /// Splits the pane to the right, moving the current item.
261 SplitAndMoveRight,
262 /// Splits the pane downward, moving the current item.
263 SplitAndMoveDown,
264 /// Swaps the current item with the one to the left.
265 SwapItemLeft,
266 /// Swaps the current item with the one to the right.
267 SwapItemRight,
268 /// Toggles preview mode for the current tab.
269 TogglePreviewTab,
270 /// Toggles pin status for the current tab.
271 TogglePinTab,
272 /// Unpins all tabs in the pane.
273 UnpinAllTabs,
274 ]
275);
276
277impl DeploySearch {
278 pub fn find() -> Self {
279 Self {
280 replace_enabled: false,
281 included_files: None,
282 excluded_files: None,
283 }
284 }
285}
286
287const MAX_NAVIGATION_HISTORY_LEN: usize = 1024;
288
289pub enum Event {
290 AddItem {
291 item: Box<dyn ItemHandle>,
292 },
293 ActivateItem {
294 local: bool,
295 focus_changed: bool,
296 },
297 Remove {
298 focus_on_pane: Option<Entity<Pane>>,
299 },
300 RemovedItem {
301 item: Box<dyn ItemHandle>,
302 },
303 Split {
304 direction: SplitDirection,
305 mode: SplitMode,
306 },
307 ItemPinned,
308 ItemUnpinned,
309 JoinAll,
310 JoinIntoNext,
311 ChangeItemTitle,
312 Focus,
313 ZoomIn,
314 ZoomOut,
315 UserSavedItem {
316 item: Box<dyn WeakItemHandle>,
317 save_intent: SaveIntent,
318 },
319}
320
321impl fmt::Debug for Event {
322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323 match self {
324 Event::AddItem { item } => f
325 .debug_struct("AddItem")
326 .field("item", &item.item_id())
327 .finish(),
328 Event::ActivateItem { local, .. } => f
329 .debug_struct("ActivateItem")
330 .field("local", local)
331 .finish(),
332 Event::Remove { .. } => f.write_str("Remove"),
333 Event::RemovedItem { item } => f
334 .debug_struct("RemovedItem")
335 .field("item", &item.item_id())
336 .finish(),
337 Event::Split { direction, mode } => f
338 .debug_struct("Split")
339 .field("direction", direction)
340 .field("mode", mode)
341 .finish(),
342 Event::JoinAll => f.write_str("JoinAll"),
343 Event::JoinIntoNext => f.write_str("JoinIntoNext"),
344 Event::ChangeItemTitle => f.write_str("ChangeItemTitle"),
345 Event::Focus => f.write_str("Focus"),
346 Event::ZoomIn => f.write_str("ZoomIn"),
347 Event::ZoomOut => f.write_str("ZoomOut"),
348 Event::UserSavedItem { item, save_intent } => f
349 .debug_struct("UserSavedItem")
350 .field("item", &item.id())
351 .field("save_intent", save_intent)
352 .finish(),
353 Event::ItemPinned => f.write_str("ItemPinned"),
354 Event::ItemUnpinned => f.write_str("ItemUnpinned"),
355 }
356 }
357}
358
359/// A container for 0 to many items that are open in the workspace.
360/// Treats all items uniformly via the [`ItemHandle`] trait, whether it's an editor, search results multibuffer, terminal or something else,
361/// responsible for managing item tabs, focus and zoom states and drag and drop features.
362/// Can be split, see `PaneGroup` for more details.
363pub struct Pane {
364 alternate_file_items: (
365 Option<Box<dyn WeakItemHandle>>,
366 Option<Box<dyn WeakItemHandle>>,
367 ),
368 focus_handle: FocusHandle,
369 items: Vec<Box<dyn ItemHandle>>,
370 activation_history: Vec<ActivationHistoryEntry>,
371 next_activation_timestamp: Arc<AtomicUsize>,
372 zoomed: bool,
373 was_focused: bool,
374 active_item_index: usize,
375 preview_item_id: Option<EntityId>,
376 last_focus_handle_by_item: HashMap<EntityId, WeakFocusHandle>,
377 nav_history: NavHistory,
378 toolbar: Entity<Toolbar>,
379 pub(crate) workspace: WeakEntity<Workspace>,
380 project: WeakEntity<Project>,
381 pub drag_split_direction: Option<SplitDirection>,
382 can_drop_predicate: Option<Arc<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool>>,
383 custom_drop_handle: Option<
384 Arc<dyn Fn(&mut Pane, &dyn Any, &mut Window, &mut Context<Pane>) -> ControlFlow<(), ()>>,
385 >,
386 can_split_predicate:
387 Option<Arc<dyn Fn(&mut Self, &dyn Any, &mut Window, &mut Context<Self>) -> bool>>,
388 can_toggle_zoom: bool,
389 should_display_tab_bar: Rc<dyn Fn(&Window, &mut Context<Pane>) -> bool>,
390 render_tab_bar_buttons: Rc<
391 dyn Fn(
392 &mut Pane,
393 &mut Window,
394 &mut Context<Pane>,
395 ) -> (Option<AnyElement>, Option<AnyElement>),
396 >,
397 render_tab_bar: Rc<dyn Fn(&mut Pane, &mut Window, &mut Context<Pane>) -> AnyElement>,
398 show_tab_bar_buttons: bool,
399 max_tabs: Option<NonZeroUsize>,
400 use_max_tabs: bool,
401 _subscriptions: Vec<Subscription>,
402 tab_bar_scroll_handle: ScrollHandle,
403 /// This is set to true if a user scroll has occurred more recently than a system scroll
404 /// We want to suppress certain system scrolls when the user has intentionally scrolled
405 suppress_scroll: bool,
406 /// Is None if navigation buttons are permanently turned off (and should not react to setting changes).
407 /// Otherwise, when `display_nav_history_buttons` is Some, it determines whether nav buttons should be displayed.
408 display_nav_history_buttons: Option<bool>,
409 double_click_dispatch_action: Box<dyn Action>,
410 save_modals_spawned: HashSet<EntityId>,
411 close_pane_if_empty: bool,
412 pub new_item_context_menu_handle: PopoverMenuHandle<ContextMenu>,
413 pub split_item_context_menu_handle: PopoverMenuHandle<ContextMenu>,
414 pinned_tab_count: usize,
415 diagnostics: HashMap<ProjectPath, DiagnosticSeverity>,
416 zoom_out_on_close: bool,
417 diagnostic_summary_update: Task<()>,
418 /// If a certain project item wants to get recreated with specific data, it can persist its data before the recreation here.
419 pub project_item_restoration_data: HashMap<ProjectItemKind, Box<dyn Any + Send>>,
420 welcome_page: Option<Entity<crate::welcome::WelcomePage>>,
421
422 pub in_center_group: bool,
423 pub is_upper_left: bool,
424 pub is_upper_right: bool,
425}
426
427pub struct ActivationHistoryEntry {
428 pub entity_id: EntityId,
429 pub timestamp: usize,
430}
431
432pub struct ItemNavHistory {
433 history: NavHistory,
434 item: Arc<dyn WeakItemHandle>,
435 is_preview: bool,
436}
437
438#[derive(Clone)]
439pub struct NavHistory(Arc<Mutex<NavHistoryState>>);
440
441struct NavHistoryState {
442 mode: NavigationMode,
443 backward_stack: VecDeque<NavigationEntry>,
444 forward_stack: VecDeque<NavigationEntry>,
445 closed_stack: VecDeque<NavigationEntry>,
446 paths_by_item: HashMap<EntityId, (ProjectPath, Option<PathBuf>)>,
447 pane: WeakEntity<Pane>,
448 next_timestamp: Arc<AtomicUsize>,
449}
450
451#[derive(Debug, Default, Copy, Clone)]
452pub enum NavigationMode {
453 #[default]
454 Normal,
455 GoingBack,
456 GoingForward,
457 ClosingItem,
458 ReopeningClosedItem,
459 Disabled,
460}
461
462pub struct NavigationEntry {
463 pub item: Arc<dyn WeakItemHandle>,
464 pub data: Option<Box<dyn Any + Send>>,
465 pub timestamp: usize,
466 pub is_preview: bool,
467}
468
469#[derive(Clone)]
470pub struct DraggedTab {
471 pub pane: Entity<Pane>,
472 pub item: Box<dyn ItemHandle>,
473 pub ix: usize,
474 pub detail: usize,
475 pub is_active: bool,
476}
477
478impl EventEmitter<Event> for Pane {}
479
480pub enum Side {
481 Left,
482 Right,
483}
484
485#[derive(Copy, Clone)]
486enum PinOperation {
487 Pin,
488 Unpin,
489}
490
491impl Pane {
492 pub fn new(
493 workspace: WeakEntity<Workspace>,
494 project: Entity<Project>,
495 next_timestamp: Arc<AtomicUsize>,
496 can_drop_predicate: Option<Arc<dyn Fn(&dyn Any, &mut Window, &mut App) -> bool + 'static>>,
497 double_click_dispatch_action: Box<dyn Action>,
498 use_max_tabs: bool,
499 window: &mut Window,
500 cx: &mut Context<Self>,
501 ) -> Self {
502 let focus_handle = cx.focus_handle();
503 let max_tabs = if use_max_tabs {
504 WorkspaceSettings::get_global(cx).max_tabs
505 } else {
506 None
507 };
508
509 let subscriptions = vec![
510 cx.on_focus(&focus_handle, window, Pane::focus_in),
511 cx.on_focus_in(&focus_handle, window, Pane::focus_in),
512 cx.on_focus_out(&focus_handle, window, Pane::focus_out),
513 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
514 cx.subscribe(&project, Self::project_events),
515 ];
516
517 let handle = cx.entity().downgrade();
518
519 Self {
520 alternate_file_items: (None, None),
521 focus_handle,
522 items: Vec::new(),
523 activation_history: Vec::new(),
524 next_activation_timestamp: next_timestamp.clone(),
525 was_focused: false,
526 zoomed: false,
527 active_item_index: 0,
528 preview_item_id: None,
529 max_tabs,
530 use_max_tabs,
531 last_focus_handle_by_item: Default::default(),
532 nav_history: NavHistory(Arc::new(Mutex::new(NavHistoryState {
533 mode: NavigationMode::Normal,
534 backward_stack: Default::default(),
535 forward_stack: Default::default(),
536 closed_stack: Default::default(),
537 paths_by_item: Default::default(),
538 pane: handle,
539 next_timestamp,
540 }))),
541 toolbar: cx.new(|_| Toolbar::new()),
542 tab_bar_scroll_handle: ScrollHandle::new(),
543 suppress_scroll: false,
544 drag_split_direction: None,
545 workspace,
546 project: project.downgrade(),
547 can_drop_predicate,
548 custom_drop_handle: None,
549 can_split_predicate: None,
550 can_toggle_zoom: true,
551 should_display_tab_bar: Rc::new(|_, cx| TabBarSettings::get_global(cx).show),
552 render_tab_bar_buttons: Rc::new(default_render_tab_bar_buttons),
553 render_tab_bar: Rc::new(Self::render_tab_bar),
554 show_tab_bar_buttons: TabBarSettings::get_global(cx).show_tab_bar_buttons,
555 display_nav_history_buttons: Some(
556 TabBarSettings::get_global(cx).show_nav_history_buttons,
557 ),
558 _subscriptions: subscriptions,
559 double_click_dispatch_action,
560 save_modals_spawned: HashSet::default(),
561 close_pane_if_empty: true,
562 split_item_context_menu_handle: Default::default(),
563 new_item_context_menu_handle: Default::default(),
564 pinned_tab_count: 0,
565 diagnostics: Default::default(),
566 zoom_out_on_close: true,
567 diagnostic_summary_update: Task::ready(()),
568 project_item_restoration_data: HashMap::default(),
569 welcome_page: None,
570 in_center_group: false,
571 is_upper_left: false,
572 is_upper_right: false,
573 }
574 }
575
576 fn alternate_file(&mut self, _: &AlternateFile, window: &mut Window, cx: &mut Context<Pane>) {
577 let (_, alternative) = &self.alternate_file_items;
578 if let Some(alternative) = alternative {
579 let existing = self
580 .items()
581 .find_position(|item| item.item_id() == alternative.id());
582 if let Some((ix, _)) = existing {
583 self.activate_item(ix, true, true, window, cx);
584 } else if let Some(upgraded) = alternative.upgrade() {
585 self.add_item(upgraded, true, true, None, window, cx);
586 }
587 }
588 }
589
590 pub fn track_alternate_file_items(&mut self) {
591 if let Some(item) = self.active_item().map(|item| item.downgrade_item()) {
592 let (current, _) = &self.alternate_file_items;
593 match current {
594 Some(current) => {
595 if current.id() != item.id() {
596 self.alternate_file_items =
597 (Some(item), self.alternate_file_items.0.take());
598 }
599 }
600 None => {
601 self.alternate_file_items = (Some(item), None);
602 }
603 }
604 }
605 }
606
607 pub fn has_focus(&self, window: &Window, cx: &App) -> bool {
608 // We not only check whether our focus handle contains focus, but also
609 // whether the active item might have focus, because we might have just activated an item
610 // that hasn't rendered yet.
611 // Before the next render, we might transfer focus
612 // to the item, and `focus_handle.contains_focus` returns false because the `active_item`
613 // is not hooked up to us in the dispatch tree.
614 self.focus_handle.contains_focused(window, cx)
615 || self
616 .active_item()
617 .is_some_and(|item| item.item_focus_handle(cx).contains_focused(window, cx))
618 }
619
620 fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
621 if !self.was_focused {
622 self.was_focused = true;
623 self.update_history(self.active_item_index);
624 if !self.suppress_scroll && self.items.get(self.active_item_index).is_some() {
625 self.update_active_tab(self.active_item_index);
626 }
627 cx.emit(Event::Focus);
628 cx.notify();
629 }
630
631 self.toolbar.update(cx, |toolbar, cx| {
632 toolbar.focus_changed(true, window, cx);
633 });
634
635 if let Some(active_item) = self.active_item() {
636 if self.focus_handle.is_focused(window) {
637 // Schedule a redraw next frame, so that the focus changes below take effect
638 cx.on_next_frame(window, |_, _, cx| {
639 cx.notify();
640 });
641
642 // Pane was focused directly. We need to either focus a view inside the active item,
643 // or focus the active item itself
644 if let Some(weak_last_focus_handle) =
645 self.last_focus_handle_by_item.get(&active_item.item_id())
646 && let Some(focus_handle) = weak_last_focus_handle.upgrade()
647 {
648 focus_handle.focus(window, cx);
649 return;
650 }
651
652 active_item.item_focus_handle(cx).focus(window, cx);
653 } else if let Some(focused) = window.focused(cx)
654 && !self.context_menu_focused(window, cx)
655 {
656 self.last_focus_handle_by_item
657 .insert(active_item.item_id(), focused.downgrade());
658 }
659 } else if let Some(welcome_page) = self.welcome_page.as_ref() {
660 if self.focus_handle.is_focused(window) {
661 welcome_page.read(cx).focus_handle(cx).focus(window, cx);
662 }
663 }
664 }
665
666 pub fn context_menu_focused(&self, window: &mut Window, cx: &mut Context<Self>) -> bool {
667 self.new_item_context_menu_handle.is_focused(window, cx)
668 || self.split_item_context_menu_handle.is_focused(window, cx)
669 }
670
671 fn focus_out(&mut self, _event: FocusOutEvent, window: &mut Window, cx: &mut Context<Self>) {
672 self.was_focused = false;
673 self.toolbar.update(cx, |toolbar, cx| {
674 toolbar.focus_changed(false, window, cx);
675 });
676
677 cx.notify();
678 }
679
680 fn project_events(
681 &mut self,
682 _project: Entity<Project>,
683 event: &project::Event,
684 cx: &mut Context<Self>,
685 ) {
686 match event {
687 project::Event::DiskBasedDiagnosticsFinished { .. }
688 | project::Event::DiagnosticsUpdated { .. } => {
689 if ItemSettings::get_global(cx).show_diagnostics != ShowDiagnostics::Off {
690 self.diagnostic_summary_update = cx.spawn(async move |this, cx| {
691 cx.background_executor()
692 .timer(Duration::from_millis(30))
693 .await;
694 this.update(cx, |this, cx| {
695 this.update_diagnostics(cx);
696 cx.notify();
697 })
698 .log_err();
699 });
700 }
701 }
702 _ => {}
703 }
704 }
705
706 fn update_diagnostics(&mut self, cx: &mut Context<Self>) {
707 let Some(project) = self.project.upgrade() else {
708 return;
709 };
710 let show_diagnostics = ItemSettings::get_global(cx).show_diagnostics;
711 self.diagnostics = if show_diagnostics != ShowDiagnostics::Off {
712 project
713 .read(cx)
714 .diagnostic_summaries(false, cx)
715 .filter_map(|(project_path, _, diagnostic_summary)| {
716 if diagnostic_summary.error_count > 0 {
717 Some((project_path, DiagnosticSeverity::ERROR))
718 } else if diagnostic_summary.warning_count > 0
719 && show_diagnostics != ShowDiagnostics::Errors
720 {
721 Some((project_path, DiagnosticSeverity::WARNING))
722 } else {
723 None
724 }
725 })
726 .collect()
727 } else {
728 HashMap::default()
729 }
730 }
731
732 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
733 let tab_bar_settings = TabBarSettings::get_global(cx);
734 let new_max_tabs = WorkspaceSettings::get_global(cx).max_tabs;
735
736 if let Some(display_nav_history_buttons) = self.display_nav_history_buttons.as_mut() {
737 *display_nav_history_buttons = tab_bar_settings.show_nav_history_buttons;
738 }
739
740 self.show_tab_bar_buttons = tab_bar_settings.show_tab_bar_buttons;
741
742 if !PreviewTabsSettings::get_global(cx).enabled {
743 self.preview_item_id = None;
744 }
745
746 if self.use_max_tabs && new_max_tabs != self.max_tabs {
747 self.max_tabs = new_max_tabs;
748 self.close_items_on_settings_change(window, cx);
749 }
750
751 self.update_diagnostics(cx);
752 cx.notify();
753 }
754
755 pub fn active_item_index(&self) -> usize {
756 self.active_item_index
757 }
758
759 pub fn activation_history(&self) -> &[ActivationHistoryEntry] {
760 &self.activation_history
761 }
762
763 pub fn set_should_display_tab_bar<F>(&mut self, should_display_tab_bar: F)
764 where
765 F: 'static + Fn(&Window, &mut Context<Pane>) -> bool,
766 {
767 self.should_display_tab_bar = Rc::new(should_display_tab_bar);
768 }
769
770 pub fn set_can_split(
771 &mut self,
772 can_split_predicate: Option<
773 Arc<dyn Fn(&mut Self, &dyn Any, &mut Window, &mut Context<Self>) -> bool + 'static>,
774 >,
775 ) {
776 self.can_split_predicate = can_split_predicate;
777 }
778
779 pub fn set_can_toggle_zoom(&mut self, can_toggle_zoom: bool, cx: &mut Context<Self>) {
780 self.can_toggle_zoom = can_toggle_zoom;
781 cx.notify();
782 }
783
784 pub fn set_close_pane_if_empty(&mut self, close_pane_if_empty: bool, cx: &mut Context<Self>) {
785 self.close_pane_if_empty = close_pane_if_empty;
786 cx.notify();
787 }
788
789 pub fn set_can_navigate(&mut self, can_navigate: bool, cx: &mut Context<Self>) {
790 self.toolbar.update(cx, |toolbar, cx| {
791 toolbar.set_can_navigate(can_navigate, cx);
792 });
793 cx.notify();
794 }
795
796 pub fn set_render_tab_bar<F>(&mut self, cx: &mut Context<Self>, render: F)
797 where
798 F: 'static + Fn(&mut Pane, &mut Window, &mut Context<Pane>) -> AnyElement,
799 {
800 self.render_tab_bar = Rc::new(render);
801 cx.notify();
802 }
803
804 pub fn set_render_tab_bar_buttons<F>(&mut self, cx: &mut Context<Self>, render: F)
805 where
806 F: 'static
807 + Fn(
808 &mut Pane,
809 &mut Window,
810 &mut Context<Pane>,
811 ) -> (Option<AnyElement>, Option<AnyElement>),
812 {
813 self.render_tab_bar_buttons = Rc::new(render);
814 cx.notify();
815 }
816
817 pub fn set_custom_drop_handle<F>(&mut self, cx: &mut Context<Self>, handle: F)
818 where
819 F: 'static
820 + Fn(&mut Pane, &dyn Any, &mut Window, &mut Context<Pane>) -> ControlFlow<(), ()>,
821 {
822 self.custom_drop_handle = Some(Arc::new(handle));
823 cx.notify();
824 }
825
826 pub fn nav_history_for_item<T: Item>(&self, item: &Entity<T>) -> ItemNavHistory {
827 ItemNavHistory {
828 history: self.nav_history.clone(),
829 item: Arc::new(item.downgrade()),
830 is_preview: self.preview_item_id == Some(item.item_id()),
831 }
832 }
833
834 pub fn nav_history(&self) -> &NavHistory {
835 &self.nav_history
836 }
837
838 pub fn nav_history_mut(&mut self) -> &mut NavHistory {
839 &mut self.nav_history
840 }
841
842 pub fn disable_history(&mut self) {
843 self.nav_history.disable();
844 }
845
846 pub fn enable_history(&mut self) {
847 self.nav_history.enable();
848 }
849
850 pub fn can_navigate_backward(&self) -> bool {
851 !self.nav_history.0.lock().backward_stack.is_empty()
852 }
853
854 pub fn can_navigate_forward(&self) -> bool {
855 !self.nav_history.0.lock().forward_stack.is_empty()
856 }
857
858 pub fn navigate_backward(&mut self, _: &GoBack, window: &mut Window, cx: &mut Context<Self>) {
859 if let Some(workspace) = self.workspace.upgrade() {
860 let pane = cx.entity().downgrade();
861 window.defer(cx, move |window, cx| {
862 workspace.update(cx, |workspace, cx| {
863 workspace.go_back(pane, window, cx).detach_and_log_err(cx)
864 })
865 })
866 }
867 }
868
869 fn navigate_forward(&mut self, _: &GoForward, window: &mut Window, cx: &mut Context<Self>) {
870 if let Some(workspace) = self.workspace.upgrade() {
871 let pane = cx.entity().downgrade();
872 window.defer(cx, move |window, cx| {
873 workspace.update(cx, |workspace, cx| {
874 workspace
875 .go_forward(pane, window, cx)
876 .detach_and_log_err(cx)
877 })
878 })
879 }
880 }
881
882 fn history_updated(&mut self, cx: &mut Context<Self>) {
883 self.toolbar.update(cx, |_, cx| cx.notify());
884 }
885
886 pub fn preview_item_id(&self) -> Option<EntityId> {
887 self.preview_item_id
888 }
889
890 pub fn preview_item(&self) -> Option<Box<dyn ItemHandle>> {
891 self.preview_item_id
892 .and_then(|id| self.items.iter().find(|item| item.item_id() == id))
893 .cloned()
894 }
895
896 pub fn preview_item_idx(&self) -> Option<usize> {
897 if let Some(preview_item_id) = self.preview_item_id {
898 self.items
899 .iter()
900 .position(|item| item.item_id() == preview_item_id)
901 } else {
902 None
903 }
904 }
905
906 pub fn is_active_preview_item(&self, item_id: EntityId) -> bool {
907 self.preview_item_id == Some(item_id)
908 }
909
910 /// Promotes the item with the given ID to not be a preview item.
911 /// This does nothing if it wasn't already a preview item.
912 pub fn unpreview_item_if_preview(&mut self, item_id: EntityId) {
913 if self.is_active_preview_item(item_id) {
914 self.preview_item_id = None;
915 }
916 }
917
918 /// Marks the item with the given ID as the preview item.
919 /// This will be ignored if the global setting `preview_tabs` is disabled.
920 ///
921 /// The old preview item (if there was one) is closed and its index is returned.
922 pub fn replace_preview_item_id(
923 &mut self,
924 item_id: EntityId,
925 window: &mut Window,
926 cx: &mut Context<Self>,
927 ) -> Option<usize> {
928 let idx = self.close_current_preview_item(window, cx);
929 self.set_preview_item_id(Some(item_id), cx);
930 idx
931 }
932
933 /// Marks the item with the given ID as the preview item.
934 /// This will be ignored if the global setting `preview_tabs` is disabled.
935 ///
936 /// This is a low-level method. Prefer `unpreview_item_if_preview()` or `set_new_preview_item()`.
937 pub(crate) fn set_preview_item_id(&mut self, item_id: Option<EntityId>, cx: &App) {
938 if item_id.is_none() || PreviewTabsSettings::get_global(cx).enabled {
939 self.preview_item_id = item_id;
940 }
941 }
942
943 /// Should only be used when deserializing a pane.
944 pub fn set_pinned_count(&mut self, count: usize) {
945 self.pinned_tab_count = count;
946 }
947
948 pub fn pinned_count(&self) -> usize {
949 self.pinned_tab_count
950 }
951
952 pub fn handle_item_edit(&mut self, item_id: EntityId, cx: &App) {
953 if let Some(preview_item) = self.preview_item()
954 && preview_item.item_id() == item_id
955 && !preview_item.preserve_preview(cx)
956 {
957 self.unpreview_item_if_preview(item_id);
958 }
959 }
960
961 pub(crate) fn open_item(
962 &mut self,
963 project_entry_id: Option<ProjectEntryId>,
964 project_path: ProjectPath,
965 focus_item: bool,
966 allow_preview: bool,
967 activate: bool,
968 suggested_position: Option<usize>,
969 window: &mut Window,
970 cx: &mut Context<Self>,
971 build_item: WorkspaceItemBuilder,
972 ) -> Box<dyn ItemHandle> {
973 let mut existing_item = None;
974 if let Some(project_entry_id) = project_entry_id {
975 for (index, item) in self.items.iter().enumerate() {
976 if item.buffer_kind(cx) == ItemBufferKind::Singleton
977 && item.project_entry_ids(cx).as_slice() == [project_entry_id]
978 {
979 let item = item.boxed_clone();
980 existing_item = Some((index, item));
981 break;
982 }
983 }
984 } else {
985 for (index, item) in self.items.iter().enumerate() {
986 if item.buffer_kind(cx) == ItemBufferKind::Singleton
987 && item.project_path(cx).as_ref() == Some(&project_path)
988 {
989 let item = item.boxed_clone();
990 existing_item = Some((index, item));
991 break;
992 }
993 }
994 }
995
996 let set_up_existing_item =
997 |index: usize, pane: &mut Self, window: &mut Window, cx: &mut Context<Self>| {
998 if !allow_preview && let Some(item) = pane.items.get(index) {
999 pane.unpreview_item_if_preview(item.item_id());
1000 }
1001 if activate {
1002 pane.activate_item(index, focus_item, focus_item, window, cx);
1003 }
1004 };
1005 let set_up_new_item = |new_item: Box<dyn ItemHandle>,
1006 destination_index: Option<usize>,
1007 pane: &mut Self,
1008 window: &mut Window,
1009 cx: &mut Context<Self>| {
1010 if allow_preview {
1011 pane.replace_preview_item_id(new_item.item_id(), window, cx);
1012 }
1013
1014 if let Some(text) = new_item.telemetry_event_text(cx) {
1015 telemetry::event!(text);
1016 }
1017
1018 pane.add_item_inner(
1019 new_item,
1020 true,
1021 focus_item,
1022 activate,
1023 destination_index,
1024 window,
1025 cx,
1026 );
1027 };
1028
1029 if let Some((index, existing_item)) = existing_item {
1030 set_up_existing_item(index, self, window, cx);
1031 existing_item
1032 } else {
1033 // If the item is being opened as preview and we have an existing preview tab,
1034 // open the new item in the position of the existing preview tab.
1035 let destination_index = if allow_preview {
1036 self.close_current_preview_item(window, cx)
1037 } else {
1038 suggested_position
1039 };
1040
1041 let new_item = build_item(self, window, cx);
1042 // A special case that won't ever get a `project_entry_id` but has to be deduplicated nonetheless.
1043 if let Some(invalid_buffer_view) = new_item.downcast::<InvalidItemView>() {
1044 let mut already_open_view = None;
1045 let mut views_to_close = HashSet::default();
1046 for existing_error_view in self
1047 .items_of_type::<InvalidItemView>()
1048 .filter(|item| item.read(cx).abs_path == invalid_buffer_view.read(cx).abs_path)
1049 {
1050 if already_open_view.is_none()
1051 && existing_error_view.read(cx).error == invalid_buffer_view.read(cx).error
1052 {
1053 already_open_view = Some(existing_error_view);
1054 } else {
1055 views_to_close.insert(existing_error_view.item_id());
1056 }
1057 }
1058
1059 let resulting_item = match already_open_view {
1060 Some(already_open_view) => {
1061 if let Some(index) = self.index_for_item_id(already_open_view.item_id()) {
1062 set_up_existing_item(index, self, window, cx);
1063 }
1064 Box::new(already_open_view) as Box<_>
1065 }
1066 None => {
1067 set_up_new_item(new_item.clone(), destination_index, self, window, cx);
1068 new_item
1069 }
1070 };
1071
1072 self.close_items(window, cx, SaveIntent::Skip, |existing_item| {
1073 views_to_close.contains(&existing_item)
1074 })
1075 .detach();
1076
1077 resulting_item
1078 } else {
1079 set_up_new_item(new_item.clone(), destination_index, self, window, cx);
1080 new_item
1081 }
1082 }
1083 }
1084
1085 pub fn close_current_preview_item(
1086 &mut self,
1087 window: &mut Window,
1088 cx: &mut Context<Self>,
1089 ) -> Option<usize> {
1090 let item_idx = self.preview_item_idx()?;
1091 let id = self.preview_item_id()?;
1092 self.set_preview_item_id(None, cx);
1093
1094 let prev_active_item_index = self.active_item_index;
1095 self.remove_item(id, false, false, window, cx);
1096 self.active_item_index = prev_active_item_index;
1097
1098 if item_idx < self.items.len() {
1099 Some(item_idx)
1100 } else {
1101 None
1102 }
1103 }
1104
1105 pub fn add_item_inner(
1106 &mut self,
1107 item: Box<dyn ItemHandle>,
1108 activate_pane: bool,
1109 focus_item: bool,
1110 activate: bool,
1111 destination_index: Option<usize>,
1112 window: &mut Window,
1113 cx: &mut Context<Self>,
1114 ) {
1115 let item_already_exists = self
1116 .items
1117 .iter()
1118 .any(|existing_item| existing_item.item_id() == item.item_id());
1119
1120 if !item_already_exists {
1121 self.close_items_on_item_open(window, cx);
1122 }
1123
1124 if item.buffer_kind(cx) == ItemBufferKind::Singleton
1125 && let Some(&entry_id) = item.project_entry_ids(cx).first()
1126 {
1127 let Some(project) = self.project.upgrade() else {
1128 return;
1129 };
1130
1131 let project = project.read(cx);
1132 if let Some(project_path) = project.path_for_entry(entry_id, cx) {
1133 let abs_path = project.absolute_path(&project_path, cx);
1134 self.nav_history
1135 .0
1136 .lock()
1137 .paths_by_item
1138 .insert(item.item_id(), (project_path, abs_path));
1139 }
1140 }
1141 // If no destination index is specified, add or move the item after the
1142 // active item (or at the start of tab bar, if the active item is pinned)
1143 let mut insertion_index = {
1144 cmp::min(
1145 if let Some(destination_index) = destination_index {
1146 destination_index
1147 } else {
1148 cmp::max(self.active_item_index + 1, self.pinned_count())
1149 },
1150 self.items.len(),
1151 )
1152 };
1153
1154 // Does the item already exist?
1155 let project_entry_id = if item.buffer_kind(cx) == ItemBufferKind::Singleton {
1156 item.project_entry_ids(cx).first().copied()
1157 } else {
1158 None
1159 };
1160
1161 let existing_item_index = self.items.iter().position(|existing_item| {
1162 if existing_item.item_id() == item.item_id() {
1163 true
1164 } else if existing_item.buffer_kind(cx) == ItemBufferKind::Singleton {
1165 existing_item
1166 .project_entry_ids(cx)
1167 .first()
1168 .is_some_and(|existing_entry_id| {
1169 Some(existing_entry_id) == project_entry_id.as_ref()
1170 })
1171 } else {
1172 false
1173 }
1174 });
1175 if let Some(existing_item_index) = existing_item_index {
1176 // If the item already exists, move it to the desired destination and activate it
1177
1178 if existing_item_index != insertion_index {
1179 let existing_item_is_active = existing_item_index == self.active_item_index;
1180
1181 // If the caller didn't specify a destination and the added item is already
1182 // the active one, don't move it
1183 if existing_item_is_active && destination_index.is_none() {
1184 insertion_index = existing_item_index;
1185 } else {
1186 self.items.remove(existing_item_index);
1187 if existing_item_index < self.active_item_index {
1188 self.active_item_index -= 1;
1189 }
1190 insertion_index = insertion_index.min(self.items.len());
1191
1192 self.items.insert(insertion_index, item.clone());
1193
1194 if existing_item_is_active {
1195 self.active_item_index = insertion_index;
1196 } else if insertion_index <= self.active_item_index {
1197 self.active_item_index += 1;
1198 }
1199 }
1200
1201 cx.notify();
1202 }
1203
1204 if activate {
1205 self.activate_item(insertion_index, activate_pane, focus_item, window, cx);
1206 }
1207 } else {
1208 self.items.insert(insertion_index, item.clone());
1209 cx.notify();
1210
1211 if activate {
1212 if insertion_index <= self.active_item_index
1213 && self.preview_item_idx() != Some(self.active_item_index)
1214 {
1215 self.active_item_index += 1;
1216 }
1217
1218 self.activate_item(insertion_index, activate_pane, focus_item, window, cx);
1219 }
1220 }
1221
1222 cx.emit(Event::AddItem { item });
1223 }
1224
1225 pub fn add_item(
1226 &mut self,
1227 item: Box<dyn ItemHandle>,
1228 activate_pane: bool,
1229 focus_item: bool,
1230 destination_index: Option<usize>,
1231 window: &mut Window,
1232 cx: &mut Context<Self>,
1233 ) {
1234 if let Some(text) = item.telemetry_event_text(cx) {
1235 telemetry::event!(text);
1236 }
1237
1238 self.add_item_inner(
1239 item,
1240 activate_pane,
1241 focus_item,
1242 true,
1243 destination_index,
1244 window,
1245 cx,
1246 )
1247 }
1248
1249 pub fn items_len(&self) -> usize {
1250 self.items.len()
1251 }
1252
1253 pub fn items(&self) -> impl DoubleEndedIterator<Item = &Box<dyn ItemHandle>> {
1254 self.items.iter()
1255 }
1256
1257 pub fn items_of_type<T: Render>(&self) -> impl '_ + Iterator<Item = Entity<T>> {
1258 self.items
1259 .iter()
1260 .filter_map(|item| item.to_any_view().downcast().ok())
1261 }
1262
1263 pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
1264 self.items.get(self.active_item_index).cloned()
1265 }
1266
1267 fn active_item_id(&self) -> EntityId {
1268 self.items[self.active_item_index].item_id()
1269 }
1270
1271 pub fn pixel_position_of_cursor(&self, cx: &App) -> Option<Point<Pixels>> {
1272 self.items
1273 .get(self.active_item_index)?
1274 .pixel_position_of_cursor(cx)
1275 }
1276
1277 pub fn item_for_entry(
1278 &self,
1279 entry_id: ProjectEntryId,
1280 cx: &App,
1281 ) -> Option<Box<dyn ItemHandle>> {
1282 self.items.iter().find_map(|item| {
1283 if item.buffer_kind(cx) == ItemBufferKind::Singleton
1284 && (item.project_entry_ids(cx).as_slice() == [entry_id])
1285 {
1286 Some(item.boxed_clone())
1287 } else {
1288 None
1289 }
1290 })
1291 }
1292
1293 pub fn item_for_path(
1294 &self,
1295 project_path: ProjectPath,
1296 cx: &App,
1297 ) -> Option<Box<dyn ItemHandle>> {
1298 self.items.iter().find_map(move |item| {
1299 if item.buffer_kind(cx) == ItemBufferKind::Singleton
1300 && (item.project_path(cx).as_slice() == [project_path.clone()])
1301 {
1302 Some(item.boxed_clone())
1303 } else {
1304 None
1305 }
1306 })
1307 }
1308
1309 pub fn index_for_item(&self, item: &dyn ItemHandle) -> Option<usize> {
1310 self.index_for_item_id(item.item_id())
1311 }
1312
1313 fn index_for_item_id(&self, item_id: EntityId) -> Option<usize> {
1314 self.items.iter().position(|i| i.item_id() == item_id)
1315 }
1316
1317 pub fn item_for_index(&self, ix: usize) -> Option<&dyn ItemHandle> {
1318 self.items.get(ix).map(|i| i.as_ref())
1319 }
1320
1321 pub fn toggle_zoom(&mut self, _: &ToggleZoom, window: &mut Window, cx: &mut Context<Self>) {
1322 if !self.can_toggle_zoom {
1323 cx.propagate();
1324 } else if self.zoomed {
1325 cx.emit(Event::ZoomOut);
1326 } else if !self.items.is_empty() {
1327 if !self.focus_handle.contains_focused(window, cx) {
1328 cx.focus_self(window);
1329 }
1330 cx.emit(Event::ZoomIn);
1331 }
1332 }
1333
1334 pub fn zoom_in(&mut self, _: &ZoomIn, window: &mut Window, cx: &mut Context<Self>) {
1335 if !self.can_toggle_zoom {
1336 cx.propagate();
1337 } else if !self.zoomed && !self.items.is_empty() {
1338 if !self.focus_handle.contains_focused(window, cx) {
1339 cx.focus_self(window);
1340 }
1341 cx.emit(Event::ZoomIn);
1342 }
1343 }
1344
1345 pub fn zoom_out(&mut self, _: &ZoomOut, _window: &mut Window, cx: &mut Context<Self>) {
1346 if !self.can_toggle_zoom {
1347 cx.propagate();
1348 } else if self.zoomed {
1349 cx.emit(Event::ZoomOut);
1350 }
1351 }
1352
1353 pub fn activate_item(
1354 &mut self,
1355 index: usize,
1356 activate_pane: bool,
1357 focus_item: bool,
1358 window: &mut Window,
1359 cx: &mut Context<Self>,
1360 ) {
1361 use NavigationMode::{GoingBack, GoingForward};
1362 if index < self.items.len() {
1363 let prev_active_item_ix = mem::replace(&mut self.active_item_index, index);
1364 if (prev_active_item_ix != self.active_item_index
1365 || matches!(self.nav_history.mode(), GoingBack | GoingForward))
1366 && let Some(prev_item) = self.items.get(prev_active_item_ix)
1367 {
1368 prev_item.deactivated(window, cx);
1369 }
1370 self.update_history(index);
1371 self.update_toolbar(window, cx);
1372 self.update_status_bar(window, cx);
1373
1374 if focus_item {
1375 self.focus_active_item(window, cx);
1376 }
1377
1378 cx.emit(Event::ActivateItem {
1379 local: activate_pane,
1380 focus_changed: focus_item,
1381 });
1382
1383 self.update_active_tab(index);
1384 cx.notify();
1385 }
1386 }
1387
1388 fn update_active_tab(&mut self, index: usize) {
1389 if !self.is_tab_pinned(index) {
1390 self.suppress_scroll = false;
1391 self.tab_bar_scroll_handle.scroll_to_item(index);
1392 }
1393 }
1394
1395 fn update_history(&mut self, index: usize) {
1396 if let Some(newly_active_item) = self.items.get(index) {
1397 self.activation_history
1398 .retain(|entry| entry.entity_id != newly_active_item.item_id());
1399 self.activation_history.push(ActivationHistoryEntry {
1400 entity_id: newly_active_item.item_id(),
1401 timestamp: self
1402 .next_activation_timestamp
1403 .fetch_add(1, Ordering::SeqCst),
1404 });
1405 }
1406 }
1407
1408 pub fn activate_previous_item(
1409 &mut self,
1410 _: &ActivatePreviousItem,
1411 window: &mut Window,
1412 cx: &mut Context<Self>,
1413 ) {
1414 let mut index = self.active_item_index;
1415 if index > 0 {
1416 index -= 1;
1417 } else if !self.items.is_empty() {
1418 index = self.items.len() - 1;
1419 }
1420 self.activate_item(index, true, true, window, cx);
1421 }
1422
1423 pub fn activate_next_item(
1424 &mut self,
1425 _: &ActivateNextItem,
1426 window: &mut Window,
1427 cx: &mut Context<Self>,
1428 ) {
1429 let mut index = self.active_item_index;
1430 if index + 1 < self.items.len() {
1431 index += 1;
1432 } else {
1433 index = 0;
1434 }
1435 self.activate_item(index, true, true, window, cx);
1436 }
1437
1438 pub fn swap_item_left(
1439 &mut self,
1440 _: &SwapItemLeft,
1441 window: &mut Window,
1442 cx: &mut Context<Self>,
1443 ) {
1444 let index = self.active_item_index;
1445 if index == 0 {
1446 return;
1447 }
1448
1449 self.items.swap(index, index - 1);
1450 self.activate_item(index - 1, true, true, window, cx);
1451 }
1452
1453 pub fn swap_item_right(
1454 &mut self,
1455 _: &SwapItemRight,
1456 window: &mut Window,
1457 cx: &mut Context<Self>,
1458 ) {
1459 let index = self.active_item_index;
1460 if index + 1 >= self.items.len() {
1461 return;
1462 }
1463
1464 self.items.swap(index, index + 1);
1465 self.activate_item(index + 1, true, true, window, cx);
1466 }
1467
1468 pub fn activate_last_item(
1469 &mut self,
1470 _: &ActivateLastItem,
1471 window: &mut Window,
1472 cx: &mut Context<Self>,
1473 ) {
1474 let index = self.items.len().saturating_sub(1);
1475 self.activate_item(index, true, true, window, cx);
1476 }
1477
1478 pub fn close_active_item(
1479 &mut self,
1480 action: &CloseActiveItem,
1481 window: &mut Window,
1482 cx: &mut Context<Self>,
1483 ) -> Task<Result<()>> {
1484 if self.items.is_empty() {
1485 // Close the window when there's no active items to close, if configured
1486 if WorkspaceSettings::get_global(cx)
1487 .when_closing_with_no_tabs
1488 .should_close()
1489 {
1490 window.dispatch_action(Box::new(CloseWindow), cx);
1491 }
1492
1493 return Task::ready(Ok(()));
1494 }
1495 if self.is_tab_pinned(self.active_item_index) && !action.close_pinned {
1496 // Activate any non-pinned tab in same pane
1497 let non_pinned_tab_index = self
1498 .items()
1499 .enumerate()
1500 .find(|(index, _item)| !self.is_tab_pinned(*index))
1501 .map(|(index, _item)| index);
1502 if let Some(index) = non_pinned_tab_index {
1503 self.activate_item(index, false, false, window, cx);
1504 return Task::ready(Ok(()));
1505 }
1506
1507 // Activate any non-pinned tab in different pane
1508 let current_pane = cx.entity();
1509 self.workspace
1510 .update(cx, |workspace, cx| {
1511 let panes = workspace.center.panes();
1512 let pane_with_unpinned_tab = panes.iter().find(|pane| {
1513 if **pane == ¤t_pane {
1514 return false;
1515 }
1516 pane.read(cx).has_unpinned_tabs()
1517 });
1518 if let Some(pane) = pane_with_unpinned_tab {
1519 pane.update(cx, |pane, cx| pane.activate_unpinned_tab(window, cx));
1520 }
1521 })
1522 .ok();
1523
1524 return Task::ready(Ok(()));
1525 };
1526
1527 let active_item_id = self.active_item_id();
1528
1529 self.close_item_by_id(
1530 active_item_id,
1531 action.save_intent.unwrap_or(SaveIntent::Close),
1532 window,
1533 cx,
1534 )
1535 }
1536
1537 pub fn close_item_by_id(
1538 &mut self,
1539 item_id_to_close: EntityId,
1540 save_intent: SaveIntent,
1541 window: &mut Window,
1542 cx: &mut Context<Self>,
1543 ) -> Task<Result<()>> {
1544 self.close_items(window, cx, save_intent, move |view_id| {
1545 view_id == item_id_to_close
1546 })
1547 }
1548
1549 pub fn close_other_items(
1550 &mut self,
1551 action: &CloseOtherItems,
1552 target_item_id: Option<EntityId>,
1553 window: &mut Window,
1554 cx: &mut Context<Self>,
1555 ) -> Task<Result<()>> {
1556 if self.items.is_empty() {
1557 return Task::ready(Ok(()));
1558 }
1559
1560 let active_item_id = match target_item_id {
1561 Some(result) => result,
1562 None => self.active_item_id(),
1563 };
1564
1565 let pinned_item_ids = self.pinned_item_ids();
1566
1567 self.close_items(
1568 window,
1569 cx,
1570 action.save_intent.unwrap_or(SaveIntent::Close),
1571 move |item_id| {
1572 item_id != active_item_id
1573 && (action.close_pinned || !pinned_item_ids.contains(&item_id))
1574 },
1575 )
1576 }
1577
1578 pub fn close_multibuffer_items(
1579 &mut self,
1580 action: &CloseMultibufferItems,
1581 window: &mut Window,
1582 cx: &mut Context<Self>,
1583 ) -> Task<Result<()>> {
1584 if self.items.is_empty() {
1585 return Task::ready(Ok(()));
1586 }
1587
1588 let pinned_item_ids = self.pinned_item_ids();
1589 let multibuffer_items = self.multibuffer_item_ids(cx);
1590
1591 self.close_items(
1592 window,
1593 cx,
1594 action.save_intent.unwrap_or(SaveIntent::Close),
1595 move |item_id| {
1596 (action.close_pinned || !pinned_item_ids.contains(&item_id))
1597 && multibuffer_items.contains(&item_id)
1598 },
1599 )
1600 }
1601
1602 pub fn close_clean_items(
1603 &mut self,
1604 action: &CloseCleanItems,
1605 window: &mut Window,
1606 cx: &mut Context<Self>,
1607 ) -> Task<Result<()>> {
1608 if self.items.is_empty() {
1609 return Task::ready(Ok(()));
1610 }
1611
1612 let clean_item_ids = self.clean_item_ids(cx);
1613 let pinned_item_ids = self.pinned_item_ids();
1614
1615 self.close_items(window, cx, SaveIntent::Close, move |item_id| {
1616 clean_item_ids.contains(&item_id)
1617 && (action.close_pinned || !pinned_item_ids.contains(&item_id))
1618 })
1619 }
1620
1621 pub fn close_items_to_the_left_by_id(
1622 &mut self,
1623 item_id: Option<EntityId>,
1624 action: &CloseItemsToTheLeft,
1625 window: &mut Window,
1626 cx: &mut Context<Self>,
1627 ) -> Task<Result<()>> {
1628 self.close_items_to_the_side_by_id(item_id, Side::Left, action.close_pinned, window, cx)
1629 }
1630
1631 pub fn close_items_to_the_right_by_id(
1632 &mut self,
1633 item_id: Option<EntityId>,
1634 action: &CloseItemsToTheRight,
1635 window: &mut Window,
1636 cx: &mut Context<Self>,
1637 ) -> Task<Result<()>> {
1638 self.close_items_to_the_side_by_id(item_id, Side::Right, action.close_pinned, window, cx)
1639 }
1640
1641 pub fn close_items_to_the_side_by_id(
1642 &mut self,
1643 item_id: Option<EntityId>,
1644 side: Side,
1645 close_pinned: bool,
1646 window: &mut Window,
1647 cx: &mut Context<Self>,
1648 ) -> Task<Result<()>> {
1649 if self.items.is_empty() {
1650 return Task::ready(Ok(()));
1651 }
1652
1653 let item_id = item_id.unwrap_or_else(|| self.active_item_id());
1654 let to_the_side_item_ids = self.to_the_side_item_ids(item_id, side);
1655 let pinned_item_ids = self.pinned_item_ids();
1656
1657 self.close_items(window, cx, SaveIntent::Close, move |item_id| {
1658 to_the_side_item_ids.contains(&item_id)
1659 && (close_pinned || !pinned_item_ids.contains(&item_id))
1660 })
1661 }
1662
1663 pub fn close_all_items(
1664 &mut self,
1665 action: &CloseAllItems,
1666 window: &mut Window,
1667 cx: &mut Context<Self>,
1668 ) -> Task<Result<()>> {
1669 if self.items.is_empty() {
1670 return Task::ready(Ok(()));
1671 }
1672
1673 let pinned_item_ids = self.pinned_item_ids();
1674
1675 self.close_items(
1676 window,
1677 cx,
1678 action.save_intent.unwrap_or(SaveIntent::Close),
1679 |item_id| action.close_pinned || !pinned_item_ids.contains(&item_id),
1680 )
1681 }
1682
1683 fn close_items_on_item_open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1684 let target = self.max_tabs.map(|m| m.get());
1685 let protect_active_item = false;
1686 self.close_items_to_target_count(target, protect_active_item, window, cx);
1687 }
1688
1689 fn close_items_on_settings_change(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1690 let target = self.max_tabs.map(|m| m.get() + 1);
1691 // The active item in this case is the settings.json file, which should be protected from being closed
1692 let protect_active_item = true;
1693 self.close_items_to_target_count(target, protect_active_item, window, cx);
1694 }
1695
1696 fn close_items_to_target_count(
1697 &mut self,
1698 target_count: Option<usize>,
1699 protect_active_item: bool,
1700 window: &mut Window,
1701 cx: &mut Context<Self>,
1702 ) {
1703 let Some(target_count) = target_count else {
1704 return;
1705 };
1706
1707 let mut index_list = Vec::new();
1708 let mut items_len = self.items_len();
1709 let mut indexes: HashMap<EntityId, usize> = HashMap::default();
1710 let active_ix = self.active_item_index();
1711
1712 for (index, item) in self.items.iter().enumerate() {
1713 indexes.insert(item.item_id(), index);
1714 }
1715
1716 // Close least recently used items to reach target count.
1717 // The target count is allowed to be exceeded, as we protect pinned
1718 // items, dirty items, and sometimes, the active item.
1719 for entry in self.activation_history.iter() {
1720 if items_len < target_count {
1721 break;
1722 }
1723
1724 let Some(&index) = indexes.get(&entry.entity_id) else {
1725 continue;
1726 };
1727
1728 if protect_active_item && index == active_ix {
1729 continue;
1730 }
1731
1732 if let Some(true) = self.items.get(index).map(|item| item.is_dirty(cx)) {
1733 continue;
1734 }
1735
1736 if self.is_tab_pinned(index) {
1737 continue;
1738 }
1739
1740 index_list.push(index);
1741 items_len -= 1;
1742 }
1743 // The sort and reverse is necessary since we remove items
1744 // using their index position, hence removing from the end
1745 // of the list first to avoid changing indexes.
1746 index_list.sort_unstable();
1747 index_list
1748 .iter()
1749 .rev()
1750 .for_each(|&index| self._remove_item(index, false, false, None, window, cx));
1751 }
1752
1753 // Usually when you close an item that has unsaved changes, we prompt you to
1754 // save it. That said, if you still have the buffer open in a different pane
1755 // we can close this one without fear of losing data.
1756 pub fn skip_save_on_close(item: &dyn ItemHandle, workspace: &Workspace, cx: &App) -> bool {
1757 let mut dirty_project_item_ids = Vec::new();
1758 item.for_each_project_item(cx, &mut |project_item_id, project_item| {
1759 if project_item.is_dirty() {
1760 dirty_project_item_ids.push(project_item_id);
1761 }
1762 });
1763 if dirty_project_item_ids.is_empty() {
1764 return !(item.buffer_kind(cx) == ItemBufferKind::Singleton && item.is_dirty(cx));
1765 }
1766
1767 for open_item in workspace.items(cx) {
1768 if open_item.item_id() == item.item_id() {
1769 continue;
1770 }
1771 if open_item.buffer_kind(cx) != ItemBufferKind::Singleton {
1772 continue;
1773 }
1774 let other_project_item_ids = open_item.project_item_model_ids(cx);
1775 dirty_project_item_ids.retain(|id| !other_project_item_ids.contains(id));
1776 }
1777 dirty_project_item_ids.is_empty()
1778 }
1779
1780 pub(super) fn file_names_for_prompt(
1781 items: &mut dyn Iterator<Item = &Box<dyn ItemHandle>>,
1782 cx: &App,
1783 ) -> String {
1784 let mut file_names = BTreeSet::default();
1785 for item in items {
1786 item.for_each_project_item(cx, &mut |_, project_item| {
1787 if !project_item.is_dirty() {
1788 return;
1789 }
1790 let filename = project_item
1791 .project_path(cx)
1792 .and_then(|path| path.path.file_name().map(ToOwned::to_owned));
1793 file_names.insert(filename.unwrap_or("untitled".to_string()));
1794 });
1795 }
1796 if file_names.len() > 6 {
1797 format!(
1798 "{}\n.. and {} more",
1799 file_names.iter().take(5).join("\n"),
1800 file_names.len() - 5
1801 )
1802 } else {
1803 file_names.into_iter().join("\n")
1804 }
1805 }
1806
1807 pub fn close_items(
1808 &self,
1809 window: &mut Window,
1810 cx: &mut Context<Pane>,
1811 mut save_intent: SaveIntent,
1812 should_close: impl Fn(EntityId) -> bool,
1813 ) -> Task<Result<()>> {
1814 // Find the items to close.
1815 let mut items_to_close = Vec::new();
1816 for item in &self.items {
1817 if should_close(item.item_id()) {
1818 items_to_close.push(item.boxed_clone());
1819 }
1820 }
1821
1822 let active_item_id = self.active_item().map(|item| item.item_id());
1823
1824 items_to_close.sort_by_key(|item| {
1825 let path = item.project_path(cx);
1826 // Put the currently active item at the end, because if the currently active item is not closed last
1827 // closing the currently active item will cause the focus to switch to another item
1828 // This will cause Zed to expand the content of the currently active item
1829 //
1830 // Beyond that sort in order of project path, with untitled files and multibuffers coming last.
1831 (active_item_id == Some(item.item_id()), path.is_none(), path)
1832 });
1833
1834 let workspace = self.workspace.clone();
1835 let Some(project) = self.project.upgrade() else {
1836 return Task::ready(Ok(()));
1837 };
1838 cx.spawn_in(window, async move |pane, cx| {
1839 let dirty_items = workspace.update(cx, |workspace, cx| {
1840 items_to_close
1841 .iter()
1842 .filter(|item| {
1843 item.is_dirty(cx) && !Self::skip_save_on_close(item.as_ref(), workspace, cx)
1844 })
1845 .map(|item| item.boxed_clone())
1846 .collect::<Vec<_>>()
1847 })?;
1848
1849 if save_intent == SaveIntent::Close && dirty_items.len() > 1 {
1850 let answer = pane.update_in(cx, |_, window, cx| {
1851 let detail = Self::file_names_for_prompt(&mut dirty_items.iter(), cx);
1852 window.prompt(
1853 PromptLevel::Warning,
1854 "Do you want to save changes to the following files?",
1855 Some(&detail),
1856 &["Save all", "Discard all", "Cancel"],
1857 cx,
1858 )
1859 })?;
1860 match answer.await {
1861 Ok(0) => save_intent = SaveIntent::SaveAll,
1862 Ok(1) => save_intent = SaveIntent::Skip,
1863 Ok(2) => return Ok(()),
1864 _ => {}
1865 }
1866 }
1867
1868 for item_to_close in items_to_close {
1869 let mut should_close = true;
1870 let mut should_save = true;
1871 if save_intent == SaveIntent::Close {
1872 workspace.update(cx, |workspace, cx| {
1873 if Self::skip_save_on_close(item_to_close.as_ref(), workspace, cx) {
1874 should_save = false;
1875 }
1876 })?;
1877 }
1878
1879 if should_save {
1880 match Self::save_item(project.clone(), &pane, &*item_to_close, save_intent, cx)
1881 .await
1882 {
1883 Ok(success) => {
1884 if !success {
1885 should_close = false;
1886 }
1887 }
1888 Err(err) => {
1889 let answer = pane.update_in(cx, |_, window, cx| {
1890 let detail = Self::file_names_for_prompt(
1891 &mut [&item_to_close].into_iter(),
1892 cx,
1893 );
1894 window.prompt(
1895 PromptLevel::Warning,
1896 &format!("Unable to save file: {}", &err),
1897 Some(&detail),
1898 &["Close Without Saving", "Cancel"],
1899 cx,
1900 )
1901 })?;
1902 match answer.await {
1903 Ok(0) => {}
1904 Ok(1..) | Err(_) => should_close = false,
1905 }
1906 }
1907 }
1908 }
1909
1910 // Remove the item from the pane.
1911 if should_close {
1912 pane.update_in(cx, |pane, window, cx| {
1913 pane.remove_item(
1914 item_to_close.item_id(),
1915 false,
1916 pane.close_pane_if_empty,
1917 window,
1918 cx,
1919 );
1920 })
1921 .ok();
1922 }
1923 }
1924
1925 pane.update(cx, |_, cx| cx.notify()).ok();
1926 Ok(())
1927 })
1928 }
1929
1930 pub fn take_active_item(
1931 &mut self,
1932 window: &mut Window,
1933 cx: &mut Context<Self>,
1934 ) -> Option<Box<dyn ItemHandle>> {
1935 let item = self.active_item()?;
1936 self.remove_item(item.item_id(), false, false, window, cx);
1937 Some(item)
1938 }
1939
1940 pub fn remove_item(
1941 &mut self,
1942 item_id: EntityId,
1943 activate_pane: bool,
1944 close_pane_if_empty: bool,
1945 window: &mut Window,
1946 cx: &mut Context<Self>,
1947 ) {
1948 let Some(item_index) = self.index_for_item_id(item_id) else {
1949 return;
1950 };
1951 self._remove_item(
1952 item_index,
1953 activate_pane,
1954 close_pane_if_empty,
1955 None,
1956 window,
1957 cx,
1958 )
1959 }
1960
1961 pub fn remove_item_and_focus_on_pane(
1962 &mut self,
1963 item_index: usize,
1964 activate_pane: bool,
1965 focus_on_pane_if_closed: Entity<Pane>,
1966 window: &mut Window,
1967 cx: &mut Context<Self>,
1968 ) {
1969 self._remove_item(
1970 item_index,
1971 activate_pane,
1972 true,
1973 Some(focus_on_pane_if_closed),
1974 window,
1975 cx,
1976 )
1977 }
1978
1979 fn _remove_item(
1980 &mut self,
1981 item_index: usize,
1982 activate_pane: bool,
1983 close_pane_if_empty: bool,
1984 focus_on_pane_if_closed: Option<Entity<Pane>>,
1985 window: &mut Window,
1986 cx: &mut Context<Self>,
1987 ) {
1988 let activate_on_close = &ItemSettings::get_global(cx).activate_on_close;
1989 self.activation_history
1990 .retain(|entry| entry.entity_id != self.items[item_index].item_id());
1991
1992 if self.is_tab_pinned(item_index) {
1993 self.pinned_tab_count -= 1;
1994 }
1995 if item_index == self.active_item_index {
1996 let left_neighbour_index = || item_index.min(self.items.len()).saturating_sub(1);
1997 let index_to_activate = match activate_on_close {
1998 ActivateOnClose::History => self
1999 .activation_history
2000 .pop()
2001 .and_then(|last_activated_item| {
2002 self.items.iter().enumerate().find_map(|(index, item)| {
2003 (item.item_id() == last_activated_item.entity_id).then_some(index)
2004 })
2005 })
2006 // We didn't have a valid activation history entry, so fallback
2007 // to activating the item to the left
2008 .unwrap_or_else(left_neighbour_index),
2009 ActivateOnClose::Neighbour => {
2010 self.activation_history.pop();
2011 if item_index + 1 < self.items.len() {
2012 item_index + 1
2013 } else {
2014 item_index.saturating_sub(1)
2015 }
2016 }
2017 ActivateOnClose::LeftNeighbour => {
2018 self.activation_history.pop();
2019 left_neighbour_index()
2020 }
2021 };
2022
2023 let should_activate = activate_pane || self.has_focus(window, cx);
2024 if self.items.len() == 1 && should_activate {
2025 self.focus_handle.focus(window, cx);
2026 } else {
2027 self.activate_item(
2028 index_to_activate,
2029 should_activate,
2030 should_activate,
2031 window,
2032 cx,
2033 );
2034 }
2035 }
2036
2037 let item = self.items.remove(item_index);
2038
2039 cx.emit(Event::RemovedItem { item: item.clone() });
2040 if self.items.is_empty() {
2041 item.deactivated(window, cx);
2042 if close_pane_if_empty {
2043 self.update_toolbar(window, cx);
2044 cx.emit(Event::Remove {
2045 focus_on_pane: focus_on_pane_if_closed,
2046 });
2047 }
2048 }
2049
2050 if item_index < self.active_item_index {
2051 self.active_item_index -= 1;
2052 }
2053
2054 let mode = self.nav_history.mode();
2055 self.nav_history.set_mode(NavigationMode::ClosingItem);
2056 item.deactivated(window, cx);
2057 item.on_removed(cx);
2058 self.nav_history.set_mode(mode);
2059
2060 self.unpreview_item_if_preview(item.item_id());
2061
2062 if let Some(path) = item.project_path(cx) {
2063 let abs_path = self
2064 .nav_history
2065 .0
2066 .lock()
2067 .paths_by_item
2068 .get(&item.item_id())
2069 .and_then(|(_, abs_path)| abs_path.clone());
2070
2071 self.nav_history
2072 .0
2073 .lock()
2074 .paths_by_item
2075 .insert(item.item_id(), (path, abs_path));
2076 } else {
2077 self.nav_history
2078 .0
2079 .lock()
2080 .paths_by_item
2081 .remove(&item.item_id());
2082 }
2083
2084 if self.zoom_out_on_close && self.items.is_empty() && close_pane_if_empty && self.zoomed {
2085 cx.emit(Event::ZoomOut);
2086 }
2087
2088 cx.notify();
2089 }
2090
2091 pub async fn save_item(
2092 project: Entity<Project>,
2093 pane: &WeakEntity<Pane>,
2094 item: &dyn ItemHandle,
2095 save_intent: SaveIntent,
2096 cx: &mut AsyncWindowContext,
2097 ) -> Result<bool> {
2098 const CONFLICT_MESSAGE: &str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
2099
2100 const DELETED_MESSAGE: &str = "This file has been deleted on disk since you started editing it. Do you want to recreate it?";
2101
2102 let path_style = project.read_with(cx, |project, cx| project.path_style(cx))?;
2103 if save_intent == SaveIntent::Skip {
2104 return Ok(true);
2105 };
2106 let Some(item_ix) = pane
2107 .read_with(cx, |pane, _| pane.index_for_item(item))
2108 .ok()
2109 .flatten()
2110 else {
2111 return Ok(true);
2112 };
2113
2114 let (
2115 mut has_conflict,
2116 mut is_dirty,
2117 mut can_save,
2118 can_save_as,
2119 is_singleton,
2120 has_deleted_file,
2121 ) = cx.update(|_window, cx| {
2122 (
2123 item.has_conflict(cx),
2124 item.is_dirty(cx),
2125 item.can_save(cx),
2126 item.can_save_as(cx),
2127 item.buffer_kind(cx) == ItemBufferKind::Singleton,
2128 item.has_deleted_file(cx),
2129 )
2130 })?;
2131
2132 // when saving a single buffer, we ignore whether or not it's dirty.
2133 if save_intent == SaveIntent::Save || save_intent == SaveIntent::SaveWithoutFormat {
2134 is_dirty = true;
2135 }
2136
2137 if save_intent == SaveIntent::SaveAs {
2138 is_dirty = true;
2139 has_conflict = false;
2140 can_save = false;
2141 }
2142
2143 if save_intent == SaveIntent::Overwrite {
2144 has_conflict = false;
2145 }
2146
2147 let should_format = save_intent != SaveIntent::SaveWithoutFormat;
2148
2149 if has_conflict && can_save {
2150 if has_deleted_file && is_singleton {
2151 let answer = pane.update_in(cx, |pane, window, cx| {
2152 pane.activate_item(item_ix, true, true, window, cx);
2153 window.prompt(
2154 PromptLevel::Warning,
2155 DELETED_MESSAGE,
2156 None,
2157 &["Save", "Close", "Cancel"],
2158 cx,
2159 )
2160 })?;
2161 match answer.await {
2162 Ok(0) => {
2163 pane.update_in(cx, |_, window, cx| {
2164 item.save(
2165 SaveOptions {
2166 format: should_format,
2167 autosave: false,
2168 },
2169 project,
2170 window,
2171 cx,
2172 )
2173 })?
2174 .await?
2175 }
2176 Ok(1) => {
2177 pane.update_in(cx, |pane, window, cx| {
2178 pane.remove_item(item.item_id(), false, true, window, cx)
2179 })?;
2180 }
2181 _ => return Ok(false),
2182 }
2183 return Ok(true);
2184 } else {
2185 let answer = pane.update_in(cx, |pane, window, cx| {
2186 pane.activate_item(item_ix, true, true, window, cx);
2187 window.prompt(
2188 PromptLevel::Warning,
2189 CONFLICT_MESSAGE,
2190 None,
2191 &["Overwrite", "Discard", "Cancel"],
2192 cx,
2193 )
2194 })?;
2195 match answer.await {
2196 Ok(0) => {
2197 pane.update_in(cx, |_, window, cx| {
2198 item.save(
2199 SaveOptions {
2200 format: should_format,
2201 autosave: false,
2202 },
2203 project,
2204 window,
2205 cx,
2206 )
2207 })?
2208 .await?
2209 }
2210 Ok(1) => {
2211 pane.update_in(cx, |_, window, cx| item.reload(project, window, cx))?
2212 .await?
2213 }
2214 _ => return Ok(false),
2215 }
2216 }
2217 } else if is_dirty && (can_save || can_save_as) {
2218 if save_intent == SaveIntent::Close {
2219 let will_autosave = cx.update(|_window, cx| {
2220 item.can_autosave(cx)
2221 && item.workspace_settings(cx).autosave.should_save_on_close()
2222 })?;
2223 if !will_autosave {
2224 let item_id = item.item_id();
2225 let answer_task = pane.update_in(cx, |pane, window, cx| {
2226 if pane.save_modals_spawned.insert(item_id) {
2227 pane.activate_item(item_ix, true, true, window, cx);
2228 let prompt = dirty_message_for(item.project_path(cx), path_style);
2229 Some(window.prompt(
2230 PromptLevel::Warning,
2231 &prompt,
2232 None,
2233 &["Save", "Don't Save", "Cancel"],
2234 cx,
2235 ))
2236 } else {
2237 None
2238 }
2239 })?;
2240 if let Some(answer_task) = answer_task {
2241 let answer = answer_task.await;
2242 pane.update(cx, |pane, _| {
2243 if !pane.save_modals_spawned.remove(&item_id) {
2244 debug_panic!(
2245 "save modal was not present in spawned modals after awaiting for its answer"
2246 )
2247 }
2248 })?;
2249 match answer {
2250 Ok(0) => {}
2251 Ok(1) => {
2252 // Don't save this file
2253 pane.update_in(cx, |pane, _, cx| {
2254 if pane.is_tab_pinned(item_ix) && !item.can_save(cx) {
2255 pane.pinned_tab_count -= 1;
2256 }
2257 })
2258 .log_err();
2259 return Ok(true);
2260 }
2261 _ => return Ok(false), // Cancel
2262 }
2263 } else {
2264 return Ok(false);
2265 }
2266 }
2267 }
2268
2269 if can_save {
2270 pane.update_in(cx, |pane, window, cx| {
2271 pane.unpreview_item_if_preview(item.item_id());
2272 item.save(
2273 SaveOptions {
2274 format: should_format,
2275 autosave: false,
2276 },
2277 project,
2278 window,
2279 cx,
2280 )
2281 })?
2282 .await?;
2283 } else if can_save_as && is_singleton {
2284 let suggested_name =
2285 cx.update(|_window, cx| item.suggested_filename(cx).to_string())?;
2286 let new_path = pane.update_in(cx, |pane, window, cx| {
2287 pane.activate_item(item_ix, true, true, window, cx);
2288 pane.workspace.update(cx, |workspace, cx| {
2289 let lister = if workspace.project().read(cx).is_local() {
2290 DirectoryLister::Local(
2291 workspace.project().clone(),
2292 workspace.app_state().fs.clone(),
2293 )
2294 } else {
2295 DirectoryLister::Project(workspace.project().clone())
2296 };
2297 workspace.prompt_for_new_path(lister, Some(suggested_name), window, cx)
2298 })
2299 })??;
2300 let Some(new_path) = new_path.await.ok().flatten().into_iter().flatten().next()
2301 else {
2302 return Ok(false);
2303 };
2304
2305 let project_path = pane
2306 .update(cx, |pane, cx| {
2307 pane.project
2308 .update(cx, |project, cx| {
2309 project.find_or_create_worktree(new_path, true, cx)
2310 })
2311 .ok()
2312 })
2313 .ok()
2314 .flatten();
2315 let save_task = if let Some(project_path) = project_path {
2316 let (worktree, path) = project_path.await?;
2317 let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id())?;
2318 let new_path = ProjectPath { worktree_id, path };
2319
2320 pane.update_in(cx, |pane, window, cx| {
2321 if let Some(item) = pane.item_for_path(new_path.clone(), cx) {
2322 pane.remove_item(item.item_id(), false, false, window, cx);
2323 }
2324
2325 item.save_as(project, new_path, window, cx)
2326 })?
2327 } else {
2328 return Ok(false);
2329 };
2330
2331 save_task.await?;
2332 return Ok(true);
2333 }
2334 }
2335
2336 pane.update(cx, |_, cx| {
2337 cx.emit(Event::UserSavedItem {
2338 item: item.downgrade_item(),
2339 save_intent,
2340 });
2341 true
2342 })
2343 }
2344
2345 pub fn autosave_item(
2346 item: &dyn ItemHandle,
2347 project: Entity<Project>,
2348 window: &mut Window,
2349 cx: &mut App,
2350 ) -> Task<Result<()>> {
2351 let format = !matches!(
2352 item.workspace_settings(cx).autosave,
2353 AutosaveSetting::AfterDelay { .. }
2354 );
2355 if item.can_autosave(cx) {
2356 item.save(
2357 SaveOptions {
2358 format,
2359 autosave: true,
2360 },
2361 project,
2362 window,
2363 cx,
2364 )
2365 } else {
2366 Task::ready(Ok(()))
2367 }
2368 }
2369
2370 pub fn focus_active_item(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2371 if let Some(active_item) = self.active_item() {
2372 let focus_handle = active_item.item_focus_handle(cx);
2373 window.focus(&focus_handle, cx);
2374 }
2375 }
2376
2377 pub fn split(
2378 &mut self,
2379 direction: SplitDirection,
2380 mode: SplitMode,
2381 window: &mut Window,
2382 cx: &mut Context<Self>,
2383 ) {
2384 if self.items.len() <= 1 && mode == SplitMode::MovePane {
2385 // MovePane with only one pane present behaves like a SplitEmpty in the opposite direction
2386 let active_item = self.active_item();
2387 cx.emit(Event::Split {
2388 direction: direction.opposite(),
2389 mode: SplitMode::EmptyPane,
2390 });
2391 // ensure that we focus the moved pane
2392 // in this case we know that the window is the same as the active_item
2393 if let Some(active_item) = active_item {
2394 cx.defer_in(window, move |_, window, cx| {
2395 let focus_handle = active_item.item_focus_handle(cx);
2396 window.focus(&focus_handle, cx);
2397 });
2398 }
2399 } else {
2400 cx.emit(Event::Split { direction, mode });
2401 }
2402 }
2403
2404 pub fn toolbar(&self) -> &Entity<Toolbar> {
2405 &self.toolbar
2406 }
2407
2408 pub fn handle_deleted_project_item(
2409 &mut self,
2410 entry_id: ProjectEntryId,
2411 window: &mut Window,
2412 cx: &mut Context<Pane>,
2413 ) -> Option<()> {
2414 let item_id = self.items().find_map(|item| {
2415 if item.buffer_kind(cx) == ItemBufferKind::Singleton
2416 && item.project_entry_ids(cx).as_slice() == [entry_id]
2417 {
2418 Some(item.item_id())
2419 } else {
2420 None
2421 }
2422 })?;
2423
2424 self.remove_item(item_id, false, true, window, cx);
2425 self.nav_history.remove_item(item_id);
2426
2427 Some(())
2428 }
2429
2430 fn update_toolbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2431 let active_item = self
2432 .items
2433 .get(self.active_item_index)
2434 .map(|item| item.as_ref());
2435 self.toolbar.update(cx, |toolbar, cx| {
2436 toolbar.set_active_item(active_item, window, cx);
2437 });
2438 }
2439
2440 fn update_status_bar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2441 let workspace = self.workspace.clone();
2442 let pane = cx.entity();
2443
2444 window.defer(cx, move |window, cx| {
2445 let Ok(status_bar) =
2446 workspace.read_with(cx, |workspace, _| workspace.status_bar.clone())
2447 else {
2448 return;
2449 };
2450
2451 status_bar.update(cx, move |status_bar, cx| {
2452 status_bar.set_active_pane(&pane, window, cx);
2453 });
2454 });
2455 }
2456
2457 fn entry_abs_path(&self, entry: ProjectEntryId, cx: &App) -> Option<PathBuf> {
2458 let worktree = self
2459 .workspace
2460 .upgrade()?
2461 .read(cx)
2462 .project()
2463 .read(cx)
2464 .worktree_for_entry(entry, cx)?
2465 .read(cx);
2466 let entry = worktree.entry_for_id(entry)?;
2467 Some(match &entry.canonical_path {
2468 Some(canonical_path) => canonical_path.to_path_buf(),
2469 None => worktree.absolutize(&entry.path),
2470 })
2471 }
2472
2473 pub fn icon_color(selected: bool) -> Color {
2474 if selected {
2475 Color::Default
2476 } else {
2477 Color::Muted
2478 }
2479 }
2480
2481 fn toggle_pin_tab(&mut self, _: &TogglePinTab, window: &mut Window, cx: &mut Context<Self>) {
2482 if self.items.is_empty() {
2483 return;
2484 }
2485 let active_tab_ix = self.active_item_index();
2486 if self.is_tab_pinned(active_tab_ix) {
2487 self.unpin_tab_at(active_tab_ix, window, cx);
2488 } else {
2489 self.pin_tab_at(active_tab_ix, window, cx);
2490 }
2491 }
2492
2493 fn unpin_all_tabs(&mut self, _: &UnpinAllTabs, window: &mut Window, cx: &mut Context<Self>) {
2494 if self.items.is_empty() {
2495 return;
2496 }
2497
2498 let pinned_item_ids = self.pinned_item_ids().into_iter().rev();
2499
2500 for pinned_item_id in pinned_item_ids {
2501 if let Some(ix) = self.index_for_item_id(pinned_item_id) {
2502 self.unpin_tab_at(ix, window, cx);
2503 }
2504 }
2505 }
2506
2507 fn pin_tab_at(&mut self, ix: usize, window: &mut Window, cx: &mut Context<Self>) {
2508 self.change_tab_pin_state(ix, PinOperation::Pin, window, cx);
2509 }
2510
2511 fn unpin_tab_at(&mut self, ix: usize, window: &mut Window, cx: &mut Context<Self>) {
2512 self.change_tab_pin_state(ix, PinOperation::Unpin, window, cx);
2513 }
2514
2515 fn change_tab_pin_state(
2516 &mut self,
2517 ix: usize,
2518 operation: PinOperation,
2519 window: &mut Window,
2520 cx: &mut Context<Self>,
2521 ) {
2522 maybe!({
2523 let pane = cx.entity();
2524
2525 let destination_index = match operation {
2526 PinOperation::Pin => self.pinned_tab_count.min(ix),
2527 PinOperation::Unpin => self.pinned_tab_count.checked_sub(1)?,
2528 };
2529
2530 let id = self.item_for_index(ix)?.item_id();
2531 let should_activate = ix == self.active_item_index;
2532
2533 if matches!(operation, PinOperation::Pin) {
2534 self.unpreview_item_if_preview(id);
2535 }
2536
2537 match operation {
2538 PinOperation::Pin => self.pinned_tab_count += 1,
2539 PinOperation::Unpin => self.pinned_tab_count -= 1,
2540 }
2541
2542 if ix == destination_index {
2543 cx.notify();
2544 } else {
2545 self.workspace
2546 .update(cx, |_, cx| {
2547 cx.defer_in(window, move |_, window, cx| {
2548 move_item(
2549 &pane,
2550 &pane,
2551 id,
2552 destination_index,
2553 should_activate,
2554 window,
2555 cx,
2556 );
2557 });
2558 })
2559 .ok()?;
2560 }
2561
2562 let event = match operation {
2563 PinOperation::Pin => Event::ItemPinned,
2564 PinOperation::Unpin => Event::ItemUnpinned,
2565 };
2566
2567 cx.emit(event);
2568
2569 Some(())
2570 });
2571 }
2572
2573 fn is_tab_pinned(&self, ix: usize) -> bool {
2574 self.pinned_tab_count > ix
2575 }
2576
2577 fn has_unpinned_tabs(&self) -> bool {
2578 self.pinned_tab_count < self.items.len()
2579 }
2580
2581 fn activate_unpinned_tab(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2582 if self.items.is_empty() {
2583 return;
2584 }
2585 let Some(index) = self
2586 .items()
2587 .enumerate()
2588 .find_map(|(index, _item)| (!self.is_tab_pinned(index)).then_some(index))
2589 else {
2590 return;
2591 };
2592 self.activate_item(index, true, true, window, cx);
2593 }
2594
2595 fn render_tab(
2596 &self,
2597 ix: usize,
2598 item: &dyn ItemHandle,
2599 detail: usize,
2600 focus_handle: &FocusHandle,
2601 window: &mut Window,
2602 cx: &mut Context<Pane>,
2603 ) -> impl IntoElement + use<> {
2604 let is_active = ix == self.active_item_index;
2605 let is_preview = self
2606 .preview_item_id
2607 .map(|id| id == item.item_id())
2608 .unwrap_or(false);
2609
2610 let label = item.tab_content(
2611 TabContentParams {
2612 detail: Some(detail),
2613 selected: is_active,
2614 preview: is_preview,
2615 deemphasized: !self.has_focus(window, cx),
2616 },
2617 window,
2618 cx,
2619 );
2620
2621 let item_diagnostic = item
2622 .project_path(cx)
2623 .map_or(None, |project_path| self.diagnostics.get(&project_path));
2624
2625 let decorated_icon = item_diagnostic.map_or(None, |diagnostic| {
2626 let icon = match item.tab_icon(window, cx) {
2627 Some(icon) => icon,
2628 None => return None,
2629 };
2630
2631 let knockout_item_color = if is_active {
2632 cx.theme().colors().tab_active_background
2633 } else {
2634 cx.theme().colors().tab_bar_background
2635 };
2636
2637 let (icon_decoration, icon_color) = if matches!(diagnostic, &DiagnosticSeverity::ERROR)
2638 {
2639 (IconDecorationKind::X, Color::Error)
2640 } else {
2641 (IconDecorationKind::Triangle, Color::Warning)
2642 };
2643
2644 Some(DecoratedIcon::new(
2645 icon.size(IconSize::Small).color(Color::Muted),
2646 Some(
2647 IconDecoration::new(icon_decoration, knockout_item_color, cx)
2648 .color(icon_color.color(cx))
2649 .position(Point {
2650 x: px(-2.),
2651 y: px(-2.),
2652 }),
2653 ),
2654 ))
2655 });
2656
2657 let icon = if decorated_icon.is_none() {
2658 match item_diagnostic {
2659 Some(&DiagnosticSeverity::ERROR) => None,
2660 Some(&DiagnosticSeverity::WARNING) => None,
2661 _ => item
2662 .tab_icon(window, cx)
2663 .map(|icon| icon.color(Color::Muted)),
2664 }
2665 .map(|icon| icon.size(IconSize::Small))
2666 } else {
2667 None
2668 };
2669
2670 let settings = ItemSettings::get_global(cx);
2671 let close_side = &settings.close_position;
2672 let show_close_button = &settings.show_close_button;
2673 let indicator = render_item_indicator(item.boxed_clone(), cx);
2674 let tab_tooltip_content = item.tab_tooltip_content(cx);
2675 let item_id = item.item_id();
2676 let is_first_item = ix == 0;
2677 let is_last_item = ix == self.items.len() - 1;
2678 let is_pinned = self.is_tab_pinned(ix);
2679 let position_relative_to_active_item = ix.cmp(&self.active_item_index);
2680
2681 let tab = Tab::new(ix)
2682 .position(if is_first_item {
2683 TabPosition::First
2684 } else if is_last_item {
2685 TabPosition::Last
2686 } else {
2687 TabPosition::Middle(position_relative_to_active_item)
2688 })
2689 .close_side(match close_side {
2690 ClosePosition::Left => ui::TabCloseSide::Start,
2691 ClosePosition::Right => ui::TabCloseSide::End,
2692 })
2693 .toggle_state(is_active)
2694 .on_click(cx.listener(move |pane: &mut Self, _, window, cx| {
2695 pane.activate_item(ix, true, true, window, cx)
2696 }))
2697 // TODO: This should be a click listener with the middle mouse button instead of a mouse down listener.
2698 .on_mouse_down(
2699 MouseButton::Middle,
2700 cx.listener(move |pane, _event, window, cx| {
2701 pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2702 .detach_and_log_err(cx);
2703 }),
2704 )
2705 .on_mouse_down(
2706 MouseButton::Left,
2707 cx.listener(move |pane, event: &MouseDownEvent, _, _| {
2708 if event.click_count > 1 {
2709 pane.unpreview_item_if_preview(item_id);
2710 }
2711 }),
2712 )
2713 .on_drag(
2714 DraggedTab {
2715 item: item.boxed_clone(),
2716 pane: cx.entity(),
2717 detail,
2718 is_active,
2719 ix,
2720 },
2721 |tab, _, _, cx| cx.new(|_| tab.clone()),
2722 )
2723 .drag_over::<DraggedTab>(move |tab, dragged_tab: &DraggedTab, _, cx| {
2724 let mut styled_tab = tab
2725 .bg(cx.theme().colors().drop_target_background)
2726 .border_color(cx.theme().colors().drop_target_border)
2727 .border_0();
2728
2729 if ix < dragged_tab.ix {
2730 styled_tab = styled_tab.border_l_2();
2731 } else if ix > dragged_tab.ix {
2732 styled_tab = styled_tab.border_r_2();
2733 }
2734
2735 styled_tab
2736 })
2737 .drag_over::<DraggedSelection>(|tab, _, _, cx| {
2738 tab.bg(cx.theme().colors().drop_target_background)
2739 })
2740 .when_some(self.can_drop_predicate.clone(), |this, p| {
2741 this.can_drop(move |a, window, cx| p(a, window, cx))
2742 })
2743 .on_drop(
2744 cx.listener(move |this, dragged_tab: &DraggedTab, window, cx| {
2745 this.drag_split_direction = None;
2746 this.handle_tab_drop(dragged_tab, ix, window, cx)
2747 }),
2748 )
2749 .on_drop(
2750 cx.listener(move |this, selection: &DraggedSelection, window, cx| {
2751 this.drag_split_direction = None;
2752 this.handle_dragged_selection_drop(selection, Some(ix), window, cx)
2753 }),
2754 )
2755 .on_drop(cx.listener(move |this, paths, window, cx| {
2756 this.drag_split_direction = None;
2757 this.handle_external_paths_drop(paths, window, cx)
2758 }))
2759 .start_slot::<Indicator>(indicator)
2760 .map(|this| {
2761 let end_slot_action: &'static dyn Action;
2762 let end_slot_tooltip_text: &'static str;
2763 let end_slot = if is_pinned {
2764 end_slot_action = &TogglePinTab;
2765 end_slot_tooltip_text = "Unpin Tab";
2766 IconButton::new("unpin tab", IconName::Pin)
2767 .shape(IconButtonShape::Square)
2768 .icon_color(Color::Muted)
2769 .size(ButtonSize::None)
2770 .icon_size(IconSize::Small)
2771 .on_click(cx.listener(move |pane, _, window, cx| {
2772 pane.unpin_tab_at(ix, window, cx);
2773 }))
2774 } else {
2775 end_slot_action = &CloseActiveItem {
2776 save_intent: None,
2777 close_pinned: false,
2778 };
2779 end_slot_tooltip_text = "Close Tab";
2780 match show_close_button {
2781 ShowCloseButton::Always => IconButton::new("close tab", IconName::Close),
2782 ShowCloseButton::Hover => {
2783 IconButton::new("close tab", IconName::Close).visible_on_hover("")
2784 }
2785 ShowCloseButton::Hidden => return this,
2786 }
2787 .shape(IconButtonShape::Square)
2788 .icon_color(Color::Muted)
2789 .size(ButtonSize::None)
2790 .icon_size(IconSize::Small)
2791 .on_click(cx.listener(move |pane, _, window, cx| {
2792 pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2793 .detach_and_log_err(cx);
2794 }))
2795 }
2796 .map(|this| {
2797 if is_active {
2798 let focus_handle = focus_handle.clone();
2799 this.tooltip(move |window, cx| {
2800 Tooltip::for_action_in(
2801 end_slot_tooltip_text,
2802 end_slot_action,
2803 &window.focused(cx).unwrap_or_else(|| focus_handle.clone()),
2804 cx,
2805 )
2806 })
2807 } else {
2808 this.tooltip(Tooltip::text(end_slot_tooltip_text))
2809 }
2810 });
2811 this.end_slot(end_slot)
2812 })
2813 .child(
2814 h_flex()
2815 .gap_1()
2816 .items_center()
2817 .children(
2818 std::iter::once(if let Some(decorated_icon) = decorated_icon {
2819 Some(div().child(decorated_icon.into_any_element()))
2820 } else {
2821 icon.map(|icon| div().child(icon.into_any_element()))
2822 })
2823 .flatten(),
2824 )
2825 .child(label)
2826 .id(("pane-tab-content", ix))
2827 .map(|this| match tab_tooltip_content {
2828 Some(TabTooltipContent::Text(text)) => this.tooltip(Tooltip::text(text)),
2829 Some(TabTooltipContent::Custom(element_fn)) => {
2830 this.tooltip(move |window, cx| element_fn(window, cx))
2831 }
2832 None => this,
2833 }),
2834 );
2835
2836 let single_entry_to_resolve = (self.items[ix].buffer_kind(cx) == ItemBufferKind::Singleton)
2837 .then(|| self.items[ix].project_entry_ids(cx).get(0).copied())
2838 .flatten();
2839
2840 let total_items = self.items.len();
2841 let has_multibuffer_items = self
2842 .items
2843 .iter()
2844 .any(|item| item.buffer_kind(cx) == ItemBufferKind::Multibuffer);
2845 let has_items_to_left = ix > 0;
2846 let has_items_to_right = ix < total_items - 1;
2847 let has_clean_items = self.items.iter().any(|item| !item.is_dirty(cx));
2848 let is_pinned = self.is_tab_pinned(ix);
2849 let pane = cx.entity().downgrade();
2850 let menu_context = item.item_focus_handle(cx);
2851 right_click_menu(ix)
2852 .trigger(|_, _, _| tab)
2853 .menu(move |window, cx| {
2854 let pane = pane.clone();
2855 let menu_context = menu_context.clone();
2856 ContextMenu::build(window, cx, move |mut menu, window, cx| {
2857 let close_active_item_action = CloseActiveItem {
2858 save_intent: None,
2859 close_pinned: true,
2860 };
2861 let close_inactive_items_action = CloseOtherItems {
2862 save_intent: None,
2863 close_pinned: false,
2864 };
2865 let close_multibuffers_action = CloseMultibufferItems {
2866 save_intent: None,
2867 close_pinned: false,
2868 };
2869 let close_items_to_the_left_action = CloseItemsToTheLeft {
2870 close_pinned: false,
2871 };
2872 let close_items_to_the_right_action = CloseItemsToTheRight {
2873 close_pinned: false,
2874 };
2875 let close_clean_items_action = CloseCleanItems {
2876 close_pinned: false,
2877 };
2878 let close_all_items_action = CloseAllItems {
2879 save_intent: None,
2880 close_pinned: false,
2881 };
2882 if let Some(pane) = pane.upgrade() {
2883 menu = menu
2884 .entry(
2885 "Close",
2886 Some(Box::new(close_active_item_action)),
2887 window.handler_for(&pane, move |pane, window, cx| {
2888 pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2889 .detach_and_log_err(cx);
2890 }),
2891 )
2892 .item(ContextMenuItem::Entry(
2893 ContextMenuEntry::new("Close Others")
2894 .action(Box::new(close_inactive_items_action.clone()))
2895 .disabled(total_items == 1)
2896 .handler(window.handler_for(&pane, move |pane, window, cx| {
2897 pane.close_other_items(
2898 &close_inactive_items_action,
2899 Some(item_id),
2900 window,
2901 cx,
2902 )
2903 .detach_and_log_err(cx);
2904 })),
2905 ))
2906 // We make this optional, instead of using disabled as to not overwhelm the context menu unnecessarily
2907 .extend(has_multibuffer_items.then(|| {
2908 ContextMenuItem::Entry(
2909 ContextMenuEntry::new("Close Multibuffers")
2910 .action(Box::new(close_multibuffers_action.clone()))
2911 .handler(window.handler_for(
2912 &pane,
2913 move |pane, window, cx| {
2914 pane.close_multibuffer_items(
2915 &close_multibuffers_action,
2916 window,
2917 cx,
2918 )
2919 .detach_and_log_err(cx);
2920 },
2921 )),
2922 )
2923 }))
2924 .separator()
2925 .item(ContextMenuItem::Entry(
2926 ContextMenuEntry::new("Close Left")
2927 .action(Box::new(close_items_to_the_left_action.clone()))
2928 .disabled(!has_items_to_left)
2929 .handler(window.handler_for(&pane, move |pane, window, cx| {
2930 pane.close_items_to_the_left_by_id(
2931 Some(item_id),
2932 &close_items_to_the_left_action,
2933 window,
2934 cx,
2935 )
2936 .detach_and_log_err(cx);
2937 })),
2938 ))
2939 .item(ContextMenuItem::Entry(
2940 ContextMenuEntry::new("Close Right")
2941 .action(Box::new(close_items_to_the_right_action.clone()))
2942 .disabled(!has_items_to_right)
2943 .handler(window.handler_for(&pane, move |pane, window, cx| {
2944 pane.close_items_to_the_right_by_id(
2945 Some(item_id),
2946 &close_items_to_the_right_action,
2947 window,
2948 cx,
2949 )
2950 .detach_and_log_err(cx);
2951 })),
2952 ))
2953 .separator()
2954 .item(ContextMenuItem::Entry(
2955 ContextMenuEntry::new("Close Clean")
2956 .action(Box::new(close_clean_items_action.clone()))
2957 .disabled(!has_clean_items)
2958 .handler(window.handler_for(&pane, move |pane, window, cx| {
2959 pane.close_clean_items(
2960 &close_clean_items_action,
2961 window,
2962 cx,
2963 )
2964 .detach_and_log_err(cx)
2965 })),
2966 ))
2967 .entry(
2968 "Close All",
2969 Some(Box::new(close_all_items_action.clone())),
2970 window.handler_for(&pane, move |pane, window, cx| {
2971 pane.close_all_items(&close_all_items_action, window, cx)
2972 .detach_and_log_err(cx)
2973 }),
2974 );
2975
2976 let pin_tab_entries = |menu: ContextMenu| {
2977 menu.separator().map(|this| {
2978 if is_pinned {
2979 this.entry(
2980 "Unpin Tab",
2981 Some(TogglePinTab.boxed_clone()),
2982 window.handler_for(&pane, move |pane, window, cx| {
2983 pane.unpin_tab_at(ix, window, cx);
2984 }),
2985 )
2986 } else {
2987 this.entry(
2988 "Pin Tab",
2989 Some(TogglePinTab.boxed_clone()),
2990 window.handler_for(&pane, move |pane, window, cx| {
2991 pane.pin_tab_at(ix, window, cx);
2992 }),
2993 )
2994 }
2995 })
2996 };
2997 if let Some(entry) = single_entry_to_resolve {
2998 let project_path = pane
2999 .read(cx)
3000 .item_for_entry(entry, cx)
3001 .and_then(|item| item.project_path(cx));
3002 let worktree = project_path.as_ref().and_then(|project_path| {
3003 pane.read(cx)
3004 .project
3005 .upgrade()?
3006 .read(cx)
3007 .worktree_for_id(project_path.worktree_id, cx)
3008 });
3009 let has_relative_path = worktree.as_ref().is_some_and(|worktree| {
3010 worktree
3011 .read(cx)
3012 .root_entry()
3013 .is_some_and(|entry| entry.is_dir())
3014 });
3015
3016 let entry_abs_path = pane.read(cx).entry_abs_path(entry, cx);
3017 let parent_abs_path = entry_abs_path
3018 .as_deref()
3019 .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
3020 let relative_path = project_path
3021 .map(|project_path| project_path.path)
3022 .filter(|_| has_relative_path);
3023
3024 let visible_in_project_panel = relative_path.is_some()
3025 && worktree.is_some_and(|worktree| worktree.read(cx).is_visible());
3026
3027 let entry_id = entry.to_proto();
3028 menu = menu
3029 .separator()
3030 .when_some(entry_abs_path, |menu, abs_path| {
3031 menu.entry(
3032 "Copy Path",
3033 Some(Box::new(zed_actions::workspace::CopyPath)),
3034 window.handler_for(&pane, move |_, _, cx| {
3035 cx.write_to_clipboard(ClipboardItem::new_string(
3036 abs_path.to_string_lossy().into_owned(),
3037 ));
3038 }),
3039 )
3040 })
3041 .when_some(relative_path, |menu, relative_path| {
3042 menu.entry(
3043 "Copy Relative Path",
3044 Some(Box::new(zed_actions::workspace::CopyRelativePath)),
3045 window.handler_for(&pane, move |this, _, cx| {
3046 let Some(project) = this.project.upgrade() else {
3047 return;
3048 };
3049 let path_style = project
3050 .update(cx, |project, cx| project.path_style(cx));
3051 cx.write_to_clipboard(ClipboardItem::new_string(
3052 relative_path.display(path_style).to_string(),
3053 ));
3054 }),
3055 )
3056 })
3057 .map(pin_tab_entries)
3058 .separator()
3059 .when(visible_in_project_panel, |menu| {
3060 menu.entry(
3061 "Reveal In Project Panel",
3062 Some(Box::new(RevealInProjectPanel::default())),
3063 window.handler_for(&pane, move |pane, _, cx| {
3064 pane.project
3065 .update(cx, |_, cx| {
3066 cx.emit(project::Event::RevealInProjectPanel(
3067 ProjectEntryId::from_proto(entry_id),
3068 ))
3069 })
3070 .ok();
3071 }),
3072 )
3073 })
3074 .when_some(parent_abs_path, |menu, parent_abs_path| {
3075 menu.entry(
3076 "Open in Terminal",
3077 Some(Box::new(OpenInTerminal)),
3078 window.handler_for(&pane, move |_, window, cx| {
3079 window.dispatch_action(
3080 OpenTerminal {
3081 working_directory: parent_abs_path.clone(),
3082 }
3083 .boxed_clone(),
3084 cx,
3085 );
3086 }),
3087 )
3088 });
3089 } else {
3090 menu = menu.map(pin_tab_entries);
3091 }
3092 }
3093
3094 menu.context(menu_context)
3095 })
3096 })
3097 }
3098
3099 fn render_tab_bar(&mut self, window: &mut Window, cx: &mut Context<Pane>) -> AnyElement {
3100 let Some(workspace) = self.workspace.upgrade() else {
3101 return gpui::Empty.into_any();
3102 };
3103
3104 let focus_handle = self.focus_handle.clone();
3105 let is_pane_focused = self.has_focus(window, cx);
3106
3107 let navigate_backward = IconButton::new("navigate_backward", IconName::ArrowLeft)
3108 .icon_size(IconSize::Small)
3109 .on_click({
3110 let entity = cx.entity();
3111 move |_, window, cx| {
3112 entity.update(cx, |pane, cx| {
3113 pane.navigate_backward(&Default::default(), window, cx)
3114 })
3115 }
3116 })
3117 .disabled(!self.can_navigate_backward())
3118 .tooltip({
3119 let focus_handle = focus_handle.clone();
3120 move |window, cx| {
3121 Tooltip::for_action_in(
3122 "Go Back",
3123 &GoBack,
3124 &window.focused(cx).unwrap_or_else(|| focus_handle.clone()),
3125 cx,
3126 )
3127 }
3128 });
3129
3130 let open_aside_left = {
3131 let workspace = workspace.read(cx);
3132 workspace.utility_pane(UtilityPaneSlot::Left).map(|pane| {
3133 let toggle_icon = pane.toggle_icon(cx);
3134 let workspace_handle = self.workspace.clone();
3135
3136 h_flex()
3137 .h_full()
3138 .pr_1p5()
3139 .border_r_1()
3140 .border_color(cx.theme().colors().border)
3141 .child(
3142 IconButton::new("open_aside_left", toggle_icon)
3143 .icon_size(IconSize::Small)
3144 .tooltip(Tooltip::text("Toggle Agent Pane")) // TODO: Probably want to make this generic
3145 .on_click(move |_, window, cx| {
3146 workspace_handle
3147 .update(cx, |workspace, cx| {
3148 workspace.toggle_utility_pane(
3149 UtilityPaneSlot::Left,
3150 window,
3151 cx,
3152 )
3153 })
3154 .ok();
3155 }),
3156 )
3157 .into_any_element()
3158 })
3159 };
3160
3161 let open_aside_right = {
3162 let workspace = workspace.read(cx);
3163 workspace.utility_pane(UtilityPaneSlot::Right).map(|pane| {
3164 let toggle_icon = pane.toggle_icon(cx);
3165 let workspace_handle = self.workspace.clone();
3166
3167 h_flex()
3168 .h_full()
3169 .when(is_pane_focused, |this| {
3170 this.pl(DynamicSpacing::Base04.rems(cx))
3171 .border_l_1()
3172 .border_color(cx.theme().colors().border)
3173 })
3174 .child(
3175 IconButton::new("open_aside_right", toggle_icon)
3176 .icon_size(IconSize::Small)
3177 .tooltip(Tooltip::text("Toggle Agent Pane")) // TODO: Probably want to make this generic
3178 .on_click(move |_, window, cx| {
3179 workspace_handle
3180 .update(cx, |workspace, cx| {
3181 workspace.toggle_utility_pane(
3182 UtilityPaneSlot::Right,
3183 window,
3184 cx,
3185 )
3186 })
3187 .ok();
3188 }),
3189 )
3190 .into_any_element()
3191 })
3192 };
3193
3194 let navigate_forward = IconButton::new("navigate_forward", IconName::ArrowRight)
3195 .icon_size(IconSize::Small)
3196 .on_click({
3197 let entity = cx.entity();
3198 move |_, window, cx| {
3199 entity.update(cx, |pane, cx| {
3200 pane.navigate_forward(&Default::default(), window, cx)
3201 })
3202 }
3203 })
3204 .disabled(!self.can_navigate_forward())
3205 .tooltip({
3206 let focus_handle = focus_handle.clone();
3207 move |window, cx| {
3208 Tooltip::for_action_in(
3209 "Go Forward",
3210 &GoForward,
3211 &window.focused(cx).unwrap_or_else(|| focus_handle.clone()),
3212 cx,
3213 )
3214 }
3215 });
3216
3217 let mut tab_items = self
3218 .items
3219 .iter()
3220 .enumerate()
3221 .zip(tab_details(&self.items, window, cx))
3222 .map(|((ix, item), detail)| {
3223 self.render_tab(ix, &**item, detail, &focus_handle, window, cx)
3224 })
3225 .collect::<Vec<_>>();
3226 let tab_count = tab_items.len();
3227 if self.is_tab_pinned(tab_count) {
3228 log::warn!(
3229 "Pinned tab count ({}) exceeds actual tab count ({}). \
3230 This should not happen. If possible, add reproduction steps, \
3231 in a comment, to https://github.com/zed-industries/zed/issues/33342",
3232 self.pinned_tab_count,
3233 tab_count
3234 );
3235 self.pinned_tab_count = tab_count;
3236 }
3237 let unpinned_tabs = tab_items.split_off(self.pinned_tab_count);
3238 let pinned_tabs = tab_items;
3239
3240 let render_aside_toggle_left = cx.has_flag::<AgentV2FeatureFlag>()
3241 && self
3242 .is_upper_left
3243 .then(|| {
3244 self.workspace.upgrade().and_then(|entity| {
3245 let workspace = entity.read(cx);
3246 workspace
3247 .utility_pane(UtilityPaneSlot::Left)
3248 .map(|pane| !pane.expanded(cx))
3249 })
3250 })
3251 .flatten()
3252 .unwrap_or(false);
3253
3254 let render_aside_toggle_right = cx.has_flag::<AgentV2FeatureFlag>()
3255 && self
3256 .is_upper_right
3257 .then(|| {
3258 self.workspace.upgrade().and_then(|entity| {
3259 let workspace = entity.read(cx);
3260 workspace
3261 .utility_pane(UtilityPaneSlot::Right)
3262 .map(|pane| !pane.expanded(cx))
3263 })
3264 })
3265 .flatten()
3266 .unwrap_or(false);
3267
3268 TabBar::new("tab_bar")
3269 .map(|tab_bar| {
3270 if let Some(open_aside_left) = open_aside_left
3271 && render_aside_toggle_left
3272 {
3273 tab_bar.start_child(open_aside_left)
3274 } else {
3275 tab_bar
3276 }
3277 })
3278 .when(
3279 self.display_nav_history_buttons.unwrap_or_default(),
3280 |tab_bar| {
3281 tab_bar
3282 .start_child(navigate_backward)
3283 .start_child(navigate_forward)
3284 },
3285 )
3286 .map(|tab_bar| {
3287 if self.show_tab_bar_buttons {
3288 let render_tab_buttons = self.render_tab_bar_buttons.clone();
3289 let (left_children, right_children) = render_tab_buttons(self, window, cx);
3290 tab_bar
3291 .start_children(left_children)
3292 .end_children(right_children)
3293 } else {
3294 tab_bar
3295 }
3296 })
3297 .children(pinned_tabs.len().ne(&0).then(|| {
3298 let max_scroll = self.tab_bar_scroll_handle.max_offset().width;
3299 // We need to check both because offset returns delta values even when the scroll handle is not scrollable
3300 let is_scrolled = self.tab_bar_scroll_handle.offset().x < px(0.);
3301 // Avoid flickering when max_offset is very small (< 2px).
3302 // The border adds 1-2px which can push max_offset back to 0, creating a loop.
3303 let is_scrollable = max_scroll > px(2.0);
3304 let has_active_unpinned_tab = self.active_item_index >= self.pinned_tab_count;
3305 h_flex()
3306 .children(pinned_tabs)
3307 .when(is_scrollable && is_scrolled, |this| {
3308 this.when(has_active_unpinned_tab, |this| this.border_r_2())
3309 .when(!has_active_unpinned_tab, |this| this.border_r_1())
3310 .border_color(cx.theme().colors().border)
3311 })
3312 }))
3313 .child(
3314 h_flex()
3315 .id("unpinned tabs")
3316 .overflow_x_scroll()
3317 .w_full()
3318 .track_scroll(&self.tab_bar_scroll_handle)
3319 .on_scroll_wheel(cx.listener(|this, _, _, _| {
3320 this.suppress_scroll = true;
3321 }))
3322 .children(unpinned_tabs)
3323 .child(
3324 div()
3325 .id("tab_bar_drop_target")
3326 .min_w_6()
3327 // HACK: This empty child is currently necessary to force the drop target to appear
3328 // despite us setting a min width above.
3329 .child("")
3330 // HACK: h_full doesn't occupy the complete height, using fixed height instead
3331 .h(Tab::container_height(cx))
3332 .flex_grow()
3333 .drag_over::<DraggedTab>(|bar, _, _, cx| {
3334 bar.bg(cx.theme().colors().drop_target_background)
3335 })
3336 .drag_over::<DraggedSelection>(|bar, _, _, cx| {
3337 bar.bg(cx.theme().colors().drop_target_background)
3338 })
3339 .on_drop(cx.listener(
3340 move |this, dragged_tab: &DraggedTab, window, cx| {
3341 this.drag_split_direction = None;
3342 this.handle_tab_drop(dragged_tab, this.items.len(), window, cx)
3343 },
3344 ))
3345 .on_drop(cx.listener(
3346 move |this, selection: &DraggedSelection, window, cx| {
3347 this.drag_split_direction = None;
3348 this.handle_project_entry_drop(
3349 &selection.active_selection.entry_id,
3350 Some(tab_count),
3351 window,
3352 cx,
3353 )
3354 },
3355 ))
3356 .on_drop(cx.listener(move |this, paths, window, cx| {
3357 this.drag_split_direction = None;
3358 this.handle_external_paths_drop(paths, window, cx)
3359 }))
3360 .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
3361 if event.click_count() == 2 {
3362 window.dispatch_action(
3363 this.double_click_dispatch_action.boxed_clone(),
3364 cx,
3365 );
3366 }
3367 })),
3368 ),
3369 )
3370 .map(|tab_bar| {
3371 if let Some(open_aside_right) = open_aside_right
3372 && render_aside_toggle_right
3373 {
3374 tab_bar.end_child(open_aside_right)
3375 } else {
3376 tab_bar
3377 }
3378 })
3379 .into_any_element()
3380 }
3381
3382 pub fn render_menu_overlay(menu: &Entity<ContextMenu>) -> Div {
3383 div().absolute().bottom_0().right_0().size_0().child(
3384 deferred(anchored().anchor(Corner::TopRight).child(menu.clone())).with_priority(1),
3385 )
3386 }
3387
3388 pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut Context<Self>) {
3389 self.zoomed = zoomed;
3390 cx.notify();
3391 }
3392
3393 pub fn is_zoomed(&self) -> bool {
3394 self.zoomed
3395 }
3396
3397 fn handle_drag_move<T: 'static>(
3398 &mut self,
3399 event: &DragMoveEvent<T>,
3400 window: &mut Window,
3401 cx: &mut Context<Self>,
3402 ) {
3403 let can_split_predicate = self.can_split_predicate.take();
3404 let can_split = match &can_split_predicate {
3405 Some(can_split_predicate) => {
3406 can_split_predicate(self, event.dragged_item(), window, cx)
3407 }
3408 None => false,
3409 };
3410 self.can_split_predicate = can_split_predicate;
3411 if !can_split {
3412 return;
3413 }
3414
3415 let rect = event.bounds.size;
3416
3417 let size = event.bounds.size.width.min(event.bounds.size.height)
3418 * WorkspaceSettings::get_global(cx).drop_target_size;
3419
3420 let relative_cursor = Point::new(
3421 event.event.position.x - event.bounds.left(),
3422 event.event.position.y - event.bounds.top(),
3423 );
3424
3425 let direction = if relative_cursor.x < size
3426 || relative_cursor.x > rect.width - size
3427 || relative_cursor.y < size
3428 || relative_cursor.y > rect.height - size
3429 {
3430 [
3431 SplitDirection::Up,
3432 SplitDirection::Right,
3433 SplitDirection::Down,
3434 SplitDirection::Left,
3435 ]
3436 .iter()
3437 .min_by_key(|side| match side {
3438 SplitDirection::Up => relative_cursor.y,
3439 SplitDirection::Right => rect.width - relative_cursor.x,
3440 SplitDirection::Down => rect.height - relative_cursor.y,
3441 SplitDirection::Left => relative_cursor.x,
3442 })
3443 .cloned()
3444 } else {
3445 None
3446 };
3447
3448 if direction != self.drag_split_direction {
3449 self.drag_split_direction = direction;
3450 }
3451 }
3452
3453 pub fn handle_tab_drop(
3454 &mut self,
3455 dragged_tab: &DraggedTab,
3456 ix: usize,
3457 window: &mut Window,
3458 cx: &mut Context<Self>,
3459 ) {
3460 if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3461 && let ControlFlow::Break(()) = custom_drop_handle(self, dragged_tab, window, cx)
3462 {
3463 return;
3464 }
3465 let mut to_pane = cx.entity();
3466 let split_direction = self.drag_split_direction;
3467 let item_id = dragged_tab.item.item_id();
3468 self.unpreview_item_if_preview(item_id);
3469
3470 let is_clone = cfg!(target_os = "macos") && window.modifiers().alt
3471 || cfg!(not(target_os = "macos")) && window.modifiers().control;
3472
3473 let from_pane = dragged_tab.pane.clone();
3474
3475 self.workspace
3476 .update(cx, |_, cx| {
3477 cx.defer_in(window, move |workspace, window, cx| {
3478 if let Some(split_direction) = split_direction {
3479 to_pane = workspace.split_pane(to_pane, split_direction, window, cx);
3480 }
3481 let database_id = workspace.database_id();
3482 let was_pinned_in_from_pane = from_pane.read_with(cx, |pane, _| {
3483 pane.index_for_item_id(item_id)
3484 .is_some_and(|ix| pane.is_tab_pinned(ix))
3485 });
3486 let to_pane_old_length = to_pane.read(cx).items.len();
3487 if is_clone {
3488 let Some(item) = from_pane
3489 .read(cx)
3490 .items()
3491 .find(|item| item.item_id() == item_id)
3492 .cloned()
3493 else {
3494 return;
3495 };
3496 if item.can_split(cx) {
3497 let task = item.clone_on_split(database_id, window, cx);
3498 let to_pane = to_pane.downgrade();
3499 cx.spawn_in(window, async move |_, cx| {
3500 if let Some(item) = task.await {
3501 to_pane
3502 .update_in(cx, |pane, window, cx| {
3503 pane.add_item(item, true, true, None, window, cx)
3504 })
3505 .ok();
3506 }
3507 })
3508 .detach();
3509 } else {
3510 move_item(&from_pane, &to_pane, item_id, ix, true, window, cx);
3511 }
3512 } else {
3513 move_item(&from_pane, &to_pane, item_id, ix, true, window, cx);
3514 }
3515 to_pane.update(cx, |this, _| {
3516 if to_pane == from_pane {
3517 let actual_ix = this
3518 .items
3519 .iter()
3520 .position(|item| item.item_id() == item_id)
3521 .unwrap_or(0);
3522
3523 let is_pinned_in_to_pane = this.is_tab_pinned(actual_ix);
3524
3525 if !was_pinned_in_from_pane && is_pinned_in_to_pane {
3526 this.pinned_tab_count += 1;
3527 } else if was_pinned_in_from_pane && !is_pinned_in_to_pane {
3528 this.pinned_tab_count -= 1;
3529 }
3530 } else if this.items.len() >= to_pane_old_length {
3531 let is_pinned_in_to_pane = this.is_tab_pinned(ix);
3532 let item_created_pane = to_pane_old_length == 0;
3533 let is_first_position = ix == 0;
3534 let was_dropped_at_beginning = item_created_pane || is_first_position;
3535 let should_remain_pinned = is_pinned_in_to_pane
3536 || (was_pinned_in_from_pane && was_dropped_at_beginning);
3537
3538 if should_remain_pinned {
3539 this.pinned_tab_count += 1;
3540 }
3541 }
3542 });
3543 });
3544 })
3545 .log_err();
3546 }
3547
3548 fn handle_dragged_selection_drop(
3549 &mut self,
3550 dragged_selection: &DraggedSelection,
3551 dragged_onto: Option<usize>,
3552 window: &mut Window,
3553 cx: &mut Context<Self>,
3554 ) {
3555 if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3556 && let ControlFlow::Break(()) = custom_drop_handle(self, dragged_selection, window, cx)
3557 {
3558 return;
3559 }
3560 self.handle_project_entry_drop(
3561 &dragged_selection.active_selection.entry_id,
3562 dragged_onto,
3563 window,
3564 cx,
3565 );
3566 }
3567
3568 fn handle_project_entry_drop(
3569 &mut self,
3570 project_entry_id: &ProjectEntryId,
3571 target: Option<usize>,
3572 window: &mut Window,
3573 cx: &mut Context<Self>,
3574 ) {
3575 if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3576 && let ControlFlow::Break(()) = custom_drop_handle(self, project_entry_id, window, cx)
3577 {
3578 return;
3579 }
3580 let mut to_pane = cx.entity();
3581 let split_direction = self.drag_split_direction;
3582 let project_entry_id = *project_entry_id;
3583 self.workspace
3584 .update(cx, |_, cx| {
3585 cx.defer_in(window, move |workspace, window, cx| {
3586 if let Some(project_path) = workspace
3587 .project()
3588 .read(cx)
3589 .path_for_entry(project_entry_id, cx)
3590 {
3591 let load_path_task = workspace.load_path(project_path.clone(), window, cx);
3592 cx.spawn_in(window, async move |workspace, cx| {
3593 if let Some((project_entry_id, build_item)) =
3594 load_path_task.await.notify_async_err(cx)
3595 {
3596 let (to_pane, new_item_handle) = workspace
3597 .update_in(cx, |workspace, window, cx| {
3598 if let Some(split_direction) = split_direction {
3599 to_pane = workspace.split_pane(
3600 to_pane,
3601 split_direction,
3602 window,
3603 cx,
3604 );
3605 }
3606 let new_item_handle = to_pane.update(cx, |pane, cx| {
3607 pane.open_item(
3608 project_entry_id,
3609 project_path,
3610 true,
3611 false,
3612 true,
3613 target,
3614 window,
3615 cx,
3616 build_item,
3617 )
3618 });
3619 (to_pane, new_item_handle)
3620 })
3621 .log_err()?;
3622 to_pane
3623 .update_in(cx, |this, window, cx| {
3624 let Some(index) = this.index_for_item(&*new_item_handle)
3625 else {
3626 return;
3627 };
3628
3629 if target.is_some_and(|target| this.is_tab_pinned(target)) {
3630 this.pin_tab_at(index, window, cx);
3631 }
3632 })
3633 .ok()?
3634 }
3635 Some(())
3636 })
3637 .detach();
3638 };
3639 });
3640 })
3641 .log_err();
3642 }
3643
3644 fn handle_external_paths_drop(
3645 &mut self,
3646 paths: &ExternalPaths,
3647 window: &mut Window,
3648 cx: &mut Context<Self>,
3649 ) {
3650 if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3651 && let ControlFlow::Break(()) = custom_drop_handle(self, paths, window, cx)
3652 {
3653 return;
3654 }
3655 let mut to_pane = cx.entity();
3656 let mut split_direction = self.drag_split_direction;
3657 let paths = paths.paths().to_vec();
3658 let is_remote = self
3659 .workspace
3660 .update(cx, |workspace, cx| {
3661 if workspace.project().read(cx).is_via_collab() {
3662 workspace.show_error(
3663 &anyhow::anyhow!("Cannot drop files on a remote project"),
3664 cx,
3665 );
3666 true
3667 } else {
3668 false
3669 }
3670 })
3671 .unwrap_or(true);
3672 if is_remote {
3673 return;
3674 }
3675
3676 self.workspace
3677 .update(cx, |workspace, cx| {
3678 let fs = Arc::clone(workspace.project().read(cx).fs());
3679 cx.spawn_in(window, async move |workspace, cx| {
3680 let mut is_file_checks = FuturesUnordered::new();
3681 for path in &paths {
3682 is_file_checks.push(fs.is_file(path))
3683 }
3684 let mut has_files_to_open = false;
3685 while let Some(is_file) = is_file_checks.next().await {
3686 if is_file {
3687 has_files_to_open = true;
3688 break;
3689 }
3690 }
3691 drop(is_file_checks);
3692 if !has_files_to_open {
3693 split_direction = None;
3694 }
3695
3696 if let Ok((open_task, to_pane)) =
3697 workspace.update_in(cx, |workspace, window, cx| {
3698 if let Some(split_direction) = split_direction {
3699 to_pane =
3700 workspace.split_pane(to_pane, split_direction, window, cx);
3701 }
3702 (
3703 workspace.open_paths(
3704 paths,
3705 OpenOptions {
3706 visible: Some(OpenVisible::OnlyDirectories),
3707 ..Default::default()
3708 },
3709 Some(to_pane.downgrade()),
3710 window,
3711 cx,
3712 ),
3713 to_pane,
3714 )
3715 })
3716 {
3717 let opened_items: Vec<_> = open_task.await;
3718 _ = workspace.update_in(cx, |workspace, window, cx| {
3719 for item in opened_items.into_iter().flatten() {
3720 if let Err(e) = item {
3721 workspace.show_error(&e, cx);
3722 }
3723 }
3724 if to_pane.read(cx).items_len() == 0 {
3725 workspace.remove_pane(to_pane, None, window, cx);
3726 }
3727 });
3728 }
3729 })
3730 .detach();
3731 })
3732 .log_err();
3733 }
3734
3735 pub fn display_nav_history_buttons(&mut self, display: Option<bool>) {
3736 self.display_nav_history_buttons = display;
3737 }
3738
3739 fn pinned_item_ids(&self) -> Vec<EntityId> {
3740 self.items
3741 .iter()
3742 .enumerate()
3743 .filter_map(|(index, item)| {
3744 if self.is_tab_pinned(index) {
3745 return Some(item.item_id());
3746 }
3747
3748 None
3749 })
3750 .collect()
3751 }
3752
3753 fn clean_item_ids(&self, cx: &mut Context<Pane>) -> Vec<EntityId> {
3754 self.items()
3755 .filter_map(|item| {
3756 if !item.is_dirty(cx) {
3757 return Some(item.item_id());
3758 }
3759
3760 None
3761 })
3762 .collect()
3763 }
3764
3765 fn to_the_side_item_ids(&self, item_id: EntityId, side: Side) -> Vec<EntityId> {
3766 match side {
3767 Side::Left => self
3768 .items()
3769 .take_while(|item| item.item_id() != item_id)
3770 .map(|item| item.item_id())
3771 .collect(),
3772 Side::Right => self
3773 .items()
3774 .rev()
3775 .take_while(|item| item.item_id() != item_id)
3776 .map(|item| item.item_id())
3777 .collect(),
3778 }
3779 }
3780
3781 fn multibuffer_item_ids(&self, cx: &mut Context<Pane>) -> Vec<EntityId> {
3782 self.items()
3783 .filter(|item| item.buffer_kind(cx) == ItemBufferKind::Multibuffer)
3784 .map(|item| item.item_id())
3785 .collect()
3786 }
3787
3788 pub fn drag_split_direction(&self) -> Option<SplitDirection> {
3789 self.drag_split_direction
3790 }
3791
3792 pub fn set_zoom_out_on_close(&mut self, zoom_out_on_close: bool) {
3793 self.zoom_out_on_close = zoom_out_on_close;
3794 }
3795}
3796
3797fn default_render_tab_bar_buttons(
3798 pane: &mut Pane,
3799 window: &mut Window,
3800 cx: &mut Context<Pane>,
3801) -> (Option<AnyElement>, Option<AnyElement>) {
3802 if !pane.has_focus(window, cx) && !pane.context_menu_focused(window, cx) {
3803 return (None, None);
3804 }
3805 let (can_clone, can_split_move) = match pane.active_item() {
3806 Some(active_item) if active_item.can_split(cx) => (true, false),
3807 Some(_) => (false, pane.items_len() > 1),
3808 None => (false, false),
3809 };
3810 // Ideally we would return a vec of elements here to pass directly to the [TabBar]'s
3811 // `end_slot`, but due to needing a view here that isn't possible.
3812 let right_children = h_flex()
3813 // Instead we need to replicate the spacing from the [TabBar]'s `end_slot` here.
3814 .gap(DynamicSpacing::Base04.rems(cx))
3815 .child(
3816 PopoverMenu::new("pane-tab-bar-popover-menu")
3817 .trigger_with_tooltip(
3818 IconButton::new("plus", IconName::Plus).icon_size(IconSize::Small),
3819 Tooltip::text("New..."),
3820 )
3821 .anchor(Corner::TopRight)
3822 .with_handle(pane.new_item_context_menu_handle.clone())
3823 .menu(move |window, cx| {
3824 Some(ContextMenu::build(window, cx, |menu, _, _| {
3825 menu.action("New File", NewFile.boxed_clone())
3826 .action("Open File", ToggleFileFinder::default().boxed_clone())
3827 .separator()
3828 .action(
3829 "Search Project",
3830 DeploySearch {
3831 replace_enabled: false,
3832 included_files: None,
3833 excluded_files: None,
3834 }
3835 .boxed_clone(),
3836 )
3837 .action("Search Symbols", ToggleProjectSymbols.boxed_clone())
3838 .separator()
3839 .action("New Terminal", NewTerminal.boxed_clone())
3840 }))
3841 }),
3842 )
3843 .child(
3844 PopoverMenu::new("pane-tab-bar-split")
3845 .trigger_with_tooltip(
3846 IconButton::new("split", IconName::Split)
3847 .icon_size(IconSize::Small)
3848 .disabled(!can_clone && !can_split_move),
3849 Tooltip::text("Split Pane"),
3850 )
3851 .anchor(Corner::TopRight)
3852 .with_handle(pane.split_item_context_menu_handle.clone())
3853 .menu(move |window, cx| {
3854 ContextMenu::build(window, cx, |menu, _, _| {
3855 let mode = SplitMode::MovePane;
3856 if can_split_move {
3857 menu.action("Split Right", SplitRight { mode }.boxed_clone())
3858 .action("Split Left", SplitLeft { mode }.boxed_clone())
3859 .action("Split Up", SplitUp { mode }.boxed_clone())
3860 .action("Split Down", SplitDown { mode }.boxed_clone())
3861 } else {
3862 menu.action("Split Right", SplitRight::default().boxed_clone())
3863 .action("Split Left", SplitLeft::default().boxed_clone())
3864 .action("Split Up", SplitUp::default().boxed_clone())
3865 .action("Split Down", SplitDown::default().boxed_clone())
3866 }
3867 })
3868 .into()
3869 }),
3870 )
3871 .child({
3872 let zoomed = pane.is_zoomed();
3873 IconButton::new("toggle_zoom", IconName::Maximize)
3874 .icon_size(IconSize::Small)
3875 .toggle_state(zoomed)
3876 .selected_icon(IconName::Minimize)
3877 .on_click(cx.listener(|pane, _, window, cx| {
3878 pane.toggle_zoom(&crate::ToggleZoom, window, cx);
3879 }))
3880 .tooltip(move |_window, cx| {
3881 Tooltip::for_action(
3882 if zoomed { "Zoom Out" } else { "Zoom In" },
3883 &ToggleZoom,
3884 cx,
3885 )
3886 })
3887 })
3888 .into_any_element()
3889 .into();
3890 (None, right_children)
3891}
3892
3893impl Focusable for Pane {
3894 fn focus_handle(&self, _cx: &App) -> FocusHandle {
3895 self.focus_handle.clone()
3896 }
3897}
3898
3899impl Render for Pane {
3900 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3901 let mut key_context = KeyContext::new_with_defaults();
3902 key_context.add("Pane");
3903 if self.active_item().is_none() {
3904 key_context.add("EmptyPane");
3905 }
3906
3907 self.toolbar
3908 .read(cx)
3909 .contribute_context(&mut key_context, cx);
3910
3911 let should_display_tab_bar = self.should_display_tab_bar.clone();
3912 let display_tab_bar = should_display_tab_bar(window, cx);
3913 let Some(project) = self.project.upgrade() else {
3914 return div().track_focus(&self.focus_handle(cx));
3915 };
3916 let is_local = project.read(cx).is_local();
3917
3918 v_flex()
3919 .key_context(key_context)
3920 .track_focus(&self.focus_handle(cx))
3921 .size_full()
3922 .flex_none()
3923 .overflow_hidden()
3924 .on_action(cx.listener(|pane, split: &SplitLeft, window, cx| {
3925 pane.split(SplitDirection::Left, split.mode, window, cx)
3926 }))
3927 .on_action(cx.listener(|pane, split: &SplitUp, window, cx| {
3928 pane.split(SplitDirection::Up, split.mode, window, cx)
3929 }))
3930 .on_action(cx.listener(|pane, split: &SplitHorizontal, window, cx| {
3931 pane.split(SplitDirection::horizontal(cx), split.mode, window, cx)
3932 }))
3933 .on_action(cx.listener(|pane, split: &SplitVertical, window, cx| {
3934 pane.split(SplitDirection::vertical(cx), split.mode, window, cx)
3935 }))
3936 .on_action(cx.listener(|pane, split: &SplitRight, window, cx| {
3937 pane.split(SplitDirection::Right, split.mode, window, cx)
3938 }))
3939 .on_action(cx.listener(|pane, split: &SplitDown, window, cx| {
3940 pane.split(SplitDirection::Down, split.mode, window, cx)
3941 }))
3942 .on_action(cx.listener(|pane, _: &SplitAndMoveUp, window, cx| {
3943 pane.split(SplitDirection::Up, SplitMode::MovePane, window, cx)
3944 }))
3945 .on_action(cx.listener(|pane, _: &SplitAndMoveDown, window, cx| {
3946 pane.split(SplitDirection::Down, SplitMode::MovePane, window, cx)
3947 }))
3948 .on_action(cx.listener(|pane, _: &SplitAndMoveLeft, window, cx| {
3949 pane.split(SplitDirection::Left, SplitMode::MovePane, window, cx)
3950 }))
3951 .on_action(cx.listener(|pane, _: &SplitAndMoveRight, window, cx| {
3952 pane.split(SplitDirection::Right, SplitMode::MovePane, window, cx)
3953 }))
3954 .on_action(cx.listener(|_, _: &JoinIntoNext, _, cx| {
3955 cx.emit(Event::JoinIntoNext);
3956 }))
3957 .on_action(cx.listener(|_, _: &JoinAll, _, cx| {
3958 cx.emit(Event::JoinAll);
3959 }))
3960 .on_action(cx.listener(Pane::toggle_zoom))
3961 .on_action(cx.listener(Pane::zoom_in))
3962 .on_action(cx.listener(Pane::zoom_out))
3963 .on_action(cx.listener(Self::navigate_backward))
3964 .on_action(cx.listener(Self::navigate_forward))
3965 .on_action(
3966 cx.listener(|pane: &mut Pane, action: &ActivateItem, window, cx| {
3967 pane.activate_item(
3968 action.0.min(pane.items.len().saturating_sub(1)),
3969 true,
3970 true,
3971 window,
3972 cx,
3973 );
3974 }),
3975 )
3976 .on_action(cx.listener(Self::alternate_file))
3977 .on_action(cx.listener(Self::activate_last_item))
3978 .on_action(cx.listener(Self::activate_previous_item))
3979 .on_action(cx.listener(Self::activate_next_item))
3980 .on_action(cx.listener(Self::swap_item_left))
3981 .on_action(cx.listener(Self::swap_item_right))
3982 .on_action(cx.listener(Self::toggle_pin_tab))
3983 .on_action(cx.listener(Self::unpin_all_tabs))
3984 .when(PreviewTabsSettings::get_global(cx).enabled, |this| {
3985 this.on_action(
3986 cx.listener(|pane: &mut Pane, _: &TogglePreviewTab, window, cx| {
3987 if let Some(active_item_id) = pane.active_item().map(|i| i.item_id()) {
3988 if pane.is_active_preview_item(active_item_id) {
3989 pane.unpreview_item_if_preview(active_item_id);
3990 } else {
3991 pane.replace_preview_item_id(active_item_id, window, cx);
3992 }
3993 }
3994 }),
3995 )
3996 })
3997 .on_action(
3998 cx.listener(|pane: &mut Self, action: &CloseActiveItem, window, cx| {
3999 pane.close_active_item(action, window, cx)
4000 .detach_and_log_err(cx)
4001 }),
4002 )
4003 .on_action(
4004 cx.listener(|pane: &mut Self, action: &CloseOtherItems, window, cx| {
4005 pane.close_other_items(action, None, window, cx)
4006 .detach_and_log_err(cx);
4007 }),
4008 )
4009 .on_action(
4010 cx.listener(|pane: &mut Self, action: &CloseCleanItems, window, cx| {
4011 pane.close_clean_items(action, window, cx)
4012 .detach_and_log_err(cx)
4013 }),
4014 )
4015 .on_action(cx.listener(
4016 |pane: &mut Self, action: &CloseItemsToTheLeft, window, cx| {
4017 pane.close_items_to_the_left_by_id(None, action, window, cx)
4018 .detach_and_log_err(cx)
4019 },
4020 ))
4021 .on_action(cx.listener(
4022 |pane: &mut Self, action: &CloseItemsToTheRight, window, cx| {
4023 pane.close_items_to_the_right_by_id(None, action, window, cx)
4024 .detach_and_log_err(cx)
4025 },
4026 ))
4027 .on_action(
4028 cx.listener(|pane: &mut Self, action: &CloseAllItems, window, cx| {
4029 pane.close_all_items(action, window, cx)
4030 .detach_and_log_err(cx)
4031 }),
4032 )
4033 .on_action(cx.listener(
4034 |pane: &mut Self, action: &CloseMultibufferItems, window, cx| {
4035 pane.close_multibuffer_items(action, window, cx)
4036 .detach_and_log_err(cx)
4037 },
4038 ))
4039 .on_action(
4040 cx.listener(|pane: &mut Self, action: &RevealInProjectPanel, _, cx| {
4041 let entry_id = action
4042 .entry_id
4043 .map(ProjectEntryId::from_proto)
4044 .or_else(|| pane.active_item()?.project_entry_ids(cx).first().copied());
4045 if let Some(entry_id) = entry_id {
4046 pane.project
4047 .update(cx, |_, cx| {
4048 cx.emit(project::Event::RevealInProjectPanel(entry_id))
4049 })
4050 .ok();
4051 }
4052 }),
4053 )
4054 .on_action(cx.listener(|_, _: &menu::Cancel, window, cx| {
4055 if cx.stop_active_drag(window) {
4056 } else {
4057 cx.propagate();
4058 }
4059 }))
4060 .when(self.active_item().is_some() && display_tab_bar, |pane| {
4061 pane.child((self.render_tab_bar.clone())(self, window, cx))
4062 })
4063 .child({
4064 let has_worktrees = project.read(cx).visible_worktrees(cx).next().is_some();
4065 // main content
4066 div()
4067 .flex_1()
4068 .relative()
4069 .group("")
4070 .overflow_hidden()
4071 .on_drag_move::<DraggedTab>(cx.listener(Self::handle_drag_move))
4072 .on_drag_move::<DraggedSelection>(cx.listener(Self::handle_drag_move))
4073 .when(is_local, |div| {
4074 div.on_drag_move::<ExternalPaths>(cx.listener(Self::handle_drag_move))
4075 })
4076 .map(|div| {
4077 if let Some(item) = self.active_item() {
4078 div.id("pane_placeholder")
4079 .v_flex()
4080 .size_full()
4081 .overflow_hidden()
4082 .child(self.toolbar.clone())
4083 .child(item.to_any_view())
4084 } else {
4085 let placeholder = div
4086 .id("pane_placeholder")
4087 .h_flex()
4088 .size_full()
4089 .justify_center()
4090 .on_click(cx.listener(
4091 move |this, event: &ClickEvent, window, cx| {
4092 if event.click_count() == 2 {
4093 window.dispatch_action(
4094 this.double_click_dispatch_action.boxed_clone(),
4095 cx,
4096 );
4097 }
4098 },
4099 ));
4100 if has_worktrees {
4101 placeholder
4102 } else {
4103 if self.welcome_page.is_none() {
4104 let workspace = self.workspace.clone();
4105 self.welcome_page = Some(cx.new(|cx| {
4106 crate::welcome::WelcomePage::new(
4107 workspace, true, window, cx,
4108 )
4109 }));
4110 }
4111 placeholder.child(self.welcome_page.clone().unwrap())
4112 }
4113 }
4114 })
4115 .child(
4116 // drag target
4117 div()
4118 .invisible()
4119 .absolute()
4120 .bg(cx.theme().colors().drop_target_background)
4121 .group_drag_over::<DraggedTab>("", |style| style.visible())
4122 .group_drag_over::<DraggedSelection>("", |style| style.visible())
4123 .when(is_local, |div| {
4124 div.group_drag_over::<ExternalPaths>("", |style| style.visible())
4125 })
4126 .when_some(self.can_drop_predicate.clone(), |this, p| {
4127 this.can_drop(move |a, window, cx| p(a, window, cx))
4128 })
4129 .on_drop(cx.listener(move |this, dragged_tab, window, cx| {
4130 this.handle_tab_drop(
4131 dragged_tab,
4132 this.active_item_index(),
4133 window,
4134 cx,
4135 )
4136 }))
4137 .on_drop(cx.listener(
4138 move |this, selection: &DraggedSelection, window, cx| {
4139 this.handle_dragged_selection_drop(selection, None, window, cx)
4140 },
4141 ))
4142 .on_drop(cx.listener(move |this, paths, window, cx| {
4143 this.handle_external_paths_drop(paths, window, cx)
4144 }))
4145 .map(|div| {
4146 let size = DefiniteLength::Fraction(0.5);
4147 match self.drag_split_direction {
4148 None => div.top_0().right_0().bottom_0().left_0(),
4149 Some(SplitDirection::Up) => {
4150 div.top_0().left_0().right_0().h(size)
4151 }
4152 Some(SplitDirection::Down) => {
4153 div.left_0().bottom_0().right_0().h(size)
4154 }
4155 Some(SplitDirection::Left) => {
4156 div.top_0().left_0().bottom_0().w(size)
4157 }
4158 Some(SplitDirection::Right) => {
4159 div.top_0().bottom_0().right_0().w(size)
4160 }
4161 }
4162 }),
4163 )
4164 })
4165 .on_mouse_down(
4166 MouseButton::Navigate(NavigationDirection::Back),
4167 cx.listener(|pane, _, window, cx| {
4168 if let Some(workspace) = pane.workspace.upgrade() {
4169 let pane = cx.entity().downgrade();
4170 window.defer(cx, move |window, cx| {
4171 workspace.update(cx, |workspace, cx| {
4172 workspace.go_back(pane, window, cx).detach_and_log_err(cx)
4173 })
4174 })
4175 }
4176 }),
4177 )
4178 .on_mouse_down(
4179 MouseButton::Navigate(NavigationDirection::Forward),
4180 cx.listener(|pane, _, window, cx| {
4181 if let Some(workspace) = pane.workspace.upgrade() {
4182 let pane = cx.entity().downgrade();
4183 window.defer(cx, move |window, cx| {
4184 workspace.update(cx, |workspace, cx| {
4185 workspace
4186 .go_forward(pane, window, cx)
4187 .detach_and_log_err(cx)
4188 })
4189 })
4190 }
4191 }),
4192 )
4193 }
4194}
4195
4196impl ItemNavHistory {
4197 pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut App) {
4198 if self
4199 .item
4200 .upgrade()
4201 .is_some_and(|item| item.include_in_nav_history())
4202 {
4203 self.history
4204 .push(data, self.item.clone(), self.is_preview, cx);
4205 }
4206 }
4207
4208 pub fn pop_backward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
4209 self.history.pop(NavigationMode::GoingBack, cx)
4210 }
4211
4212 pub fn pop_forward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
4213 self.history.pop(NavigationMode::GoingForward, cx)
4214 }
4215}
4216
4217impl NavHistory {
4218 pub fn for_each_entry(
4219 &self,
4220 cx: &App,
4221 mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
4222 ) {
4223 let borrowed_history = self.0.lock();
4224 borrowed_history
4225 .forward_stack
4226 .iter()
4227 .chain(borrowed_history.backward_stack.iter())
4228 .chain(borrowed_history.closed_stack.iter())
4229 .for_each(|entry| {
4230 if let Some(project_and_abs_path) =
4231 borrowed_history.paths_by_item.get(&entry.item.id())
4232 {
4233 f(entry, project_and_abs_path.clone());
4234 } else if let Some(item) = entry.item.upgrade()
4235 && let Some(path) = item.project_path(cx)
4236 {
4237 f(entry, (path, None));
4238 }
4239 })
4240 }
4241
4242 pub fn set_mode(&mut self, mode: NavigationMode) {
4243 self.0.lock().mode = mode;
4244 }
4245
4246 pub fn mode(&self) -> NavigationMode {
4247 self.0.lock().mode
4248 }
4249
4250 pub fn disable(&mut self) {
4251 self.0.lock().mode = NavigationMode::Disabled;
4252 }
4253
4254 pub fn enable(&mut self) {
4255 self.0.lock().mode = NavigationMode::Normal;
4256 }
4257
4258 pub fn clear(&mut self, cx: &mut App) {
4259 let mut state = self.0.lock();
4260
4261 if state.backward_stack.is_empty()
4262 && state.forward_stack.is_empty()
4263 && state.closed_stack.is_empty()
4264 && state.paths_by_item.is_empty()
4265 {
4266 return;
4267 }
4268
4269 state.mode = NavigationMode::Normal;
4270 state.backward_stack.clear();
4271 state.forward_stack.clear();
4272 state.closed_stack.clear();
4273 state.paths_by_item.clear();
4274 state.did_update(cx);
4275 }
4276
4277 pub fn pop(&mut self, mode: NavigationMode, cx: &mut App) -> Option<NavigationEntry> {
4278 let mut state = self.0.lock();
4279 let entry = match mode {
4280 NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
4281 return None;
4282 }
4283 NavigationMode::GoingBack => &mut state.backward_stack,
4284 NavigationMode::GoingForward => &mut state.forward_stack,
4285 NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
4286 }
4287 .pop_back();
4288 if entry.is_some() {
4289 state.did_update(cx);
4290 }
4291 entry
4292 }
4293
4294 pub fn push<D: 'static + Send + Any>(
4295 &mut self,
4296 data: Option<D>,
4297 item: Arc<dyn WeakItemHandle>,
4298 is_preview: bool,
4299 cx: &mut App,
4300 ) {
4301 let state = &mut *self.0.lock();
4302 match state.mode {
4303 NavigationMode::Disabled => {}
4304 NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
4305 if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4306 state.backward_stack.pop_front();
4307 }
4308 state.backward_stack.push_back(NavigationEntry {
4309 item,
4310 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4311 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4312 is_preview,
4313 });
4314 state.forward_stack.clear();
4315 }
4316 NavigationMode::GoingBack => {
4317 if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4318 state.forward_stack.pop_front();
4319 }
4320 state.forward_stack.push_back(NavigationEntry {
4321 item,
4322 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4323 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4324 is_preview,
4325 });
4326 }
4327 NavigationMode::GoingForward => {
4328 if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4329 state.backward_stack.pop_front();
4330 }
4331 state.backward_stack.push_back(NavigationEntry {
4332 item,
4333 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4334 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4335 is_preview,
4336 });
4337 }
4338 NavigationMode::ClosingItem if is_preview => return,
4339 NavigationMode::ClosingItem => {
4340 if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4341 state.closed_stack.pop_front();
4342 }
4343 state.closed_stack.push_back(NavigationEntry {
4344 item,
4345 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4346 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4347 is_preview,
4348 });
4349 }
4350 }
4351 state.did_update(cx);
4352 }
4353
4354 pub fn remove_item(&mut self, item_id: EntityId) {
4355 let mut state = self.0.lock();
4356 state.paths_by_item.remove(&item_id);
4357 state
4358 .backward_stack
4359 .retain(|entry| entry.item.id() != item_id);
4360 state
4361 .forward_stack
4362 .retain(|entry| entry.item.id() != item_id);
4363 state
4364 .closed_stack
4365 .retain(|entry| entry.item.id() != item_id);
4366 }
4367
4368 pub fn rename_item(
4369 &mut self,
4370 item_id: EntityId,
4371 project_path: ProjectPath,
4372 abs_path: Option<PathBuf>,
4373 ) {
4374 let mut state = self.0.lock();
4375 let path_for_item = state.paths_by_item.get_mut(&item_id);
4376 if let Some(path_for_item) = path_for_item {
4377 path_for_item.0 = project_path;
4378 path_for_item.1 = abs_path;
4379 }
4380 }
4381
4382 pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
4383 self.0.lock().paths_by_item.get(&item_id).cloned()
4384 }
4385}
4386
4387impl NavHistoryState {
4388 pub fn did_update(&self, cx: &mut App) {
4389 if let Some(pane) = self.pane.upgrade() {
4390 cx.defer(move |cx| {
4391 pane.update(cx, |pane, cx| pane.history_updated(cx));
4392 });
4393 }
4394 }
4395}
4396
4397fn dirty_message_for(buffer_path: Option<ProjectPath>, path_style: PathStyle) -> String {
4398 let path = buffer_path
4399 .as_ref()
4400 .and_then(|p| {
4401 let path = p.path.display(path_style);
4402 if path.is_empty() { None } else { Some(path) }
4403 })
4404 .unwrap_or("This buffer".into());
4405 let path = truncate_and_remove_front(&path, 80);
4406 format!("{path} contains unsaved edits. Do you want to save it?")
4407}
4408
4409pub fn tab_details(items: &[Box<dyn ItemHandle>], _window: &Window, cx: &App) -> Vec<usize> {
4410 let mut tab_details = items.iter().map(|_| 0).collect::<Vec<_>>();
4411 let mut tab_descriptions = HashMap::default();
4412 let mut done = false;
4413 while !done {
4414 done = true;
4415
4416 // Store item indices by their tab description.
4417 for (ix, (item, detail)) in items.iter().zip(&tab_details).enumerate() {
4418 let description = item.tab_content_text(*detail, cx);
4419 if *detail == 0 || description != item.tab_content_text(detail - 1, cx) {
4420 tab_descriptions
4421 .entry(description)
4422 .or_insert(Vec::new())
4423 .push(ix);
4424 }
4425 }
4426
4427 // If two or more items have the same tab description, increase their level
4428 // of detail and try again.
4429 for (_, item_ixs) in tab_descriptions.drain() {
4430 if item_ixs.len() > 1 {
4431 done = false;
4432 for ix in item_ixs {
4433 tab_details[ix] += 1;
4434 }
4435 }
4436 }
4437 }
4438
4439 tab_details
4440}
4441
4442pub fn render_item_indicator(item: Box<dyn ItemHandle>, cx: &App) -> Option<Indicator> {
4443 maybe!({
4444 let indicator_color = match (item.has_conflict(cx), item.is_dirty(cx)) {
4445 (true, _) => Color::Warning,
4446 (_, true) => Color::Accent,
4447 (false, false) => return None,
4448 };
4449
4450 Some(Indicator::dot().color(indicator_color))
4451 })
4452}
4453
4454impl Render for DraggedTab {
4455 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4456 let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
4457 let label = self.item.tab_content(
4458 TabContentParams {
4459 detail: Some(self.detail),
4460 selected: false,
4461 preview: false,
4462 deemphasized: false,
4463 },
4464 window,
4465 cx,
4466 );
4467 Tab::new("")
4468 .toggle_state(self.is_active)
4469 .child(label)
4470 .render(window, cx)
4471 .font(ui_font)
4472 }
4473}
4474
4475#[cfg(test)]
4476mod tests {
4477 use std::{iter::zip, num::NonZero};
4478
4479 use super::*;
4480 use crate::{
4481 Member,
4482 item::test::{TestItem, TestProjectItem},
4483 };
4484 use gpui::{AppContext, Axis, TestAppContext, VisualTestContext, size};
4485 use project::FakeFs;
4486 use settings::SettingsStore;
4487 use theme::LoadThemes;
4488 use util::TryFutureExt;
4489
4490 #[gpui::test]
4491 async fn test_add_item_capped_to_max_tabs(cx: &mut TestAppContext) {
4492 init_test(cx);
4493 let fs = FakeFs::new(cx.executor());
4494
4495 let project = Project::test(fs, None, cx).await;
4496 let (workspace, cx) =
4497 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4498 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4499
4500 for i in 0..7 {
4501 add_labeled_item(&pane, format!("{}", i).as_str(), false, cx);
4502 }
4503
4504 set_max_tabs(cx, Some(5));
4505 add_labeled_item(&pane, "7", false, cx);
4506 // Remove items to respect the max tab cap.
4507 assert_item_labels(&pane, ["3", "4", "5", "6", "7*"], cx);
4508 pane.update_in(cx, |pane, window, cx| {
4509 pane.activate_item(0, false, false, window, cx);
4510 });
4511 add_labeled_item(&pane, "X", false, cx);
4512 // Respect activation order.
4513 assert_item_labels(&pane, ["3", "X*", "5", "6", "7"], cx);
4514
4515 for i in 0..7 {
4516 add_labeled_item(&pane, format!("D{}", i).as_str(), true, cx);
4517 }
4518 // Keeps dirty items, even over max tab cap.
4519 assert_item_labels(
4520 &pane,
4521 ["D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6*^"],
4522 cx,
4523 );
4524
4525 set_max_tabs(cx, None);
4526 for i in 0..7 {
4527 add_labeled_item(&pane, format!("N{}", i).as_str(), false, cx);
4528 }
4529 // No cap when max tabs is None.
4530 assert_item_labels(
4531 &pane,
4532 [
4533 "D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6^", "N0", "N1", "N2", "N3", "N4",
4534 "N5", "N6*",
4535 ],
4536 cx,
4537 );
4538 }
4539
4540 #[gpui::test]
4541 async fn test_reduce_max_tabs_closes_existing_items(cx: &mut TestAppContext) {
4542 init_test(cx);
4543 let fs = FakeFs::new(cx.executor());
4544
4545 let project = Project::test(fs, None, cx).await;
4546 let (workspace, cx) =
4547 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4548 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4549
4550 add_labeled_item(&pane, "A", false, cx);
4551 add_labeled_item(&pane, "B", false, cx);
4552 let item_c = add_labeled_item(&pane, "C", false, cx);
4553 let item_d = add_labeled_item(&pane, "D", false, cx);
4554 add_labeled_item(&pane, "E", false, cx);
4555 add_labeled_item(&pane, "Settings", false, cx);
4556 assert_item_labels(&pane, ["A", "B", "C", "D", "E", "Settings*"], cx);
4557
4558 set_max_tabs(cx, Some(5));
4559 assert_item_labels(&pane, ["B", "C", "D", "E", "Settings*"], cx);
4560
4561 set_max_tabs(cx, Some(4));
4562 assert_item_labels(&pane, ["C", "D", "E", "Settings*"], cx);
4563
4564 pane.update_in(cx, |pane, window, cx| {
4565 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4566 pane.pin_tab_at(ix, window, cx);
4567
4568 let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4569 pane.pin_tab_at(ix, window, cx);
4570 });
4571 assert_item_labels(&pane, ["C!", "D!", "E", "Settings*"], cx);
4572
4573 set_max_tabs(cx, Some(2));
4574 assert_item_labels(&pane, ["C!", "D!", "Settings*"], cx);
4575 }
4576
4577 #[gpui::test]
4578 async fn test_allow_pinning_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
4579 init_test(cx);
4580 let fs = FakeFs::new(cx.executor());
4581
4582 let project = Project::test(fs, None, cx).await;
4583 let (workspace, cx) =
4584 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4585 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4586
4587 set_max_tabs(cx, Some(1));
4588 let item_a = add_labeled_item(&pane, "A", true, cx);
4589
4590 pane.update_in(cx, |pane, window, cx| {
4591 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4592 pane.pin_tab_at(ix, window, cx);
4593 });
4594 assert_item_labels(&pane, ["A*^!"], cx);
4595 }
4596
4597 #[gpui::test]
4598 async fn test_allow_pinning_non_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
4599 init_test(cx);
4600 let fs = FakeFs::new(cx.executor());
4601
4602 let project = Project::test(fs, None, cx).await;
4603 let (workspace, cx) =
4604 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4605 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4606
4607 set_max_tabs(cx, Some(1));
4608 let item_a = add_labeled_item(&pane, "A", false, cx);
4609
4610 pane.update_in(cx, |pane, window, cx| {
4611 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4612 pane.pin_tab_at(ix, window, cx);
4613 });
4614 assert_item_labels(&pane, ["A*!"], cx);
4615 }
4616
4617 #[gpui::test]
4618 async fn test_pin_tabs_incrementally_at_max_capacity(cx: &mut TestAppContext) {
4619 init_test(cx);
4620 let fs = FakeFs::new(cx.executor());
4621
4622 let project = Project::test(fs, None, cx).await;
4623 let (workspace, cx) =
4624 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4625 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4626
4627 set_max_tabs(cx, Some(3));
4628
4629 let item_a = add_labeled_item(&pane, "A", false, cx);
4630 assert_item_labels(&pane, ["A*"], cx);
4631
4632 pane.update_in(cx, |pane, window, cx| {
4633 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4634 pane.pin_tab_at(ix, window, cx);
4635 });
4636 assert_item_labels(&pane, ["A*!"], cx);
4637
4638 let item_b = add_labeled_item(&pane, "B", false, cx);
4639 assert_item_labels(&pane, ["A!", "B*"], cx);
4640
4641 pane.update_in(cx, |pane, window, cx| {
4642 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4643 pane.pin_tab_at(ix, window, cx);
4644 });
4645 assert_item_labels(&pane, ["A!", "B*!"], cx);
4646
4647 let item_c = add_labeled_item(&pane, "C", false, cx);
4648 assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4649
4650 pane.update_in(cx, |pane, window, cx| {
4651 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4652 pane.pin_tab_at(ix, window, cx);
4653 });
4654 assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4655 }
4656
4657 #[gpui::test]
4658 async fn test_pin_tabs_left_to_right_after_opening_at_max_capacity(cx: &mut TestAppContext) {
4659 init_test(cx);
4660 let fs = FakeFs::new(cx.executor());
4661
4662 let project = Project::test(fs, None, cx).await;
4663 let (workspace, cx) =
4664 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4665 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4666
4667 set_max_tabs(cx, Some(3));
4668
4669 let item_a = add_labeled_item(&pane, "A", false, cx);
4670 assert_item_labels(&pane, ["A*"], cx);
4671
4672 let item_b = add_labeled_item(&pane, "B", false, cx);
4673 assert_item_labels(&pane, ["A", "B*"], cx);
4674
4675 let item_c = add_labeled_item(&pane, "C", false, cx);
4676 assert_item_labels(&pane, ["A", "B", "C*"], cx);
4677
4678 pane.update_in(cx, |pane, window, cx| {
4679 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4680 pane.pin_tab_at(ix, window, cx);
4681 });
4682 assert_item_labels(&pane, ["A!", "B", "C*"], cx);
4683
4684 pane.update_in(cx, |pane, window, cx| {
4685 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4686 pane.pin_tab_at(ix, window, cx);
4687 });
4688 assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4689
4690 pane.update_in(cx, |pane, window, cx| {
4691 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4692 pane.pin_tab_at(ix, window, cx);
4693 });
4694 assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4695 }
4696
4697 #[gpui::test]
4698 async fn test_pin_tabs_right_to_left_after_opening_at_max_capacity(cx: &mut TestAppContext) {
4699 init_test(cx);
4700 let fs = FakeFs::new(cx.executor());
4701
4702 let project = Project::test(fs, None, cx).await;
4703 let (workspace, cx) =
4704 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4705 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4706
4707 set_max_tabs(cx, Some(3));
4708
4709 let item_a = add_labeled_item(&pane, "A", false, cx);
4710 assert_item_labels(&pane, ["A*"], cx);
4711
4712 let item_b = add_labeled_item(&pane, "B", false, cx);
4713 assert_item_labels(&pane, ["A", "B*"], cx);
4714
4715 let item_c = add_labeled_item(&pane, "C", false, cx);
4716 assert_item_labels(&pane, ["A", "B", "C*"], cx);
4717
4718 pane.update_in(cx, |pane, window, cx| {
4719 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4720 pane.pin_tab_at(ix, window, cx);
4721 });
4722 assert_item_labels(&pane, ["C*!", "A", "B"], cx);
4723
4724 pane.update_in(cx, |pane, window, cx| {
4725 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4726 pane.pin_tab_at(ix, window, cx);
4727 });
4728 assert_item_labels(&pane, ["C*!", "B!", "A"], cx);
4729
4730 pane.update_in(cx, |pane, window, cx| {
4731 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4732 pane.pin_tab_at(ix, window, cx);
4733 });
4734 assert_item_labels(&pane, ["C*!", "B!", "A!"], cx);
4735 }
4736
4737 #[gpui::test]
4738 async fn test_pinned_tabs_never_closed_at_max_tabs(cx: &mut TestAppContext) {
4739 init_test(cx);
4740 let fs = FakeFs::new(cx.executor());
4741
4742 let project = Project::test(fs, None, cx).await;
4743 let (workspace, cx) =
4744 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4745 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4746
4747 let item_a = add_labeled_item(&pane, "A", false, cx);
4748 pane.update_in(cx, |pane, window, cx| {
4749 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4750 pane.pin_tab_at(ix, window, cx);
4751 });
4752
4753 let item_b = add_labeled_item(&pane, "B", false, cx);
4754 pane.update_in(cx, |pane, window, cx| {
4755 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4756 pane.pin_tab_at(ix, window, cx);
4757 });
4758
4759 add_labeled_item(&pane, "C", false, cx);
4760 add_labeled_item(&pane, "D", false, cx);
4761 add_labeled_item(&pane, "E", false, cx);
4762 assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
4763
4764 set_max_tabs(cx, Some(3));
4765 add_labeled_item(&pane, "F", false, cx);
4766 assert_item_labels(&pane, ["A!", "B!", "F*"], cx);
4767
4768 add_labeled_item(&pane, "G", false, cx);
4769 assert_item_labels(&pane, ["A!", "B!", "G*"], cx);
4770
4771 add_labeled_item(&pane, "H", false, cx);
4772 assert_item_labels(&pane, ["A!", "B!", "H*"], cx);
4773 }
4774
4775 #[gpui::test]
4776 async fn test_always_allows_one_unpinned_item_over_max_tabs_regardless_of_pinned_count(
4777 cx: &mut TestAppContext,
4778 ) {
4779 init_test(cx);
4780 let fs = FakeFs::new(cx.executor());
4781
4782 let project = Project::test(fs, None, cx).await;
4783 let (workspace, cx) =
4784 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4785 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4786
4787 set_max_tabs(cx, Some(3));
4788
4789 let item_a = add_labeled_item(&pane, "A", false, cx);
4790 pane.update_in(cx, |pane, window, cx| {
4791 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4792 pane.pin_tab_at(ix, window, cx);
4793 });
4794
4795 let item_b = add_labeled_item(&pane, "B", false, cx);
4796 pane.update_in(cx, |pane, window, cx| {
4797 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4798 pane.pin_tab_at(ix, window, cx);
4799 });
4800
4801 let item_c = add_labeled_item(&pane, "C", false, cx);
4802 pane.update_in(cx, |pane, window, cx| {
4803 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4804 pane.pin_tab_at(ix, window, cx);
4805 });
4806
4807 assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4808
4809 let item_d = add_labeled_item(&pane, "D", false, cx);
4810 assert_item_labels(&pane, ["A!", "B!", "C!", "D*"], cx);
4811
4812 pane.update_in(cx, |pane, window, cx| {
4813 let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4814 pane.pin_tab_at(ix, window, cx);
4815 });
4816 assert_item_labels(&pane, ["A!", "B!", "C!", "D*!"], cx);
4817
4818 add_labeled_item(&pane, "E", false, cx);
4819 assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "E*"], cx);
4820
4821 add_labeled_item(&pane, "F", false, cx);
4822 assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "F*"], cx);
4823 }
4824
4825 #[gpui::test]
4826 async fn test_can_open_one_item_when_all_tabs_are_dirty_at_max(cx: &mut TestAppContext) {
4827 init_test(cx);
4828 let fs = FakeFs::new(cx.executor());
4829
4830 let project = Project::test(fs, None, cx).await;
4831 let (workspace, cx) =
4832 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4833 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4834
4835 set_max_tabs(cx, Some(3));
4836
4837 add_labeled_item(&pane, "A", true, cx);
4838 assert_item_labels(&pane, ["A*^"], cx);
4839
4840 add_labeled_item(&pane, "B", true, cx);
4841 assert_item_labels(&pane, ["A^", "B*^"], cx);
4842
4843 add_labeled_item(&pane, "C", true, cx);
4844 assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
4845
4846 add_labeled_item(&pane, "D", false, cx);
4847 assert_item_labels(&pane, ["A^", "B^", "C^", "D*"], cx);
4848
4849 add_labeled_item(&pane, "E", false, cx);
4850 assert_item_labels(&pane, ["A^", "B^", "C^", "E*"], cx);
4851
4852 add_labeled_item(&pane, "F", false, cx);
4853 assert_item_labels(&pane, ["A^", "B^", "C^", "F*"], cx);
4854
4855 add_labeled_item(&pane, "G", true, cx);
4856 assert_item_labels(&pane, ["A^", "B^", "C^", "G*^"], cx);
4857 }
4858
4859 #[gpui::test]
4860 async fn test_toggle_pin_tab(cx: &mut TestAppContext) {
4861 init_test(cx);
4862 let fs = FakeFs::new(cx.executor());
4863
4864 let project = Project::test(fs, None, cx).await;
4865 let (workspace, cx) =
4866 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4867 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4868
4869 set_labeled_items(&pane, ["A", "B*", "C"], cx);
4870 assert_item_labels(&pane, ["A", "B*", "C"], cx);
4871
4872 pane.update_in(cx, |pane, window, cx| {
4873 pane.toggle_pin_tab(&TogglePinTab, window, cx);
4874 });
4875 assert_item_labels(&pane, ["B*!", "A", "C"], cx);
4876
4877 pane.update_in(cx, |pane, window, cx| {
4878 pane.toggle_pin_tab(&TogglePinTab, window, cx);
4879 });
4880 assert_item_labels(&pane, ["B*", "A", "C"], cx);
4881 }
4882
4883 #[gpui::test]
4884 async fn test_unpin_all_tabs(cx: &mut TestAppContext) {
4885 init_test(cx);
4886 let fs = FakeFs::new(cx.executor());
4887
4888 let project = Project::test(fs, None, cx).await;
4889 let (workspace, cx) =
4890 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4891 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4892
4893 // Unpin all, in an empty pane
4894 pane.update_in(cx, |pane, window, cx| {
4895 pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4896 });
4897
4898 assert_item_labels(&pane, [], cx);
4899
4900 let item_a = add_labeled_item(&pane, "A", false, cx);
4901 let item_b = add_labeled_item(&pane, "B", false, cx);
4902 let item_c = add_labeled_item(&pane, "C", false, cx);
4903 assert_item_labels(&pane, ["A", "B", "C*"], cx);
4904
4905 // Unpin all, when no tabs are pinned
4906 pane.update_in(cx, |pane, window, cx| {
4907 pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4908 });
4909
4910 assert_item_labels(&pane, ["A", "B", "C*"], cx);
4911
4912 // Pin inactive tabs only
4913 pane.update_in(cx, |pane, window, cx| {
4914 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4915 pane.pin_tab_at(ix, window, cx);
4916
4917 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4918 pane.pin_tab_at(ix, window, cx);
4919 });
4920 assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4921
4922 pane.update_in(cx, |pane, window, cx| {
4923 pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4924 });
4925
4926 assert_item_labels(&pane, ["A", "B", "C*"], cx);
4927
4928 // Pin all tabs
4929 pane.update_in(cx, |pane, window, cx| {
4930 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4931 pane.pin_tab_at(ix, window, cx);
4932
4933 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4934 pane.pin_tab_at(ix, window, cx);
4935
4936 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4937 pane.pin_tab_at(ix, window, cx);
4938 });
4939 assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4940
4941 // Activate middle tab
4942 pane.update_in(cx, |pane, window, cx| {
4943 pane.activate_item(1, false, false, window, cx);
4944 });
4945 assert_item_labels(&pane, ["A!", "B*!", "C!"], cx);
4946
4947 pane.update_in(cx, |pane, window, cx| {
4948 pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4949 });
4950
4951 // Order has not changed
4952 assert_item_labels(&pane, ["A", "B*", "C"], cx);
4953 }
4954
4955 #[gpui::test]
4956 async fn test_pinning_active_tab_without_position_change_maintains_focus(
4957 cx: &mut TestAppContext,
4958 ) {
4959 init_test(cx);
4960 let fs = FakeFs::new(cx.executor());
4961
4962 let project = Project::test(fs, None, cx).await;
4963 let (workspace, cx) =
4964 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4965 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4966
4967 // Add A
4968 let item_a = add_labeled_item(&pane, "A", false, cx);
4969 assert_item_labels(&pane, ["A*"], cx);
4970
4971 // Add B
4972 add_labeled_item(&pane, "B", false, cx);
4973 assert_item_labels(&pane, ["A", "B*"], cx);
4974
4975 // Activate A again
4976 pane.update_in(cx, |pane, window, cx| {
4977 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4978 pane.activate_item(ix, true, true, window, cx);
4979 });
4980 assert_item_labels(&pane, ["A*", "B"], cx);
4981
4982 // Pin A - remains active
4983 pane.update_in(cx, |pane, window, cx| {
4984 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4985 pane.pin_tab_at(ix, window, cx);
4986 });
4987 assert_item_labels(&pane, ["A*!", "B"], cx);
4988
4989 // Unpin A - remain active
4990 pane.update_in(cx, |pane, window, cx| {
4991 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4992 pane.unpin_tab_at(ix, window, cx);
4993 });
4994 assert_item_labels(&pane, ["A*", "B"], cx);
4995 }
4996
4997 #[gpui::test]
4998 async fn test_pinning_active_tab_with_position_change_maintains_focus(cx: &mut TestAppContext) {
4999 init_test(cx);
5000 let fs = FakeFs::new(cx.executor());
5001
5002 let project = Project::test(fs, None, cx).await;
5003 let (workspace, cx) =
5004 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5005 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5006
5007 // Add A, B, C
5008 add_labeled_item(&pane, "A", false, cx);
5009 add_labeled_item(&pane, "B", false, cx);
5010 let item_c = add_labeled_item(&pane, "C", false, cx);
5011 assert_item_labels(&pane, ["A", "B", "C*"], cx);
5012
5013 // Pin C - moves to pinned area, remains active
5014 pane.update_in(cx, |pane, window, cx| {
5015 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5016 pane.pin_tab_at(ix, window, cx);
5017 });
5018 assert_item_labels(&pane, ["C*!", "A", "B"], cx);
5019
5020 // Unpin C - moves after pinned area, remains active
5021 pane.update_in(cx, |pane, window, cx| {
5022 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5023 pane.unpin_tab_at(ix, window, cx);
5024 });
5025 assert_item_labels(&pane, ["C*", "A", "B"], cx);
5026 }
5027
5028 #[gpui::test]
5029 async fn test_pinning_inactive_tab_without_position_change_preserves_existing_focus(
5030 cx: &mut TestAppContext,
5031 ) {
5032 init_test(cx);
5033 let fs = FakeFs::new(cx.executor());
5034
5035 let project = Project::test(fs, None, cx).await;
5036 let (workspace, cx) =
5037 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5038 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5039
5040 // Add A, B
5041 let item_a = add_labeled_item(&pane, "A", false, cx);
5042 add_labeled_item(&pane, "B", false, cx);
5043 assert_item_labels(&pane, ["A", "B*"], cx);
5044
5045 // Pin A - already in pinned area, B remains active
5046 pane.update_in(cx, |pane, window, cx| {
5047 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5048 pane.pin_tab_at(ix, window, cx);
5049 });
5050 assert_item_labels(&pane, ["A!", "B*"], cx);
5051
5052 // Unpin A - stays in place, B remains active
5053 pane.update_in(cx, |pane, window, cx| {
5054 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5055 pane.unpin_tab_at(ix, window, cx);
5056 });
5057 assert_item_labels(&pane, ["A", "B*"], cx);
5058 }
5059
5060 #[gpui::test]
5061 async fn test_pinning_inactive_tab_with_position_change_preserves_existing_focus(
5062 cx: &mut TestAppContext,
5063 ) {
5064 init_test(cx);
5065 let fs = FakeFs::new(cx.executor());
5066
5067 let project = Project::test(fs, None, cx).await;
5068 let (workspace, cx) =
5069 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5070 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5071
5072 // Add A, B, C
5073 add_labeled_item(&pane, "A", false, cx);
5074 let item_b = add_labeled_item(&pane, "B", false, cx);
5075 let item_c = add_labeled_item(&pane, "C", false, cx);
5076 assert_item_labels(&pane, ["A", "B", "C*"], cx);
5077
5078 // Activate B
5079 pane.update_in(cx, |pane, window, cx| {
5080 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5081 pane.activate_item(ix, true, true, window, cx);
5082 });
5083 assert_item_labels(&pane, ["A", "B*", "C"], cx);
5084
5085 // Pin C - moves to pinned area, B remains active
5086 pane.update_in(cx, |pane, window, cx| {
5087 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5088 pane.pin_tab_at(ix, window, cx);
5089 });
5090 assert_item_labels(&pane, ["C!", "A", "B*"], cx);
5091
5092 // Unpin C - moves after pinned area, B remains active
5093 pane.update_in(cx, |pane, window, cx| {
5094 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5095 pane.unpin_tab_at(ix, window, cx);
5096 });
5097 assert_item_labels(&pane, ["C", "A", "B*"], cx);
5098 }
5099
5100 #[gpui::test]
5101 async fn test_drag_unpinned_tab_to_split_creates_pane_with_unpinned_tab(
5102 cx: &mut TestAppContext,
5103 ) {
5104 init_test(cx);
5105 let fs = FakeFs::new(cx.executor());
5106
5107 let project = Project::test(fs, None, cx).await;
5108 let (workspace, cx) =
5109 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5110 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5111
5112 // Add A, B. Pin B. Activate A
5113 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5114 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5115
5116 pane_a.update_in(cx, |pane, window, cx| {
5117 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5118 pane.pin_tab_at(ix, window, cx);
5119
5120 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5121 pane.activate_item(ix, true, true, window, cx);
5122 });
5123
5124 // Drag A to create new split
5125 pane_a.update_in(cx, |pane, window, cx| {
5126 pane.drag_split_direction = Some(SplitDirection::Right);
5127
5128 let dragged_tab = DraggedTab {
5129 pane: pane_a.clone(),
5130 item: item_a.boxed_clone(),
5131 ix: 0,
5132 detail: 0,
5133 is_active: true,
5134 };
5135 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5136 });
5137
5138 // A should be moved to new pane. B should remain pinned, A should not be pinned
5139 let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
5140 let panes = workspace.panes();
5141 (panes[0].clone(), panes[1].clone())
5142 });
5143 assert_item_labels(&pane_a, ["B*!"], cx);
5144 assert_item_labels(&pane_b, ["A*"], cx);
5145 }
5146
5147 #[gpui::test]
5148 async fn test_drag_pinned_tab_to_split_creates_pane_with_pinned_tab(cx: &mut TestAppContext) {
5149 init_test(cx);
5150 let fs = FakeFs::new(cx.executor());
5151
5152 let project = Project::test(fs, None, cx).await;
5153 let (workspace, cx) =
5154 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5155 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5156
5157 // Add A, B. Pin both. Activate A
5158 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5159 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5160
5161 pane_a.update_in(cx, |pane, window, cx| {
5162 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5163 pane.pin_tab_at(ix, window, cx);
5164
5165 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5166 pane.pin_tab_at(ix, window, cx);
5167
5168 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5169 pane.activate_item(ix, true, true, window, cx);
5170 });
5171 assert_item_labels(&pane_a, ["A*!", "B!"], cx);
5172
5173 // Drag A to create new split
5174 pane_a.update_in(cx, |pane, window, cx| {
5175 pane.drag_split_direction = Some(SplitDirection::Right);
5176
5177 let dragged_tab = DraggedTab {
5178 pane: pane_a.clone(),
5179 item: item_a.boxed_clone(),
5180 ix: 0,
5181 detail: 0,
5182 is_active: true,
5183 };
5184 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5185 });
5186
5187 // A should be moved to new pane. Both A and B should still be pinned
5188 let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
5189 let panes = workspace.panes();
5190 (panes[0].clone(), panes[1].clone())
5191 });
5192 assert_item_labels(&pane_a, ["B*!"], cx);
5193 assert_item_labels(&pane_b, ["A*!"], cx);
5194 }
5195
5196 #[gpui::test]
5197 async fn test_drag_pinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
5198 init_test(cx);
5199 let fs = FakeFs::new(cx.executor());
5200
5201 let project = Project::test(fs, None, cx).await;
5202 let (workspace, cx) =
5203 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5204 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5205
5206 // Add A to pane A and pin
5207 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5208 pane_a.update_in(cx, |pane, window, cx| {
5209 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5210 pane.pin_tab_at(ix, window, cx);
5211 });
5212 assert_item_labels(&pane_a, ["A*!"], cx);
5213
5214 // Add B to pane B and pin
5215 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5216 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5217 });
5218 let item_b = add_labeled_item(&pane_b, "B", false, cx);
5219 pane_b.update_in(cx, |pane, window, cx| {
5220 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5221 pane.pin_tab_at(ix, window, cx);
5222 });
5223 assert_item_labels(&pane_b, ["B*!"], cx);
5224
5225 // Move A from pane A to pane B's pinned region
5226 pane_b.update_in(cx, |pane, window, cx| {
5227 let dragged_tab = DraggedTab {
5228 pane: pane_a.clone(),
5229 item: item_a.boxed_clone(),
5230 ix: 0,
5231 detail: 0,
5232 is_active: true,
5233 };
5234 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5235 });
5236
5237 // A should stay pinned
5238 assert_item_labels(&pane_a, [], cx);
5239 assert_item_labels(&pane_b, ["A*!", "B!"], cx);
5240 }
5241
5242 #[gpui::test]
5243 async fn test_drag_pinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
5244 init_test(cx);
5245 let fs = FakeFs::new(cx.executor());
5246
5247 let project = Project::test(fs, None, cx).await;
5248 let (workspace, cx) =
5249 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5250 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5251
5252 // Add A to pane A and pin
5253 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5254 pane_a.update_in(cx, |pane, window, cx| {
5255 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5256 pane.pin_tab_at(ix, window, cx);
5257 });
5258 assert_item_labels(&pane_a, ["A*!"], cx);
5259
5260 // Create pane B with pinned item B
5261 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5262 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5263 });
5264 let item_b = add_labeled_item(&pane_b, "B", false, cx);
5265 assert_item_labels(&pane_b, ["B*"], cx);
5266
5267 pane_b.update_in(cx, |pane, window, cx| {
5268 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5269 pane.pin_tab_at(ix, window, cx);
5270 });
5271 assert_item_labels(&pane_b, ["B*!"], cx);
5272
5273 // Move A from pane A to pane B's unpinned region
5274 pane_b.update_in(cx, |pane, window, cx| {
5275 let dragged_tab = DraggedTab {
5276 pane: pane_a.clone(),
5277 item: item_a.boxed_clone(),
5278 ix: 0,
5279 detail: 0,
5280 is_active: true,
5281 };
5282 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5283 });
5284
5285 // A should become pinned
5286 assert_item_labels(&pane_a, [], cx);
5287 assert_item_labels(&pane_b, ["B!", "A*"], cx);
5288 }
5289
5290 #[gpui::test]
5291 async fn test_drag_pinned_tab_into_existing_panes_first_position_with_no_pinned_tabs(
5292 cx: &mut TestAppContext,
5293 ) {
5294 init_test(cx);
5295 let fs = FakeFs::new(cx.executor());
5296
5297 let project = Project::test(fs, None, cx).await;
5298 let (workspace, cx) =
5299 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5300 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5301
5302 // Add A to pane A and pin
5303 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5304 pane_a.update_in(cx, |pane, window, cx| {
5305 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5306 pane.pin_tab_at(ix, window, cx);
5307 });
5308 assert_item_labels(&pane_a, ["A*!"], cx);
5309
5310 // Add B to pane B
5311 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5312 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5313 });
5314 add_labeled_item(&pane_b, "B", false, cx);
5315 assert_item_labels(&pane_b, ["B*"], cx);
5316
5317 // Move A from pane A to position 0 in pane B, indicating it should stay pinned
5318 pane_b.update_in(cx, |pane, window, cx| {
5319 let dragged_tab = DraggedTab {
5320 pane: pane_a.clone(),
5321 item: item_a.boxed_clone(),
5322 ix: 0,
5323 detail: 0,
5324 is_active: true,
5325 };
5326 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5327 });
5328
5329 // A should stay pinned
5330 assert_item_labels(&pane_a, [], cx);
5331 assert_item_labels(&pane_b, ["A*!", "B"], cx);
5332 }
5333
5334 #[gpui::test]
5335 async fn test_drag_pinned_tab_into_existing_pane_at_max_capacity_closes_unpinned_tabs(
5336 cx: &mut TestAppContext,
5337 ) {
5338 init_test(cx);
5339 let fs = FakeFs::new(cx.executor());
5340
5341 let project = Project::test(fs, None, cx).await;
5342 let (workspace, cx) =
5343 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5344 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5345 set_max_tabs(cx, Some(2));
5346
5347 // Add A, B to pane A. Pin both
5348 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5349 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5350 pane_a.update_in(cx, |pane, window, cx| {
5351 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5352 pane.pin_tab_at(ix, window, cx);
5353
5354 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5355 pane.pin_tab_at(ix, window, cx);
5356 });
5357 assert_item_labels(&pane_a, ["A!", "B*!"], cx);
5358
5359 // Add C, D to pane B. Pin both
5360 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5361 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5362 });
5363 let item_c = add_labeled_item(&pane_b, "C", false, cx);
5364 let item_d = add_labeled_item(&pane_b, "D", false, cx);
5365 pane_b.update_in(cx, |pane, window, cx| {
5366 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5367 pane.pin_tab_at(ix, window, cx);
5368
5369 let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
5370 pane.pin_tab_at(ix, window, cx);
5371 });
5372 assert_item_labels(&pane_b, ["C!", "D*!"], cx);
5373
5374 // Add a third unpinned item to pane B (exceeds max tabs), but is allowed,
5375 // as we allow 1 tab over max if the others are pinned or dirty
5376 add_labeled_item(&pane_b, "E", false, cx);
5377 assert_item_labels(&pane_b, ["C!", "D!", "E*"], cx);
5378
5379 // Drag pinned A from pane A to position 0 in pane B
5380 pane_b.update_in(cx, |pane, window, cx| {
5381 let dragged_tab = DraggedTab {
5382 pane: pane_a.clone(),
5383 item: item_a.boxed_clone(),
5384 ix: 0,
5385 detail: 0,
5386 is_active: true,
5387 };
5388 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5389 });
5390
5391 // E (unpinned) should be closed, leaving 3 pinned items
5392 assert_item_labels(&pane_a, ["B*!"], cx);
5393 assert_item_labels(&pane_b, ["A*!", "C!", "D!"], cx);
5394 }
5395
5396 #[gpui::test]
5397 async fn test_drag_last_pinned_tab_to_same_position_stays_pinned(cx: &mut TestAppContext) {
5398 init_test(cx);
5399 let fs = FakeFs::new(cx.executor());
5400
5401 let project = Project::test(fs, None, cx).await;
5402 let (workspace, cx) =
5403 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5404 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5405
5406 // Add A to pane A and pin it
5407 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5408 pane_a.update_in(cx, |pane, window, cx| {
5409 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5410 pane.pin_tab_at(ix, window, cx);
5411 });
5412 assert_item_labels(&pane_a, ["A*!"], cx);
5413
5414 // Drag pinned A to position 1 (directly to the right) in the same pane
5415 pane_a.update_in(cx, |pane, window, cx| {
5416 let dragged_tab = DraggedTab {
5417 pane: pane_a.clone(),
5418 item: item_a.boxed_clone(),
5419 ix: 0,
5420 detail: 0,
5421 is_active: true,
5422 };
5423 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5424 });
5425
5426 // A should still be pinned and active
5427 assert_item_labels(&pane_a, ["A*!"], cx);
5428 }
5429
5430 #[gpui::test]
5431 async fn test_drag_pinned_tab_beyond_last_pinned_tab_in_same_pane_stays_pinned(
5432 cx: &mut TestAppContext,
5433 ) {
5434 init_test(cx);
5435 let fs = FakeFs::new(cx.executor());
5436
5437 let project = Project::test(fs, None, cx).await;
5438 let (workspace, cx) =
5439 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5440 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5441
5442 // Add A, B to pane A and pin both
5443 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5444 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5445 pane_a.update_in(cx, |pane, window, cx| {
5446 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5447 pane.pin_tab_at(ix, window, cx);
5448
5449 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5450 pane.pin_tab_at(ix, window, cx);
5451 });
5452 assert_item_labels(&pane_a, ["A!", "B*!"], cx);
5453
5454 // Drag pinned A right of B in the same pane
5455 pane_a.update_in(cx, |pane, window, cx| {
5456 let dragged_tab = DraggedTab {
5457 pane: pane_a.clone(),
5458 item: item_a.boxed_clone(),
5459 ix: 0,
5460 detail: 0,
5461 is_active: true,
5462 };
5463 pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5464 });
5465
5466 // A stays pinned
5467 assert_item_labels(&pane_a, ["B!", "A*!"], cx);
5468 }
5469
5470 #[gpui::test]
5471 async fn test_dragging_pinned_tab_onto_unpinned_tab_reduces_unpinned_tab_count(
5472 cx: &mut TestAppContext,
5473 ) {
5474 init_test(cx);
5475 let fs = FakeFs::new(cx.executor());
5476
5477 let project = Project::test(fs, None, cx).await;
5478 let (workspace, cx) =
5479 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5480 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5481
5482 // Add A, B to pane A and pin A
5483 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5484 add_labeled_item(&pane_a, "B", false, cx);
5485 pane_a.update_in(cx, |pane, window, cx| {
5486 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5487 pane.pin_tab_at(ix, window, cx);
5488 });
5489 assert_item_labels(&pane_a, ["A!", "B*"], cx);
5490
5491 // Drag pinned A on top of B in the same pane, which changes tab order to B, A
5492 pane_a.update_in(cx, |pane, window, cx| {
5493 let dragged_tab = DraggedTab {
5494 pane: pane_a.clone(),
5495 item: item_a.boxed_clone(),
5496 ix: 0,
5497 detail: 0,
5498 is_active: true,
5499 };
5500 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5501 });
5502
5503 // Neither are pinned
5504 assert_item_labels(&pane_a, ["B", "A*"], cx);
5505 }
5506
5507 #[gpui::test]
5508 async fn test_drag_pinned_tab_beyond_unpinned_tab_in_same_pane_becomes_unpinned(
5509 cx: &mut TestAppContext,
5510 ) {
5511 init_test(cx);
5512 let fs = FakeFs::new(cx.executor());
5513
5514 let project = Project::test(fs, None, cx).await;
5515 let (workspace, cx) =
5516 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5517 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5518
5519 // Add A, B to pane A and pin A
5520 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5521 add_labeled_item(&pane_a, "B", false, cx);
5522 pane_a.update_in(cx, |pane, window, cx| {
5523 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5524 pane.pin_tab_at(ix, window, cx);
5525 });
5526 assert_item_labels(&pane_a, ["A!", "B*"], cx);
5527
5528 // Drag pinned A right of B in the same pane
5529 pane_a.update_in(cx, |pane, window, cx| {
5530 let dragged_tab = DraggedTab {
5531 pane: pane_a.clone(),
5532 item: item_a.boxed_clone(),
5533 ix: 0,
5534 detail: 0,
5535 is_active: true,
5536 };
5537 pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5538 });
5539
5540 // A becomes unpinned
5541 assert_item_labels(&pane_a, ["B", "A*"], cx);
5542 }
5543
5544 #[gpui::test]
5545 async fn test_drag_unpinned_tab_in_front_of_pinned_tab_in_same_pane_becomes_pinned(
5546 cx: &mut TestAppContext,
5547 ) {
5548 init_test(cx);
5549 let fs = FakeFs::new(cx.executor());
5550
5551 let project = Project::test(fs, None, cx).await;
5552 let (workspace, cx) =
5553 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5554 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5555
5556 // Add A, B to pane A and pin A
5557 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5558 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5559 pane_a.update_in(cx, |pane, window, cx| {
5560 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5561 pane.pin_tab_at(ix, window, cx);
5562 });
5563 assert_item_labels(&pane_a, ["A!", "B*"], cx);
5564
5565 // Drag pinned B left of A in the same pane
5566 pane_a.update_in(cx, |pane, window, cx| {
5567 let dragged_tab = DraggedTab {
5568 pane: pane_a.clone(),
5569 item: item_b.boxed_clone(),
5570 ix: 1,
5571 detail: 0,
5572 is_active: true,
5573 };
5574 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5575 });
5576
5577 // A becomes unpinned
5578 assert_item_labels(&pane_a, ["B*!", "A!"], cx);
5579 }
5580
5581 #[gpui::test]
5582 async fn test_drag_unpinned_tab_to_the_pinned_region_stays_pinned(cx: &mut TestAppContext) {
5583 init_test(cx);
5584 let fs = FakeFs::new(cx.executor());
5585
5586 let project = Project::test(fs, None, cx).await;
5587 let (workspace, cx) =
5588 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5589 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5590
5591 // Add A, B, C to pane A and pin A
5592 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5593 add_labeled_item(&pane_a, "B", false, cx);
5594 let item_c = add_labeled_item(&pane_a, "C", false, cx);
5595 pane_a.update_in(cx, |pane, window, cx| {
5596 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5597 pane.pin_tab_at(ix, window, cx);
5598 });
5599 assert_item_labels(&pane_a, ["A!", "B", "C*"], cx);
5600
5601 // Drag pinned C left of B in the same pane
5602 pane_a.update_in(cx, |pane, window, cx| {
5603 let dragged_tab = DraggedTab {
5604 pane: pane_a.clone(),
5605 item: item_c.boxed_clone(),
5606 ix: 2,
5607 detail: 0,
5608 is_active: true,
5609 };
5610 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5611 });
5612
5613 // A stays pinned, B and C remain unpinned
5614 assert_item_labels(&pane_a, ["A!", "C*", "B"], cx);
5615 }
5616
5617 #[gpui::test]
5618 async fn test_drag_unpinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
5619 init_test(cx);
5620 let fs = FakeFs::new(cx.executor());
5621
5622 let project = Project::test(fs, None, cx).await;
5623 let (workspace, cx) =
5624 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5625 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5626
5627 // Add unpinned item A to pane A
5628 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5629 assert_item_labels(&pane_a, ["A*"], cx);
5630
5631 // Create pane B with pinned item B
5632 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5633 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5634 });
5635 let item_b = add_labeled_item(&pane_b, "B", false, cx);
5636 pane_b.update_in(cx, |pane, window, cx| {
5637 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5638 pane.pin_tab_at(ix, window, cx);
5639 });
5640 assert_item_labels(&pane_b, ["B*!"], cx);
5641
5642 // Move A from pane A to pane B's pinned region
5643 pane_b.update_in(cx, |pane, window, cx| {
5644 let dragged_tab = DraggedTab {
5645 pane: pane_a.clone(),
5646 item: item_a.boxed_clone(),
5647 ix: 0,
5648 detail: 0,
5649 is_active: true,
5650 };
5651 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5652 });
5653
5654 // A should become pinned since it was dropped in the pinned region
5655 assert_item_labels(&pane_a, [], cx);
5656 assert_item_labels(&pane_b, ["A*!", "B!"], cx);
5657 }
5658
5659 #[gpui::test]
5660 async fn test_drag_unpinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
5661 init_test(cx);
5662 let fs = FakeFs::new(cx.executor());
5663
5664 let project = Project::test(fs, None, cx).await;
5665 let (workspace, cx) =
5666 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5667 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5668
5669 // Add unpinned item A to pane A
5670 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5671 assert_item_labels(&pane_a, ["A*"], cx);
5672
5673 // Create pane B with one pinned item B
5674 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5675 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5676 });
5677 let item_b = add_labeled_item(&pane_b, "B", false, cx);
5678 pane_b.update_in(cx, |pane, window, cx| {
5679 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5680 pane.pin_tab_at(ix, window, cx);
5681 });
5682 assert_item_labels(&pane_b, ["B*!"], cx);
5683
5684 // Move A from pane A to pane B's unpinned region
5685 pane_b.update_in(cx, |pane, window, cx| {
5686 let dragged_tab = DraggedTab {
5687 pane: pane_a.clone(),
5688 item: item_a.boxed_clone(),
5689 ix: 0,
5690 detail: 0,
5691 is_active: true,
5692 };
5693 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5694 });
5695
5696 // A should remain unpinned since it was dropped outside the pinned region
5697 assert_item_labels(&pane_a, [], cx);
5698 assert_item_labels(&pane_b, ["B!", "A*"], cx);
5699 }
5700
5701 #[gpui::test]
5702 async fn test_drag_pinned_tab_throughout_entire_range_of_pinned_tabs_both_directions(
5703 cx: &mut TestAppContext,
5704 ) {
5705 init_test(cx);
5706 let fs = FakeFs::new(cx.executor());
5707
5708 let project = Project::test(fs, None, cx).await;
5709 let (workspace, cx) =
5710 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5711 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5712
5713 // Add A, B, C and pin all
5714 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5715 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5716 let item_c = add_labeled_item(&pane_a, "C", false, cx);
5717 assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5718
5719 pane_a.update_in(cx, |pane, window, cx| {
5720 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5721 pane.pin_tab_at(ix, window, cx);
5722
5723 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5724 pane.pin_tab_at(ix, window, cx);
5725
5726 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5727 pane.pin_tab_at(ix, window, cx);
5728 });
5729 assert_item_labels(&pane_a, ["A!", "B!", "C*!"], cx);
5730
5731 // Move A to right of B
5732 pane_a.update_in(cx, |pane, window, cx| {
5733 let dragged_tab = DraggedTab {
5734 pane: pane_a.clone(),
5735 item: item_a.boxed_clone(),
5736 ix: 0,
5737 detail: 0,
5738 is_active: true,
5739 };
5740 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5741 });
5742
5743 // A should be after B and all are pinned
5744 assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
5745
5746 // Move A to right of C
5747 pane_a.update_in(cx, |pane, window, cx| {
5748 let dragged_tab = DraggedTab {
5749 pane: pane_a.clone(),
5750 item: item_a.boxed_clone(),
5751 ix: 1,
5752 detail: 0,
5753 is_active: true,
5754 };
5755 pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5756 });
5757
5758 // A should be after C and all are pinned
5759 assert_item_labels(&pane_a, ["B!", "C!", "A*!"], cx);
5760
5761 // Move A to left of C
5762 pane_a.update_in(cx, |pane, window, cx| {
5763 let dragged_tab = DraggedTab {
5764 pane: pane_a.clone(),
5765 item: item_a.boxed_clone(),
5766 ix: 2,
5767 detail: 0,
5768 is_active: true,
5769 };
5770 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5771 });
5772
5773 // A should be before C and all are pinned
5774 assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
5775
5776 // Move A to left of B
5777 pane_a.update_in(cx, |pane, window, cx| {
5778 let dragged_tab = DraggedTab {
5779 pane: pane_a.clone(),
5780 item: item_a.boxed_clone(),
5781 ix: 1,
5782 detail: 0,
5783 is_active: true,
5784 };
5785 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5786 });
5787
5788 // A should be before B and all are pinned
5789 assert_item_labels(&pane_a, ["A*!", "B!", "C!"], cx);
5790 }
5791
5792 #[gpui::test]
5793 async fn test_drag_first_tab_to_last_position(cx: &mut TestAppContext) {
5794 init_test(cx);
5795 let fs = FakeFs::new(cx.executor());
5796
5797 let project = Project::test(fs, None, cx).await;
5798 let (workspace, cx) =
5799 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5800 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5801
5802 // Add A, B, C
5803 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5804 add_labeled_item(&pane_a, "B", false, cx);
5805 add_labeled_item(&pane_a, "C", false, cx);
5806 assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5807
5808 // Move A to the end
5809 pane_a.update_in(cx, |pane, window, cx| {
5810 let dragged_tab = DraggedTab {
5811 pane: pane_a.clone(),
5812 item: item_a.boxed_clone(),
5813 ix: 0,
5814 detail: 0,
5815 is_active: true,
5816 };
5817 pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5818 });
5819
5820 // A should be at the end
5821 assert_item_labels(&pane_a, ["B", "C", "A*"], cx);
5822 }
5823
5824 #[gpui::test]
5825 async fn test_drag_last_tab_to_first_position(cx: &mut TestAppContext) {
5826 init_test(cx);
5827 let fs = FakeFs::new(cx.executor());
5828
5829 let project = Project::test(fs, None, cx).await;
5830 let (workspace, cx) =
5831 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5832 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5833
5834 // Add A, B, C
5835 add_labeled_item(&pane_a, "A", false, cx);
5836 add_labeled_item(&pane_a, "B", false, cx);
5837 let item_c = add_labeled_item(&pane_a, "C", false, cx);
5838 assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5839
5840 // Move C to the beginning
5841 pane_a.update_in(cx, |pane, window, cx| {
5842 let dragged_tab = DraggedTab {
5843 pane: pane_a.clone(),
5844 item: item_c.boxed_clone(),
5845 ix: 2,
5846 detail: 0,
5847 is_active: true,
5848 };
5849 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5850 });
5851
5852 // C should be at the beginning
5853 assert_item_labels(&pane_a, ["C*", "A", "B"], cx);
5854 }
5855
5856 #[gpui::test]
5857 async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
5858 init_test(cx);
5859 let fs = FakeFs::new(cx.executor());
5860
5861 let project = Project::test(fs, None, cx).await;
5862 let (workspace, cx) =
5863 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5864 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5865
5866 // 1. Add with a destination index
5867 // a. Add before the active item
5868 set_labeled_items(&pane, ["A", "B*", "C"], cx);
5869 pane.update_in(cx, |pane, window, cx| {
5870 pane.add_item(
5871 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5872 false,
5873 false,
5874 Some(0),
5875 window,
5876 cx,
5877 );
5878 });
5879 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
5880
5881 // b. Add after the active item
5882 set_labeled_items(&pane, ["A", "B*", "C"], cx);
5883 pane.update_in(cx, |pane, window, cx| {
5884 pane.add_item(
5885 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5886 false,
5887 false,
5888 Some(2),
5889 window,
5890 cx,
5891 );
5892 });
5893 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
5894
5895 // c. Add at the end of the item list (including off the length)
5896 set_labeled_items(&pane, ["A", "B*", "C"], cx);
5897 pane.update_in(cx, |pane, window, cx| {
5898 pane.add_item(
5899 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5900 false,
5901 false,
5902 Some(5),
5903 window,
5904 cx,
5905 );
5906 });
5907 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5908
5909 // 2. Add without a destination index
5910 // a. Add with active item at the start of the item list
5911 set_labeled_items(&pane, ["A*", "B", "C"], cx);
5912 pane.update_in(cx, |pane, window, cx| {
5913 pane.add_item(
5914 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5915 false,
5916 false,
5917 None,
5918 window,
5919 cx,
5920 );
5921 });
5922 set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
5923
5924 // b. Add with active item at the end of the item list
5925 set_labeled_items(&pane, ["A", "B", "C*"], cx);
5926 pane.update_in(cx, |pane, window, cx| {
5927 pane.add_item(
5928 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5929 false,
5930 false,
5931 None,
5932 window,
5933 cx,
5934 );
5935 });
5936 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5937 }
5938
5939 #[gpui::test]
5940 async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
5941 init_test(cx);
5942 let fs = FakeFs::new(cx.executor());
5943
5944 let project = Project::test(fs, None, cx).await;
5945 let (workspace, cx) =
5946 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5947 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5948
5949 // 1. Add with a destination index
5950 // 1a. Add before the active item
5951 let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5952 pane.update_in(cx, |pane, window, cx| {
5953 pane.add_item(d, false, false, Some(0), window, cx);
5954 });
5955 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
5956
5957 // 1b. Add after the active item
5958 let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5959 pane.update_in(cx, |pane, window, cx| {
5960 pane.add_item(d, false, false, Some(2), window, cx);
5961 });
5962 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
5963
5964 // 1c. Add at the end of the item list (including off the length)
5965 let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5966 pane.update_in(cx, |pane, window, cx| {
5967 pane.add_item(a, false, false, Some(5), window, cx);
5968 });
5969 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
5970
5971 // 1d. Add same item to active index
5972 let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
5973 pane.update_in(cx, |pane, window, cx| {
5974 pane.add_item(b, false, false, Some(1), window, cx);
5975 });
5976 assert_item_labels(&pane, ["A", "B*", "C"], cx);
5977
5978 // 1e. Add item to index after same item in last position
5979 let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
5980 pane.update_in(cx, |pane, window, cx| {
5981 pane.add_item(c, false, false, Some(2), window, cx);
5982 });
5983 assert_item_labels(&pane, ["A", "B", "C*"], cx);
5984
5985 // 2. Add without a destination index
5986 // 2a. Add with active item at the start of the item list
5987 let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
5988 pane.update_in(cx, |pane, window, cx| {
5989 pane.add_item(d, false, false, None, window, cx);
5990 });
5991 assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
5992
5993 // 2b. Add with active item at the end of the item list
5994 let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
5995 pane.update_in(cx, |pane, window, cx| {
5996 pane.add_item(a, false, false, None, window, cx);
5997 });
5998 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
5999
6000 // 2c. Add active item to active item at end of list
6001 let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
6002 pane.update_in(cx, |pane, window, cx| {
6003 pane.add_item(c, false, false, None, window, cx);
6004 });
6005 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6006
6007 // 2d. Add active item to active item at start of list
6008 let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
6009 pane.update_in(cx, |pane, window, cx| {
6010 pane.add_item(a, false, false, None, window, cx);
6011 });
6012 assert_item_labels(&pane, ["A*", "B", "C"], cx);
6013 }
6014
6015 #[gpui::test]
6016 async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
6017 init_test(cx);
6018 let fs = FakeFs::new(cx.executor());
6019
6020 let project = Project::test(fs, None, cx).await;
6021 let (workspace, cx) =
6022 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6023 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6024
6025 // singleton view
6026 pane.update_in(cx, |pane, window, cx| {
6027 pane.add_item(
6028 Box::new(cx.new(|cx| {
6029 TestItem::new(cx)
6030 .with_buffer_kind(ItemBufferKind::Singleton)
6031 .with_label("buffer 1")
6032 .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
6033 })),
6034 false,
6035 false,
6036 None,
6037 window,
6038 cx,
6039 );
6040 });
6041 assert_item_labels(&pane, ["buffer 1*"], cx);
6042
6043 // new singleton view with the same project entry
6044 pane.update_in(cx, |pane, window, cx| {
6045 pane.add_item(
6046 Box::new(cx.new(|cx| {
6047 TestItem::new(cx)
6048 .with_buffer_kind(ItemBufferKind::Singleton)
6049 .with_label("buffer 1")
6050 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
6051 })),
6052 false,
6053 false,
6054 None,
6055 window,
6056 cx,
6057 );
6058 });
6059 assert_item_labels(&pane, ["buffer 1*"], cx);
6060
6061 // new singleton view with different project entry
6062 pane.update_in(cx, |pane, window, cx| {
6063 pane.add_item(
6064 Box::new(cx.new(|cx| {
6065 TestItem::new(cx)
6066 .with_buffer_kind(ItemBufferKind::Singleton)
6067 .with_label("buffer 2")
6068 .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
6069 })),
6070 false,
6071 false,
6072 None,
6073 window,
6074 cx,
6075 );
6076 });
6077 assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
6078
6079 // new multibuffer view with the same project entry
6080 pane.update_in(cx, |pane, window, cx| {
6081 pane.add_item(
6082 Box::new(cx.new(|cx| {
6083 TestItem::new(cx)
6084 .with_buffer_kind(ItemBufferKind::Multibuffer)
6085 .with_label("multibuffer 1")
6086 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
6087 })),
6088 false,
6089 false,
6090 None,
6091 window,
6092 cx,
6093 );
6094 });
6095 assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
6096
6097 // another multibuffer view with the same project entry
6098 pane.update_in(cx, |pane, window, cx| {
6099 pane.add_item(
6100 Box::new(cx.new(|cx| {
6101 TestItem::new(cx)
6102 .with_buffer_kind(ItemBufferKind::Multibuffer)
6103 .with_label("multibuffer 1b")
6104 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
6105 })),
6106 false,
6107 false,
6108 None,
6109 window,
6110 cx,
6111 );
6112 });
6113 assert_item_labels(
6114 &pane,
6115 ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
6116 cx,
6117 );
6118 }
6119
6120 #[gpui::test]
6121 async fn test_remove_item_ordering_history(cx: &mut TestAppContext) {
6122 init_test(cx);
6123 let fs = FakeFs::new(cx.executor());
6124
6125 let project = Project::test(fs, None, cx).await;
6126 let (workspace, cx) =
6127 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6128 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6129
6130 add_labeled_item(&pane, "A", false, cx);
6131 add_labeled_item(&pane, "B", false, cx);
6132 add_labeled_item(&pane, "C", false, cx);
6133 add_labeled_item(&pane, "D", false, cx);
6134 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6135
6136 pane.update_in(cx, |pane, window, cx| {
6137 pane.activate_item(1, false, false, window, cx)
6138 });
6139 add_labeled_item(&pane, "1", false, cx);
6140 assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
6141
6142 pane.update_in(cx, |pane, window, cx| {
6143 pane.close_active_item(
6144 &CloseActiveItem {
6145 save_intent: None,
6146 close_pinned: false,
6147 },
6148 window,
6149 cx,
6150 )
6151 })
6152 .await
6153 .unwrap();
6154 assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
6155
6156 pane.update_in(cx, |pane, window, cx| {
6157 pane.activate_item(3, false, false, window, cx)
6158 });
6159 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6160
6161 pane.update_in(cx, |pane, window, cx| {
6162 pane.close_active_item(
6163 &CloseActiveItem {
6164 save_intent: None,
6165 close_pinned: false,
6166 },
6167 window,
6168 cx,
6169 )
6170 })
6171 .await
6172 .unwrap();
6173 assert_item_labels(&pane, ["A", "B*", "C"], cx);
6174
6175 pane.update_in(cx, |pane, window, cx| {
6176 pane.close_active_item(
6177 &CloseActiveItem {
6178 save_intent: None,
6179 close_pinned: false,
6180 },
6181 window,
6182 cx,
6183 )
6184 })
6185 .await
6186 .unwrap();
6187 assert_item_labels(&pane, ["A", "C*"], cx);
6188
6189 pane.update_in(cx, |pane, window, cx| {
6190 pane.close_active_item(
6191 &CloseActiveItem {
6192 save_intent: None,
6193 close_pinned: false,
6194 },
6195 window,
6196 cx,
6197 )
6198 })
6199 .await
6200 .unwrap();
6201 assert_item_labels(&pane, ["A*"], cx);
6202 }
6203
6204 #[gpui::test]
6205 async fn test_remove_item_ordering_neighbour(cx: &mut TestAppContext) {
6206 init_test(cx);
6207 cx.update_global::<SettingsStore, ()>(|s, cx| {
6208 s.update_user_settings(cx, |s| {
6209 s.tabs.get_or_insert_default().activate_on_close = Some(ActivateOnClose::Neighbour);
6210 });
6211 });
6212 let fs = FakeFs::new(cx.executor());
6213
6214 let project = Project::test(fs, None, cx).await;
6215 let (workspace, cx) =
6216 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6217 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6218
6219 add_labeled_item(&pane, "A", false, cx);
6220 add_labeled_item(&pane, "B", false, cx);
6221 add_labeled_item(&pane, "C", false, cx);
6222 add_labeled_item(&pane, "D", false, cx);
6223 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6224
6225 pane.update_in(cx, |pane, window, cx| {
6226 pane.activate_item(1, false, false, window, cx)
6227 });
6228 add_labeled_item(&pane, "1", false, cx);
6229 assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
6230
6231 pane.update_in(cx, |pane, window, cx| {
6232 pane.close_active_item(
6233 &CloseActiveItem {
6234 save_intent: None,
6235 close_pinned: false,
6236 },
6237 window,
6238 cx,
6239 )
6240 })
6241 .await
6242 .unwrap();
6243 assert_item_labels(&pane, ["A", "B", "C*", "D"], cx);
6244
6245 pane.update_in(cx, |pane, window, cx| {
6246 pane.activate_item(3, false, false, window, cx)
6247 });
6248 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6249
6250 pane.update_in(cx, |pane, window, cx| {
6251 pane.close_active_item(
6252 &CloseActiveItem {
6253 save_intent: None,
6254 close_pinned: false,
6255 },
6256 window,
6257 cx,
6258 )
6259 })
6260 .await
6261 .unwrap();
6262 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6263
6264 pane.update_in(cx, |pane, window, cx| {
6265 pane.close_active_item(
6266 &CloseActiveItem {
6267 save_intent: None,
6268 close_pinned: false,
6269 },
6270 window,
6271 cx,
6272 )
6273 })
6274 .await
6275 .unwrap();
6276 assert_item_labels(&pane, ["A", "B*"], cx);
6277
6278 pane.update_in(cx, |pane, window, cx| {
6279 pane.close_active_item(
6280 &CloseActiveItem {
6281 save_intent: None,
6282 close_pinned: false,
6283 },
6284 window,
6285 cx,
6286 )
6287 })
6288 .await
6289 .unwrap();
6290 assert_item_labels(&pane, ["A*"], cx);
6291 }
6292
6293 #[gpui::test]
6294 async fn test_remove_item_ordering_left_neighbour(cx: &mut TestAppContext) {
6295 init_test(cx);
6296 cx.update_global::<SettingsStore, ()>(|s, cx| {
6297 s.update_user_settings(cx, |s| {
6298 s.tabs.get_or_insert_default().activate_on_close =
6299 Some(ActivateOnClose::LeftNeighbour);
6300 });
6301 });
6302 let fs = FakeFs::new(cx.executor());
6303
6304 let project = Project::test(fs, None, cx).await;
6305 let (workspace, cx) =
6306 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6307 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6308
6309 add_labeled_item(&pane, "A", false, cx);
6310 add_labeled_item(&pane, "B", false, cx);
6311 add_labeled_item(&pane, "C", false, cx);
6312 add_labeled_item(&pane, "D", false, cx);
6313 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6314
6315 pane.update_in(cx, |pane, window, cx| {
6316 pane.activate_item(1, false, false, window, cx)
6317 });
6318 add_labeled_item(&pane, "1", false, cx);
6319 assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
6320
6321 pane.update_in(cx, |pane, window, cx| {
6322 pane.close_active_item(
6323 &CloseActiveItem {
6324 save_intent: None,
6325 close_pinned: false,
6326 },
6327 window,
6328 cx,
6329 )
6330 })
6331 .await
6332 .unwrap();
6333 assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
6334
6335 pane.update_in(cx, |pane, window, cx| {
6336 pane.activate_item(3, false, false, window, cx)
6337 });
6338 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6339
6340 pane.update_in(cx, |pane, window, cx| {
6341 pane.close_active_item(
6342 &CloseActiveItem {
6343 save_intent: None,
6344 close_pinned: false,
6345 },
6346 window,
6347 cx,
6348 )
6349 })
6350 .await
6351 .unwrap();
6352 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6353
6354 pane.update_in(cx, |pane, window, cx| {
6355 pane.activate_item(0, false, false, window, cx)
6356 });
6357 assert_item_labels(&pane, ["A*", "B", "C"], cx);
6358
6359 pane.update_in(cx, |pane, window, cx| {
6360 pane.close_active_item(
6361 &CloseActiveItem {
6362 save_intent: None,
6363 close_pinned: false,
6364 },
6365 window,
6366 cx,
6367 )
6368 })
6369 .await
6370 .unwrap();
6371 assert_item_labels(&pane, ["B*", "C"], cx);
6372
6373 pane.update_in(cx, |pane, window, cx| {
6374 pane.close_active_item(
6375 &CloseActiveItem {
6376 save_intent: None,
6377 close_pinned: false,
6378 },
6379 window,
6380 cx,
6381 )
6382 })
6383 .await
6384 .unwrap();
6385 assert_item_labels(&pane, ["C*"], cx);
6386 }
6387
6388 #[gpui::test]
6389 async fn test_close_inactive_items(cx: &mut TestAppContext) {
6390 init_test(cx);
6391 let fs = FakeFs::new(cx.executor());
6392
6393 let project = Project::test(fs, None, cx).await;
6394 let (workspace, cx) =
6395 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6396 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6397
6398 let item_a = add_labeled_item(&pane, "A", false, cx);
6399 pane.update_in(cx, |pane, window, cx| {
6400 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6401 pane.pin_tab_at(ix, window, cx);
6402 });
6403 assert_item_labels(&pane, ["A*!"], cx);
6404
6405 let item_b = add_labeled_item(&pane, "B", false, cx);
6406 pane.update_in(cx, |pane, window, cx| {
6407 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6408 pane.pin_tab_at(ix, window, cx);
6409 });
6410 assert_item_labels(&pane, ["A!", "B*!"], cx);
6411
6412 add_labeled_item(&pane, "C", false, cx);
6413 assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
6414
6415 add_labeled_item(&pane, "D", false, cx);
6416 add_labeled_item(&pane, "E", false, cx);
6417 assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
6418
6419 pane.update_in(cx, |pane, window, cx| {
6420 pane.close_other_items(
6421 &CloseOtherItems {
6422 save_intent: None,
6423 close_pinned: false,
6424 },
6425 None,
6426 window,
6427 cx,
6428 )
6429 })
6430 .await
6431 .unwrap();
6432 assert_item_labels(&pane, ["A!", "B!", "E*"], cx);
6433 }
6434
6435 #[gpui::test]
6436 async fn test_running_close_inactive_items_via_an_inactive_item(cx: &mut TestAppContext) {
6437 init_test(cx);
6438 let fs = FakeFs::new(cx.executor());
6439
6440 let project = Project::test(fs, None, cx).await;
6441 let (workspace, cx) =
6442 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6443 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6444
6445 add_labeled_item(&pane, "A", false, cx);
6446 assert_item_labels(&pane, ["A*"], cx);
6447
6448 let item_b = add_labeled_item(&pane, "B", false, cx);
6449 assert_item_labels(&pane, ["A", "B*"], cx);
6450
6451 add_labeled_item(&pane, "C", false, cx);
6452 add_labeled_item(&pane, "D", false, cx);
6453 add_labeled_item(&pane, "E", false, cx);
6454 assert_item_labels(&pane, ["A", "B", "C", "D", "E*"], cx);
6455
6456 pane.update_in(cx, |pane, window, cx| {
6457 pane.close_other_items(
6458 &CloseOtherItems {
6459 save_intent: None,
6460 close_pinned: false,
6461 },
6462 Some(item_b.item_id()),
6463 window,
6464 cx,
6465 )
6466 })
6467 .await
6468 .unwrap();
6469 assert_item_labels(&pane, ["B*"], cx);
6470 }
6471
6472 #[gpui::test]
6473 async fn test_close_clean_items(cx: &mut TestAppContext) {
6474 init_test(cx);
6475 let fs = FakeFs::new(cx.executor());
6476
6477 let project = Project::test(fs, None, cx).await;
6478 let (workspace, cx) =
6479 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6480 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6481
6482 add_labeled_item(&pane, "A", true, cx);
6483 add_labeled_item(&pane, "B", false, cx);
6484 add_labeled_item(&pane, "C", true, cx);
6485 add_labeled_item(&pane, "D", false, cx);
6486 add_labeled_item(&pane, "E", false, cx);
6487 assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
6488
6489 pane.update_in(cx, |pane, window, cx| {
6490 pane.close_clean_items(
6491 &CloseCleanItems {
6492 close_pinned: false,
6493 },
6494 window,
6495 cx,
6496 )
6497 })
6498 .await
6499 .unwrap();
6500 assert_item_labels(&pane, ["A^", "C*^"], cx);
6501 }
6502
6503 #[gpui::test]
6504 async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
6505 init_test(cx);
6506 let fs = FakeFs::new(cx.executor());
6507
6508 let project = Project::test(fs, None, cx).await;
6509 let (workspace, cx) =
6510 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6511 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6512
6513 set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
6514
6515 pane.update_in(cx, |pane, window, cx| {
6516 pane.close_items_to_the_left_by_id(
6517 None,
6518 &CloseItemsToTheLeft {
6519 close_pinned: false,
6520 },
6521 window,
6522 cx,
6523 )
6524 })
6525 .await
6526 .unwrap();
6527 assert_item_labels(&pane, ["C*", "D", "E"], cx);
6528 }
6529
6530 #[gpui::test]
6531 async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
6532 init_test(cx);
6533 let fs = FakeFs::new(cx.executor());
6534
6535 let project = Project::test(fs, None, cx).await;
6536 let (workspace, cx) =
6537 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6538 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6539
6540 set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
6541
6542 pane.update_in(cx, |pane, window, cx| {
6543 pane.close_items_to_the_right_by_id(
6544 None,
6545 &CloseItemsToTheRight {
6546 close_pinned: false,
6547 },
6548 window,
6549 cx,
6550 )
6551 })
6552 .await
6553 .unwrap();
6554 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6555 }
6556
6557 #[gpui::test]
6558 async fn test_close_all_items(cx: &mut TestAppContext) {
6559 init_test(cx);
6560 let fs = FakeFs::new(cx.executor());
6561
6562 let project = Project::test(fs, None, cx).await;
6563 let (workspace, cx) =
6564 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6565 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6566
6567 let item_a = add_labeled_item(&pane, "A", false, cx);
6568 add_labeled_item(&pane, "B", false, cx);
6569 add_labeled_item(&pane, "C", false, cx);
6570 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6571
6572 pane.update_in(cx, |pane, window, cx| {
6573 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6574 pane.pin_tab_at(ix, window, cx);
6575 pane.close_all_items(
6576 &CloseAllItems {
6577 save_intent: None,
6578 close_pinned: false,
6579 },
6580 window,
6581 cx,
6582 )
6583 })
6584 .await
6585 .unwrap();
6586 assert_item_labels(&pane, ["A*!"], cx);
6587
6588 pane.update_in(cx, |pane, window, cx| {
6589 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6590 pane.unpin_tab_at(ix, window, cx);
6591 pane.close_all_items(
6592 &CloseAllItems {
6593 save_intent: None,
6594 close_pinned: false,
6595 },
6596 window,
6597 cx,
6598 )
6599 })
6600 .await
6601 .unwrap();
6602
6603 assert_item_labels(&pane, [], cx);
6604
6605 add_labeled_item(&pane, "A", true, cx).update(cx, |item, cx| {
6606 item.project_items
6607 .push(TestProjectItem::new_dirty(1, "A.txt", cx))
6608 });
6609 add_labeled_item(&pane, "B", true, cx).update(cx, |item, cx| {
6610 item.project_items
6611 .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6612 });
6613 add_labeled_item(&pane, "C", true, cx).update(cx, |item, cx| {
6614 item.project_items
6615 .push(TestProjectItem::new_dirty(3, "C.txt", cx))
6616 });
6617 assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6618
6619 let save = pane.update_in(cx, |pane, window, cx| {
6620 pane.close_all_items(
6621 &CloseAllItems {
6622 save_intent: None,
6623 close_pinned: false,
6624 },
6625 window,
6626 cx,
6627 )
6628 });
6629
6630 cx.executor().run_until_parked();
6631 cx.simulate_prompt_answer("Save all");
6632 save.await.unwrap();
6633 assert_item_labels(&pane, [], cx);
6634
6635 add_labeled_item(&pane, "A", true, cx);
6636 add_labeled_item(&pane, "B", true, cx);
6637 add_labeled_item(&pane, "C", true, cx);
6638 assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6639 let save = pane.update_in(cx, |pane, window, cx| {
6640 pane.close_all_items(
6641 &CloseAllItems {
6642 save_intent: None,
6643 close_pinned: false,
6644 },
6645 window,
6646 cx,
6647 )
6648 });
6649
6650 cx.executor().run_until_parked();
6651 cx.simulate_prompt_answer("Discard all");
6652 save.await.unwrap();
6653 assert_item_labels(&pane, [], cx);
6654
6655 add_labeled_item(&pane, "A", true, cx).update(cx, |item, cx| {
6656 item.project_items
6657 .push(TestProjectItem::new_dirty(1, "A.txt", cx))
6658 });
6659 add_labeled_item(&pane, "B", true, cx).update(cx, |item, cx| {
6660 item.project_items
6661 .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6662 });
6663 add_labeled_item(&pane, "C", true, cx).update(cx, |item, cx| {
6664 item.project_items
6665 .push(TestProjectItem::new_dirty(3, "C.txt", cx))
6666 });
6667 assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6668
6669 let close_task = pane.update_in(cx, |pane, window, cx| {
6670 pane.close_all_items(
6671 &CloseAllItems {
6672 save_intent: None,
6673 close_pinned: false,
6674 },
6675 window,
6676 cx,
6677 )
6678 });
6679
6680 cx.executor().run_until_parked();
6681 cx.simulate_prompt_answer("Discard all");
6682 close_task.await.unwrap();
6683 assert_item_labels(&pane, [], cx);
6684
6685 add_labeled_item(&pane, "Clean1", false, cx);
6686 add_labeled_item(&pane, "Dirty", true, cx).update(cx, |item, cx| {
6687 item.project_items
6688 .push(TestProjectItem::new_dirty(1, "Dirty.txt", cx))
6689 });
6690 add_labeled_item(&pane, "Clean2", false, cx);
6691 assert_item_labels(&pane, ["Clean1", "Dirty^", "Clean2*"], cx);
6692
6693 let close_task = pane.update_in(cx, |pane, window, cx| {
6694 pane.close_all_items(
6695 &CloseAllItems {
6696 save_intent: None,
6697 close_pinned: false,
6698 },
6699 window,
6700 cx,
6701 )
6702 });
6703
6704 cx.executor().run_until_parked();
6705 cx.simulate_prompt_answer("Cancel");
6706 close_task.await.unwrap();
6707 assert_item_labels(&pane, ["Dirty*^"], cx);
6708 }
6709
6710 #[gpui::test]
6711 async fn test_close_multibuffer_items(cx: &mut TestAppContext) {
6712 init_test(cx);
6713 let fs = FakeFs::new(cx.executor());
6714
6715 let project = Project::test(fs, None, cx).await;
6716 let (workspace, cx) =
6717 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6718 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6719
6720 let add_labeled_item = |pane: &Entity<Pane>,
6721 label,
6722 is_dirty,
6723 kind: ItemBufferKind,
6724 cx: &mut VisualTestContext| {
6725 pane.update_in(cx, |pane, window, cx| {
6726 let labeled_item = Box::new(cx.new(|cx| {
6727 TestItem::new(cx)
6728 .with_label(label)
6729 .with_dirty(is_dirty)
6730 .with_buffer_kind(kind)
6731 }));
6732 pane.add_item(labeled_item.clone(), false, false, None, window, cx);
6733 labeled_item
6734 })
6735 };
6736
6737 let item_a = add_labeled_item(&pane, "A", false, ItemBufferKind::Multibuffer, cx);
6738 add_labeled_item(&pane, "B", false, ItemBufferKind::Multibuffer, cx);
6739 add_labeled_item(&pane, "C", false, ItemBufferKind::Singleton, cx);
6740 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6741
6742 pane.update_in(cx, |pane, window, cx| {
6743 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6744 pane.pin_tab_at(ix, window, cx);
6745 pane.close_multibuffer_items(
6746 &CloseMultibufferItems {
6747 save_intent: None,
6748 close_pinned: false,
6749 },
6750 window,
6751 cx,
6752 )
6753 })
6754 .await
6755 .unwrap();
6756 assert_item_labels(&pane, ["A!", "C*"], cx);
6757
6758 pane.update_in(cx, |pane, window, cx| {
6759 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6760 pane.unpin_tab_at(ix, window, cx);
6761 pane.close_multibuffer_items(
6762 &CloseMultibufferItems {
6763 save_intent: None,
6764 close_pinned: false,
6765 },
6766 window,
6767 cx,
6768 )
6769 })
6770 .await
6771 .unwrap();
6772
6773 assert_item_labels(&pane, ["C*"], cx);
6774
6775 add_labeled_item(&pane, "A", true, ItemBufferKind::Singleton, cx).update(cx, |item, cx| {
6776 item.project_items
6777 .push(TestProjectItem::new_dirty(1, "A.txt", cx))
6778 });
6779 add_labeled_item(&pane, "B", true, ItemBufferKind::Multibuffer, cx).update(
6780 cx,
6781 |item, cx| {
6782 item.project_items
6783 .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6784 },
6785 );
6786 add_labeled_item(&pane, "D", true, ItemBufferKind::Multibuffer, cx).update(
6787 cx,
6788 |item, cx| {
6789 item.project_items
6790 .push(TestProjectItem::new_dirty(3, "D.txt", cx))
6791 },
6792 );
6793 assert_item_labels(&pane, ["C", "A^", "B^", "D*^"], cx);
6794
6795 let save = pane.update_in(cx, |pane, window, cx| {
6796 pane.close_multibuffer_items(
6797 &CloseMultibufferItems {
6798 save_intent: None,
6799 close_pinned: false,
6800 },
6801 window,
6802 cx,
6803 )
6804 });
6805
6806 cx.executor().run_until_parked();
6807 cx.simulate_prompt_answer("Save all");
6808 save.await.unwrap();
6809 assert_item_labels(&pane, ["C", "A*^"], cx);
6810
6811 add_labeled_item(&pane, "B", true, ItemBufferKind::Multibuffer, cx).update(
6812 cx,
6813 |item, cx| {
6814 item.project_items
6815 .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6816 },
6817 );
6818 add_labeled_item(&pane, "D", true, ItemBufferKind::Multibuffer, cx).update(
6819 cx,
6820 |item, cx| {
6821 item.project_items
6822 .push(TestProjectItem::new_dirty(3, "D.txt", cx))
6823 },
6824 );
6825 assert_item_labels(&pane, ["C", "A^", "B^", "D*^"], cx);
6826 let save = pane.update_in(cx, |pane, window, cx| {
6827 pane.close_multibuffer_items(
6828 &CloseMultibufferItems {
6829 save_intent: None,
6830 close_pinned: false,
6831 },
6832 window,
6833 cx,
6834 )
6835 });
6836
6837 cx.executor().run_until_parked();
6838 cx.simulate_prompt_answer("Discard all");
6839 save.await.unwrap();
6840 assert_item_labels(&pane, ["C", "A*^"], cx);
6841 }
6842
6843 #[gpui::test]
6844 async fn test_close_with_save_intent(cx: &mut TestAppContext) {
6845 init_test(cx);
6846 let fs = FakeFs::new(cx.executor());
6847
6848 let project = Project::test(fs, None, cx).await;
6849 let (workspace, cx) =
6850 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6851 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6852
6853 let a = cx.update(|_, cx| TestProjectItem::new_dirty(1, "A.txt", cx));
6854 let b = cx.update(|_, cx| TestProjectItem::new_dirty(1, "B.txt", cx));
6855 let c = cx.update(|_, cx| TestProjectItem::new_dirty(1, "C.txt", cx));
6856
6857 add_labeled_item(&pane, "AB", true, cx).update(cx, |item, _| {
6858 item.project_items.push(a.clone());
6859 item.project_items.push(b.clone());
6860 });
6861 add_labeled_item(&pane, "C", true, cx)
6862 .update(cx, |item, _| item.project_items.push(c.clone()));
6863 assert_item_labels(&pane, ["AB^", "C*^"], cx);
6864
6865 pane.update_in(cx, |pane, window, cx| {
6866 pane.close_all_items(
6867 &CloseAllItems {
6868 save_intent: Some(SaveIntent::Save),
6869 close_pinned: false,
6870 },
6871 window,
6872 cx,
6873 )
6874 })
6875 .await
6876 .unwrap();
6877
6878 assert_item_labels(&pane, [], cx);
6879 cx.update(|_, cx| {
6880 assert!(!a.read(cx).is_dirty);
6881 assert!(!b.read(cx).is_dirty);
6882 assert!(!c.read(cx).is_dirty);
6883 });
6884 }
6885
6886 #[gpui::test]
6887 async fn test_new_tab_scrolls_into_view_completely(cx: &mut TestAppContext) {
6888 // Arrange
6889 init_test(cx);
6890 let fs = FakeFs::new(cx.executor());
6891
6892 let project = Project::test(fs, None, cx).await;
6893 let (workspace, cx) =
6894 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6895 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6896
6897 cx.simulate_resize(size(px(300.), px(300.)));
6898
6899 add_labeled_item(&pane, "untitled", false, cx);
6900 add_labeled_item(&pane, "untitled", false, cx);
6901 add_labeled_item(&pane, "untitled", false, cx);
6902 add_labeled_item(&pane, "untitled", false, cx);
6903 // Act: this should trigger a scroll
6904 add_labeled_item(&pane, "untitled", false, cx);
6905 // Assert
6906 let tab_bar_scroll_handle =
6907 pane.update_in(cx, |pane, _window, _cx| pane.tab_bar_scroll_handle.clone());
6908 assert_eq!(tab_bar_scroll_handle.children_count(), 6);
6909 let tab_bounds = cx.debug_bounds("TAB-4").unwrap();
6910 let new_tab_button_bounds = cx.debug_bounds("ICON-Plus").unwrap();
6911 let scroll_bounds = tab_bar_scroll_handle.bounds();
6912 let scroll_offset = tab_bar_scroll_handle.offset();
6913 assert!(tab_bounds.right() <= scroll_bounds.right());
6914 // -43.0 is the magic number for this setup
6915 assert_eq!(scroll_offset.x, px(-43.0));
6916 assert!(
6917 !tab_bounds.intersects(&new_tab_button_bounds),
6918 "Tab should not overlap with the new tab button, if this is failing check if there's been a redesign!"
6919 );
6920 }
6921
6922 #[gpui::test]
6923 async fn test_close_all_items_including_pinned(cx: &mut TestAppContext) {
6924 init_test(cx);
6925 let fs = FakeFs::new(cx.executor());
6926
6927 let project = Project::test(fs, None, cx).await;
6928 let (workspace, cx) =
6929 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6930 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6931
6932 let item_a = add_labeled_item(&pane, "A", false, cx);
6933 add_labeled_item(&pane, "B", false, cx);
6934 add_labeled_item(&pane, "C", false, cx);
6935 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6936
6937 pane.update_in(cx, |pane, window, cx| {
6938 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6939 pane.pin_tab_at(ix, window, cx);
6940 pane.close_all_items(
6941 &CloseAllItems {
6942 save_intent: None,
6943 close_pinned: true,
6944 },
6945 window,
6946 cx,
6947 )
6948 })
6949 .await
6950 .unwrap();
6951 assert_item_labels(&pane, [], cx);
6952 }
6953
6954 #[gpui::test]
6955 async fn test_close_pinned_tab_with_non_pinned_in_same_pane(cx: &mut TestAppContext) {
6956 init_test(cx);
6957 let fs = FakeFs::new(cx.executor());
6958 let project = Project::test(fs, None, cx).await;
6959 let (workspace, cx) =
6960 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6961
6962 // Non-pinned tabs in same pane
6963 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6964 add_labeled_item(&pane, "A", false, cx);
6965 add_labeled_item(&pane, "B", false, cx);
6966 add_labeled_item(&pane, "C", false, cx);
6967 pane.update_in(cx, |pane, window, cx| {
6968 pane.pin_tab_at(0, window, cx);
6969 });
6970 set_labeled_items(&pane, ["A*", "B", "C"], cx);
6971 pane.update_in(cx, |pane, window, cx| {
6972 pane.close_active_item(
6973 &CloseActiveItem {
6974 save_intent: None,
6975 close_pinned: false,
6976 },
6977 window,
6978 cx,
6979 )
6980 .unwrap();
6981 });
6982 // Non-pinned tab should be active
6983 assert_item_labels(&pane, ["A!", "B*", "C"], cx);
6984 }
6985
6986 #[gpui::test]
6987 async fn test_close_pinned_tab_with_non_pinned_in_different_pane(cx: &mut TestAppContext) {
6988 init_test(cx);
6989 let fs = FakeFs::new(cx.executor());
6990 let project = Project::test(fs, None, cx).await;
6991 let (workspace, cx) =
6992 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6993
6994 // No non-pinned tabs in same pane, non-pinned tabs in another pane
6995 let pane1 = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6996 let pane2 = workspace.update_in(cx, |workspace, window, cx| {
6997 workspace.split_pane(pane1.clone(), SplitDirection::Right, window, cx)
6998 });
6999 add_labeled_item(&pane1, "A", false, cx);
7000 pane1.update_in(cx, |pane, window, cx| {
7001 pane.pin_tab_at(0, window, cx);
7002 });
7003 set_labeled_items(&pane1, ["A*"], cx);
7004 add_labeled_item(&pane2, "B", false, cx);
7005 set_labeled_items(&pane2, ["B"], cx);
7006 pane1.update_in(cx, |pane, window, cx| {
7007 pane.close_active_item(
7008 &CloseActiveItem {
7009 save_intent: None,
7010 close_pinned: false,
7011 },
7012 window,
7013 cx,
7014 )
7015 .unwrap();
7016 });
7017 // Non-pinned tab of other pane should be active
7018 assert_item_labels(&pane2, ["B*"], cx);
7019 }
7020
7021 #[gpui::test]
7022 async fn ensure_item_closing_actions_do_not_panic_when_no_items_exist(cx: &mut TestAppContext) {
7023 init_test(cx);
7024 let fs = FakeFs::new(cx.executor());
7025 let project = Project::test(fs, None, cx).await;
7026 let (workspace, cx) =
7027 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
7028
7029 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7030 assert_item_labels(&pane, [], cx);
7031
7032 pane.update_in(cx, |pane, window, cx| {
7033 pane.close_active_item(
7034 &CloseActiveItem {
7035 save_intent: None,
7036 close_pinned: false,
7037 },
7038 window,
7039 cx,
7040 )
7041 })
7042 .await
7043 .unwrap();
7044
7045 pane.update_in(cx, |pane, window, cx| {
7046 pane.close_other_items(
7047 &CloseOtherItems {
7048 save_intent: None,
7049 close_pinned: false,
7050 },
7051 None,
7052 window,
7053 cx,
7054 )
7055 })
7056 .await
7057 .unwrap();
7058
7059 pane.update_in(cx, |pane, window, cx| {
7060 pane.close_all_items(
7061 &CloseAllItems {
7062 save_intent: None,
7063 close_pinned: false,
7064 },
7065 window,
7066 cx,
7067 )
7068 })
7069 .await
7070 .unwrap();
7071
7072 pane.update_in(cx, |pane, window, cx| {
7073 pane.close_clean_items(
7074 &CloseCleanItems {
7075 close_pinned: false,
7076 },
7077 window,
7078 cx,
7079 )
7080 })
7081 .await
7082 .unwrap();
7083
7084 pane.update_in(cx, |pane, window, cx| {
7085 pane.close_items_to_the_right_by_id(
7086 None,
7087 &CloseItemsToTheRight {
7088 close_pinned: false,
7089 },
7090 window,
7091 cx,
7092 )
7093 })
7094 .await
7095 .unwrap();
7096
7097 pane.update_in(cx, |pane, window, cx| {
7098 pane.close_items_to_the_left_by_id(
7099 None,
7100 &CloseItemsToTheLeft {
7101 close_pinned: false,
7102 },
7103 window,
7104 cx,
7105 )
7106 })
7107 .await
7108 .unwrap();
7109 }
7110
7111 #[gpui::test]
7112 async fn test_item_swapping_actions(cx: &mut TestAppContext) {
7113 init_test(cx);
7114 let fs = FakeFs::new(cx.executor());
7115 let project = Project::test(fs, None, cx).await;
7116 let (workspace, cx) =
7117 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
7118
7119 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7120 assert_item_labels(&pane, [], cx);
7121
7122 // Test that these actions do not panic
7123 pane.update_in(cx, |pane, window, cx| {
7124 pane.swap_item_right(&Default::default(), window, cx);
7125 });
7126
7127 pane.update_in(cx, |pane, window, cx| {
7128 pane.swap_item_left(&Default::default(), window, cx);
7129 });
7130
7131 add_labeled_item(&pane, "A", false, cx);
7132 add_labeled_item(&pane, "B", false, cx);
7133 add_labeled_item(&pane, "C", false, cx);
7134 assert_item_labels(&pane, ["A", "B", "C*"], cx);
7135
7136 pane.update_in(cx, |pane, window, cx| {
7137 pane.swap_item_right(&Default::default(), window, cx);
7138 });
7139 assert_item_labels(&pane, ["A", "B", "C*"], cx);
7140
7141 pane.update_in(cx, |pane, window, cx| {
7142 pane.swap_item_left(&Default::default(), window, cx);
7143 });
7144 assert_item_labels(&pane, ["A", "C*", "B"], cx);
7145
7146 pane.update_in(cx, |pane, window, cx| {
7147 pane.swap_item_left(&Default::default(), window, cx);
7148 });
7149 assert_item_labels(&pane, ["C*", "A", "B"], cx);
7150
7151 pane.update_in(cx, |pane, window, cx| {
7152 pane.swap_item_left(&Default::default(), window, cx);
7153 });
7154 assert_item_labels(&pane, ["C*", "A", "B"], cx);
7155
7156 pane.update_in(cx, |pane, window, cx| {
7157 pane.swap_item_right(&Default::default(), window, cx);
7158 });
7159 assert_item_labels(&pane, ["A", "C*", "B"], cx);
7160 }
7161
7162 #[gpui::test]
7163 async fn test_split_empty(cx: &mut TestAppContext) {
7164 for split_direction in SplitDirection::all() {
7165 test_single_pane_split(["A"], split_direction, SplitMode::EmptyPane, cx).await;
7166 }
7167 }
7168
7169 #[gpui::test]
7170 async fn test_split_clone(cx: &mut TestAppContext) {
7171 for split_direction in SplitDirection::all() {
7172 test_single_pane_split(["A"], split_direction, SplitMode::ClonePane, cx).await;
7173 }
7174 }
7175
7176 #[gpui::test]
7177 async fn test_split_move_right_on_single_pane(cx: &mut TestAppContext) {
7178 test_single_pane_split(["A"], SplitDirection::Right, SplitMode::MovePane, cx).await;
7179 }
7180
7181 #[gpui::test]
7182 async fn test_split_move(cx: &mut TestAppContext) {
7183 for split_direction in SplitDirection::all() {
7184 test_single_pane_split(["A", "B"], split_direction, SplitMode::MovePane, cx).await;
7185 }
7186 }
7187
7188 fn init_test(cx: &mut TestAppContext) {
7189 cx.update(|cx| {
7190 let settings_store = SettingsStore::test(cx);
7191 cx.set_global(settings_store);
7192 theme::init(LoadThemes::JustBase, cx);
7193 });
7194 }
7195
7196 fn set_max_tabs(cx: &mut TestAppContext, value: Option<usize>) {
7197 cx.update_global(|store: &mut SettingsStore, cx| {
7198 store.update_user_settings(cx, |settings| {
7199 settings.workspace.max_tabs = value.map(|v| NonZero::new(v).unwrap())
7200 });
7201 });
7202 }
7203
7204 fn add_labeled_item(
7205 pane: &Entity<Pane>,
7206 label: &str,
7207 is_dirty: bool,
7208 cx: &mut VisualTestContext,
7209 ) -> Box<Entity<TestItem>> {
7210 pane.update_in(cx, |pane, window, cx| {
7211 let labeled_item =
7212 Box::new(cx.new(|cx| TestItem::new(cx).with_label(label).with_dirty(is_dirty)));
7213 pane.add_item(labeled_item.clone(), false, false, None, window, cx);
7214 labeled_item
7215 })
7216 }
7217
7218 fn set_labeled_items<const COUNT: usize>(
7219 pane: &Entity<Pane>,
7220 labels: [&str; COUNT],
7221 cx: &mut VisualTestContext,
7222 ) -> [Box<Entity<TestItem>>; COUNT] {
7223 pane.update_in(cx, |pane, window, cx| {
7224 pane.items.clear();
7225 let mut active_item_index = 0;
7226
7227 let mut index = 0;
7228 let items = labels.map(|mut label| {
7229 if label.ends_with('*') {
7230 label = label.trim_end_matches('*');
7231 active_item_index = index;
7232 }
7233
7234 let labeled_item = Box::new(cx.new(|cx| TestItem::new(cx).with_label(label)));
7235 pane.add_item(labeled_item.clone(), false, false, None, window, cx);
7236 index += 1;
7237 labeled_item
7238 });
7239
7240 pane.activate_item(active_item_index, false, false, window, cx);
7241
7242 items
7243 })
7244 }
7245
7246 // Assert the item label, with the active item label suffixed with a '*'
7247 #[track_caller]
7248 fn assert_item_labels<const COUNT: usize>(
7249 pane: &Entity<Pane>,
7250 expected_states: [&str; COUNT],
7251 cx: &mut VisualTestContext,
7252 ) {
7253 let actual_states = pane.update(cx, |pane, cx| {
7254 pane.items
7255 .iter()
7256 .enumerate()
7257 .map(|(ix, item)| {
7258 let mut state = item
7259 .to_any_view()
7260 .downcast::<TestItem>()
7261 .unwrap()
7262 .read(cx)
7263 .label
7264 .clone();
7265 if ix == pane.active_item_index {
7266 state.push('*');
7267 }
7268 if item.is_dirty(cx) {
7269 state.push('^');
7270 }
7271 if pane.is_tab_pinned(ix) {
7272 state.push('!');
7273 }
7274 state
7275 })
7276 .collect::<Vec<_>>()
7277 });
7278 assert_eq!(
7279 actual_states, expected_states,
7280 "pane items do not match expectation"
7281 );
7282 }
7283
7284 // Assert the item label, with the active item label expected active index
7285 #[track_caller]
7286 fn assert_item_labels_active_index(
7287 pane: &Entity<Pane>,
7288 expected_states: &[&str],
7289 expected_active_idx: usize,
7290 cx: &mut VisualTestContext,
7291 ) {
7292 let actual_states = pane.update(cx, |pane, cx| {
7293 pane.items
7294 .iter()
7295 .enumerate()
7296 .map(|(ix, item)| {
7297 let mut state = item
7298 .to_any_view()
7299 .downcast::<TestItem>()
7300 .unwrap()
7301 .read(cx)
7302 .label
7303 .clone();
7304 if ix == pane.active_item_index {
7305 assert_eq!(ix, expected_active_idx);
7306 }
7307 if item.is_dirty(cx) {
7308 state.push('^');
7309 }
7310 if pane.is_tab_pinned(ix) {
7311 state.push('!');
7312 }
7313 state
7314 })
7315 .collect::<Vec<_>>()
7316 });
7317 assert_eq!(
7318 actual_states, expected_states,
7319 "pane items do not match expectation"
7320 );
7321 }
7322
7323 #[track_caller]
7324 fn assert_pane_ids_on_axis<const COUNT: usize>(
7325 workspace: &Entity<Workspace>,
7326 expected_ids: [&EntityId; COUNT],
7327 expected_axis: Axis,
7328 cx: &mut VisualTestContext,
7329 ) {
7330 workspace.read_with(cx, |workspace, _| match &workspace.center.root {
7331 Member::Axis(axis) => {
7332 assert_eq!(axis.axis, expected_axis);
7333 assert_eq!(axis.members.len(), expected_ids.len());
7334 assert!(
7335 zip(expected_ids, &axis.members).all(|(e, a)| {
7336 if let Member::Pane(p) = a {
7337 p.entity_id() == *e
7338 } else {
7339 false
7340 }
7341 }),
7342 "pane ids do not match expectation: {expected_ids:?} != {actual_ids:?}",
7343 actual_ids = axis.members
7344 );
7345 }
7346 Member::Pane(_) => panic!("expected axis"),
7347 });
7348 }
7349
7350 async fn test_single_pane_split<const COUNT: usize>(
7351 pane_labels: [&str; COUNT],
7352 direction: SplitDirection,
7353 operation: SplitMode,
7354 cx: &mut TestAppContext,
7355 ) {
7356 init_test(cx);
7357 let fs = FakeFs::new(cx.executor());
7358 let project = Project::test(fs, None, cx).await;
7359 let (workspace, cx) =
7360 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
7361
7362 let mut pane_before =
7363 workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7364 for label in pane_labels {
7365 add_labeled_item(&pane_before, label, false, cx);
7366 }
7367 pane_before.update_in(cx, |pane, window, cx| {
7368 pane.split(direction, operation, window, cx)
7369 });
7370 cx.executor().run_until_parked();
7371 let pane_after = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7372
7373 let num_labels = pane_labels.len();
7374 let last_as_active = format!("{}*", String::from(pane_labels[num_labels - 1]));
7375
7376 // check labels for all split operations
7377 match operation {
7378 SplitMode::EmptyPane => {
7379 assert_item_labels_active_index(&pane_before, &pane_labels, num_labels - 1, cx);
7380 assert_item_labels(&pane_after, [], cx);
7381 }
7382 SplitMode::ClonePane => {
7383 assert_item_labels_active_index(&pane_before, &pane_labels, num_labels - 1, cx);
7384 assert_item_labels(&pane_after, [&last_as_active], cx);
7385 }
7386 SplitMode::MovePane => {
7387 let head = &pane_labels[..(num_labels - 1)];
7388 if num_labels == 1 {
7389 // We special-case this behavior and actually execute an empty pane command
7390 // followed by a refocus of the old pane for this case.
7391 pane_before = workspace.read_with(cx, |workspace, _cx| {
7392 workspace
7393 .panes()
7394 .into_iter()
7395 .find(|pane| *pane != &pane_after)
7396 .unwrap()
7397 .clone()
7398 });
7399 };
7400
7401 assert_item_labels_active_index(
7402 &pane_before,
7403 &head,
7404 head.len().saturating_sub(1),
7405 cx,
7406 );
7407 assert_item_labels(&pane_after, [&last_as_active], cx);
7408 pane_after.update_in(cx, |pane, window, cx| {
7409 window.focused(cx).is_some_and(|focus_handle| {
7410 focus_handle == pane.active_item().unwrap().item_focus_handle(cx)
7411 })
7412 });
7413 }
7414 }
7415
7416 // expected axis depends on split direction
7417 let expected_axis = match direction {
7418 SplitDirection::Right | SplitDirection::Left => Axis::Horizontal,
7419 SplitDirection::Up | SplitDirection::Down => Axis::Vertical,
7420 };
7421
7422 // expected ids depends on split direction
7423 let expected_ids = match direction {
7424 SplitDirection::Right | SplitDirection::Down => {
7425 [&pane_before.entity_id(), &pane_after.entity_id()]
7426 }
7427 SplitDirection::Left | SplitDirection::Up => {
7428 [&pane_after.entity_id(), &pane_before.entity_id()]
7429 }
7430 };
7431
7432 // check pane axes for all operations
7433 match operation {
7434 SplitMode::EmptyPane | SplitMode::ClonePane => {
7435 assert_pane_ids_on_axis(&workspace, expected_ids, expected_axis, cx);
7436 }
7437 SplitMode::MovePane => {
7438 assert_pane_ids_on_axis(&workspace, expected_ids, expected_axis, cx);
7439 }
7440 }
7441 }
7442}