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