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