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