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 #[serde(default)]
199 pub query: Option<String>,
200 #[serde(default)]
201 pub regex: Option<bool>,
202 #[serde(default)]
203 pub case_sensitive: Option<bool>,
204 #[serde(default)]
205 pub whole_word: Option<bool>,
206 #[serde(default)]
207 pub include_ignored: Option<bool>,
208}
209
210#[derive(Clone, Copy, PartialEq, Debug, Deserialize, JsonSchema, Default)]
211#[serde(deny_unknown_fields)]
212pub enum SplitMode {
213 /// Clone the current pane.
214 #[default]
215 ClonePane,
216 /// Create an empty new pane.
217 EmptyPane,
218 /// Move the item into a new pane. This will map to nop if only one pane exists.
219 MovePane,
220}
221
222macro_rules! split_structs {
223 ($($name:ident => $doc:literal),* $(,)?) => {
224 $(
225 #[doc = $doc]
226 #[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Default, Action)]
227 #[action(namespace = pane)]
228 #[serde(deny_unknown_fields, default)]
229 pub struct $name {
230 pub mode: SplitMode,
231 }
232 )*
233 };
234}
235
236split_structs!(
237 SplitLeft => "Splits the pane to the left.",
238 SplitRight => "Splits the pane to the right.",
239 SplitUp => "Splits the pane upward.",
240 SplitDown => "Splits the pane downward.",
241 SplitHorizontal => "Splits the pane horizontally.",
242 SplitVertical => "Splits the pane vertically."
243);
244
245/// Activates the previous item in the pane.
246#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
247#[action(namespace = pane)]
248#[serde(deny_unknown_fields, default)]
249pub struct ActivatePreviousItem {
250 /// Whether to wrap from the first item to the last item.
251 #[serde(default = "default_true")]
252 pub wrap_around: bool,
253}
254
255impl Default for ActivatePreviousItem {
256 fn default() -> Self {
257 Self { wrap_around: true }
258 }
259}
260
261/// Activates the next item in the pane.
262#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
263#[action(namespace = pane)]
264#[serde(deny_unknown_fields, default)]
265pub struct ActivateNextItem {
266 /// Whether to wrap from the last item to the first item.
267 #[serde(default = "default_true")]
268 pub wrap_around: bool,
269}
270
271impl Default for ActivateNextItem {
272 fn default() -> Self {
273 Self { wrap_around: true }
274 }
275}
276
277actions!(
278 pane,
279 [
280 /// Activates the last item in the pane.
281 ActivateLastItem,
282 /// Switches to the alternate file.
283 AlternateFile,
284 /// Navigates back in history.
285 GoBack,
286 /// Navigates forward in history.
287 GoForward,
288 /// Navigates back in the tag stack.
289 GoToOlderTag,
290 /// Navigates forward in the tag stack.
291 GoToNewerTag,
292 /// Joins this pane into the next pane.
293 JoinIntoNext,
294 /// Joins all panes into one.
295 JoinAll,
296 /// Reopens the most recently closed item.
297 ReopenClosedItem,
298 /// Splits the pane to the left, moving the current item.
299 SplitAndMoveLeft,
300 /// Splits the pane upward, moving the current item.
301 SplitAndMoveUp,
302 /// Splits the pane to the right, moving the current item.
303 SplitAndMoveRight,
304 /// Splits the pane downward, moving the current item.
305 SplitAndMoveDown,
306 /// Swaps the current item with the one to the left.
307 SwapItemLeft,
308 /// Swaps the current item with the one to the right.
309 SwapItemRight,
310 /// Toggles preview mode for the current tab.
311 TogglePreviewTab,
312 /// Toggles pin status for the current tab.
313 TogglePinTab,
314 /// Unpins all tabs in the pane.
315 UnpinAllTabs,
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("Search Project", DeploySearch::default().boxed_clone())
4189 .action("Search Symbols", ToggleProjectSymbols.boxed_clone())
4190 .separator()
4191 .action("New Terminal", NewTerminal::default().boxed_clone())
4192 }))
4193 }),
4194 )
4195 .child(
4196 PopoverMenu::new("pane-tab-bar-split")
4197 .trigger_with_tooltip(
4198 IconButton::new("split", IconName::Split)
4199 .icon_size(IconSize::Small)
4200 .disabled(!can_clone && !can_split_move),
4201 Tooltip::text("Split Pane"),
4202 )
4203 .anchor(Corner::TopRight)
4204 .with_handle(pane.split_item_context_menu_handle.clone())
4205 .menu(move |window, cx| {
4206 ContextMenu::build(window, cx, |menu, _, _| {
4207 let mode = SplitMode::MovePane;
4208 if can_split_move {
4209 menu.action("Split Right", SplitRight { mode }.boxed_clone())
4210 .action("Split Left", SplitLeft { mode }.boxed_clone())
4211 .action("Split Up", SplitUp { mode }.boxed_clone())
4212 .action("Split Down", SplitDown { mode }.boxed_clone())
4213 } else {
4214 menu.action("Split Right", SplitRight::default().boxed_clone())
4215 .action("Split Left", SplitLeft::default().boxed_clone())
4216 .action("Split Up", SplitUp::default().boxed_clone())
4217 .action("Split Down", SplitDown::default().boxed_clone())
4218 }
4219 })
4220 .into()
4221 }),
4222 )
4223 .child({
4224 let zoomed = pane.is_zoomed();
4225 IconButton::new("toggle_zoom", IconName::Maximize)
4226 .icon_size(IconSize::Small)
4227 .toggle_state(zoomed)
4228 .selected_icon(IconName::Minimize)
4229 .on_click(cx.listener(|pane, _, window, cx| {
4230 pane.toggle_zoom(&crate::ToggleZoom, window, cx);
4231 }))
4232 .tooltip(move |_window, cx| {
4233 Tooltip::for_action(
4234 if zoomed { "Zoom Out" } else { "Zoom In" },
4235 &ToggleZoom,
4236 cx,
4237 )
4238 })
4239 })
4240 .into_any_element()
4241 .into();
4242 (None, right_children)
4243}
4244
4245impl Focusable for Pane {
4246 fn focus_handle(&self, _cx: &App) -> FocusHandle {
4247 self.focus_handle.clone()
4248 }
4249}
4250
4251impl Render for Pane {
4252 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4253 let mut key_context = KeyContext::new_with_defaults();
4254 key_context.add("Pane");
4255 if self.active_item().is_none() {
4256 key_context.add("EmptyPane");
4257 }
4258
4259 self.toolbar
4260 .read(cx)
4261 .contribute_context(&mut key_context, cx);
4262
4263 let should_display_tab_bar = self.should_display_tab_bar.clone();
4264 let display_tab_bar = should_display_tab_bar(window, cx);
4265 let Some(project) = self.project.upgrade() else {
4266 return div().track_focus(&self.focus_handle(cx));
4267 };
4268 let is_local = project.read(cx).is_local();
4269
4270 v_flex()
4271 .key_context(key_context)
4272 .track_focus(&self.focus_handle(cx))
4273 .size_full()
4274 .flex_none()
4275 .overflow_hidden()
4276 .on_action(cx.listener(|pane, split: &SplitLeft, window, cx| {
4277 pane.split(SplitDirection::Left, split.mode, window, cx)
4278 }))
4279 .on_action(cx.listener(|pane, split: &SplitUp, window, cx| {
4280 pane.split(SplitDirection::Up, split.mode, window, cx)
4281 }))
4282 .on_action(cx.listener(|pane, split: &SplitHorizontal, window, cx| {
4283 pane.split(SplitDirection::horizontal(cx), split.mode, window, cx)
4284 }))
4285 .on_action(cx.listener(|pane, split: &SplitVertical, window, cx| {
4286 pane.split(SplitDirection::vertical(cx), split.mode, window, cx)
4287 }))
4288 .on_action(cx.listener(|pane, split: &SplitRight, window, cx| {
4289 pane.split(SplitDirection::Right, split.mode, window, cx)
4290 }))
4291 .on_action(cx.listener(|pane, split: &SplitDown, window, cx| {
4292 pane.split(SplitDirection::Down, split.mode, window, cx)
4293 }))
4294 .on_action(cx.listener(|pane, _: &SplitAndMoveUp, window, cx| {
4295 pane.split(SplitDirection::Up, SplitMode::MovePane, window, cx)
4296 }))
4297 .on_action(cx.listener(|pane, _: &SplitAndMoveDown, window, cx| {
4298 pane.split(SplitDirection::Down, SplitMode::MovePane, window, cx)
4299 }))
4300 .on_action(cx.listener(|pane, _: &SplitAndMoveLeft, window, cx| {
4301 pane.split(SplitDirection::Left, SplitMode::MovePane, window, cx)
4302 }))
4303 .on_action(cx.listener(|pane, _: &SplitAndMoveRight, window, cx| {
4304 pane.split(SplitDirection::Right, SplitMode::MovePane, window, cx)
4305 }))
4306 .on_action(cx.listener(|_, _: &JoinIntoNext, _, cx| {
4307 cx.emit(Event::JoinIntoNext);
4308 }))
4309 .on_action(cx.listener(|_, _: &JoinAll, _, cx| {
4310 cx.emit(Event::JoinAll);
4311 }))
4312 .on_action(cx.listener(Pane::toggle_zoom))
4313 .on_action(cx.listener(Pane::zoom_in))
4314 .on_action(cx.listener(Pane::zoom_out))
4315 .on_action(cx.listener(Self::navigate_backward))
4316 .on_action(cx.listener(Self::navigate_forward))
4317 .on_action(cx.listener(Self::go_to_older_tag))
4318 .on_action(cx.listener(Self::go_to_newer_tag))
4319 .on_action(
4320 cx.listener(|pane: &mut Pane, action: &ActivateItem, window, cx| {
4321 pane.activate_item(
4322 action.0.min(pane.items.len().saturating_sub(1)),
4323 true,
4324 true,
4325 window,
4326 cx,
4327 );
4328 }),
4329 )
4330 .on_action(cx.listener(Self::alternate_file))
4331 .on_action(cx.listener(Self::activate_last_item))
4332 .on_action(cx.listener(Self::activate_previous_item))
4333 .on_action(cx.listener(Self::activate_next_item))
4334 .on_action(cx.listener(Self::swap_item_left))
4335 .on_action(cx.listener(Self::swap_item_right))
4336 .on_action(cx.listener(Self::toggle_pin_tab))
4337 .on_action(cx.listener(Self::unpin_all_tabs))
4338 .when(PreviewTabsSettings::get_global(cx).enabled, |this| {
4339 this.on_action(
4340 cx.listener(|pane: &mut Pane, _: &TogglePreviewTab, window, cx| {
4341 if let Some(active_item_id) = pane.active_item().map(|i| i.item_id()) {
4342 if pane.is_active_preview_item(active_item_id) {
4343 pane.unpreview_item_if_preview(active_item_id);
4344 } else {
4345 pane.replace_preview_item_id(active_item_id, window, cx);
4346 }
4347 }
4348 }),
4349 )
4350 })
4351 .on_action(
4352 cx.listener(|pane: &mut Self, action: &CloseActiveItem, window, cx| {
4353 pane.close_active_item(action, window, cx)
4354 .detach_and_log_err(cx)
4355 }),
4356 )
4357 .on_action(
4358 cx.listener(|pane: &mut Self, action: &CloseOtherItems, window, cx| {
4359 pane.close_other_items(action, None, window, cx)
4360 .detach_and_log_err(cx);
4361 }),
4362 )
4363 .on_action(
4364 cx.listener(|pane: &mut Self, action: &CloseCleanItems, window, cx| {
4365 pane.close_clean_items(action, window, cx)
4366 .detach_and_log_err(cx)
4367 }),
4368 )
4369 .on_action(cx.listener(
4370 |pane: &mut Self, action: &CloseItemsToTheLeft, window, cx| {
4371 pane.close_items_to_the_left_by_id(None, action, window, cx)
4372 .detach_and_log_err(cx)
4373 },
4374 ))
4375 .on_action(cx.listener(
4376 |pane: &mut Self, action: &CloseItemsToTheRight, window, cx| {
4377 pane.close_items_to_the_right_by_id(None, action, window, cx)
4378 .detach_and_log_err(cx)
4379 },
4380 ))
4381 .on_action(
4382 cx.listener(|pane: &mut Self, action: &CloseAllItems, window, cx| {
4383 pane.close_all_items(action, window, cx)
4384 .detach_and_log_err(cx)
4385 }),
4386 )
4387 .on_action(cx.listener(
4388 |pane: &mut Self, action: &CloseMultibufferItems, window, cx| {
4389 pane.close_multibuffer_items(action, window, cx)
4390 .detach_and_log_err(cx)
4391 },
4392 ))
4393 .on_action(cx.listener(
4394 |pane: &mut Self, action: &RevealInProjectPanel, _window, cx| {
4395 let active_item = pane.active_item();
4396 let entry_id = active_item.as_ref().and_then(|item| {
4397 action
4398 .entry_id
4399 .map(ProjectEntryId::from_proto)
4400 .or_else(|| item.project_entry_ids(cx).first().copied())
4401 });
4402
4403 pane.project
4404 .update(cx, |project, cx| {
4405 if let Some(entry_id) = entry_id
4406 && project
4407 .worktree_for_entry(entry_id, cx)
4408 .is_some_and(|worktree| worktree.read(cx).is_visible())
4409 {
4410 return cx.emit(project::Event::RevealInProjectPanel(entry_id));
4411 }
4412
4413 // When no entry is found, which is the case when
4414 // working with an unsaved buffer, or the worktree
4415 // is not visible, for example, a file that doesn't
4416 // belong to an open project, we can't reveal the
4417 // entry but we still want to activate the project
4418 // panel.
4419 cx.emit(project::Event::ActivateProjectPanel);
4420 })
4421 .log_err();
4422 },
4423 ))
4424 .on_action(cx.listener(|_, _: &menu::Cancel, window, cx| {
4425 if cx.stop_active_drag(window) {
4426 } else {
4427 cx.propagate();
4428 }
4429 }))
4430 .when(self.active_item().is_some() && display_tab_bar, |pane| {
4431 pane.child((self.render_tab_bar.clone())(self, window, cx))
4432 })
4433 .child({
4434 let has_worktrees = project.read(cx).visible_worktrees(cx).next().is_some();
4435 // main content
4436 div()
4437 .flex_1()
4438 .relative()
4439 .group("")
4440 .overflow_hidden()
4441 .on_drag_move::<DraggedTab>(cx.listener(Self::handle_drag_move))
4442 .on_drag_move::<DraggedSelection>(cx.listener(Self::handle_drag_move))
4443 .when(is_local, |div| {
4444 div.on_drag_move::<ExternalPaths>(cx.listener(Self::handle_drag_move))
4445 })
4446 .map(|div| {
4447 if let Some(item) = self.active_item() {
4448 div.id("pane_placeholder")
4449 .v_flex()
4450 .size_full()
4451 .overflow_hidden()
4452 .child(self.toolbar.clone())
4453 .child(item.to_any_view())
4454 } else {
4455 let placeholder = div
4456 .id("pane_placeholder")
4457 .h_flex()
4458 .size_full()
4459 .justify_center()
4460 .on_click(cx.listener(
4461 move |this, event: &ClickEvent, window, cx| {
4462 if event.click_count() == 2 {
4463 window.dispatch_action(
4464 this.double_click_dispatch_action.boxed_clone(),
4465 cx,
4466 );
4467 }
4468 },
4469 ));
4470 if has_worktrees || !self.should_display_welcome_page {
4471 placeholder
4472 } else {
4473 if self.welcome_page.is_none() {
4474 let workspace = self.workspace.clone();
4475 self.welcome_page = Some(cx.new(|cx| {
4476 crate::welcome::WelcomePage::new(
4477 workspace, true, window, cx,
4478 )
4479 }));
4480 }
4481 placeholder.child(self.welcome_page.clone().unwrap())
4482 }
4483 }
4484 .focus_follows_mouse(self.focus_follows_mouse, cx)
4485 })
4486 .child(
4487 // drag target
4488 div()
4489 .invisible()
4490 .absolute()
4491 .bg(cx.theme().colors().drop_target_background)
4492 .group_drag_over::<DraggedTab>("", |style| style.visible())
4493 .group_drag_over::<DraggedSelection>("", |style| style.visible())
4494 .when(is_local, |div| {
4495 div.group_drag_over::<ExternalPaths>("", |style| style.visible())
4496 })
4497 .when_some(self.can_drop_predicate.clone(), |this, p| {
4498 this.can_drop(move |a, window, cx| p(a, window, cx))
4499 })
4500 .on_drop(cx.listener(move |this, dragged_tab, window, cx| {
4501 this.handle_tab_drop(
4502 dragged_tab,
4503 this.active_item_index(),
4504 true,
4505 window,
4506 cx,
4507 )
4508 }))
4509 .on_drop(cx.listener(
4510 move |this, selection: &DraggedSelection, window, cx| {
4511 this.handle_dragged_selection_drop(selection, None, window, cx)
4512 },
4513 ))
4514 .on_drop(cx.listener(move |this, paths, window, cx| {
4515 this.handle_external_paths_drop(paths, window, cx)
4516 }))
4517 .map(|div| {
4518 let size = DefiniteLength::Fraction(0.5);
4519 match self.drag_split_direction {
4520 None => div.top_0().right_0().bottom_0().left_0(),
4521 Some(SplitDirection::Up) => {
4522 div.top_0().left_0().right_0().h(size)
4523 }
4524 Some(SplitDirection::Down) => {
4525 div.left_0().bottom_0().right_0().h(size)
4526 }
4527 Some(SplitDirection::Left) => {
4528 div.top_0().left_0().bottom_0().w(size)
4529 }
4530 Some(SplitDirection::Right) => {
4531 div.top_0().bottom_0().right_0().w(size)
4532 }
4533 }
4534 }),
4535 )
4536 })
4537 .on_mouse_down(
4538 MouseButton::Navigate(NavigationDirection::Back),
4539 cx.listener(|pane, _, window, cx| {
4540 if let Some(workspace) = pane.workspace.upgrade() {
4541 let pane = cx.entity().downgrade();
4542 window.defer(cx, move |window, cx| {
4543 workspace.update(cx, |workspace, cx| {
4544 workspace.go_back(pane, window, cx).detach_and_log_err(cx)
4545 })
4546 })
4547 }
4548 }),
4549 )
4550 .on_mouse_down(
4551 MouseButton::Navigate(NavigationDirection::Forward),
4552 cx.listener(|pane, _, window, cx| {
4553 if let Some(workspace) = pane.workspace.upgrade() {
4554 let pane = cx.entity().downgrade();
4555 window.defer(cx, move |window, cx| {
4556 workspace.update(cx, |workspace, cx| {
4557 workspace
4558 .go_forward(pane, window, cx)
4559 .detach_and_log_err(cx)
4560 })
4561 })
4562 }
4563 }),
4564 )
4565 }
4566}
4567
4568impl ItemNavHistory {
4569 pub fn push<D: 'static + Any + Send + Sync>(
4570 &mut self,
4571 data: Option<D>,
4572 row: Option<u32>,
4573 cx: &mut App,
4574 ) {
4575 if self
4576 .item
4577 .upgrade()
4578 .is_some_and(|item| item.include_in_nav_history())
4579 {
4580 let is_preview_item = self.history.0.lock().preview_item_id == Some(self.item.id());
4581 self.history
4582 .push(data, self.item.clone(), is_preview_item, row, cx);
4583 }
4584 }
4585
4586 pub fn navigation_entry(&self, data: Option<Arc<dyn Any + Send + Sync>>) -> NavigationEntry {
4587 let is_preview_item = self.history.0.lock().preview_item_id == Some(self.item.id());
4588 NavigationEntry {
4589 item: self.item.clone(),
4590 data,
4591 timestamp: 0,
4592 is_preview: is_preview_item,
4593 row: None,
4594 }
4595 }
4596
4597 pub fn push_tag(&mut self, origin: Option<NavigationEntry>, target: Option<NavigationEntry>) {
4598 if let (Some(origin_entry), Some(target_entry)) = (origin, target) {
4599 self.history.push_tag(origin_entry, target_entry);
4600 }
4601 }
4602
4603 pub fn pop_backward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
4604 self.history.pop(NavigationMode::GoingBack, cx)
4605 }
4606
4607 pub fn pop_forward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
4608 self.history.pop(NavigationMode::GoingForward, cx)
4609 }
4610}
4611
4612impl NavHistory {
4613 pub fn for_each_entry(
4614 &self,
4615 cx: &App,
4616 f: &mut dyn FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
4617 ) {
4618 let borrowed_history = self.0.lock();
4619 borrowed_history
4620 .forward_stack
4621 .iter()
4622 .chain(borrowed_history.backward_stack.iter())
4623 .chain(borrowed_history.closed_stack.iter())
4624 .for_each(|entry| {
4625 if let Some(project_and_abs_path) =
4626 borrowed_history.paths_by_item.get(&entry.item.id())
4627 {
4628 f(entry, project_and_abs_path.clone());
4629 } else if let Some(item) = entry.item.upgrade()
4630 && let Some(path) = item.project_path(cx)
4631 {
4632 f(entry, (path, None));
4633 }
4634 })
4635 }
4636
4637 pub fn set_mode(&mut self, mode: NavigationMode) {
4638 self.0.lock().mode = mode;
4639 }
4640
4641 pub fn mode(&self) -> NavigationMode {
4642 self.0.lock().mode
4643 }
4644
4645 pub fn disable(&mut self) {
4646 self.0.lock().mode = NavigationMode::Disabled;
4647 }
4648
4649 pub fn enable(&mut self) {
4650 self.0.lock().mode = NavigationMode::Normal;
4651 }
4652
4653 pub fn clear(&mut self, cx: &mut App) {
4654 let mut state = self.0.lock();
4655
4656 if state.backward_stack.is_empty()
4657 && state.forward_stack.is_empty()
4658 && state.closed_stack.is_empty()
4659 && state.paths_by_item.is_empty()
4660 && state.tag_stack.is_empty()
4661 {
4662 return;
4663 }
4664
4665 state.mode = NavigationMode::Normal;
4666 state.backward_stack.clear();
4667 state.forward_stack.clear();
4668 state.closed_stack.clear();
4669 state.paths_by_item.clear();
4670 state.tag_stack.clear();
4671 state.tag_stack_pos = 0;
4672 state.did_update(cx);
4673 }
4674
4675 pub fn pop(&mut self, mode: NavigationMode, cx: &mut App) -> Option<NavigationEntry> {
4676 let mut state = self.0.lock();
4677 let entry = match mode {
4678 NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
4679 return None;
4680 }
4681 NavigationMode::GoingBack => &mut state.backward_stack,
4682 NavigationMode::GoingForward => &mut state.forward_stack,
4683 NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
4684 }
4685 .pop_back();
4686 if entry.is_some() {
4687 state.did_update(cx);
4688 }
4689 entry
4690 }
4691
4692 pub fn push<D: 'static + Any + Send + Sync>(
4693 &mut self,
4694 data: Option<D>,
4695 item: Arc<dyn WeakItemHandle + Send + Sync>,
4696 is_preview: bool,
4697 row: Option<u32>,
4698 cx: &mut App,
4699 ) {
4700 let state = &mut *self.0.lock();
4701 let new_item_id = item.id();
4702
4703 let is_same_location =
4704 |entry: &NavigationEntry| entry.item.id() == new_item_id && entry.row == row;
4705
4706 match state.mode {
4707 NavigationMode::Disabled => {}
4708 NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
4709 state
4710 .backward_stack
4711 .retain(|entry| !is_same_location(entry));
4712
4713 if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4714 state.backward_stack.pop_front();
4715 }
4716 state.backward_stack.push_back(NavigationEntry {
4717 item,
4718 data: data.map(|data| Arc::new(data) as Arc<dyn Any + Send + Sync>),
4719 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4720 is_preview,
4721 row,
4722 });
4723 state.forward_stack.clear();
4724 }
4725 NavigationMode::GoingBack => {
4726 state.forward_stack.retain(|entry| !is_same_location(entry));
4727
4728 if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4729 state.forward_stack.pop_front();
4730 }
4731 state.forward_stack.push_back(NavigationEntry {
4732 item,
4733 data: data.map(|data| Arc::new(data) as Arc<dyn Any + Send + Sync>),
4734 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4735 is_preview,
4736 row,
4737 });
4738 }
4739 NavigationMode::GoingForward => {
4740 state
4741 .backward_stack
4742 .retain(|entry| !is_same_location(entry));
4743
4744 if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4745 state.backward_stack.pop_front();
4746 }
4747 state.backward_stack.push_back(NavigationEntry {
4748 item,
4749 data: data.map(|data| Arc::new(data) as Arc<dyn Any + Send + Sync>),
4750 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4751 is_preview,
4752 row,
4753 });
4754 }
4755 NavigationMode::ClosingItem if is_preview => return,
4756 NavigationMode::ClosingItem => {
4757 if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4758 state.closed_stack.pop_front();
4759 }
4760 state.closed_stack.push_back(NavigationEntry {
4761 item,
4762 data: data.map(|data| Arc::new(data) as Arc<dyn Any + Send + Sync>),
4763 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4764 is_preview,
4765 row,
4766 });
4767 }
4768 }
4769 state.did_update(cx);
4770 }
4771
4772 pub fn remove_item(&mut self, item_id: EntityId) {
4773 let mut state = self.0.lock();
4774 state.paths_by_item.remove(&item_id);
4775 state
4776 .backward_stack
4777 .retain(|entry| entry.item.id() != item_id);
4778 state
4779 .forward_stack
4780 .retain(|entry| entry.item.id() != item_id);
4781 state
4782 .closed_stack
4783 .retain(|entry| entry.item.id() != item_id);
4784 state
4785 .tag_stack
4786 .retain(|entry| entry.origin.item.id() != item_id && entry.target.item.id() != item_id);
4787 }
4788
4789 pub fn rename_item(
4790 &mut self,
4791 item_id: EntityId,
4792 project_path: ProjectPath,
4793 abs_path: Option<PathBuf>,
4794 ) {
4795 let mut state = self.0.lock();
4796 let path_for_item = state.paths_by_item.get_mut(&item_id);
4797 if let Some(path_for_item) = path_for_item {
4798 path_for_item.0 = project_path;
4799 path_for_item.1 = abs_path;
4800 }
4801 }
4802
4803 pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
4804 self.0.lock().paths_by_item.get(&item_id).cloned()
4805 }
4806
4807 pub fn push_tag(&mut self, origin: NavigationEntry, target: NavigationEntry) {
4808 let mut state = self.0.lock();
4809 let truncate_to = state.tag_stack_pos;
4810 state.tag_stack.truncate(truncate_to);
4811 state.tag_stack.push_back(TagStackEntry { origin, target });
4812 state.tag_stack_pos = state.tag_stack.len();
4813 }
4814
4815 pub fn pop_tag(&mut self, mode: TagNavigationMode) -> Option<NavigationEntry> {
4816 let mut state = self.0.lock();
4817 match mode {
4818 TagNavigationMode::Older => {
4819 if state.tag_stack_pos > 0 {
4820 state.tag_stack_pos -= 1;
4821 state
4822 .tag_stack
4823 .get(state.tag_stack_pos)
4824 .map(|e| e.origin.clone())
4825 } else {
4826 None
4827 }
4828 }
4829 TagNavigationMode::Newer => {
4830 let entry = state
4831 .tag_stack
4832 .get(state.tag_stack_pos)
4833 .map(|e| e.target.clone());
4834 if state.tag_stack_pos < state.tag_stack.len() {
4835 state.tag_stack_pos += 1;
4836 }
4837 entry
4838 }
4839 }
4840 }
4841}
4842
4843impl NavHistoryState {
4844 pub fn did_update(&self, cx: &mut App) {
4845 if let Some(pane) = self.pane.upgrade() {
4846 cx.defer(move |cx| {
4847 pane.update(cx, |pane, cx| pane.history_updated(cx));
4848 });
4849 }
4850 }
4851}
4852
4853fn dirty_message_for(buffer_path: Option<ProjectPath>, path_style: PathStyle) -> String {
4854 let path = buffer_path
4855 .as_ref()
4856 .and_then(|p| {
4857 let path = p.path.display(path_style);
4858 if path.is_empty() { None } else { Some(path) }
4859 })
4860 .unwrap_or("This buffer".into());
4861 let path = truncate_and_remove_front(&path, 80);
4862 format!("{path} contains unsaved edits. Do you want to save it?")
4863}
4864
4865pub fn tab_details(items: &[Box<dyn ItemHandle>], _window: &Window, cx: &App) -> Vec<usize> {
4866 util::disambiguate::compute_disambiguation_details(items, |item, detail| {
4867 item.tab_content_text(detail, cx)
4868 })
4869}
4870
4871pub fn render_item_indicator(item: Box<dyn ItemHandle>, cx: &App) -> Option<Indicator> {
4872 maybe!({
4873 let indicator_color = match (item.has_conflict(cx), item.is_dirty(cx)) {
4874 (true, _) => Color::Warning,
4875 (_, true) => Color::Accent,
4876 (false, false) => return None,
4877 };
4878
4879 Some(Indicator::dot().color(indicator_color))
4880 })
4881}
4882
4883impl Render for DraggedTab {
4884 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4885 let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
4886 let label = self.item.tab_content(
4887 TabContentParams {
4888 detail: Some(self.detail),
4889 selected: false,
4890 preview: false,
4891 deemphasized: false,
4892 },
4893 window,
4894 cx,
4895 );
4896 Tab::new("")
4897 .toggle_state(self.is_active)
4898 .child(label)
4899 .render(window, cx)
4900 .font(ui_font)
4901 }
4902}
4903
4904#[cfg(test)]
4905mod tests {
4906 use std::{cell::Cell, iter::zip, num::NonZero, rc::Rc};
4907
4908 use super::*;
4909 use crate::{
4910 Member,
4911 item::test::{TestItem, TestProjectItem},
4912 };
4913 use gpui::{
4914 AppContext, Axis, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
4915 TestAppContext, VisualTestContext, size,
4916 };
4917 use project::FakeFs;
4918 use settings::SettingsStore;
4919 use theme::LoadThemes;
4920 use util::TryFutureExt;
4921
4922 // drop_call_count is a Cell here because `handle_drop` takes &self, not &mut self.
4923 struct CustomDropHandlingItem {
4924 focus_handle: gpui::FocusHandle,
4925 drop_call_count: Cell<usize>,
4926 }
4927
4928 impl CustomDropHandlingItem {
4929 fn new(cx: &mut Context<Self>) -> Self {
4930 Self {
4931 focus_handle: cx.focus_handle(),
4932 drop_call_count: Cell::new(0),
4933 }
4934 }
4935
4936 fn drop_call_count(&self) -> usize {
4937 self.drop_call_count.get()
4938 }
4939 }
4940
4941 impl EventEmitter<()> for CustomDropHandlingItem {}
4942
4943 impl Focusable for CustomDropHandlingItem {
4944 fn focus_handle(&self, _cx: &App) -> gpui::FocusHandle {
4945 self.focus_handle.clone()
4946 }
4947 }
4948
4949 impl Render for CustomDropHandlingItem {
4950 fn render(
4951 &mut self,
4952 _window: &mut Window,
4953 _cx: &mut Context<Self>,
4954 ) -> impl gpui::IntoElement {
4955 gpui::Empty
4956 }
4957 }
4958
4959 impl Item for CustomDropHandlingItem {
4960 type Event = ();
4961
4962 fn tab_content_text(&self, _detail: usize, _cx: &App) -> gpui::SharedString {
4963 "custom_drop_handling_item".into()
4964 }
4965
4966 fn handle_drop(
4967 &self,
4968 _active_pane: &Pane,
4969 dropped: &dyn std::any::Any,
4970 _window: &mut Window,
4971 _cx: &mut App,
4972 ) -> bool {
4973 let is_dragged_tab = dropped.downcast_ref::<DraggedTab>().is_some();
4974 if is_dragged_tab {
4975 self.drop_call_count.set(self.drop_call_count.get() + 1);
4976 }
4977 is_dragged_tab
4978 }
4979 }
4980
4981 #[gpui::test]
4982 async fn test_add_item_capped_to_max_tabs(cx: &mut TestAppContext) {
4983 init_test(cx);
4984 let fs = FakeFs::new(cx.executor());
4985
4986 let project = Project::test(fs, None, cx).await;
4987 let (workspace, cx) =
4988 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4989 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4990
4991 for i in 0..7 {
4992 add_labeled_item(&pane, format!("{}", i).as_str(), false, cx);
4993 }
4994
4995 set_max_tabs(cx, Some(5));
4996 add_labeled_item(&pane, "7", false, cx);
4997 // Remove items to respect the max tab cap.
4998 assert_item_labels(&pane, ["3", "4", "5", "6", "7*"], cx);
4999 pane.update_in(cx, |pane, window, cx| {
5000 pane.activate_item(0, false, false, window, cx);
5001 });
5002 add_labeled_item(&pane, "X", false, cx);
5003 // Respect activation order.
5004 assert_item_labels(&pane, ["3", "X*", "5", "6", "7"], cx);
5005
5006 for i in 0..7 {
5007 add_labeled_item(&pane, format!("D{}", i).as_str(), true, cx);
5008 }
5009 // Keeps dirty items, even over max tab cap.
5010 assert_item_labels(
5011 &pane,
5012 ["D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6*^"],
5013 cx,
5014 );
5015
5016 set_max_tabs(cx, None);
5017 for i in 0..7 {
5018 add_labeled_item(&pane, format!("N{}", i).as_str(), false, cx);
5019 }
5020 // No cap when max tabs is None.
5021 assert_item_labels(
5022 &pane,
5023 [
5024 "D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6^", "N0", "N1", "N2", "N3", "N4",
5025 "N5", "N6*",
5026 ],
5027 cx,
5028 );
5029 }
5030
5031 #[gpui::test]
5032 async fn test_reduce_max_tabs_closes_existing_items(cx: &mut TestAppContext) {
5033 init_test(cx);
5034 let fs = FakeFs::new(cx.executor());
5035
5036 let project = Project::test(fs, None, cx).await;
5037 let (workspace, cx) =
5038 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5039 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5040
5041 add_labeled_item(&pane, "A", false, cx);
5042 add_labeled_item(&pane, "B", false, cx);
5043 let item_c = add_labeled_item(&pane, "C", false, cx);
5044 let item_d = add_labeled_item(&pane, "D", false, cx);
5045 add_labeled_item(&pane, "E", false, cx);
5046 add_labeled_item(&pane, "Settings", false, cx);
5047 assert_item_labels(&pane, ["A", "B", "C", "D", "E", "Settings*"], cx);
5048
5049 set_max_tabs(cx, Some(5));
5050 assert_item_labels(&pane, ["B", "C", "D", "E", "Settings*"], cx);
5051
5052 set_max_tabs(cx, Some(4));
5053 assert_item_labels(&pane, ["C", "D", "E", "Settings*"], cx);
5054
5055 pane.update_in(cx, |pane, window, cx| {
5056 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5057 pane.pin_tab_at(ix, window, cx);
5058
5059 let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
5060 pane.pin_tab_at(ix, window, cx);
5061 });
5062 assert_item_labels(&pane, ["C!", "D!", "E", "Settings*"], cx);
5063
5064 set_max_tabs(cx, Some(2));
5065 assert_item_labels(&pane, ["C!", "D!", "Settings*"], cx);
5066 }
5067
5068 #[gpui::test]
5069 async fn test_allow_pinning_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
5070 init_test(cx);
5071 let fs = FakeFs::new(cx.executor());
5072
5073 let project = Project::test(fs, None, cx).await;
5074 let (workspace, cx) =
5075 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5076 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5077
5078 set_max_tabs(cx, Some(1));
5079 let item_a = add_labeled_item(&pane, "A", true, cx);
5080
5081 pane.update_in(cx, |pane, window, cx| {
5082 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5083 pane.pin_tab_at(ix, window, cx);
5084 });
5085 assert_item_labels(&pane, ["A*^!"], cx);
5086 }
5087
5088 #[gpui::test]
5089 async fn test_allow_pinning_non_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
5090 init_test(cx);
5091 let fs = FakeFs::new(cx.executor());
5092
5093 let project = Project::test(fs, None, cx).await;
5094 let (workspace, cx) =
5095 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5096 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5097
5098 set_max_tabs(cx, Some(1));
5099 let item_a = add_labeled_item(&pane, "A", false, cx);
5100
5101 pane.update_in(cx, |pane, window, cx| {
5102 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5103 pane.pin_tab_at(ix, window, cx);
5104 });
5105 assert_item_labels(&pane, ["A*!"], cx);
5106 }
5107
5108 #[gpui::test]
5109 async fn test_pin_tabs_incrementally_at_max_capacity(cx: &mut TestAppContext) {
5110 init_test(cx);
5111 let fs = FakeFs::new(cx.executor());
5112
5113 let project = Project::test(fs, None, cx).await;
5114 let (workspace, cx) =
5115 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5116 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5117
5118 set_max_tabs(cx, Some(3));
5119
5120 let item_a = add_labeled_item(&pane, "A", false, cx);
5121 assert_item_labels(&pane, ["A*"], cx);
5122
5123 pane.update_in(cx, |pane, window, cx| {
5124 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5125 pane.pin_tab_at(ix, window, cx);
5126 });
5127 assert_item_labels(&pane, ["A*!"], cx);
5128
5129 let item_b = add_labeled_item(&pane, "B", false, cx);
5130 assert_item_labels(&pane, ["A!", "B*"], cx);
5131
5132 pane.update_in(cx, |pane, window, cx| {
5133 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5134 pane.pin_tab_at(ix, window, cx);
5135 });
5136 assert_item_labels(&pane, ["A!", "B*!"], cx);
5137
5138 let item_c = add_labeled_item(&pane, "C", false, cx);
5139 assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
5140
5141 pane.update_in(cx, |pane, window, cx| {
5142 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5143 pane.pin_tab_at(ix, window, cx);
5144 });
5145 assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
5146 }
5147
5148 #[gpui::test]
5149 async fn test_pin_tabs_left_to_right_after_opening_at_max_capacity(cx: &mut TestAppContext) {
5150 init_test(cx);
5151 let fs = FakeFs::new(cx.executor());
5152
5153 let project = Project::test(fs, None, cx).await;
5154 let (workspace, cx) =
5155 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5156 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5157
5158 set_max_tabs(cx, Some(3));
5159
5160 let item_a = add_labeled_item(&pane, "A", false, cx);
5161 assert_item_labels(&pane, ["A*"], cx);
5162
5163 let item_b = add_labeled_item(&pane, "B", false, cx);
5164 assert_item_labels(&pane, ["A", "B*"], cx);
5165
5166 let item_c = add_labeled_item(&pane, "C", false, cx);
5167 assert_item_labels(&pane, ["A", "B", "C*"], cx);
5168
5169 pane.update_in(cx, |pane, window, cx| {
5170 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5171 pane.pin_tab_at(ix, window, cx);
5172 });
5173 assert_item_labels(&pane, ["A!", "B", "C*"], cx);
5174
5175 pane.update_in(cx, |pane, window, cx| {
5176 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5177 pane.pin_tab_at(ix, window, cx);
5178 });
5179 assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
5180
5181 pane.update_in(cx, |pane, window, cx| {
5182 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5183 pane.pin_tab_at(ix, window, cx);
5184 });
5185 assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
5186 }
5187
5188 #[gpui::test]
5189 async fn test_pin_tabs_right_to_left_after_opening_at_max_capacity(cx: &mut TestAppContext) {
5190 init_test(cx);
5191 let fs = FakeFs::new(cx.executor());
5192
5193 let project = Project::test(fs, None, cx).await;
5194 let (workspace, cx) =
5195 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5196 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5197
5198 set_max_tabs(cx, Some(3));
5199
5200 let item_a = add_labeled_item(&pane, "A", false, cx);
5201 assert_item_labels(&pane, ["A*"], cx);
5202
5203 let item_b = add_labeled_item(&pane, "B", false, cx);
5204 assert_item_labels(&pane, ["A", "B*"], cx);
5205
5206 let item_c = add_labeled_item(&pane, "C", false, cx);
5207 assert_item_labels(&pane, ["A", "B", "C*"], cx);
5208
5209 pane.update_in(cx, |pane, window, cx| {
5210 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5211 pane.pin_tab_at(ix, window, cx);
5212 });
5213 assert_item_labels(&pane, ["C*!", "A", "B"], cx);
5214
5215 pane.update_in(cx, |pane, window, cx| {
5216 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5217 pane.pin_tab_at(ix, window, cx);
5218 });
5219 assert_item_labels(&pane, ["C*!", "B!", "A"], cx);
5220
5221 pane.update_in(cx, |pane, window, cx| {
5222 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5223 pane.pin_tab_at(ix, window, cx);
5224 });
5225 assert_item_labels(&pane, ["C*!", "B!", "A!"], cx);
5226 }
5227
5228 #[gpui::test]
5229 async fn test_pinned_tabs_never_closed_at_max_tabs(cx: &mut TestAppContext) {
5230 init_test(cx);
5231 let fs = FakeFs::new(cx.executor());
5232
5233 let project = Project::test(fs, None, cx).await;
5234 let (workspace, cx) =
5235 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5236 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5237
5238 let item_a = add_labeled_item(&pane, "A", false, cx);
5239 pane.update_in(cx, |pane, window, cx| {
5240 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5241 pane.pin_tab_at(ix, window, cx);
5242 });
5243
5244 let item_b = add_labeled_item(&pane, "B", false, cx);
5245 pane.update_in(cx, |pane, window, cx| {
5246 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5247 pane.pin_tab_at(ix, window, cx);
5248 });
5249
5250 add_labeled_item(&pane, "C", false, cx);
5251 add_labeled_item(&pane, "D", false, cx);
5252 add_labeled_item(&pane, "E", false, cx);
5253 assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
5254
5255 set_max_tabs(cx, Some(3));
5256 add_labeled_item(&pane, "F", false, cx);
5257 assert_item_labels(&pane, ["A!", "B!", "F*"], cx);
5258
5259 add_labeled_item(&pane, "G", false, cx);
5260 assert_item_labels(&pane, ["A!", "B!", "G*"], cx);
5261
5262 add_labeled_item(&pane, "H", false, cx);
5263 assert_item_labels(&pane, ["A!", "B!", "H*"], cx);
5264 }
5265
5266 #[gpui::test]
5267 async fn test_always_allows_one_unpinned_item_over_max_tabs_regardless_of_pinned_count(
5268 cx: &mut TestAppContext,
5269 ) {
5270 init_test(cx);
5271 let fs = FakeFs::new(cx.executor());
5272
5273 let project = Project::test(fs, None, cx).await;
5274 let (workspace, cx) =
5275 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5276 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5277
5278 set_max_tabs(cx, Some(3));
5279
5280 let item_a = add_labeled_item(&pane, "A", false, cx);
5281 pane.update_in(cx, |pane, window, cx| {
5282 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5283 pane.pin_tab_at(ix, window, cx);
5284 });
5285
5286 let item_b = add_labeled_item(&pane, "B", false, cx);
5287 pane.update_in(cx, |pane, window, cx| {
5288 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5289 pane.pin_tab_at(ix, window, cx);
5290 });
5291
5292 let item_c = add_labeled_item(&pane, "C", false, cx);
5293 pane.update_in(cx, |pane, window, cx| {
5294 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5295 pane.pin_tab_at(ix, window, cx);
5296 });
5297
5298 assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
5299
5300 let item_d = add_labeled_item(&pane, "D", false, cx);
5301 assert_item_labels(&pane, ["A!", "B!", "C!", "D*"], cx);
5302
5303 pane.update_in(cx, |pane, window, cx| {
5304 let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
5305 pane.pin_tab_at(ix, window, cx);
5306 });
5307 assert_item_labels(&pane, ["A!", "B!", "C!", "D*!"], cx);
5308
5309 add_labeled_item(&pane, "E", false, cx);
5310 assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "E*"], cx);
5311
5312 add_labeled_item(&pane, "F", false, cx);
5313 assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "F*"], cx);
5314 }
5315
5316 #[gpui::test]
5317 async fn test_can_open_one_item_when_all_tabs_are_dirty_at_max(cx: &mut TestAppContext) {
5318 init_test(cx);
5319 let fs = FakeFs::new(cx.executor());
5320
5321 let project = Project::test(fs, None, cx).await;
5322 let (workspace, cx) =
5323 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5324 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5325
5326 set_max_tabs(cx, Some(3));
5327
5328 add_labeled_item(&pane, "A", true, cx);
5329 assert_item_labels(&pane, ["A*^"], cx);
5330
5331 add_labeled_item(&pane, "B", true, cx);
5332 assert_item_labels(&pane, ["A^", "B*^"], cx);
5333
5334 add_labeled_item(&pane, "C", true, cx);
5335 assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
5336
5337 add_labeled_item(&pane, "D", false, cx);
5338 assert_item_labels(&pane, ["A^", "B^", "C^", "D*"], cx);
5339
5340 add_labeled_item(&pane, "E", false, cx);
5341 assert_item_labels(&pane, ["A^", "B^", "C^", "E*"], cx);
5342
5343 add_labeled_item(&pane, "F", false, cx);
5344 assert_item_labels(&pane, ["A^", "B^", "C^", "F*"], cx);
5345
5346 add_labeled_item(&pane, "G", true, cx);
5347 assert_item_labels(&pane, ["A^", "B^", "C^", "G*^"], cx);
5348 }
5349
5350 #[gpui::test]
5351 async fn test_toggle_pin_tab(cx: &mut TestAppContext) {
5352 init_test(cx);
5353 let fs = FakeFs::new(cx.executor());
5354
5355 let project = Project::test(fs, None, cx).await;
5356 let (workspace, cx) =
5357 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5358 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5359
5360 set_labeled_items(&pane, ["A", "B*", "C"], cx);
5361 assert_item_labels(&pane, ["A", "B*", "C"], cx);
5362
5363 pane.update_in(cx, |pane, window, cx| {
5364 pane.toggle_pin_tab(&TogglePinTab, window, cx);
5365 });
5366 assert_item_labels(&pane, ["B*!", "A", "C"], cx);
5367
5368 pane.update_in(cx, |pane, window, cx| {
5369 pane.toggle_pin_tab(&TogglePinTab, window, cx);
5370 });
5371 assert_item_labels(&pane, ["B*", "A", "C"], cx);
5372 }
5373
5374 #[gpui::test]
5375 async fn test_unpin_all_tabs(cx: &mut TestAppContext) {
5376 init_test(cx);
5377 let fs = FakeFs::new(cx.executor());
5378
5379 let project = Project::test(fs, None, cx).await;
5380 let (workspace, cx) =
5381 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5382 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5383
5384 // Unpin all, in an empty pane
5385 pane.update_in(cx, |pane, window, cx| {
5386 pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
5387 });
5388
5389 assert_item_labels(&pane, [], cx);
5390
5391 let item_a = add_labeled_item(&pane, "A", false, cx);
5392 let item_b = add_labeled_item(&pane, "B", false, cx);
5393 let item_c = add_labeled_item(&pane, "C", false, cx);
5394 assert_item_labels(&pane, ["A", "B", "C*"], cx);
5395
5396 // Unpin all, when no tabs are pinned
5397 pane.update_in(cx, |pane, window, cx| {
5398 pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
5399 });
5400
5401 assert_item_labels(&pane, ["A", "B", "C*"], cx);
5402
5403 // Pin inactive tabs only
5404 pane.update_in(cx, |pane, window, cx| {
5405 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5406 pane.pin_tab_at(ix, window, cx);
5407
5408 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5409 pane.pin_tab_at(ix, window, cx);
5410 });
5411 assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
5412
5413 pane.update_in(cx, |pane, window, cx| {
5414 pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
5415 });
5416
5417 assert_item_labels(&pane, ["A", "B", "C*"], cx);
5418
5419 // Pin all tabs
5420 pane.update_in(cx, |pane, window, cx| {
5421 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5422 pane.pin_tab_at(ix, window, cx);
5423
5424 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5425 pane.pin_tab_at(ix, window, cx);
5426
5427 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5428 pane.pin_tab_at(ix, window, cx);
5429 });
5430 assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
5431
5432 // Activate middle tab
5433 pane.update_in(cx, |pane, window, cx| {
5434 pane.activate_item(1, false, false, window, cx);
5435 });
5436 assert_item_labels(&pane, ["A!", "B*!", "C!"], cx);
5437
5438 pane.update_in(cx, |pane, window, cx| {
5439 pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
5440 });
5441
5442 // Order has not changed
5443 assert_item_labels(&pane, ["A", "B*", "C"], cx);
5444 }
5445
5446 #[gpui::test]
5447 async fn test_separate_pinned_row_disabled_by_default(cx: &mut TestAppContext) {
5448 init_test(cx);
5449 let fs = FakeFs::new(cx.executor());
5450
5451 let project = Project::test(fs, None, cx).await;
5452 let (workspace, cx) =
5453 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5454 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5455
5456 let item_a = add_labeled_item(&pane, "A", false, cx);
5457 add_labeled_item(&pane, "B", false, cx);
5458 add_labeled_item(&pane, "C", false, cx);
5459
5460 // Pin one tab
5461 pane.update_in(cx, |pane, window, cx| {
5462 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5463 pane.pin_tab_at(ix, window, cx);
5464 });
5465 assert_item_labels(&pane, ["A!", "B", "C*"], cx);
5466
5467 // Verify setting is disabled by default
5468 let is_separate_row_enabled = pane.read_with(cx, |_, cx| {
5469 TabBarSettings::get_global(cx).show_pinned_tabs_in_separate_row
5470 });
5471 assert!(
5472 !is_separate_row_enabled,
5473 "Separate pinned row should be disabled by default"
5474 );
5475
5476 // Verify pinned_tabs_row element does NOT exist (single row layout)
5477 let pinned_row_bounds = cx.debug_bounds("pinned_tabs_row");
5478 assert!(
5479 pinned_row_bounds.is_none(),
5480 "pinned_tabs_row should not exist when setting is disabled"
5481 );
5482 }
5483
5484 #[gpui::test]
5485 async fn test_separate_pinned_row_two_rows_when_both_tab_types_exist(cx: &mut TestAppContext) {
5486 init_test(cx);
5487 let fs = FakeFs::new(cx.executor());
5488
5489 let project = Project::test(fs, None, cx).await;
5490 let (workspace, cx) =
5491 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5492 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5493
5494 // Enable separate row setting
5495 set_pinned_tabs_separate_row(cx, true);
5496
5497 let item_a = add_labeled_item(&pane, "A", false, cx);
5498 add_labeled_item(&pane, "B", false, cx);
5499 add_labeled_item(&pane, "C", false, cx);
5500
5501 // Pin one tab - now we have both pinned and unpinned tabs
5502 pane.update_in(cx, |pane, window, cx| {
5503 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5504 pane.pin_tab_at(ix, window, cx);
5505 });
5506 assert_item_labels(&pane, ["A!", "B", "C*"], cx);
5507
5508 // Verify pinned_tabs_row element exists (two row layout)
5509 let pinned_row_bounds = cx.debug_bounds("pinned_tabs_row");
5510 assert!(
5511 pinned_row_bounds.is_some(),
5512 "pinned_tabs_row should exist when setting is enabled and both tab types exist"
5513 );
5514 }
5515
5516 #[gpui::test]
5517 async fn test_separate_pinned_row_single_row_when_only_pinned_tabs(cx: &mut TestAppContext) {
5518 init_test(cx);
5519 let fs = FakeFs::new(cx.executor());
5520
5521 let project = Project::test(fs, None, cx).await;
5522 let (workspace, cx) =
5523 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5524 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5525
5526 // Enable separate row setting
5527 set_pinned_tabs_separate_row(cx, true);
5528
5529 let item_a = add_labeled_item(&pane, "A", false, cx);
5530 let item_b = add_labeled_item(&pane, "B", false, cx);
5531
5532 // Pin all tabs - only pinned tabs exist
5533 pane.update_in(cx, |pane, window, cx| {
5534 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5535 pane.pin_tab_at(ix, window, cx);
5536 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5537 pane.pin_tab_at(ix, window, cx);
5538 });
5539 assert_item_labels(&pane, ["A!", "B*!"], cx);
5540
5541 // Verify pinned_tabs_row does NOT exist (single row layout for pinned-only)
5542 let pinned_row_bounds = cx.debug_bounds("pinned_tabs_row");
5543 assert!(
5544 pinned_row_bounds.is_none(),
5545 "pinned_tabs_row should not exist when only pinned tabs exist (uses single row)"
5546 );
5547 }
5548
5549 #[gpui::test]
5550 async fn test_separate_pinned_row_single_row_when_only_unpinned_tabs(cx: &mut TestAppContext) {
5551 init_test(cx);
5552 let fs = FakeFs::new(cx.executor());
5553
5554 let project = Project::test(fs, None, cx).await;
5555 let (workspace, cx) =
5556 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5557 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5558
5559 // Enable separate row setting
5560 set_pinned_tabs_separate_row(cx, true);
5561
5562 // Add only unpinned tabs
5563 add_labeled_item(&pane, "A", false, cx);
5564 add_labeled_item(&pane, "B", false, cx);
5565 add_labeled_item(&pane, "C", false, cx);
5566 assert_item_labels(&pane, ["A", "B", "C*"], cx);
5567
5568 // Verify pinned_tabs_row does NOT exist (single row layout for unpinned-only)
5569 let pinned_row_bounds = cx.debug_bounds("pinned_tabs_row");
5570 assert!(
5571 pinned_row_bounds.is_none(),
5572 "pinned_tabs_row should not exist when only unpinned tabs exist (uses single row)"
5573 );
5574 }
5575
5576 #[gpui::test]
5577 async fn test_separate_pinned_row_toggles_between_layouts(cx: &mut TestAppContext) {
5578 init_test(cx);
5579 let fs = FakeFs::new(cx.executor());
5580
5581 let project = Project::test(fs, None, cx).await;
5582 let (workspace, cx) =
5583 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5584 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5585
5586 let item_a = add_labeled_item(&pane, "A", false, cx);
5587 add_labeled_item(&pane, "B", false, cx);
5588
5589 // Pin one tab
5590 pane.update_in(cx, |pane, window, cx| {
5591 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5592 pane.pin_tab_at(ix, window, cx);
5593 });
5594
5595 // Initially disabled - single row
5596 let pinned_row_bounds = cx.debug_bounds("pinned_tabs_row");
5597 assert!(
5598 pinned_row_bounds.is_none(),
5599 "Should be single row when disabled"
5600 );
5601
5602 // Enable - two rows
5603 set_pinned_tabs_separate_row(cx, true);
5604 cx.run_until_parked();
5605 let pinned_row_bounds = cx.debug_bounds("pinned_tabs_row");
5606 assert!(
5607 pinned_row_bounds.is_some(),
5608 "Should be two rows when enabled"
5609 );
5610
5611 // Disable again - back to single row
5612 set_pinned_tabs_separate_row(cx, false);
5613 cx.run_until_parked();
5614 let pinned_row_bounds = cx.debug_bounds("pinned_tabs_row");
5615 assert!(
5616 pinned_row_bounds.is_none(),
5617 "Should be single row when disabled again"
5618 );
5619 }
5620
5621 #[gpui::test]
5622 async fn test_separate_pinned_row_has_right_border(cx: &mut TestAppContext) {
5623 init_test(cx);
5624 let fs = FakeFs::new(cx.executor());
5625
5626 let project = Project::test(fs, None, cx).await;
5627 let (workspace, cx) =
5628 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5629 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5630
5631 // Enable separate row setting
5632 set_pinned_tabs_separate_row(cx, true);
5633
5634 let item_a = add_labeled_item(&pane, "A", false, cx);
5635 add_labeled_item(&pane, "B", false, cx);
5636 add_labeled_item(&pane, "C", false, cx);
5637
5638 // Pin one tab - now we have both pinned and unpinned tabs (two-row layout)
5639 pane.update_in(cx, |pane, window, cx| {
5640 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5641 pane.pin_tab_at(ix, window, cx);
5642 });
5643 assert_item_labels(&pane, ["A!", "B", "C*"], cx);
5644 cx.run_until_parked();
5645
5646 // Verify two-row layout is active
5647 let pinned_row_bounds = cx.debug_bounds("pinned_tabs_row");
5648 assert!(
5649 pinned_row_bounds.is_some(),
5650 "Two-row layout should be active when both pinned and unpinned tabs exist"
5651 );
5652
5653 // Verify pinned_tabs_border element exists (the right border after pinned tabs)
5654 let border_bounds = cx.debug_bounds("pinned_tabs_border");
5655 assert!(
5656 border_bounds.is_some(),
5657 "pinned_tabs_border should exist in two-row layout to show right border"
5658 );
5659 }
5660
5661 #[gpui::test]
5662 async fn test_pinning_active_tab_without_position_change_maintains_focus(
5663 cx: &mut TestAppContext,
5664 ) {
5665 init_test(cx);
5666 let fs = FakeFs::new(cx.executor());
5667
5668 let project = Project::test(fs, None, cx).await;
5669 let (workspace, cx) =
5670 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5671 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5672
5673 // Add A
5674 let item_a = add_labeled_item(&pane, "A", false, cx);
5675 assert_item_labels(&pane, ["A*"], cx);
5676
5677 // Add B
5678 add_labeled_item(&pane, "B", false, cx);
5679 assert_item_labels(&pane, ["A", "B*"], cx);
5680
5681 // Activate A again
5682 pane.update_in(cx, |pane, window, cx| {
5683 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5684 pane.activate_item(ix, true, true, window, cx);
5685 });
5686 assert_item_labels(&pane, ["A*", "B"], cx);
5687
5688 // Pin A - remains active
5689 pane.update_in(cx, |pane, window, cx| {
5690 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5691 pane.pin_tab_at(ix, window, cx);
5692 });
5693 assert_item_labels(&pane, ["A*!", "B"], cx);
5694
5695 // Unpin A - remain active
5696 pane.update_in(cx, |pane, window, cx| {
5697 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5698 pane.unpin_tab_at(ix, window, cx);
5699 });
5700 assert_item_labels(&pane, ["A*", "B"], cx);
5701 }
5702
5703 #[gpui::test]
5704 async fn test_pinning_active_tab_with_position_change_maintains_focus(cx: &mut TestAppContext) {
5705 init_test(cx);
5706 let fs = FakeFs::new(cx.executor());
5707
5708 let project = Project::test(fs, None, cx).await;
5709 let (workspace, cx) =
5710 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5711 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5712
5713 // Add A, B, C
5714 add_labeled_item(&pane, "A", false, cx);
5715 add_labeled_item(&pane, "B", false, cx);
5716 let item_c = add_labeled_item(&pane, "C", false, cx);
5717 assert_item_labels(&pane, ["A", "B", "C*"], cx);
5718
5719 // Pin C - moves to pinned area, remains active
5720 pane.update_in(cx, |pane, window, cx| {
5721 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5722 pane.pin_tab_at(ix, window, cx);
5723 });
5724 assert_item_labels(&pane, ["C*!", "A", "B"], cx);
5725
5726 // Unpin C - moves after pinned area, remains active
5727 pane.update_in(cx, |pane, window, cx| {
5728 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5729 pane.unpin_tab_at(ix, window, cx);
5730 });
5731 assert_item_labels(&pane, ["C*", "A", "B"], cx);
5732 }
5733
5734 #[gpui::test]
5735 async fn test_pinning_inactive_tab_without_position_change_preserves_existing_focus(
5736 cx: &mut TestAppContext,
5737 ) {
5738 init_test(cx);
5739 let fs = FakeFs::new(cx.executor());
5740
5741 let project = Project::test(fs, None, cx).await;
5742 let (workspace, cx) =
5743 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5744 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5745
5746 // Add A, B
5747 let item_a = add_labeled_item(&pane, "A", false, cx);
5748 add_labeled_item(&pane, "B", false, cx);
5749 assert_item_labels(&pane, ["A", "B*"], cx);
5750
5751 // Pin A - already in pinned area, B remains active
5752 pane.update_in(cx, |pane, window, cx| {
5753 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5754 pane.pin_tab_at(ix, window, cx);
5755 });
5756 assert_item_labels(&pane, ["A!", "B*"], cx);
5757
5758 // Unpin A - stays in place, B remains active
5759 pane.update_in(cx, |pane, window, cx| {
5760 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5761 pane.unpin_tab_at(ix, window, cx);
5762 });
5763 assert_item_labels(&pane, ["A", "B*"], cx);
5764 }
5765
5766 #[gpui::test]
5767 async fn test_pinning_inactive_tab_with_position_change_preserves_existing_focus(
5768 cx: &mut TestAppContext,
5769 ) {
5770 init_test(cx);
5771 let fs = FakeFs::new(cx.executor());
5772
5773 let project = Project::test(fs, None, cx).await;
5774 let (workspace, cx) =
5775 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5776 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5777
5778 // Add A, B, C
5779 add_labeled_item(&pane, "A", false, cx);
5780 let item_b = add_labeled_item(&pane, "B", false, cx);
5781 let item_c = add_labeled_item(&pane, "C", false, cx);
5782 assert_item_labels(&pane, ["A", "B", "C*"], cx);
5783
5784 // Activate B
5785 pane.update_in(cx, |pane, window, cx| {
5786 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5787 pane.activate_item(ix, true, true, window, cx);
5788 });
5789 assert_item_labels(&pane, ["A", "B*", "C"], cx);
5790
5791 // Pin C - moves to pinned area, B remains active
5792 pane.update_in(cx, |pane, window, cx| {
5793 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5794 pane.pin_tab_at(ix, window, cx);
5795 });
5796 assert_item_labels(&pane, ["C!", "A", "B*"], cx);
5797
5798 // Unpin C - moves after pinned area, B remains active
5799 pane.update_in(cx, |pane, window, cx| {
5800 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5801 pane.unpin_tab_at(ix, window, cx);
5802 });
5803 assert_item_labels(&pane, ["C", "A", "B*"], cx);
5804 }
5805
5806 #[gpui::test]
5807 async fn test_handle_tab_drop_respects_is_pane_target(cx: &mut TestAppContext) {
5808 init_test(cx);
5809 let fs = FakeFs::new(cx.executor());
5810 let project = Project::test(fs, None, cx).await;
5811 let (workspace, cx) =
5812 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5813 let source_pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5814
5815 let item_a = add_labeled_item(&source_pane, "A", false, cx);
5816 let item_b = add_labeled_item(&source_pane, "B", false, cx);
5817
5818 let target_pane = workspace.update_in(cx, |workspace, window, cx| {
5819 workspace.split_pane(source_pane.clone(), SplitDirection::Right, window, cx)
5820 });
5821
5822 let custom_item = target_pane.update_in(cx, |pane, window, cx| {
5823 let custom_item = Box::new(cx.new(CustomDropHandlingItem::new));
5824 pane.add_item(custom_item.clone(), true, true, None, window, cx);
5825 custom_item
5826 });
5827
5828 let moved_item_id = item_a.item_id();
5829 let other_item_id = item_b.item_id();
5830 let custom_item_id = custom_item.item_id();
5831
5832 let pane_item_ids = |pane: &Entity<Pane>, cx: &mut VisualTestContext| {
5833 pane.read_with(cx, |pane, _| {
5834 pane.items().map(|item| item.item_id()).collect::<Vec<_>>()
5835 })
5836 };
5837
5838 let source_before_item_ids = pane_item_ids(&source_pane, cx);
5839 assert_eq!(source_before_item_ids, vec![moved_item_id, other_item_id]);
5840
5841 let target_before_item_ids = pane_item_ids(&target_pane, cx);
5842 assert_eq!(target_before_item_ids, vec![custom_item_id]);
5843
5844 let dragged_tab = DraggedTab {
5845 pane: source_pane.clone(),
5846 item: item_a.boxed_clone(),
5847 ix: 0,
5848 detail: 0,
5849 is_active: true,
5850 };
5851
5852 // Dropping item_a onto the target pane itself means the
5853 // custom item handles the drop and no tab move should occur
5854 target_pane.update_in(cx, |pane, window, cx| {
5855 pane.handle_tab_drop(&dragged_tab, pane.active_item_index(), true, window, cx);
5856 });
5857 cx.run_until_parked();
5858
5859 assert_eq!(
5860 custom_item.read_with(cx, |item, _| item.drop_call_count()),
5861 1
5862 );
5863 assert_eq!(pane_item_ids(&source_pane, cx), source_before_item_ids);
5864 assert_eq!(pane_item_ids(&target_pane, cx), target_before_item_ids);
5865
5866 // Dropping item_a onto the tab target means the custom handler
5867 // should be skipped and the pane's default tab drop behavior should run.
5868 target_pane.update_in(cx, |pane, window, cx| {
5869 pane.handle_tab_drop(&dragged_tab, pane.active_item_index(), false, window, cx);
5870 });
5871 cx.run_until_parked();
5872
5873 assert_eq!(
5874 custom_item.read_with(cx, |item, _| item.drop_call_count()),
5875 1
5876 );
5877 assert_eq!(pane_item_ids(&source_pane, cx), vec![other_item_id]);
5878
5879 let target_item_ids = pane_item_ids(&target_pane, cx);
5880 assert_eq!(target_item_ids, vec![moved_item_id, custom_item_id]);
5881 }
5882
5883 #[gpui::test]
5884 async fn test_drag_unpinned_tab_to_split_creates_pane_with_unpinned_tab(
5885 cx: &mut TestAppContext,
5886 ) {
5887 init_test(cx);
5888 let fs = FakeFs::new(cx.executor());
5889
5890 let project = Project::test(fs, None, cx).await;
5891 let (workspace, cx) =
5892 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5893 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5894
5895 // Add A, B. Pin B. Activate A
5896 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5897 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5898
5899 pane_a.update_in(cx, |pane, window, cx| {
5900 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5901 pane.pin_tab_at(ix, window, cx);
5902
5903 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5904 pane.activate_item(ix, true, true, window, cx);
5905 });
5906
5907 // Drag A to create new split
5908 pane_a.update_in(cx, |pane, window, cx| {
5909 pane.drag_split_direction = Some(SplitDirection::Right);
5910
5911 let dragged_tab = DraggedTab {
5912 pane: pane_a.clone(),
5913 item: item_a.boxed_clone(),
5914 ix: 0,
5915 detail: 0,
5916 is_active: true,
5917 };
5918 pane.handle_tab_drop(&dragged_tab, 0, true, window, cx);
5919 });
5920
5921 // A should be moved to new pane. B should remain pinned, A should not be pinned
5922 let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
5923 let panes = workspace.panes();
5924 (panes[0].clone(), panes[1].clone())
5925 });
5926 assert_item_labels(&pane_a, ["B*!"], cx);
5927 assert_item_labels(&pane_b, ["A*"], cx);
5928 }
5929
5930 #[gpui::test]
5931 async fn test_drag_pinned_tab_to_split_creates_pane_with_pinned_tab(cx: &mut TestAppContext) {
5932 init_test(cx);
5933 let fs = FakeFs::new(cx.executor());
5934
5935 let project = Project::test(fs, None, cx).await;
5936 let (workspace, cx) =
5937 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5938 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5939
5940 // Add A, B. Pin both. Activate A
5941 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5942 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5943
5944 pane_a.update_in(cx, |pane, window, cx| {
5945 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5946 pane.pin_tab_at(ix, window, cx);
5947
5948 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5949 pane.pin_tab_at(ix, window, cx);
5950
5951 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5952 pane.activate_item(ix, true, true, window, cx);
5953 });
5954 assert_item_labels(&pane_a, ["A*!", "B!"], cx);
5955
5956 // Drag A to create new split
5957 pane_a.update_in(cx, |pane, window, cx| {
5958 pane.drag_split_direction = Some(SplitDirection::Right);
5959
5960 let dragged_tab = DraggedTab {
5961 pane: pane_a.clone(),
5962 item: item_a.boxed_clone(),
5963 ix: 0,
5964 detail: 0,
5965 is_active: true,
5966 };
5967 pane.handle_tab_drop(&dragged_tab, 0, true, window, cx);
5968 });
5969
5970 // A should be moved to new pane. Both A and B should still be pinned
5971 let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
5972 let panes = workspace.panes();
5973 (panes[0].clone(), panes[1].clone())
5974 });
5975 assert_item_labels(&pane_a, ["B*!"], cx);
5976 assert_item_labels(&pane_b, ["A*!"], cx);
5977 }
5978
5979 #[gpui::test]
5980 async fn test_drag_pinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
5981 init_test(cx);
5982 let fs = FakeFs::new(cx.executor());
5983
5984 let project = Project::test(fs, None, cx).await;
5985 let (workspace, cx) =
5986 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5987 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5988
5989 // Add A to pane A and pin
5990 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5991 pane_a.update_in(cx, |pane, window, cx| {
5992 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5993 pane.pin_tab_at(ix, window, cx);
5994 });
5995 assert_item_labels(&pane_a, ["A*!"], cx);
5996
5997 // Add B to pane B and pin
5998 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5999 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
6000 });
6001 let item_b = add_labeled_item(&pane_b, "B", false, cx);
6002 pane_b.update_in(cx, |pane, window, cx| {
6003 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6004 pane.pin_tab_at(ix, window, cx);
6005 });
6006 assert_item_labels(&pane_b, ["B*!"], cx);
6007
6008 // Move A from pane A to pane B's pinned region
6009 pane_b.update_in(cx, |pane, window, cx| {
6010 let dragged_tab = DraggedTab {
6011 pane: pane_a.clone(),
6012 item: item_a.boxed_clone(),
6013 ix: 0,
6014 detail: 0,
6015 is_active: true,
6016 };
6017 pane.handle_tab_drop(&dragged_tab, 0, false, window, cx);
6018 });
6019
6020 // A should stay pinned
6021 assert_item_labels(&pane_a, [], cx);
6022 assert_item_labels(&pane_b, ["A*!", "B!"], cx);
6023 }
6024
6025 #[gpui::test]
6026 async fn test_drag_pinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
6027 init_test(cx);
6028 let fs = FakeFs::new(cx.executor());
6029
6030 let project = Project::test(fs, None, cx).await;
6031 let (workspace, cx) =
6032 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6033 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6034
6035 // Add A to pane A and pin
6036 let item_a = add_labeled_item(&pane_a, "A", false, cx);
6037 pane_a.update_in(cx, |pane, window, cx| {
6038 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6039 pane.pin_tab_at(ix, window, cx);
6040 });
6041 assert_item_labels(&pane_a, ["A*!"], cx);
6042
6043 // Create pane B with pinned item B
6044 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
6045 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
6046 });
6047 let item_b = add_labeled_item(&pane_b, "B", false, cx);
6048 assert_item_labels(&pane_b, ["B*"], cx);
6049
6050 pane_b.update_in(cx, |pane, window, cx| {
6051 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6052 pane.pin_tab_at(ix, window, cx);
6053 });
6054 assert_item_labels(&pane_b, ["B*!"], cx);
6055
6056 // Move A from pane A to pane B's unpinned region
6057 pane_b.update_in(cx, |pane, window, cx| {
6058 let dragged_tab = DraggedTab {
6059 pane: pane_a.clone(),
6060 item: item_a.boxed_clone(),
6061 ix: 0,
6062 detail: 0,
6063 is_active: true,
6064 };
6065 pane.handle_tab_drop(&dragged_tab, 1, false, window, cx);
6066 });
6067
6068 // A should become pinned
6069 assert_item_labels(&pane_a, [], cx);
6070 assert_item_labels(&pane_b, ["B!", "A*"], cx);
6071 }
6072
6073 #[gpui::test]
6074 async fn test_drag_pinned_tab_into_existing_panes_first_position_with_no_pinned_tabs(
6075 cx: &mut TestAppContext,
6076 ) {
6077 init_test(cx);
6078 let fs = FakeFs::new(cx.executor());
6079
6080 let project = Project::test(fs, None, cx).await;
6081 let (workspace, cx) =
6082 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6083 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6084
6085 // Add A to pane A and pin
6086 let item_a = add_labeled_item(&pane_a, "A", false, cx);
6087 pane_a.update_in(cx, |pane, window, cx| {
6088 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6089 pane.pin_tab_at(ix, window, cx);
6090 });
6091 assert_item_labels(&pane_a, ["A*!"], cx);
6092
6093 // Add B to pane B
6094 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
6095 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
6096 });
6097 add_labeled_item(&pane_b, "B", false, cx);
6098 assert_item_labels(&pane_b, ["B*"], cx);
6099
6100 // Move A from pane A to position 0 in pane B, indicating it should stay pinned
6101 pane_b.update_in(cx, |pane, window, cx| {
6102 let dragged_tab = DraggedTab {
6103 pane: pane_a.clone(),
6104 item: item_a.boxed_clone(),
6105 ix: 0,
6106 detail: 0,
6107 is_active: true,
6108 };
6109 pane.handle_tab_drop(&dragged_tab, 0, false, window, cx);
6110 });
6111
6112 // A should stay pinned
6113 assert_item_labels(&pane_a, [], cx);
6114 assert_item_labels(&pane_b, ["A*!", "B"], cx);
6115 }
6116
6117 #[gpui::test]
6118 async fn test_drag_pinned_tab_into_existing_pane_at_max_capacity_closes_unpinned_tabs(
6119 cx: &mut TestAppContext,
6120 ) {
6121 init_test(cx);
6122 let fs = FakeFs::new(cx.executor());
6123
6124 let project = Project::test(fs, None, cx).await;
6125 let (workspace, cx) =
6126 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6127 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6128 set_max_tabs(cx, Some(2));
6129
6130 // Add A, B to pane A. Pin both
6131 let item_a = add_labeled_item(&pane_a, "A", false, cx);
6132 let item_b = add_labeled_item(&pane_a, "B", false, cx);
6133 pane_a.update_in(cx, |pane, window, cx| {
6134 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6135 pane.pin_tab_at(ix, window, cx);
6136
6137 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6138 pane.pin_tab_at(ix, window, cx);
6139 });
6140 assert_item_labels(&pane_a, ["A!", "B*!"], cx);
6141
6142 // Add C, D to pane B. Pin both
6143 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
6144 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
6145 });
6146 let item_c = add_labeled_item(&pane_b, "C", false, cx);
6147 let item_d = add_labeled_item(&pane_b, "D", false, cx);
6148 pane_b.update_in(cx, |pane, window, cx| {
6149 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
6150 pane.pin_tab_at(ix, window, cx);
6151
6152 let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
6153 pane.pin_tab_at(ix, window, cx);
6154 });
6155 assert_item_labels(&pane_b, ["C!", "D*!"], cx);
6156
6157 // Add a third unpinned item to pane B (exceeds max tabs), but is allowed,
6158 // as we allow 1 tab over max if the others are pinned or dirty
6159 add_labeled_item(&pane_b, "E", false, cx);
6160 assert_item_labels(&pane_b, ["C!", "D!", "E*"], cx);
6161
6162 // Drag pinned A from pane A to position 0 in pane B
6163 pane_b.update_in(cx, |pane, window, cx| {
6164 let dragged_tab = DraggedTab {
6165 pane: pane_a.clone(),
6166 item: item_a.boxed_clone(),
6167 ix: 0,
6168 detail: 0,
6169 is_active: true,
6170 };
6171 pane.handle_tab_drop(&dragged_tab, 0, false, window, cx);
6172 });
6173
6174 // E (unpinned) should be closed, leaving 3 pinned items
6175 assert_item_labels(&pane_a, ["B*!"], cx);
6176 assert_item_labels(&pane_b, ["A*!", "C!", "D!"], cx);
6177 }
6178
6179 #[gpui::test]
6180 async fn test_drag_last_pinned_tab_to_same_position_stays_pinned(cx: &mut TestAppContext) {
6181 init_test(cx);
6182 let fs = FakeFs::new(cx.executor());
6183
6184 let project = Project::test(fs, None, cx).await;
6185 let (workspace, cx) =
6186 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6187 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6188
6189 // Add A to pane A and pin it
6190 let item_a = add_labeled_item(&pane_a, "A", false, cx);
6191 pane_a.update_in(cx, |pane, window, cx| {
6192 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6193 pane.pin_tab_at(ix, window, cx);
6194 });
6195 assert_item_labels(&pane_a, ["A*!"], cx);
6196
6197 // Drag pinned A to position 1 (directly to the right) in the same pane
6198 pane_a.update_in(cx, |pane, window, cx| {
6199 let dragged_tab = DraggedTab {
6200 pane: pane_a.clone(),
6201 item: item_a.boxed_clone(),
6202 ix: 0,
6203 detail: 0,
6204 is_active: true,
6205 };
6206 pane.handle_tab_drop(&dragged_tab, 1, false, window, cx);
6207 });
6208
6209 // A should still be pinned and active
6210 assert_item_labels(&pane_a, ["A*!"], cx);
6211 }
6212
6213 #[gpui::test]
6214 async fn test_drag_pinned_tab_beyond_last_pinned_tab_in_same_pane_stays_pinned(
6215 cx: &mut TestAppContext,
6216 ) {
6217 init_test(cx);
6218 let fs = FakeFs::new(cx.executor());
6219
6220 let project = Project::test(fs, None, cx).await;
6221 let (workspace, cx) =
6222 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6223 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6224
6225 // Add A, B to pane A and pin both
6226 let item_a = add_labeled_item(&pane_a, "A", false, cx);
6227 let item_b = add_labeled_item(&pane_a, "B", false, cx);
6228 pane_a.update_in(cx, |pane, window, cx| {
6229 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6230 pane.pin_tab_at(ix, window, cx);
6231
6232 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6233 pane.pin_tab_at(ix, window, cx);
6234 });
6235 assert_item_labels(&pane_a, ["A!", "B*!"], cx);
6236
6237 // Drag pinned A right of B in the same pane
6238 pane_a.update_in(cx, |pane, window, cx| {
6239 let dragged_tab = DraggedTab {
6240 pane: pane_a.clone(),
6241 item: item_a.boxed_clone(),
6242 ix: 0,
6243 detail: 0,
6244 is_active: true,
6245 };
6246 pane.handle_tab_drop(&dragged_tab, 2, false, window, cx);
6247 });
6248
6249 // A stays pinned
6250 assert_item_labels(&pane_a, ["B!", "A*!"], cx);
6251 }
6252
6253 #[gpui::test]
6254 async fn test_dragging_pinned_tab_onto_unpinned_tab_reduces_unpinned_tab_count(
6255 cx: &mut TestAppContext,
6256 ) {
6257 init_test(cx);
6258 let fs = FakeFs::new(cx.executor());
6259
6260 let project = Project::test(fs, None, cx).await;
6261 let (workspace, cx) =
6262 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6263 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6264
6265 // Add A, B to pane A and pin A
6266 let item_a = add_labeled_item(&pane_a, "A", false, cx);
6267 add_labeled_item(&pane_a, "B", false, cx);
6268 pane_a.update_in(cx, |pane, window, cx| {
6269 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6270 pane.pin_tab_at(ix, window, cx);
6271 });
6272 assert_item_labels(&pane_a, ["A!", "B*"], cx);
6273
6274 // Drag pinned A on top of B in the same pane, which changes tab order to B, A
6275 pane_a.update_in(cx, |pane, window, cx| {
6276 let dragged_tab = DraggedTab {
6277 pane: pane_a.clone(),
6278 item: item_a.boxed_clone(),
6279 ix: 0,
6280 detail: 0,
6281 is_active: true,
6282 };
6283 pane.handle_tab_drop(&dragged_tab, 1, false, window, cx);
6284 });
6285
6286 // Neither are pinned
6287 assert_item_labels(&pane_a, ["B", "A*"], cx);
6288 }
6289
6290 #[gpui::test]
6291 async fn test_drag_pinned_tab_beyond_unpinned_tab_in_same_pane_becomes_unpinned(
6292 cx: &mut TestAppContext,
6293 ) {
6294 init_test(cx);
6295 let fs = FakeFs::new(cx.executor());
6296
6297 let project = Project::test(fs, None, cx).await;
6298 let (workspace, cx) =
6299 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6300 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6301
6302 // Add A, B to pane A and pin A
6303 let item_a = add_labeled_item(&pane_a, "A", false, cx);
6304 add_labeled_item(&pane_a, "B", false, cx);
6305 pane_a.update_in(cx, |pane, window, cx| {
6306 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6307 pane.pin_tab_at(ix, window, cx);
6308 });
6309 assert_item_labels(&pane_a, ["A!", "B*"], cx);
6310
6311 // Drag pinned A right of B in the same pane
6312 pane_a.update_in(cx, |pane, window, cx| {
6313 let dragged_tab = DraggedTab {
6314 pane: pane_a.clone(),
6315 item: item_a.boxed_clone(),
6316 ix: 0,
6317 detail: 0,
6318 is_active: true,
6319 };
6320 pane.handle_tab_drop(&dragged_tab, 2, false, window, cx);
6321 });
6322
6323 // A becomes unpinned
6324 assert_item_labels(&pane_a, ["B", "A*"], cx);
6325 }
6326
6327 #[gpui::test]
6328 async fn test_drag_unpinned_tab_in_front_of_pinned_tab_in_same_pane_becomes_pinned(
6329 cx: &mut TestAppContext,
6330 ) {
6331 init_test(cx);
6332 let fs = FakeFs::new(cx.executor());
6333
6334 let project = Project::test(fs, None, cx).await;
6335 let (workspace, cx) =
6336 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6337 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6338
6339 // Add A, B to pane A and pin A
6340 let item_a = add_labeled_item(&pane_a, "A", false, cx);
6341 let item_b = add_labeled_item(&pane_a, "B", false, cx);
6342 pane_a.update_in(cx, |pane, window, cx| {
6343 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6344 pane.pin_tab_at(ix, window, cx);
6345 });
6346 assert_item_labels(&pane_a, ["A!", "B*"], cx);
6347
6348 // Drag pinned B left of A in the same pane
6349 pane_a.update_in(cx, |pane, window, cx| {
6350 let dragged_tab = DraggedTab {
6351 pane: pane_a.clone(),
6352 item: item_b.boxed_clone(),
6353 ix: 1,
6354 detail: 0,
6355 is_active: true,
6356 };
6357 pane.handle_tab_drop(&dragged_tab, 0, false, window, cx);
6358 });
6359
6360 // A becomes unpinned
6361 assert_item_labels(&pane_a, ["B*!", "A!"], cx);
6362 }
6363
6364 #[gpui::test]
6365 async fn test_drag_unpinned_tab_to_the_pinned_region_stays_pinned(cx: &mut TestAppContext) {
6366 init_test(cx);
6367 let fs = FakeFs::new(cx.executor());
6368
6369 let project = Project::test(fs, None, cx).await;
6370 let (workspace, cx) =
6371 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6372 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6373
6374 // Add A, B, C to pane A and pin A
6375 let item_a = add_labeled_item(&pane_a, "A", false, cx);
6376 add_labeled_item(&pane_a, "B", false, cx);
6377 let item_c = add_labeled_item(&pane_a, "C", false, cx);
6378 pane_a.update_in(cx, |pane, window, cx| {
6379 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6380 pane.pin_tab_at(ix, window, cx);
6381 });
6382 assert_item_labels(&pane_a, ["A!", "B", "C*"], cx);
6383
6384 // Drag pinned C left of B in the same pane
6385 pane_a.update_in(cx, |pane, window, cx| {
6386 let dragged_tab = DraggedTab {
6387 pane: pane_a.clone(),
6388 item: item_c.boxed_clone(),
6389 ix: 2,
6390 detail: 0,
6391 is_active: true,
6392 };
6393 pane.handle_tab_drop(&dragged_tab, 1, false, window, cx);
6394 });
6395
6396 // A stays pinned, B and C remain unpinned
6397 assert_item_labels(&pane_a, ["A!", "C*", "B"], cx);
6398 }
6399
6400 #[gpui::test]
6401 async fn test_drag_unpinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
6402 init_test(cx);
6403 let fs = FakeFs::new(cx.executor());
6404
6405 let project = Project::test(fs, None, cx).await;
6406 let (workspace, cx) =
6407 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6408 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6409
6410 // Add unpinned item A to pane A
6411 let item_a = add_labeled_item(&pane_a, "A", false, cx);
6412 assert_item_labels(&pane_a, ["A*"], cx);
6413
6414 // Create pane B with pinned item B
6415 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
6416 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
6417 });
6418 let item_b = add_labeled_item(&pane_b, "B", false, cx);
6419 pane_b.update_in(cx, |pane, window, cx| {
6420 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6421 pane.pin_tab_at(ix, window, cx);
6422 });
6423 assert_item_labels(&pane_b, ["B*!"], cx);
6424
6425 // Move A from pane A to pane B's pinned region
6426 pane_b.update_in(cx, |pane, window, cx| {
6427 let dragged_tab = DraggedTab {
6428 pane: pane_a.clone(),
6429 item: item_a.boxed_clone(),
6430 ix: 0,
6431 detail: 0,
6432 is_active: true,
6433 };
6434 pane.handle_tab_drop(&dragged_tab, 0, false, window, cx);
6435 });
6436
6437 // A should become pinned since it was dropped in the pinned region
6438 assert_item_labels(&pane_a, [], cx);
6439 assert_item_labels(&pane_b, ["A*!", "B!"], cx);
6440 }
6441
6442 #[gpui::test]
6443 async fn test_drag_unpinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
6444 init_test(cx);
6445 let fs = FakeFs::new(cx.executor());
6446
6447 let project = Project::test(fs, None, cx).await;
6448 let (workspace, cx) =
6449 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6450 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6451
6452 // Add unpinned item A to pane A
6453 let item_a = add_labeled_item(&pane_a, "A", false, cx);
6454 assert_item_labels(&pane_a, ["A*"], cx);
6455
6456 // Create pane B with one pinned item B
6457 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
6458 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
6459 });
6460 let item_b = add_labeled_item(&pane_b, "B", false, cx);
6461 pane_b.update_in(cx, |pane, window, cx| {
6462 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6463 pane.pin_tab_at(ix, window, cx);
6464 });
6465 assert_item_labels(&pane_b, ["B*!"], cx);
6466
6467 // Move A from pane A to pane B's unpinned region
6468 pane_b.update_in(cx, |pane, window, cx| {
6469 let dragged_tab = DraggedTab {
6470 pane: pane_a.clone(),
6471 item: item_a.boxed_clone(),
6472 ix: 0,
6473 detail: 0,
6474 is_active: true,
6475 };
6476 pane.handle_tab_drop(&dragged_tab, 1, true, window, cx);
6477 });
6478
6479 // A should remain unpinned since it was dropped outside the pinned region
6480 assert_item_labels(&pane_a, [], cx);
6481 assert_item_labels(&pane_b, ["B!", "A*"], cx);
6482 }
6483
6484 #[gpui::test]
6485 async fn test_drag_pinned_tab_throughout_entire_range_of_pinned_tabs_both_directions(
6486 cx: &mut TestAppContext,
6487 ) {
6488 init_test(cx);
6489 let fs = FakeFs::new(cx.executor());
6490
6491 let project = Project::test(fs, None, cx).await;
6492 let (workspace, cx) =
6493 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6494 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6495
6496 // Add A, B, C and pin all
6497 let item_a = add_labeled_item(&pane_a, "A", false, cx);
6498 let item_b = add_labeled_item(&pane_a, "B", false, cx);
6499 let item_c = add_labeled_item(&pane_a, "C", false, cx);
6500 assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
6501
6502 pane_a.update_in(cx, |pane, window, cx| {
6503 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6504 pane.pin_tab_at(ix, window, cx);
6505
6506 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6507 pane.pin_tab_at(ix, window, cx);
6508
6509 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
6510 pane.pin_tab_at(ix, window, cx);
6511 });
6512 assert_item_labels(&pane_a, ["A!", "B!", "C*!"], cx);
6513
6514 // Move A to right of B
6515 pane_a.update_in(cx, |pane, window, cx| {
6516 let dragged_tab = DraggedTab {
6517 pane: pane_a.clone(),
6518 item: item_a.boxed_clone(),
6519 ix: 0,
6520 detail: 0,
6521 is_active: true,
6522 };
6523 pane.handle_tab_drop(&dragged_tab, 1, false, window, cx);
6524 });
6525
6526 // A should be after B and all are pinned
6527 assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
6528
6529 // Move A to right of C
6530 pane_a.update_in(cx, |pane, window, cx| {
6531 let dragged_tab = DraggedTab {
6532 pane: pane_a.clone(),
6533 item: item_a.boxed_clone(),
6534 ix: 1,
6535 detail: 0,
6536 is_active: true,
6537 };
6538 pane.handle_tab_drop(&dragged_tab, 2, false, window, cx);
6539 });
6540
6541 // A should be after C and all are pinned
6542 assert_item_labels(&pane_a, ["B!", "C!", "A*!"], cx);
6543
6544 // Move A to left of C
6545 pane_a.update_in(cx, |pane, window, cx| {
6546 let dragged_tab = DraggedTab {
6547 pane: pane_a.clone(),
6548 item: item_a.boxed_clone(),
6549 ix: 2,
6550 detail: 0,
6551 is_active: true,
6552 };
6553 pane.handle_tab_drop(&dragged_tab, 1, false, window, cx);
6554 });
6555
6556 // A should be before C and all are pinned
6557 assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
6558
6559 // Move A to left of B
6560 pane_a.update_in(cx, |pane, window, cx| {
6561 let dragged_tab = DraggedTab {
6562 pane: pane_a.clone(),
6563 item: item_a.boxed_clone(),
6564 ix: 1,
6565 detail: 0,
6566 is_active: true,
6567 };
6568 pane.handle_tab_drop(&dragged_tab, 0, false, window, cx);
6569 });
6570
6571 // A should be before B and all are pinned
6572 assert_item_labels(&pane_a, ["A*!", "B!", "C!"], cx);
6573 }
6574
6575 #[gpui::test]
6576 async fn test_drag_first_tab_to_last_position(cx: &mut TestAppContext) {
6577 init_test(cx);
6578 let fs = FakeFs::new(cx.executor());
6579
6580 let project = Project::test(fs, None, cx).await;
6581 let (workspace, cx) =
6582 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6583 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6584
6585 // Add A, B, C
6586 let item_a = add_labeled_item(&pane_a, "A", false, cx);
6587 add_labeled_item(&pane_a, "B", false, cx);
6588 add_labeled_item(&pane_a, "C", false, cx);
6589 assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
6590
6591 // Move A to the end
6592 pane_a.update_in(cx, |pane, window, cx| {
6593 let dragged_tab = DraggedTab {
6594 pane: pane_a.clone(),
6595 item: item_a.boxed_clone(),
6596 ix: 0,
6597 detail: 0,
6598 is_active: true,
6599 };
6600 pane.handle_tab_drop(&dragged_tab, 2, false, window, cx);
6601 });
6602
6603 // A should be at the end
6604 assert_item_labels(&pane_a, ["B", "C", "A*"], cx);
6605 }
6606
6607 #[gpui::test]
6608 async fn test_drag_last_tab_to_first_position(cx: &mut TestAppContext) {
6609 init_test(cx);
6610 let fs = FakeFs::new(cx.executor());
6611
6612 let project = Project::test(fs, None, cx).await;
6613 let (workspace, cx) =
6614 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6615 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6616
6617 // Add A, B, C
6618 add_labeled_item(&pane_a, "A", false, cx);
6619 add_labeled_item(&pane_a, "B", false, cx);
6620 let item_c = add_labeled_item(&pane_a, "C", false, cx);
6621 assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
6622
6623 // Move C to the beginning
6624 pane_a.update_in(cx, |pane, window, cx| {
6625 let dragged_tab = DraggedTab {
6626 pane: pane_a.clone(),
6627 item: item_c.boxed_clone(),
6628 ix: 2,
6629 detail: 0,
6630 is_active: true,
6631 };
6632 pane.handle_tab_drop(&dragged_tab, 0, false, window, cx);
6633 });
6634
6635 // C should be at the beginning
6636 assert_item_labels(&pane_a, ["C*", "A", "B"], cx);
6637 }
6638
6639 #[gpui::test]
6640 async fn test_drag_tab_to_middle_tab_with_mouse_events(cx: &mut TestAppContext) {
6641 init_test(cx);
6642 let fs = FakeFs::new(cx.executor());
6643
6644 let project = Project::test(fs, None, cx).await;
6645 let (workspace, cx) =
6646 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6647 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6648
6649 add_labeled_item(&pane, "A", false, cx);
6650 add_labeled_item(&pane, "B", false, cx);
6651 add_labeled_item(&pane, "C", false, cx);
6652 add_labeled_item(&pane, "D", false, cx);
6653 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6654 cx.run_until_parked();
6655
6656 let tab_a_bounds = cx
6657 .debug_bounds("TAB-0")
6658 .expect("Tab A (index 0) should have debug bounds");
6659 let tab_c_bounds = cx
6660 .debug_bounds("TAB-2")
6661 .expect("Tab C (index 2) should have debug bounds");
6662
6663 cx.simulate_event(MouseDownEvent {
6664 position: tab_a_bounds.center(),
6665 button: MouseButton::Left,
6666 modifiers: Modifiers::default(),
6667 click_count: 1,
6668 first_mouse: false,
6669 });
6670 cx.run_until_parked();
6671 cx.simulate_event(MouseMoveEvent {
6672 position: tab_c_bounds.center(),
6673 pressed_button: Some(MouseButton::Left),
6674 modifiers: Modifiers::default(),
6675 });
6676 cx.run_until_parked();
6677 cx.simulate_event(MouseUpEvent {
6678 position: tab_c_bounds.center(),
6679 button: MouseButton::Left,
6680 modifiers: Modifiers::default(),
6681 click_count: 1,
6682 });
6683 cx.run_until_parked();
6684
6685 assert_item_labels(&pane, ["B", "C", "A*", "D"], cx);
6686 }
6687
6688 #[gpui::test]
6689 async fn test_drag_pinned_tab_when_show_pinned_tabs_in_separate_row_enabled(
6690 cx: &mut TestAppContext,
6691 ) {
6692 init_test(cx);
6693 set_pinned_tabs_separate_row(cx, true);
6694 let fs = FakeFs::new(cx.executor());
6695
6696 let project = Project::test(fs, None, cx).await;
6697 let (workspace, cx) =
6698 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6699 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6700
6701 let item_a = add_labeled_item(&pane, "A", false, cx);
6702 let item_b = add_labeled_item(&pane, "B", false, cx);
6703 let item_c = add_labeled_item(&pane, "C", false, cx);
6704 let item_d = add_labeled_item(&pane, "D", false, cx);
6705
6706 pane.update_in(cx, |pane, window, cx| {
6707 pane.pin_tab_at(
6708 pane.index_for_item_id(item_a.item_id()).unwrap(),
6709 window,
6710 cx,
6711 );
6712 pane.pin_tab_at(
6713 pane.index_for_item_id(item_b.item_id()).unwrap(),
6714 window,
6715 cx,
6716 );
6717 pane.pin_tab_at(
6718 pane.index_for_item_id(item_c.item_id()).unwrap(),
6719 window,
6720 cx,
6721 );
6722 pane.pin_tab_at(
6723 pane.index_for_item_id(item_d.item_id()).unwrap(),
6724 window,
6725 cx,
6726 );
6727 });
6728 assert_item_labels(&pane, ["A!", "B!", "C!", "D*!"], cx);
6729 cx.run_until_parked();
6730
6731 let tab_a_bounds = cx
6732 .debug_bounds("TAB-0")
6733 .expect("Tab A (index 0) should have debug bounds");
6734 let tab_c_bounds = cx
6735 .debug_bounds("TAB-2")
6736 .expect("Tab C (index 2) should have debug bounds");
6737
6738 cx.simulate_event(MouseDownEvent {
6739 position: tab_a_bounds.center(),
6740 button: MouseButton::Left,
6741 modifiers: Modifiers::default(),
6742 click_count: 1,
6743 first_mouse: false,
6744 });
6745 cx.run_until_parked();
6746 cx.simulate_event(MouseMoveEvent {
6747 position: tab_c_bounds.center(),
6748 pressed_button: Some(MouseButton::Left),
6749 modifiers: Modifiers::default(),
6750 });
6751 cx.run_until_parked();
6752 cx.simulate_event(MouseUpEvent {
6753 position: tab_c_bounds.center(),
6754 button: MouseButton::Left,
6755 modifiers: Modifiers::default(),
6756 click_count: 1,
6757 });
6758 cx.run_until_parked();
6759
6760 assert_item_labels(&pane, ["B!", "C!", "A*!", "D!"], cx);
6761 }
6762
6763 #[gpui::test]
6764 async fn test_drag_unpinned_tab_when_show_pinned_tabs_in_separate_row_enabled(
6765 cx: &mut TestAppContext,
6766 ) {
6767 init_test(cx);
6768 set_pinned_tabs_separate_row(cx, true);
6769 let fs = FakeFs::new(cx.executor());
6770
6771 let project = Project::test(fs, None, cx).await;
6772 let (workspace, cx) =
6773 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6774 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6775
6776 add_labeled_item(&pane, "A", false, cx);
6777 add_labeled_item(&pane, "B", false, cx);
6778 add_labeled_item(&pane, "C", false, cx);
6779 add_labeled_item(&pane, "D", false, cx);
6780 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6781 cx.run_until_parked();
6782
6783 let tab_a_bounds = cx
6784 .debug_bounds("TAB-0")
6785 .expect("Tab A (index 0) should have debug bounds");
6786 let tab_c_bounds = cx
6787 .debug_bounds("TAB-2")
6788 .expect("Tab C (index 2) should have debug bounds");
6789
6790 cx.simulate_event(MouseDownEvent {
6791 position: tab_a_bounds.center(),
6792 button: MouseButton::Left,
6793 modifiers: Modifiers::default(),
6794 click_count: 1,
6795 first_mouse: false,
6796 });
6797 cx.run_until_parked();
6798 cx.simulate_event(MouseMoveEvent {
6799 position: tab_c_bounds.center(),
6800 pressed_button: Some(MouseButton::Left),
6801 modifiers: Modifiers::default(),
6802 });
6803 cx.run_until_parked();
6804 cx.simulate_event(MouseUpEvent {
6805 position: tab_c_bounds.center(),
6806 button: MouseButton::Left,
6807 modifiers: Modifiers::default(),
6808 click_count: 1,
6809 });
6810 cx.run_until_parked();
6811
6812 assert_item_labels(&pane, ["B", "C", "A*", "D"], cx);
6813 }
6814
6815 #[gpui::test]
6816 async fn test_drag_mixed_tabs_when_show_pinned_tabs_in_separate_row_enabled(
6817 cx: &mut TestAppContext,
6818 ) {
6819 init_test(cx);
6820 set_pinned_tabs_separate_row(cx, true);
6821 let fs = FakeFs::new(cx.executor());
6822
6823 let project = Project::test(fs, None, cx).await;
6824 let (workspace, cx) =
6825 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6826 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6827
6828 let item_a = add_labeled_item(&pane, "A", false, cx);
6829 let item_b = add_labeled_item(&pane, "B", false, cx);
6830 add_labeled_item(&pane, "C", false, cx);
6831 add_labeled_item(&pane, "D", false, cx);
6832 add_labeled_item(&pane, "E", false, cx);
6833 add_labeled_item(&pane, "F", false, cx);
6834
6835 pane.update_in(cx, |pane, window, cx| {
6836 pane.pin_tab_at(
6837 pane.index_for_item_id(item_a.item_id()).unwrap(),
6838 window,
6839 cx,
6840 );
6841 pane.pin_tab_at(
6842 pane.index_for_item_id(item_b.item_id()).unwrap(),
6843 window,
6844 cx,
6845 );
6846 });
6847 assert_item_labels(&pane, ["A!", "B!", "C", "D", "E", "F*"], cx);
6848 cx.run_until_parked();
6849
6850 let tab_c_bounds = cx
6851 .debug_bounds("TAB-2")
6852 .expect("Tab C (index 2) should have debug bounds");
6853 let tab_e_bounds = cx
6854 .debug_bounds("TAB-4")
6855 .expect("Tab E (index 4) should have debug bounds");
6856
6857 cx.simulate_event(MouseDownEvent {
6858 position: tab_c_bounds.center(),
6859 button: MouseButton::Left,
6860 modifiers: Modifiers::default(),
6861 click_count: 1,
6862 first_mouse: false,
6863 });
6864 cx.run_until_parked();
6865 cx.simulate_event(MouseMoveEvent {
6866 position: tab_e_bounds.center(),
6867 pressed_button: Some(MouseButton::Left),
6868 modifiers: Modifiers::default(),
6869 });
6870 cx.run_until_parked();
6871 cx.simulate_event(MouseUpEvent {
6872 position: tab_e_bounds.center(),
6873 button: MouseButton::Left,
6874 modifiers: Modifiers::default(),
6875 click_count: 1,
6876 });
6877 cx.run_until_parked();
6878
6879 assert_item_labels(&pane, ["A!", "B!", "D", "E", "C*", "F"], cx);
6880 }
6881
6882 #[gpui::test]
6883 async fn test_middle_click_pinned_tab_does_not_close(cx: &mut TestAppContext) {
6884 init_test(cx);
6885 let fs = FakeFs::new(cx.executor());
6886
6887 let project = Project::test(fs, None, cx).await;
6888 let (workspace, cx) =
6889 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6890 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6891
6892 let item_a = add_labeled_item(&pane, "A", false, cx);
6893 add_labeled_item(&pane, "B", false, cx);
6894
6895 pane.update_in(cx, |pane, window, cx| {
6896 pane.pin_tab_at(
6897 pane.index_for_item_id(item_a.item_id()).unwrap(),
6898 window,
6899 cx,
6900 );
6901 });
6902 assert_item_labels(&pane, ["A!", "B*"], cx);
6903 cx.run_until_parked();
6904
6905 let tab_a_bounds = cx
6906 .debug_bounds("TAB-0")
6907 .expect("Tab A (index 1) should have debug bounds");
6908 let tab_b_bounds = cx
6909 .debug_bounds("TAB-1")
6910 .expect("Tab B (index 2) should have debug bounds");
6911
6912 cx.simulate_event(MouseDownEvent {
6913 position: tab_a_bounds.center(),
6914 button: MouseButton::Middle,
6915 modifiers: Modifiers::default(),
6916 click_count: 1,
6917 first_mouse: false,
6918 });
6919
6920 cx.run_until_parked();
6921
6922 cx.simulate_event(MouseUpEvent {
6923 position: tab_a_bounds.center(),
6924 button: MouseButton::Middle,
6925 modifiers: Modifiers::default(),
6926 click_count: 1,
6927 });
6928
6929 cx.run_until_parked();
6930
6931 cx.simulate_event(MouseDownEvent {
6932 position: tab_b_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_b_bounds.center(),
6943 button: MouseButton::Middle,
6944 modifiers: Modifiers::default(),
6945 click_count: 1,
6946 });
6947
6948 cx.run_until_parked();
6949
6950 assert_item_labels(&pane, ["A*!"], cx);
6951 }
6952
6953 #[gpui::test]
6954 async fn test_double_click_pinned_tab_bar_empty_space_creates_new_tab(cx: &mut TestAppContext) {
6955 init_test(cx);
6956 let fs = FakeFs::new(cx.executor());
6957
6958 let project = Project::test(fs, None, cx).await;
6959 let (workspace, cx) =
6960 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6961 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6962
6963 // The real NewFile handler lives in editor::init, which isn't initialized
6964 // in workspace tests. Register a global action handler that sets a flag so
6965 // we can verify the action is dispatched without depending on the editor crate.
6966 // TODO: If editor::init is ever available in workspace tests, remove this
6967 // flag and assert the resulting tab bar state directly instead.
6968 let new_file_dispatched = Rc::new(Cell::new(false));
6969 cx.update(|_, cx| {
6970 let new_file_dispatched = new_file_dispatched.clone();
6971 cx.on_action(move |_: &NewFile, _cx| {
6972 new_file_dispatched.set(true);
6973 });
6974 });
6975
6976 set_pinned_tabs_separate_row(cx, true);
6977
6978 let item_a = add_labeled_item(&pane, "A", false, cx);
6979 add_labeled_item(&pane, "B", false, cx);
6980
6981 pane.update_in(cx, |pane, window, cx| {
6982 let ix = pane
6983 .index_for_item_id(item_a.item_id())
6984 .expect("item A should exist");
6985 pane.pin_tab_at(ix, window, cx);
6986 });
6987 assert_item_labels(&pane, ["A!", "B*"], cx);
6988 cx.run_until_parked();
6989
6990 let pinned_drop_target_bounds = cx
6991 .debug_bounds("pinned_tabs_border")
6992 .expect("pinned_tabs_border should have debug bounds");
6993
6994 cx.simulate_event(MouseDownEvent {
6995 position: pinned_drop_target_bounds.center(),
6996 button: MouseButton::Left,
6997 modifiers: Modifiers::default(),
6998 click_count: 2,
6999 first_mouse: false,
7000 });
7001
7002 cx.run_until_parked();
7003
7004 cx.simulate_event(MouseUpEvent {
7005 position: pinned_drop_target_bounds.center(),
7006 button: MouseButton::Left,
7007 modifiers: Modifiers::default(),
7008 click_count: 2,
7009 });
7010
7011 cx.run_until_parked();
7012
7013 // TODO: If editor::init is ever available in workspace tests, replace this
7014 // with an assert_item_labels check that verifies a new tab is actually created.
7015 assert!(
7016 new_file_dispatched.get(),
7017 "Double-clicking pinned tab bar empty space should dispatch the new file action"
7018 );
7019 }
7020
7021 #[gpui::test]
7022 async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
7023 init_test(cx);
7024 let fs = FakeFs::new(cx.executor());
7025
7026 let project = Project::test(fs, None, cx).await;
7027 let (workspace, cx) =
7028 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7029 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7030
7031 // 1. Add with a destination index
7032 // a. Add before the active item
7033 set_labeled_items(&pane, ["A", "B*", "C"], cx);
7034 pane.update_in(cx, |pane, window, cx| {
7035 pane.add_item(
7036 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
7037 false,
7038 false,
7039 Some(0),
7040 window,
7041 cx,
7042 );
7043 });
7044 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
7045
7046 // b. Add after the active item
7047 set_labeled_items(&pane, ["A", "B*", "C"], cx);
7048 pane.update_in(cx, |pane, window, cx| {
7049 pane.add_item(
7050 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
7051 false,
7052 false,
7053 Some(2),
7054 window,
7055 cx,
7056 );
7057 });
7058 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
7059
7060 // c. Add at the end of the item list (including off the length)
7061 set_labeled_items(&pane, ["A", "B*", "C"], cx);
7062 pane.update_in(cx, |pane, window, cx| {
7063 pane.add_item(
7064 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
7065 false,
7066 false,
7067 Some(5),
7068 window,
7069 cx,
7070 );
7071 });
7072 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
7073
7074 // 2. Add without a destination index
7075 // a. Add with active item at the start of the item list
7076 set_labeled_items(&pane, ["A*", "B", "C"], cx);
7077 pane.update_in(cx, |pane, window, cx| {
7078 pane.add_item(
7079 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
7080 false,
7081 false,
7082 None,
7083 window,
7084 cx,
7085 );
7086 });
7087 set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
7088
7089 // b. Add with active item at the end of the item list
7090 set_labeled_items(&pane, ["A", "B", "C*"], cx);
7091 pane.update_in(cx, |pane, window, cx| {
7092 pane.add_item(
7093 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
7094 false,
7095 false,
7096 None,
7097 window,
7098 cx,
7099 );
7100 });
7101 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
7102 }
7103
7104 #[gpui::test]
7105 async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
7106 init_test(cx);
7107 let fs = FakeFs::new(cx.executor());
7108
7109 let project = Project::test(fs, None, cx).await;
7110 let (workspace, cx) =
7111 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7112 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7113
7114 // 1. Add with a destination index
7115 // 1a. Add before the active item
7116 let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
7117 pane.update_in(cx, |pane, window, cx| {
7118 pane.add_item(d, false, false, Some(0), window, cx);
7119 });
7120 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
7121
7122 // 1b. Add after the active item
7123 let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
7124 pane.update_in(cx, |pane, window, cx| {
7125 pane.add_item(d, false, false, Some(2), window, cx);
7126 });
7127 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
7128
7129 // 1c. Add at the end of the item list (including off the length)
7130 let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
7131 pane.update_in(cx, |pane, window, cx| {
7132 pane.add_item(a, false, false, Some(5), window, cx);
7133 });
7134 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
7135
7136 // 1d. Add same item to active index
7137 let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
7138 pane.update_in(cx, |pane, window, cx| {
7139 pane.add_item(b, false, false, Some(1), window, cx);
7140 });
7141 assert_item_labels(&pane, ["A", "B*", "C"], cx);
7142
7143 // 1e. Add item to index after same item in last position
7144 let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
7145 pane.update_in(cx, |pane, window, cx| {
7146 pane.add_item(c, false, false, Some(2), window, cx);
7147 });
7148 assert_item_labels(&pane, ["A", "B", "C*"], cx);
7149
7150 // 2. Add without a destination index
7151 // 2a. Add with active item at the start of the item list
7152 let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
7153 pane.update_in(cx, |pane, window, cx| {
7154 pane.add_item(d, false, false, None, window, cx);
7155 });
7156 assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
7157
7158 // 2b. Add with active item at the end of the item list
7159 let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
7160 pane.update_in(cx, |pane, window, cx| {
7161 pane.add_item(a, false, false, None, window, cx);
7162 });
7163 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
7164
7165 // 2c. Add active item to active item at end of list
7166 let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
7167 pane.update_in(cx, |pane, window, cx| {
7168 pane.add_item(c, false, false, None, window, cx);
7169 });
7170 assert_item_labels(&pane, ["A", "B", "C*"], cx);
7171
7172 // 2d. Add active item to active item at start of list
7173 let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
7174 pane.update_in(cx, |pane, window, cx| {
7175 pane.add_item(a, false, false, None, window, cx);
7176 });
7177 assert_item_labels(&pane, ["A*", "B", "C"], cx);
7178 }
7179
7180 #[gpui::test]
7181 async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
7182 init_test(cx);
7183 let fs = FakeFs::new(cx.executor());
7184
7185 let project = Project::test(fs, None, cx).await;
7186 let (workspace, cx) =
7187 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7188 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7189
7190 // singleton view
7191 pane.update_in(cx, |pane, window, cx| {
7192 pane.add_item(
7193 Box::new(cx.new(|cx| {
7194 TestItem::new(cx)
7195 .with_buffer_kind(ItemBufferKind::Singleton)
7196 .with_label("buffer 1")
7197 .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
7198 })),
7199 false,
7200 false,
7201 None,
7202 window,
7203 cx,
7204 );
7205 });
7206 assert_item_labels(&pane, ["buffer 1*"], cx);
7207
7208 // new singleton view with the same project entry
7209 pane.update_in(cx, |pane, window, cx| {
7210 pane.add_item(
7211 Box::new(cx.new(|cx| {
7212 TestItem::new(cx)
7213 .with_buffer_kind(ItemBufferKind::Singleton)
7214 .with_label("buffer 1")
7215 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
7216 })),
7217 false,
7218 false,
7219 None,
7220 window,
7221 cx,
7222 );
7223 });
7224 assert_item_labels(&pane, ["buffer 1*"], cx);
7225
7226 // new singleton view with different project entry
7227 pane.update_in(cx, |pane, window, cx| {
7228 pane.add_item(
7229 Box::new(cx.new(|cx| {
7230 TestItem::new(cx)
7231 .with_buffer_kind(ItemBufferKind::Singleton)
7232 .with_label("buffer 2")
7233 .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
7234 })),
7235 false,
7236 false,
7237 None,
7238 window,
7239 cx,
7240 );
7241 });
7242 assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
7243
7244 // new multibuffer view with the same project entry
7245 pane.update_in(cx, |pane, window, cx| {
7246 pane.add_item(
7247 Box::new(cx.new(|cx| {
7248 TestItem::new(cx)
7249 .with_buffer_kind(ItemBufferKind::Multibuffer)
7250 .with_label("multibuffer 1")
7251 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
7252 })),
7253 false,
7254 false,
7255 None,
7256 window,
7257 cx,
7258 );
7259 });
7260 assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
7261
7262 // another multibuffer view with the same project entry
7263 pane.update_in(cx, |pane, window, cx| {
7264 pane.add_item(
7265 Box::new(cx.new(|cx| {
7266 TestItem::new(cx)
7267 .with_buffer_kind(ItemBufferKind::Multibuffer)
7268 .with_label("multibuffer 1b")
7269 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
7270 })),
7271 false,
7272 false,
7273 None,
7274 window,
7275 cx,
7276 );
7277 });
7278 assert_item_labels(
7279 &pane,
7280 ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
7281 cx,
7282 );
7283 }
7284
7285 #[gpui::test]
7286 async fn test_remove_item_ordering_history(cx: &mut TestAppContext) {
7287 init_test(cx);
7288 let fs = FakeFs::new(cx.executor());
7289
7290 let project = Project::test(fs, None, cx).await;
7291 let (workspace, cx) =
7292 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7293 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7294
7295 add_labeled_item(&pane, "A", false, cx);
7296 add_labeled_item(&pane, "B", false, cx);
7297 add_labeled_item(&pane, "C", false, cx);
7298 add_labeled_item(&pane, "D", false, cx);
7299 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
7300
7301 pane.update_in(cx, |pane, window, cx| {
7302 pane.activate_item(1, false, false, window, cx)
7303 });
7304 add_labeled_item(&pane, "1", false, cx);
7305 assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
7306
7307 pane.update_in(cx, |pane, window, cx| {
7308 pane.close_active_item(
7309 &CloseActiveItem {
7310 save_intent: None,
7311 close_pinned: false,
7312 },
7313 window,
7314 cx,
7315 )
7316 })
7317 .await
7318 .unwrap();
7319 assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
7320
7321 pane.update_in(cx, |pane, window, cx| {
7322 pane.activate_item(3, false, false, window, cx)
7323 });
7324 assert_item_labels(&pane, ["A", "B", "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"], cx);
7339
7340 pane.update_in(cx, |pane, window, cx| {
7341 pane.close_active_item(
7342 &CloseActiveItem {
7343 save_intent: None,
7344 close_pinned: false,
7345 },
7346 window,
7347 cx,
7348 )
7349 })
7350 .await
7351 .unwrap();
7352 assert_item_labels(&pane, ["A", "C*"], cx);
7353
7354 pane.update_in(cx, |pane, window, cx| {
7355 pane.close_active_item(
7356 &CloseActiveItem {
7357 save_intent: None,
7358 close_pinned: false,
7359 },
7360 window,
7361 cx,
7362 )
7363 })
7364 .await
7365 .unwrap();
7366 assert_item_labels(&pane, ["A*"], cx);
7367 }
7368
7369 #[gpui::test]
7370 async fn test_remove_item_ordering_neighbour(cx: &mut TestAppContext) {
7371 init_test(cx);
7372 cx.update_global::<SettingsStore, ()>(|s, cx| {
7373 s.update_user_settings(cx, |s| {
7374 s.tabs.get_or_insert_default().activate_on_close = Some(ActivateOnClose::Neighbour);
7375 });
7376 });
7377 let fs = FakeFs::new(cx.executor());
7378
7379 let project = Project::test(fs, None, cx).await;
7380 let (workspace, cx) =
7381 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7382 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7383
7384 add_labeled_item(&pane, "A", false, cx);
7385 add_labeled_item(&pane, "B", false, cx);
7386 add_labeled_item(&pane, "C", false, cx);
7387 add_labeled_item(&pane, "D", false, cx);
7388 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
7389
7390 pane.update_in(cx, |pane, window, cx| {
7391 pane.activate_item(1, false, false, window, cx)
7392 });
7393 add_labeled_item(&pane, "1", false, cx);
7394 assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
7395
7396 pane.update_in(cx, |pane, window, cx| {
7397 pane.close_active_item(
7398 &CloseActiveItem {
7399 save_intent: None,
7400 close_pinned: false,
7401 },
7402 window,
7403 cx,
7404 )
7405 })
7406 .await
7407 .unwrap();
7408 assert_item_labels(&pane, ["A", "B", "C*", "D"], cx);
7409
7410 pane.update_in(cx, |pane, window, cx| {
7411 pane.activate_item(3, false, false, window, cx)
7412 });
7413 assert_item_labels(&pane, ["A", "B", "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*"], cx);
7428
7429 pane.update_in(cx, |pane, window, cx| {
7430 pane.close_active_item(
7431 &CloseActiveItem {
7432 save_intent: None,
7433 close_pinned: false,
7434 },
7435 window,
7436 cx,
7437 )
7438 })
7439 .await
7440 .unwrap();
7441 assert_item_labels(&pane, ["A", "B*"], cx);
7442
7443 pane.update_in(cx, |pane, window, cx| {
7444 pane.close_active_item(
7445 &CloseActiveItem {
7446 save_intent: None,
7447 close_pinned: false,
7448 },
7449 window,
7450 cx,
7451 )
7452 })
7453 .await
7454 .unwrap();
7455 assert_item_labels(&pane, ["A*"], cx);
7456 }
7457
7458 #[gpui::test]
7459 async fn test_remove_item_ordering_left_neighbour(cx: &mut TestAppContext) {
7460 init_test(cx);
7461 cx.update_global::<SettingsStore, ()>(|s, cx| {
7462 s.update_user_settings(cx, |s| {
7463 s.tabs.get_or_insert_default().activate_on_close =
7464 Some(ActivateOnClose::LeftNeighbour);
7465 });
7466 });
7467 let fs = FakeFs::new(cx.executor());
7468
7469 let project = Project::test(fs, None, cx).await;
7470 let (workspace, cx) =
7471 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7472 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7473
7474 add_labeled_item(&pane, "A", false, cx);
7475 add_labeled_item(&pane, "B", false, cx);
7476 add_labeled_item(&pane, "C", false, cx);
7477 add_labeled_item(&pane, "D", false, cx);
7478 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
7479
7480 pane.update_in(cx, |pane, window, cx| {
7481 pane.activate_item(1, false, false, window, cx)
7482 });
7483 add_labeled_item(&pane, "1", false, cx);
7484 assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
7485
7486 pane.update_in(cx, |pane, window, cx| {
7487 pane.close_active_item(
7488 &CloseActiveItem {
7489 save_intent: None,
7490 close_pinned: false,
7491 },
7492 window,
7493 cx,
7494 )
7495 })
7496 .await
7497 .unwrap();
7498 assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
7499
7500 pane.update_in(cx, |pane, window, cx| {
7501 pane.activate_item(3, false, false, window, cx)
7502 });
7503 assert_item_labels(&pane, ["A", "B", "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*"], cx);
7518
7519 pane.update_in(cx, |pane, window, cx| {
7520 pane.activate_item(0, false, false, window, cx)
7521 });
7522 assert_item_labels(&pane, ["A*", "B", "C"], 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, ["B*", "C"], cx);
7537
7538 pane.update_in(cx, |pane, window, cx| {
7539 pane.close_active_item(
7540 &CloseActiveItem {
7541 save_intent: None,
7542 close_pinned: false,
7543 },
7544 window,
7545 cx,
7546 )
7547 })
7548 .await
7549 .unwrap();
7550 assert_item_labels(&pane, ["C*"], cx);
7551 }
7552
7553 #[gpui::test]
7554 async fn test_close_inactive_items(cx: &mut TestAppContext) {
7555 init_test(cx);
7556 let fs = FakeFs::new(cx.executor());
7557
7558 let project = Project::test(fs, None, cx).await;
7559 let (workspace, cx) =
7560 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7561 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7562
7563 let item_a = add_labeled_item(&pane, "A", false, cx);
7564 pane.update_in(cx, |pane, window, cx| {
7565 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
7566 pane.pin_tab_at(ix, window, cx);
7567 });
7568 assert_item_labels(&pane, ["A*!"], cx);
7569
7570 let item_b = add_labeled_item(&pane, "B", false, cx);
7571 pane.update_in(cx, |pane, window, cx| {
7572 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
7573 pane.pin_tab_at(ix, window, cx);
7574 });
7575 assert_item_labels(&pane, ["A!", "B*!"], cx);
7576
7577 add_labeled_item(&pane, "C", false, cx);
7578 assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
7579
7580 add_labeled_item(&pane, "D", false, cx);
7581 add_labeled_item(&pane, "E", false, cx);
7582 assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
7583
7584 pane.update_in(cx, |pane, window, cx| {
7585 pane.close_other_items(
7586 &CloseOtherItems {
7587 save_intent: None,
7588 close_pinned: false,
7589 },
7590 None,
7591 window,
7592 cx,
7593 )
7594 })
7595 .await
7596 .unwrap();
7597 assert_item_labels(&pane, ["A!", "B!", "E*"], cx);
7598 }
7599
7600 #[gpui::test]
7601 async fn test_running_close_inactive_items_via_an_inactive_item(cx: &mut TestAppContext) {
7602 init_test(cx);
7603 let fs = FakeFs::new(cx.executor());
7604
7605 let project = Project::test(fs, None, cx).await;
7606 let (workspace, cx) =
7607 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7608 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7609
7610 add_labeled_item(&pane, "A", false, cx);
7611 assert_item_labels(&pane, ["A*"], cx);
7612
7613 let item_b = add_labeled_item(&pane, "B", false, cx);
7614 assert_item_labels(&pane, ["A", "B*"], cx);
7615
7616 add_labeled_item(&pane, "C", false, cx);
7617 add_labeled_item(&pane, "D", false, cx);
7618 add_labeled_item(&pane, "E", false, cx);
7619 assert_item_labels(&pane, ["A", "B", "C", "D", "E*"], cx);
7620
7621 pane.update_in(cx, |pane, window, cx| {
7622 pane.close_other_items(
7623 &CloseOtherItems {
7624 save_intent: None,
7625 close_pinned: false,
7626 },
7627 Some(item_b.item_id()),
7628 window,
7629 cx,
7630 )
7631 })
7632 .await
7633 .unwrap();
7634 assert_item_labels(&pane, ["B*"], cx);
7635 }
7636
7637 #[gpui::test]
7638 async fn test_close_other_items_unpreviews_active_item(cx: &mut TestAppContext) {
7639 init_test(cx);
7640 let fs = FakeFs::new(cx.executor());
7641
7642 let project = Project::test(fs, None, cx).await;
7643 let (workspace, cx) =
7644 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7645 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7646
7647 add_labeled_item(&pane, "A", false, cx);
7648 add_labeled_item(&pane, "B", false, cx);
7649 let item_c = add_labeled_item(&pane, "C", false, cx);
7650 assert_item_labels(&pane, ["A", "B", "C*"], cx);
7651
7652 pane.update(cx, |pane, cx| {
7653 pane.set_preview_item_id(Some(item_c.item_id()), cx);
7654 });
7655 assert!(pane.read_with(cx, |pane, _| pane.preview_item_id()
7656 == Some(item_c.item_id())));
7657
7658 pane.update_in(cx, |pane, window, cx| {
7659 pane.close_other_items(
7660 &CloseOtherItems {
7661 save_intent: None,
7662 close_pinned: false,
7663 },
7664 Some(item_c.item_id()),
7665 window,
7666 cx,
7667 )
7668 })
7669 .await
7670 .unwrap();
7671
7672 assert!(pane.read_with(cx, |pane, _| pane.preview_item_id().is_none()));
7673 assert_item_labels(&pane, ["C*"], cx);
7674 }
7675
7676 #[gpui::test]
7677 async fn test_close_clean_items(cx: &mut TestAppContext) {
7678 init_test(cx);
7679 let fs = FakeFs::new(cx.executor());
7680
7681 let project = Project::test(fs, None, cx).await;
7682 let (workspace, cx) =
7683 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7684 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7685
7686 add_labeled_item(&pane, "A", true, cx);
7687 add_labeled_item(&pane, "B", false, cx);
7688 add_labeled_item(&pane, "C", true, cx);
7689 add_labeled_item(&pane, "D", false, cx);
7690 add_labeled_item(&pane, "E", false, cx);
7691 assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
7692
7693 pane.update_in(cx, |pane, window, cx| {
7694 pane.close_clean_items(
7695 &CloseCleanItems {
7696 close_pinned: false,
7697 },
7698 window,
7699 cx,
7700 )
7701 })
7702 .await
7703 .unwrap();
7704 assert_item_labels(&pane, ["A^", "C*^"], cx);
7705 }
7706
7707 #[gpui::test]
7708 async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
7709 init_test(cx);
7710 let fs = FakeFs::new(cx.executor());
7711
7712 let project = Project::test(fs, None, cx).await;
7713 let (workspace, cx) =
7714 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7715 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7716
7717 set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
7718
7719 pane.update_in(cx, |pane, window, cx| {
7720 pane.close_items_to_the_left_by_id(
7721 None,
7722 &CloseItemsToTheLeft {
7723 close_pinned: false,
7724 },
7725 window,
7726 cx,
7727 )
7728 })
7729 .await
7730 .unwrap();
7731 assert_item_labels(&pane, ["C*", "D", "E"], cx);
7732 }
7733
7734 #[gpui::test]
7735 async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
7736 init_test(cx);
7737 let fs = FakeFs::new(cx.executor());
7738
7739 let project = Project::test(fs, None, cx).await;
7740 let (workspace, cx) =
7741 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7742 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7743
7744 set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
7745
7746 pane.update_in(cx, |pane, window, cx| {
7747 pane.close_items_to_the_right_by_id(
7748 None,
7749 &CloseItemsToTheRight {
7750 close_pinned: false,
7751 },
7752 window,
7753 cx,
7754 )
7755 })
7756 .await
7757 .unwrap();
7758 assert_item_labels(&pane, ["A", "B", "C*"], cx);
7759 }
7760
7761 #[gpui::test]
7762 async fn test_close_all_items(cx: &mut TestAppContext) {
7763 init_test(cx);
7764 let fs = FakeFs::new(cx.executor());
7765
7766 let project = Project::test(fs, None, cx).await;
7767 let (workspace, cx) =
7768 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7769 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7770
7771 let item_a = add_labeled_item(&pane, "A", false, cx);
7772 add_labeled_item(&pane, "B", false, cx);
7773 add_labeled_item(&pane, "C", false, cx);
7774 assert_item_labels(&pane, ["A", "B", "C*"], cx);
7775
7776 pane.update_in(cx, |pane, window, cx| {
7777 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
7778 pane.pin_tab_at(ix, window, cx);
7779 pane.close_all_items(
7780 &CloseAllItems {
7781 save_intent: None,
7782 close_pinned: false,
7783 },
7784 window,
7785 cx,
7786 )
7787 })
7788 .await
7789 .unwrap();
7790 assert_item_labels(&pane, ["A*!"], cx);
7791
7792 pane.update_in(cx, |pane, window, cx| {
7793 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
7794 pane.unpin_tab_at(ix, window, cx);
7795 pane.close_all_items(
7796 &CloseAllItems {
7797 save_intent: None,
7798 close_pinned: false,
7799 },
7800 window,
7801 cx,
7802 )
7803 })
7804 .await
7805 .unwrap();
7806
7807 assert_item_labels(&pane, [], cx);
7808
7809 add_labeled_item(&pane, "A", true, cx).update(cx, |item, cx| {
7810 item.project_items
7811 .push(TestProjectItem::new_dirty(1, "A.txt", cx))
7812 });
7813 add_labeled_item(&pane, "B", true, cx).update(cx, |item, cx| {
7814 item.project_items
7815 .push(TestProjectItem::new_dirty(2, "B.txt", cx))
7816 });
7817 add_labeled_item(&pane, "C", true, cx).update(cx, |item, cx| {
7818 item.project_items
7819 .push(TestProjectItem::new_dirty(3, "C.txt", cx))
7820 });
7821 assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
7822
7823 let save = pane.update_in(cx, |pane, window, cx| {
7824 pane.close_all_items(
7825 &CloseAllItems {
7826 save_intent: None,
7827 close_pinned: false,
7828 },
7829 window,
7830 cx,
7831 )
7832 });
7833
7834 cx.executor().run_until_parked();
7835 cx.simulate_prompt_answer("Save all");
7836 save.await.unwrap();
7837 assert_item_labels(&pane, [], cx);
7838
7839 add_labeled_item(&pane, "A", true, cx);
7840 add_labeled_item(&pane, "B", true, cx);
7841 add_labeled_item(&pane, "C", true, cx);
7842 assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
7843 let save = pane.update_in(cx, |pane, window, cx| {
7844 pane.close_all_items(
7845 &CloseAllItems {
7846 save_intent: None,
7847 close_pinned: false,
7848 },
7849 window,
7850 cx,
7851 )
7852 });
7853
7854 cx.executor().run_until_parked();
7855 cx.simulate_prompt_answer("Discard all");
7856 save.await.unwrap();
7857 assert_item_labels(&pane, [], cx);
7858
7859 add_labeled_item(&pane, "A", true, cx).update(cx, |item, cx| {
7860 item.project_items
7861 .push(TestProjectItem::new_dirty(1, "A.txt", cx))
7862 });
7863 add_labeled_item(&pane, "B", true, cx).update(cx, |item, cx| {
7864 item.project_items
7865 .push(TestProjectItem::new_dirty(2, "B.txt", cx))
7866 });
7867 add_labeled_item(&pane, "C", true, cx).update(cx, |item, cx| {
7868 item.project_items
7869 .push(TestProjectItem::new_dirty(3, "C.txt", cx))
7870 });
7871 assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
7872
7873 let close_task = pane.update_in(cx, |pane, window, cx| {
7874 pane.close_all_items(
7875 &CloseAllItems {
7876 save_intent: None,
7877 close_pinned: false,
7878 },
7879 window,
7880 cx,
7881 )
7882 });
7883
7884 cx.executor().run_until_parked();
7885 cx.simulate_prompt_answer("Discard all");
7886 close_task.await.unwrap();
7887 assert_item_labels(&pane, [], cx);
7888
7889 add_labeled_item(&pane, "Clean1", false, cx);
7890 add_labeled_item(&pane, "Dirty", true, cx).update(cx, |item, cx| {
7891 item.project_items
7892 .push(TestProjectItem::new_dirty(1, "Dirty.txt", cx))
7893 });
7894 add_labeled_item(&pane, "Clean2", false, cx);
7895 assert_item_labels(&pane, ["Clean1", "Dirty^", "Clean2*"], cx);
7896
7897 let close_task = pane.update_in(cx, |pane, window, cx| {
7898 pane.close_all_items(
7899 &CloseAllItems {
7900 save_intent: None,
7901 close_pinned: false,
7902 },
7903 window,
7904 cx,
7905 )
7906 });
7907
7908 cx.executor().run_until_parked();
7909 cx.simulate_prompt_answer("Cancel");
7910 close_task.await.unwrap();
7911 assert_item_labels(&pane, ["Dirty*^"], cx);
7912 }
7913
7914 #[gpui::test]
7915 async fn test_discard_all_reloads_from_disk(cx: &mut TestAppContext) {
7916 init_test(cx);
7917 let fs = FakeFs::new(cx.executor());
7918
7919 let project = Project::test(fs, None, cx).await;
7920 let (workspace, cx) =
7921 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7922 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7923
7924 let item_a = add_labeled_item(&pane, "A", true, cx);
7925 item_a.update(cx, |item, cx| {
7926 item.project_items
7927 .push(TestProjectItem::new_dirty(1, "A.txt", cx))
7928 });
7929 let item_b = add_labeled_item(&pane, "B", true, cx);
7930 item_b.update(cx, |item, cx| {
7931 item.project_items
7932 .push(TestProjectItem::new_dirty(2, "B.txt", cx))
7933 });
7934 assert_item_labels(&pane, ["A^", "B*^"], cx);
7935
7936 let close_task = pane.update_in(cx, |pane, window, cx| {
7937 pane.close_all_items(
7938 &CloseAllItems {
7939 save_intent: None,
7940 close_pinned: false,
7941 },
7942 window,
7943 cx,
7944 )
7945 });
7946
7947 cx.executor().run_until_parked();
7948 cx.simulate_prompt_answer("Discard all");
7949 close_task.await.unwrap();
7950 assert_item_labels(&pane, [], cx);
7951
7952 item_a.read_with(cx, |item, _| {
7953 assert_eq!(item.reload_count, 1, "item A should have been reloaded");
7954 assert!(
7955 !item.is_dirty,
7956 "item A should no longer be dirty after reload"
7957 );
7958 });
7959 item_b.read_with(cx, |item, _| {
7960 assert_eq!(item.reload_count, 1, "item B should have been reloaded");
7961 assert!(
7962 !item.is_dirty,
7963 "item B should no longer be dirty after reload"
7964 );
7965 });
7966 }
7967
7968 #[gpui::test]
7969 async fn test_dont_save_single_file_reloads_from_disk(cx: &mut TestAppContext) {
7970 init_test(cx);
7971 let fs = FakeFs::new(cx.executor());
7972
7973 let project = Project::test(fs, None, cx).await;
7974 let (workspace, cx) =
7975 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
7976 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7977
7978 let item = add_labeled_item(&pane, "Dirty", true, cx);
7979 item.update(cx, |item, cx| {
7980 item.project_items
7981 .push(TestProjectItem::new_dirty(1, "Dirty.txt", cx))
7982 });
7983 assert_item_labels(&pane, ["Dirty*^"], cx);
7984
7985 let close_task = pane.update_in(cx, |pane, window, cx| {
7986 pane.close_item_by_id(item.item_id(), SaveIntent::Close, window, cx)
7987 });
7988
7989 cx.executor().run_until_parked();
7990 cx.simulate_prompt_answer("Don't Save");
7991 close_task.await.unwrap();
7992 assert_item_labels(&pane, [], cx);
7993
7994 item.read_with(cx, |item, _| {
7995 assert_eq!(item.reload_count, 1, "item should have been reloaded");
7996 assert!(
7997 !item.is_dirty,
7998 "item should no longer be dirty after reload"
7999 );
8000 });
8001 }
8002
8003 #[gpui::test]
8004 async fn test_discard_does_not_reload_multibuffer(cx: &mut TestAppContext) {
8005 init_test(cx);
8006 let fs = FakeFs::new(cx.executor());
8007
8008 let project = Project::test(fs, None, cx).await;
8009 let (workspace, cx) =
8010 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8011 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8012
8013 let singleton_item = pane.update_in(cx, |pane, window, cx| {
8014 let item = Box::new(cx.new(|cx| {
8015 TestItem::new(cx)
8016 .with_label("Singleton")
8017 .with_dirty(true)
8018 .with_buffer_kind(ItemBufferKind::Singleton)
8019 }));
8020 pane.add_item(item.clone(), false, false, None, window, cx);
8021 item
8022 });
8023 singleton_item.update(cx, |item, cx| {
8024 item.project_items
8025 .push(TestProjectItem::new_dirty(1, "Singleton.txt", cx))
8026 });
8027
8028 let multi_item = pane.update_in(cx, |pane, window, cx| {
8029 let item = Box::new(cx.new(|cx| {
8030 TestItem::new(cx)
8031 .with_label("Multi")
8032 .with_dirty(true)
8033 .with_buffer_kind(ItemBufferKind::Multibuffer)
8034 }));
8035 pane.add_item(item.clone(), false, false, None, window, cx);
8036 item
8037 });
8038 multi_item.update(cx, |item, cx| {
8039 item.project_items
8040 .push(TestProjectItem::new_dirty(2, "Multi.txt", cx))
8041 });
8042
8043 let close_task = pane.update_in(cx, |pane, window, cx| {
8044 pane.close_all_items(
8045 &CloseAllItems {
8046 save_intent: None,
8047 close_pinned: false,
8048 },
8049 window,
8050 cx,
8051 )
8052 });
8053
8054 cx.executor().run_until_parked();
8055 cx.simulate_prompt_answer("Discard all");
8056 close_task.await.unwrap();
8057 assert_item_labels(&pane, [], cx);
8058
8059 singleton_item.read_with(cx, |item, _| {
8060 assert_eq!(item.reload_count, 1, "singleton should have been reloaded");
8061 assert!(
8062 !item.is_dirty,
8063 "singleton should no longer be dirty after reload"
8064 );
8065 });
8066 multi_item.read_with(cx, |item, _| {
8067 assert_eq!(
8068 item.reload_count, 0,
8069 "multibuffer should not have been reloaded"
8070 );
8071 });
8072 }
8073
8074 #[gpui::test]
8075 async fn test_close_multibuffer_items(cx: &mut TestAppContext) {
8076 init_test(cx);
8077 let fs = FakeFs::new(cx.executor());
8078
8079 let project = Project::test(fs, None, cx).await;
8080 let (workspace, cx) =
8081 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8082 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8083
8084 let add_labeled_item = |pane: &Entity<Pane>,
8085 label,
8086 is_dirty,
8087 kind: ItemBufferKind,
8088 cx: &mut VisualTestContext| {
8089 pane.update_in(cx, |pane, window, cx| {
8090 let labeled_item = Box::new(cx.new(|cx| {
8091 TestItem::new(cx)
8092 .with_label(label)
8093 .with_dirty(is_dirty)
8094 .with_buffer_kind(kind)
8095 }));
8096 pane.add_item(labeled_item.clone(), false, false, None, window, cx);
8097 labeled_item
8098 })
8099 };
8100
8101 let item_a = add_labeled_item(&pane, "A", false, ItemBufferKind::Multibuffer, cx);
8102 add_labeled_item(&pane, "B", false, ItemBufferKind::Multibuffer, cx);
8103 add_labeled_item(&pane, "C", false, ItemBufferKind::Singleton, cx);
8104 assert_item_labels(&pane, ["A", "B", "C*"], cx);
8105
8106 pane.update_in(cx, |pane, window, cx| {
8107 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
8108 pane.pin_tab_at(ix, window, cx);
8109 pane.close_multibuffer_items(
8110 &CloseMultibufferItems {
8111 save_intent: None,
8112 close_pinned: false,
8113 },
8114 window,
8115 cx,
8116 )
8117 })
8118 .await
8119 .unwrap();
8120 assert_item_labels(&pane, ["A!", "C*"], cx);
8121
8122 pane.update_in(cx, |pane, window, cx| {
8123 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
8124 pane.unpin_tab_at(ix, window, cx);
8125 pane.close_multibuffer_items(
8126 &CloseMultibufferItems {
8127 save_intent: None,
8128 close_pinned: false,
8129 },
8130 window,
8131 cx,
8132 )
8133 })
8134 .await
8135 .unwrap();
8136
8137 assert_item_labels(&pane, ["C*"], cx);
8138
8139 add_labeled_item(&pane, "A", true, ItemBufferKind::Singleton, cx).update(cx, |item, cx| {
8140 item.project_items
8141 .push(TestProjectItem::new_dirty(1, "A.txt", cx))
8142 });
8143 add_labeled_item(&pane, "B", true, ItemBufferKind::Multibuffer, cx).update(
8144 cx,
8145 |item, cx| {
8146 item.project_items
8147 .push(TestProjectItem::new_dirty(2, "B.txt", cx))
8148 },
8149 );
8150 add_labeled_item(&pane, "D", true, ItemBufferKind::Multibuffer, cx).update(
8151 cx,
8152 |item, cx| {
8153 item.project_items
8154 .push(TestProjectItem::new_dirty(3, "D.txt", cx))
8155 },
8156 );
8157 assert_item_labels(&pane, ["C", "A^", "B^", "D*^"], cx);
8158
8159 let save = pane.update_in(cx, |pane, window, cx| {
8160 pane.close_multibuffer_items(
8161 &CloseMultibufferItems {
8162 save_intent: None,
8163 close_pinned: false,
8164 },
8165 window,
8166 cx,
8167 )
8168 });
8169
8170 cx.executor().run_until_parked();
8171 cx.simulate_prompt_answer("Save all");
8172 save.await.unwrap();
8173 assert_item_labels(&pane, ["C", "A*^"], cx);
8174
8175 add_labeled_item(&pane, "B", true, ItemBufferKind::Multibuffer, cx).update(
8176 cx,
8177 |item, cx| {
8178 item.project_items
8179 .push(TestProjectItem::new_dirty(2, "B.txt", cx))
8180 },
8181 );
8182 add_labeled_item(&pane, "D", true, ItemBufferKind::Multibuffer, cx).update(
8183 cx,
8184 |item, cx| {
8185 item.project_items
8186 .push(TestProjectItem::new_dirty(3, "D.txt", cx))
8187 },
8188 );
8189 assert_item_labels(&pane, ["C", "A^", "B^", "D*^"], cx);
8190 let save = pane.update_in(cx, |pane, window, cx| {
8191 pane.close_multibuffer_items(
8192 &CloseMultibufferItems {
8193 save_intent: None,
8194 close_pinned: false,
8195 },
8196 window,
8197 cx,
8198 )
8199 });
8200
8201 cx.executor().run_until_parked();
8202 cx.simulate_prompt_answer("Discard all");
8203 save.await.unwrap();
8204 assert_item_labels(&pane, ["C", "A*^"], cx);
8205 }
8206
8207 #[gpui::test]
8208 async fn test_close_with_save_intent(cx: &mut TestAppContext) {
8209 init_test(cx);
8210 let fs = FakeFs::new(cx.executor());
8211
8212 let project = Project::test(fs, None, cx).await;
8213 let (workspace, cx) =
8214 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8215 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8216
8217 let a = cx.update(|_, cx| TestProjectItem::new_dirty(1, "A.txt", cx));
8218 let b = cx.update(|_, cx| TestProjectItem::new_dirty(1, "B.txt", cx));
8219 let c = cx.update(|_, cx| TestProjectItem::new_dirty(1, "C.txt", cx));
8220
8221 add_labeled_item(&pane, "AB", true, cx).update(cx, |item, _| {
8222 item.project_items.push(a.clone());
8223 item.project_items.push(b.clone());
8224 });
8225 add_labeled_item(&pane, "C", true, cx)
8226 .update(cx, |item, _| item.project_items.push(c.clone()));
8227 assert_item_labels(&pane, ["AB^", "C*^"], cx);
8228
8229 pane.update_in(cx, |pane, window, cx| {
8230 pane.close_all_items(
8231 &CloseAllItems {
8232 save_intent: Some(SaveIntent::Save),
8233 close_pinned: false,
8234 },
8235 window,
8236 cx,
8237 )
8238 })
8239 .await
8240 .unwrap();
8241
8242 assert_item_labels(&pane, [], cx);
8243 cx.update(|_, cx| {
8244 assert!(!a.read(cx).is_dirty);
8245 assert!(!b.read(cx).is_dirty);
8246 assert!(!c.read(cx).is_dirty);
8247 });
8248 }
8249
8250 #[gpui::test]
8251 async fn test_new_tab_scrolls_into_view_completely(cx: &mut TestAppContext) {
8252 // Arrange
8253 init_test(cx);
8254 let fs = FakeFs::new(cx.executor());
8255
8256 let project = Project::test(fs, None, cx).await;
8257 let (workspace, cx) =
8258 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8259 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8260
8261 cx.simulate_resize(size(px(300.), px(300.)));
8262
8263 add_labeled_item(&pane, "untitled", false, cx);
8264 add_labeled_item(&pane, "untitled", false, cx);
8265 add_labeled_item(&pane, "untitled", false, cx);
8266 add_labeled_item(&pane, "untitled", false, cx);
8267 // Act: this should trigger a scroll
8268 add_labeled_item(&pane, "untitled", false, cx);
8269 // Assert
8270 let tab_bar_scroll_handle =
8271 pane.update_in(cx, |pane, _window, _cx| pane.tab_bar_scroll_handle.clone());
8272 assert_eq!(tab_bar_scroll_handle.children_count(), 6);
8273 let tab_bounds = cx.debug_bounds("TAB-4").unwrap();
8274 let new_tab_button_bounds = cx.debug_bounds("ICON-Plus").unwrap();
8275 let scroll_bounds = tab_bar_scroll_handle.bounds();
8276 let scroll_offset = tab_bar_scroll_handle.offset();
8277 assert!(tab_bounds.right() <= scroll_bounds.right());
8278 // -39.5 is the magic number for this setup
8279 assert_eq!(scroll_offset.x, px(-39.5));
8280 assert!(
8281 !tab_bounds.intersects(&new_tab_button_bounds),
8282 "Tab should not overlap with the new tab button, if this is failing check if there's been a redesign!"
8283 );
8284 }
8285
8286 #[gpui::test]
8287 async fn test_pinned_tabs_scroll_to_item_uses_correct_index(cx: &mut TestAppContext) {
8288 init_test(cx);
8289 let fs = FakeFs::new(cx.executor());
8290
8291 let project = Project::test(fs, None, cx).await;
8292 let (workspace, cx) =
8293 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8294 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8295
8296 cx.simulate_resize(size(px(400.), px(300.)));
8297
8298 for label in ["A", "B", "C"] {
8299 add_labeled_item(&pane, label, false, cx);
8300 }
8301
8302 pane.update_in(cx, |pane, window, cx| {
8303 pane.pin_tab_at(0, window, cx);
8304 pane.pin_tab_at(1, window, cx);
8305 pane.pin_tab_at(2, window, cx);
8306 });
8307
8308 for label in ["D", "E", "F", "G", "H", "I", "J", "K"] {
8309 add_labeled_item(&pane, label, false, cx);
8310 }
8311
8312 assert_item_labels(
8313 &pane,
8314 ["A!", "B!", "C!", "D", "E", "F", "G", "H", "I", "J", "K*"],
8315 cx,
8316 );
8317
8318 cx.run_until_parked();
8319
8320 // Verify overflow exists (precondition for scroll test)
8321 let scroll_handle =
8322 pane.update_in(cx, |pane, _window, _cx| pane.tab_bar_scroll_handle.clone());
8323 assert!(
8324 scroll_handle.max_offset().x > px(0.),
8325 "Test requires tab overflow to verify scrolling. Increase tab count or reduce window width."
8326 );
8327
8328 // Activate a different tab first, then activate K
8329 // This ensures we're not just re-activating an already-active tab
8330 pane.update_in(cx, |pane, window, cx| {
8331 pane.activate_item(3, true, true, window, cx);
8332 });
8333 cx.run_until_parked();
8334
8335 pane.update_in(cx, |pane, window, cx| {
8336 pane.activate_item(10, true, true, window, cx);
8337 });
8338 cx.run_until_parked();
8339
8340 let scroll_handle =
8341 pane.update_in(cx, |pane, _window, _cx| pane.tab_bar_scroll_handle.clone());
8342 let k_tab_bounds = cx.debug_bounds("TAB-10").unwrap();
8343 let scroll_bounds = scroll_handle.bounds();
8344
8345 assert!(
8346 k_tab_bounds.left() >= scroll_bounds.left(),
8347 "Active tab K should be scrolled into view"
8348 );
8349 }
8350
8351 #[gpui::test]
8352 async fn test_close_all_items_including_pinned(cx: &mut TestAppContext) {
8353 init_test(cx);
8354 let fs = FakeFs::new(cx.executor());
8355
8356 let project = Project::test(fs, None, cx).await;
8357 let (workspace, cx) =
8358 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8359 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8360
8361 let item_a = add_labeled_item(&pane, "A", false, cx);
8362 add_labeled_item(&pane, "B", false, cx);
8363 add_labeled_item(&pane, "C", false, cx);
8364 assert_item_labels(&pane, ["A", "B", "C*"], cx);
8365
8366 pane.update_in(cx, |pane, window, cx| {
8367 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
8368 pane.pin_tab_at(ix, window, cx);
8369 pane.close_all_items(
8370 &CloseAllItems {
8371 save_intent: None,
8372 close_pinned: true,
8373 },
8374 window,
8375 cx,
8376 )
8377 })
8378 .await
8379 .unwrap();
8380 assert_item_labels(&pane, [], cx);
8381 }
8382
8383 #[gpui::test]
8384 async fn test_close_pinned_tab_with_non_pinned_in_same_pane(cx: &mut TestAppContext) {
8385 init_test(cx);
8386 let fs = FakeFs::new(cx.executor());
8387 let project = Project::test(fs, None, cx).await;
8388 let (workspace, cx) =
8389 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8390
8391 // Non-pinned tabs in same pane
8392 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8393 add_labeled_item(&pane, "A", false, cx);
8394 add_labeled_item(&pane, "B", false, cx);
8395 add_labeled_item(&pane, "C", false, cx);
8396 pane.update_in(cx, |pane, window, cx| {
8397 pane.pin_tab_at(0, window, cx);
8398 });
8399 set_labeled_items(&pane, ["A*", "B", "C"], cx);
8400 pane.update_in(cx, |pane, window, cx| {
8401 pane.close_active_item(
8402 &CloseActiveItem {
8403 save_intent: None,
8404 close_pinned: false,
8405 },
8406 window,
8407 cx,
8408 )
8409 .unwrap();
8410 });
8411 // Non-pinned tab should be active
8412 assert_item_labels(&pane, ["A!", "B*", "C"], cx);
8413 }
8414
8415 #[gpui::test]
8416 async fn test_close_pinned_tab_with_non_pinned_in_different_pane(cx: &mut TestAppContext) {
8417 init_test(cx);
8418 let fs = FakeFs::new(cx.executor());
8419 let project = Project::test(fs, None, cx).await;
8420 let (workspace, cx) =
8421 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8422
8423 // No non-pinned tabs in same pane, non-pinned tabs in another pane
8424 let pane1 = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8425 let pane2 = workspace.update_in(cx, |workspace, window, cx| {
8426 workspace.split_pane(pane1.clone(), SplitDirection::Right, window, cx)
8427 });
8428 add_labeled_item(&pane1, "A", false, cx);
8429 pane1.update_in(cx, |pane, window, cx| {
8430 pane.pin_tab_at(0, window, cx);
8431 });
8432 set_labeled_items(&pane1, ["A*"], cx);
8433 add_labeled_item(&pane2, "B", false, cx);
8434 set_labeled_items(&pane2, ["B"], cx);
8435 pane1.update_in(cx, |pane, window, cx| {
8436 pane.close_active_item(
8437 &CloseActiveItem {
8438 save_intent: None,
8439 close_pinned: false,
8440 },
8441 window,
8442 cx,
8443 )
8444 .unwrap();
8445 });
8446 // Non-pinned tab of other pane should be active
8447 assert_item_labels(&pane2, ["B*"], cx);
8448 }
8449
8450 #[gpui::test]
8451 async fn ensure_item_closing_actions_do_not_panic_when_no_items_exist(cx: &mut TestAppContext) {
8452 init_test(cx);
8453 let fs = FakeFs::new(cx.executor());
8454 let project = Project::test(fs, None, cx).await;
8455 let (workspace, cx) =
8456 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8457
8458 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8459 assert_item_labels(&pane, [], cx);
8460
8461 pane.update_in(cx, |pane, window, cx| {
8462 pane.close_active_item(
8463 &CloseActiveItem {
8464 save_intent: None,
8465 close_pinned: false,
8466 },
8467 window,
8468 cx,
8469 )
8470 })
8471 .await
8472 .unwrap();
8473
8474 pane.update_in(cx, |pane, window, cx| {
8475 pane.close_other_items(
8476 &CloseOtherItems {
8477 save_intent: None,
8478 close_pinned: false,
8479 },
8480 None,
8481 window,
8482 cx,
8483 )
8484 })
8485 .await
8486 .unwrap();
8487
8488 pane.update_in(cx, |pane, window, cx| {
8489 pane.close_all_items(
8490 &CloseAllItems {
8491 save_intent: None,
8492 close_pinned: false,
8493 },
8494 window,
8495 cx,
8496 )
8497 })
8498 .await
8499 .unwrap();
8500
8501 pane.update_in(cx, |pane, window, cx| {
8502 pane.close_clean_items(
8503 &CloseCleanItems {
8504 close_pinned: false,
8505 },
8506 window,
8507 cx,
8508 )
8509 })
8510 .await
8511 .unwrap();
8512
8513 pane.update_in(cx, |pane, window, cx| {
8514 pane.close_items_to_the_right_by_id(
8515 None,
8516 &CloseItemsToTheRight {
8517 close_pinned: false,
8518 },
8519 window,
8520 cx,
8521 )
8522 })
8523 .await
8524 .unwrap();
8525
8526 pane.update_in(cx, |pane, window, cx| {
8527 pane.close_items_to_the_left_by_id(
8528 None,
8529 &CloseItemsToTheLeft {
8530 close_pinned: false,
8531 },
8532 window,
8533 cx,
8534 )
8535 })
8536 .await
8537 .unwrap();
8538 }
8539
8540 #[gpui::test]
8541 async fn test_item_swapping_actions(cx: &mut TestAppContext) {
8542 init_test(cx);
8543 let fs = FakeFs::new(cx.executor());
8544 let project = Project::test(fs, None, cx).await;
8545 let (workspace, cx) =
8546 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8547
8548 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8549 assert_item_labels(&pane, [], cx);
8550
8551 // Test that these actions do not panic
8552 pane.update_in(cx, |pane, window, cx| {
8553 pane.swap_item_right(&Default::default(), window, cx);
8554 });
8555
8556 pane.update_in(cx, |pane, window, cx| {
8557 pane.swap_item_left(&Default::default(), window, cx);
8558 });
8559
8560 add_labeled_item(&pane, "A", false, cx);
8561 add_labeled_item(&pane, "B", false, cx);
8562 add_labeled_item(&pane, "C", false, cx);
8563 assert_item_labels(&pane, ["A", "B", "C*"], cx);
8564
8565 pane.update_in(cx, |pane, window, cx| {
8566 pane.swap_item_right(&Default::default(), window, cx);
8567 });
8568 assert_item_labels(&pane, ["A", "B", "C*"], cx);
8569
8570 pane.update_in(cx, |pane, window, cx| {
8571 pane.swap_item_left(&Default::default(), window, cx);
8572 });
8573 assert_item_labels(&pane, ["A", "C*", "B"], cx);
8574
8575 pane.update_in(cx, |pane, window, cx| {
8576 pane.swap_item_left(&Default::default(), window, cx);
8577 });
8578 assert_item_labels(&pane, ["C*", "A", "B"], cx);
8579
8580 pane.update_in(cx, |pane, window, cx| {
8581 pane.swap_item_left(&Default::default(), window, cx);
8582 });
8583 assert_item_labels(&pane, ["C*", "A", "B"], cx);
8584
8585 pane.update_in(cx, |pane, window, cx| {
8586 pane.swap_item_right(&Default::default(), window, cx);
8587 });
8588 assert_item_labels(&pane, ["A", "C*", "B"], cx);
8589 }
8590
8591 #[gpui::test]
8592 async fn test_split_empty(cx: &mut TestAppContext) {
8593 for split_direction in SplitDirection::all() {
8594 test_single_pane_split(["A"], split_direction, SplitMode::EmptyPane, cx).await;
8595 }
8596 }
8597
8598 #[gpui::test]
8599 async fn test_split_clone(cx: &mut TestAppContext) {
8600 for split_direction in SplitDirection::all() {
8601 test_single_pane_split(["A"], split_direction, SplitMode::ClonePane, cx).await;
8602 }
8603 }
8604
8605 #[gpui::test]
8606 async fn test_split_move_right_on_single_pane(cx: &mut TestAppContext) {
8607 test_single_pane_split(["A"], SplitDirection::Right, SplitMode::MovePane, cx).await;
8608 }
8609
8610 #[gpui::test]
8611 async fn test_split_move(cx: &mut TestAppContext) {
8612 for split_direction in SplitDirection::all() {
8613 test_single_pane_split(["A", "B"], split_direction, SplitMode::MovePane, cx).await;
8614 }
8615 }
8616
8617 #[gpui::test]
8618 async fn test_reopening_closed_item_after_unpreview(cx: &mut TestAppContext) {
8619 init_test(cx);
8620
8621 cx.update_global::<SettingsStore, ()>(|store, cx| {
8622 store.update_user_settings(cx, |settings| {
8623 settings.preview_tabs.get_or_insert_default().enabled = Some(true);
8624 });
8625 });
8626
8627 let fs = FakeFs::new(cx.executor());
8628 let project = Project::test(fs, None, cx).await;
8629 let (workspace, cx) =
8630 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8631 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8632
8633 // Add an item as preview
8634 let item = pane.update_in(cx, |pane, window, cx| {
8635 let item = Box::new(cx.new(|cx| TestItem::new(cx).with_label("A")));
8636 pane.add_item(item.clone(), true, true, None, window, cx);
8637 pane.set_preview_item_id(Some(item.item_id()), cx);
8638 item
8639 });
8640
8641 // Verify item is preview
8642 pane.read_with(cx, |pane, _| {
8643 assert_eq!(pane.preview_item_id(), Some(item.item_id()));
8644 });
8645
8646 // Unpreview the item
8647 pane.update_in(cx, |pane, _window, _cx| {
8648 pane.unpreview_item_if_preview(item.item_id());
8649 });
8650
8651 // Verify item is no longer preview
8652 pane.read_with(cx, |pane, _| {
8653 assert_eq!(pane.preview_item_id(), None);
8654 });
8655
8656 // Close the item
8657 pane.update_in(cx, |pane, window, cx| {
8658 pane.close_item_by_id(item.item_id(), SaveIntent::Skip, window, cx)
8659 .detach_and_log_err(cx);
8660 });
8661
8662 cx.run_until_parked();
8663
8664 // The item should be in the closed_stack and reopenable
8665 let has_closed_items = pane.read_with(cx, |pane, _| {
8666 !pane.nav_history.0.lock().closed_stack.is_empty()
8667 });
8668 assert!(
8669 has_closed_items,
8670 "closed item should be in closed_stack and reopenable"
8671 );
8672 }
8673
8674 #[gpui::test]
8675 async fn test_activate_item_with_wrap_around(cx: &mut TestAppContext) {
8676 init_test(cx);
8677 let fs = FakeFs::new(cx.executor());
8678 let project = Project::test(fs, None, cx).await;
8679 let (workspace, cx) =
8680 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
8681 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8682
8683 add_labeled_item(&pane, "A", false, cx);
8684 add_labeled_item(&pane, "B", false, cx);
8685 add_labeled_item(&pane, "C", false, cx);
8686 assert_item_labels(&pane, ["A", "B", "C*"], cx);
8687
8688 pane.update_in(cx, |pane, window, cx| {
8689 pane.activate_next_item(&ActivateNextItem { wrap_around: false }, window, cx);
8690 });
8691 assert_item_labels(&pane, ["A", "B", "C*"], cx);
8692
8693 pane.update_in(cx, |pane, window, cx| {
8694 pane.activate_next_item(&ActivateNextItem::default(), window, cx);
8695 });
8696 assert_item_labels(&pane, ["A*", "B", "C"], cx);
8697
8698 pane.update_in(cx, |pane, window, cx| {
8699 pane.activate_previous_item(&ActivatePreviousItem { wrap_around: false }, window, cx);
8700 });
8701 assert_item_labels(&pane, ["A*", "B", "C"], cx);
8702
8703 pane.update_in(cx, |pane, window, cx| {
8704 pane.activate_previous_item(&ActivatePreviousItem::default(), window, cx);
8705 });
8706 assert_item_labels(&pane, ["A", "B", "C*"], cx);
8707
8708 pane.update_in(cx, |pane, window, cx| {
8709 pane.activate_previous_item(&ActivatePreviousItem { wrap_around: false }, window, cx);
8710 });
8711 assert_item_labels(&pane, ["A", "B*", "C"], cx);
8712
8713 pane.update_in(cx, |pane, window, cx| {
8714 pane.activate_next_item(&ActivateNextItem { wrap_around: false }, window, cx);
8715 });
8716 assert_item_labels(&pane, ["A", "B", "C*"], cx);
8717 }
8718
8719 fn init_test(cx: &mut TestAppContext) {
8720 cx.update(|cx| {
8721 let settings_store = SettingsStore::test(cx);
8722 cx.set_global(settings_store);
8723 theme_settings::init(LoadThemes::JustBase, cx);
8724 });
8725 }
8726
8727 fn set_max_tabs(cx: &mut TestAppContext, value: Option<usize>) {
8728 cx.update_global(|store: &mut SettingsStore, cx| {
8729 store.update_user_settings(cx, |settings| {
8730 settings.workspace.max_tabs = value.map(|v| NonZero::new(v).unwrap())
8731 });
8732 });
8733 }
8734
8735 fn set_pinned_tabs_separate_row(cx: &mut TestAppContext, enabled: bool) {
8736 cx.update_global(|store: &mut SettingsStore, cx| {
8737 store.update_user_settings(cx, |settings| {
8738 settings
8739 .tab_bar
8740 .get_or_insert_default()
8741 .show_pinned_tabs_in_separate_row = Some(enabled);
8742 });
8743 });
8744 }
8745
8746 fn add_labeled_item(
8747 pane: &Entity<Pane>,
8748 label: &str,
8749 is_dirty: bool,
8750 cx: &mut VisualTestContext,
8751 ) -> Box<Entity<TestItem>> {
8752 pane.update_in(cx, |pane, window, cx| {
8753 let labeled_item =
8754 Box::new(cx.new(|cx| TestItem::new(cx).with_label(label).with_dirty(is_dirty)));
8755 pane.add_item(labeled_item.clone(), false, false, None, window, cx);
8756 labeled_item
8757 })
8758 }
8759
8760 fn set_labeled_items<const COUNT: usize>(
8761 pane: &Entity<Pane>,
8762 labels: [&str; COUNT],
8763 cx: &mut VisualTestContext,
8764 ) -> [Box<Entity<TestItem>>; COUNT] {
8765 pane.update_in(cx, |pane, window, cx| {
8766 pane.items.clear();
8767 let mut active_item_index = 0;
8768
8769 let mut index = 0;
8770 let items = labels.map(|mut label| {
8771 if label.ends_with('*') {
8772 label = label.trim_end_matches('*');
8773 active_item_index = index;
8774 }
8775
8776 let labeled_item = Box::new(cx.new(|cx| TestItem::new(cx).with_label(label)));
8777 pane.add_item(labeled_item.clone(), false, false, None, window, cx);
8778 index += 1;
8779 labeled_item
8780 });
8781
8782 pane.activate_item(active_item_index, false, false, window, cx);
8783
8784 items
8785 })
8786 }
8787
8788 // Assert the item label, with the active item label suffixed with a '*'
8789 #[track_caller]
8790 fn assert_item_labels<const COUNT: usize>(
8791 pane: &Entity<Pane>,
8792 expected_states: [&str; COUNT],
8793 cx: &mut VisualTestContext,
8794 ) {
8795 let actual_states = pane.update(cx, |pane, cx| {
8796 pane.items
8797 .iter()
8798 .enumerate()
8799 .map(|(ix, item)| {
8800 let mut state = item
8801 .to_any_view()
8802 .downcast::<TestItem>()
8803 .unwrap()
8804 .read(cx)
8805 .label
8806 .clone();
8807 if ix == pane.active_item_index {
8808 state.push('*');
8809 }
8810 if item.is_dirty(cx) {
8811 state.push('^');
8812 }
8813 if pane.is_tab_pinned(ix) {
8814 state.push('!');
8815 }
8816 state
8817 })
8818 .collect::<Vec<_>>()
8819 });
8820 assert_eq!(
8821 actual_states, expected_states,
8822 "pane items do not match expectation"
8823 );
8824 }
8825
8826 // Assert the item label, with the active item label expected active index
8827 #[track_caller]
8828 fn assert_item_labels_active_index(
8829 pane: &Entity<Pane>,
8830 expected_states: &[&str],
8831 expected_active_idx: usize,
8832 cx: &mut VisualTestContext,
8833 ) {
8834 let actual_states = pane.update(cx, |pane, cx| {
8835 pane.items
8836 .iter()
8837 .enumerate()
8838 .map(|(ix, item)| {
8839 let mut state = item
8840 .to_any_view()
8841 .downcast::<TestItem>()
8842 .unwrap()
8843 .read(cx)
8844 .label
8845 .clone();
8846 if ix == pane.active_item_index {
8847 assert_eq!(ix, expected_active_idx);
8848 }
8849 if item.is_dirty(cx) {
8850 state.push('^');
8851 }
8852 if pane.is_tab_pinned(ix) {
8853 state.push('!');
8854 }
8855 state
8856 })
8857 .collect::<Vec<_>>()
8858 });
8859 assert_eq!(
8860 actual_states, expected_states,
8861 "pane items do not match expectation"
8862 );
8863 }
8864
8865 #[track_caller]
8866 fn assert_pane_ids_on_axis<const COUNT: usize>(
8867 workspace: &Entity<Workspace>,
8868 expected_ids: [&EntityId; COUNT],
8869 expected_axis: Axis,
8870 cx: &mut VisualTestContext,
8871 ) {
8872 workspace.read_with(cx, |workspace, _| match &workspace.center.root {
8873 Member::Axis(axis) => {
8874 assert_eq!(axis.axis, expected_axis);
8875 assert_eq!(axis.members.len(), expected_ids.len());
8876 assert!(
8877 zip(expected_ids, &axis.members).all(|(e, a)| {
8878 if let Member::Pane(p) = a {
8879 p.entity_id() == *e
8880 } else {
8881 false
8882 }
8883 }),
8884 "pane ids do not match expectation: {expected_ids:?} != {actual_ids:?}",
8885 actual_ids = axis.members
8886 );
8887 }
8888 Member::Pane(_) => panic!("expected axis"),
8889 });
8890 }
8891
8892 async fn test_single_pane_split<const COUNT: usize>(
8893 pane_labels: [&str; COUNT],
8894 direction: SplitDirection,
8895 operation: SplitMode,
8896 cx: &mut TestAppContext,
8897 ) {
8898 init_test(cx);
8899 let fs = FakeFs::new(cx.executor());
8900 let project = Project::test(fs, None, cx).await;
8901 let (workspace, cx) =
8902 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
8903
8904 let mut pane_before =
8905 workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8906 for label in pane_labels {
8907 add_labeled_item(&pane_before, label, false, cx);
8908 }
8909 pane_before.update_in(cx, |pane, window, cx| {
8910 pane.split(direction, operation, window, cx)
8911 });
8912 cx.executor().run_until_parked();
8913 let pane_after = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
8914
8915 let num_labels = pane_labels.len();
8916 let last_as_active = format!("{}*", String::from(pane_labels[num_labels - 1]));
8917
8918 // check labels for all split operations
8919 match operation {
8920 SplitMode::EmptyPane => {
8921 assert_item_labels_active_index(&pane_before, &pane_labels, num_labels - 1, cx);
8922 assert_item_labels(&pane_after, [], cx);
8923 }
8924 SplitMode::ClonePane => {
8925 assert_item_labels_active_index(&pane_before, &pane_labels, num_labels - 1, cx);
8926 assert_item_labels(&pane_after, [&last_as_active], cx);
8927 }
8928 SplitMode::MovePane => {
8929 let head = &pane_labels[..(num_labels - 1)];
8930 if num_labels == 1 {
8931 // We special-case this behavior and actually execute an empty pane command
8932 // followed by a refocus of the old pane for this case.
8933 pane_before = workspace.read_with(cx, |workspace, _cx| {
8934 workspace
8935 .panes()
8936 .into_iter()
8937 .find(|pane| *pane != &pane_after)
8938 .unwrap()
8939 .clone()
8940 });
8941 };
8942
8943 assert_item_labels_active_index(
8944 &pane_before,
8945 &head,
8946 head.len().saturating_sub(1),
8947 cx,
8948 );
8949 assert_item_labels(&pane_after, [&last_as_active], cx);
8950 pane_after.update_in(cx, |pane, window, cx| {
8951 window.focused(cx).is_some_and(|focus_handle| {
8952 focus_handle == pane.active_item().unwrap().item_focus_handle(cx)
8953 })
8954 });
8955 }
8956 }
8957
8958 // expected axis depends on split direction
8959 let expected_axis = match direction {
8960 SplitDirection::Right | SplitDirection::Left => Axis::Horizontal,
8961 SplitDirection::Up | SplitDirection::Down => Axis::Vertical,
8962 };
8963
8964 // expected ids depends on split direction
8965 let expected_ids = match direction {
8966 SplitDirection::Right | SplitDirection::Down => {
8967 [&pane_before.entity_id(), &pane_after.entity_id()]
8968 }
8969 SplitDirection::Left | SplitDirection::Up => {
8970 [&pane_after.entity_id(), &pane_before.entity_id()]
8971 }
8972 };
8973
8974 // check pane axes for all operations
8975 match operation {
8976 SplitMode::EmptyPane | SplitMode::ClonePane => {
8977 assert_pane_ids_on_axis(&workspace, expected_ids, expected_axis, cx);
8978 }
8979 SplitMode::MovePane => {
8980 assert_pane_ids_on_axis(&workspace, expected_ids, expected_axis, cx);
8981 }
8982 }
8983 }
8984}