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