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