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