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