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::{Capability, 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 self.unpreview_item_if_preview(active_item_id);
1566
1567 let pinned_item_ids = self.pinned_item_ids();
1568
1569 self.close_items(
1570 window,
1571 cx,
1572 action.save_intent.unwrap_or(SaveIntent::Close),
1573 move |item_id| {
1574 item_id != active_item_id
1575 && (action.close_pinned || !pinned_item_ids.contains(&item_id))
1576 },
1577 )
1578 }
1579
1580 pub fn close_multibuffer_items(
1581 &mut self,
1582 action: &CloseMultibufferItems,
1583 window: &mut Window,
1584 cx: &mut Context<Self>,
1585 ) -> Task<Result<()>> {
1586 if self.items.is_empty() {
1587 return Task::ready(Ok(()));
1588 }
1589
1590 let pinned_item_ids = self.pinned_item_ids();
1591 let multibuffer_items = self.multibuffer_item_ids(cx);
1592
1593 self.close_items(
1594 window,
1595 cx,
1596 action.save_intent.unwrap_or(SaveIntent::Close),
1597 move |item_id| {
1598 (action.close_pinned || !pinned_item_ids.contains(&item_id))
1599 && multibuffer_items.contains(&item_id)
1600 },
1601 )
1602 }
1603
1604 pub fn close_clean_items(
1605 &mut self,
1606 action: &CloseCleanItems,
1607 window: &mut Window,
1608 cx: &mut Context<Self>,
1609 ) -> Task<Result<()>> {
1610 if self.items.is_empty() {
1611 return Task::ready(Ok(()));
1612 }
1613
1614 let clean_item_ids = self.clean_item_ids(cx);
1615 let pinned_item_ids = self.pinned_item_ids();
1616
1617 self.close_items(window, cx, SaveIntent::Close, move |item_id| {
1618 clean_item_ids.contains(&item_id)
1619 && (action.close_pinned || !pinned_item_ids.contains(&item_id))
1620 })
1621 }
1622
1623 pub fn close_items_to_the_left_by_id(
1624 &mut self,
1625 item_id: Option<EntityId>,
1626 action: &CloseItemsToTheLeft,
1627 window: &mut Window,
1628 cx: &mut Context<Self>,
1629 ) -> Task<Result<()>> {
1630 self.close_items_to_the_side_by_id(item_id, Side::Left, action.close_pinned, window, cx)
1631 }
1632
1633 pub fn close_items_to_the_right_by_id(
1634 &mut self,
1635 item_id: Option<EntityId>,
1636 action: &CloseItemsToTheRight,
1637 window: &mut Window,
1638 cx: &mut Context<Self>,
1639 ) -> Task<Result<()>> {
1640 self.close_items_to_the_side_by_id(item_id, Side::Right, action.close_pinned, window, cx)
1641 }
1642
1643 pub fn close_items_to_the_side_by_id(
1644 &mut self,
1645 item_id: Option<EntityId>,
1646 side: Side,
1647 close_pinned: bool,
1648 window: &mut Window,
1649 cx: &mut Context<Self>,
1650 ) -> Task<Result<()>> {
1651 if self.items.is_empty() {
1652 return Task::ready(Ok(()));
1653 }
1654
1655 let item_id = item_id.unwrap_or_else(|| self.active_item_id());
1656 let to_the_side_item_ids = self.to_the_side_item_ids(item_id, side);
1657 let pinned_item_ids = self.pinned_item_ids();
1658
1659 self.close_items(window, cx, SaveIntent::Close, move |item_id| {
1660 to_the_side_item_ids.contains(&item_id)
1661 && (close_pinned || !pinned_item_ids.contains(&item_id))
1662 })
1663 }
1664
1665 pub fn close_all_items(
1666 &mut self,
1667 action: &CloseAllItems,
1668 window: &mut Window,
1669 cx: &mut Context<Self>,
1670 ) -> Task<Result<()>> {
1671 if self.items.is_empty() {
1672 return Task::ready(Ok(()));
1673 }
1674
1675 let pinned_item_ids = self.pinned_item_ids();
1676
1677 self.close_items(
1678 window,
1679 cx,
1680 action.save_intent.unwrap_or(SaveIntent::Close),
1681 |item_id| action.close_pinned || !pinned_item_ids.contains(&item_id),
1682 )
1683 }
1684
1685 fn close_items_on_item_open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1686 let target = self.max_tabs.map(|m| m.get());
1687 let protect_active_item = false;
1688 self.close_items_to_target_count(target, protect_active_item, window, cx);
1689 }
1690
1691 fn close_items_on_settings_change(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1692 let target = self.max_tabs.map(|m| m.get() + 1);
1693 // The active item in this case is the settings.json file, which should be protected from being closed
1694 let protect_active_item = true;
1695 self.close_items_to_target_count(target, protect_active_item, window, cx);
1696 }
1697
1698 fn close_items_to_target_count(
1699 &mut self,
1700 target_count: Option<usize>,
1701 protect_active_item: bool,
1702 window: &mut Window,
1703 cx: &mut Context<Self>,
1704 ) {
1705 let Some(target_count) = target_count else {
1706 return;
1707 };
1708
1709 let mut index_list = Vec::new();
1710 let mut items_len = self.items_len();
1711 let mut indexes: HashMap<EntityId, usize> = HashMap::default();
1712 let active_ix = self.active_item_index();
1713
1714 for (index, item) in self.items.iter().enumerate() {
1715 indexes.insert(item.item_id(), index);
1716 }
1717
1718 // Close least recently used items to reach target count.
1719 // The target count is allowed to be exceeded, as we protect pinned
1720 // items, dirty items, and sometimes, the active item.
1721 for entry in self.activation_history.iter() {
1722 if items_len < target_count {
1723 break;
1724 }
1725
1726 let Some(&index) = indexes.get(&entry.entity_id) else {
1727 continue;
1728 };
1729
1730 if protect_active_item && index == active_ix {
1731 continue;
1732 }
1733
1734 if let Some(true) = self.items.get(index).map(|item| item.is_dirty(cx)) {
1735 continue;
1736 }
1737
1738 if self.is_tab_pinned(index) {
1739 continue;
1740 }
1741
1742 index_list.push(index);
1743 items_len -= 1;
1744 }
1745 // The sort and reverse is necessary since we remove items
1746 // using their index position, hence removing from the end
1747 // of the list first to avoid changing indexes.
1748 index_list.sort_unstable();
1749 index_list
1750 .iter()
1751 .rev()
1752 .for_each(|&index| self._remove_item(index, false, false, None, window, cx));
1753 }
1754
1755 // Usually when you close an item that has unsaved changes, we prompt you to
1756 // save it. That said, if you still have the buffer open in a different pane
1757 // we can close this one without fear of losing data.
1758 pub fn skip_save_on_close(item: &dyn ItemHandle, workspace: &Workspace, cx: &App) -> bool {
1759 let mut dirty_project_item_ids = Vec::new();
1760 item.for_each_project_item(cx, &mut |project_item_id, project_item| {
1761 if project_item.is_dirty() {
1762 dirty_project_item_ids.push(project_item_id);
1763 }
1764 });
1765 if dirty_project_item_ids.is_empty() {
1766 return !(item.buffer_kind(cx) == ItemBufferKind::Singleton && item.is_dirty(cx));
1767 }
1768
1769 for open_item in workspace.items(cx) {
1770 if open_item.item_id() == item.item_id() {
1771 continue;
1772 }
1773 if open_item.buffer_kind(cx) != ItemBufferKind::Singleton {
1774 continue;
1775 }
1776 let other_project_item_ids = open_item.project_item_model_ids(cx);
1777 dirty_project_item_ids.retain(|id| !other_project_item_ids.contains(id));
1778 }
1779 dirty_project_item_ids.is_empty()
1780 }
1781
1782 pub(super) fn file_names_for_prompt(
1783 items: &mut dyn Iterator<Item = &Box<dyn ItemHandle>>,
1784 cx: &App,
1785 ) -> String {
1786 let mut file_names = BTreeSet::default();
1787 for item in items {
1788 item.for_each_project_item(cx, &mut |_, project_item| {
1789 if !project_item.is_dirty() {
1790 return;
1791 }
1792 let filename = project_item
1793 .project_path(cx)
1794 .and_then(|path| path.path.file_name().map(ToOwned::to_owned));
1795 file_names.insert(filename.unwrap_or("untitled".to_string()));
1796 });
1797 }
1798 if file_names.len() > 6 {
1799 format!(
1800 "{}\n.. and {} more",
1801 file_names.iter().take(5).join("\n"),
1802 file_names.len() - 5
1803 )
1804 } else {
1805 file_names.into_iter().join("\n")
1806 }
1807 }
1808
1809 pub fn close_items(
1810 &self,
1811 window: &mut Window,
1812 cx: &mut Context<Pane>,
1813 mut save_intent: SaveIntent,
1814 should_close: impl Fn(EntityId) -> bool,
1815 ) -> Task<Result<()>> {
1816 // Find the items to close.
1817 let mut items_to_close = Vec::new();
1818 for item in &self.items {
1819 if should_close(item.item_id()) {
1820 items_to_close.push(item.boxed_clone());
1821 }
1822 }
1823
1824 let active_item_id = self.active_item().map(|item| item.item_id());
1825
1826 items_to_close.sort_by_key(|item| {
1827 let path = item.project_path(cx);
1828 // Put the currently active item at the end, because if the currently active item is not closed last
1829 // closing the currently active item will cause the focus to switch to another item
1830 // This will cause Zed to expand the content of the currently active item
1831 //
1832 // Beyond that sort in order of project path, with untitled files and multibuffers coming last.
1833 (active_item_id == Some(item.item_id()), path.is_none(), path)
1834 });
1835
1836 let workspace = self.workspace.clone();
1837 let Some(project) = self.project.upgrade() else {
1838 return Task::ready(Ok(()));
1839 };
1840 cx.spawn_in(window, async move |pane, cx| {
1841 let dirty_items = workspace.update(cx, |workspace, cx| {
1842 items_to_close
1843 .iter()
1844 .filter(|item| {
1845 item.is_dirty(cx) && !Self::skip_save_on_close(item.as_ref(), workspace, cx)
1846 })
1847 .map(|item| item.boxed_clone())
1848 .collect::<Vec<_>>()
1849 })?;
1850
1851 if save_intent == SaveIntent::Close && dirty_items.len() > 1 {
1852 let answer = pane.update_in(cx, |_, window, cx| {
1853 let detail = Self::file_names_for_prompt(&mut dirty_items.iter(), cx);
1854 window.prompt(
1855 PromptLevel::Warning,
1856 "Do you want to save changes to the following files?",
1857 Some(&detail),
1858 &["Save all", "Discard all", "Cancel"],
1859 cx,
1860 )
1861 })?;
1862 match answer.await {
1863 Ok(0) => save_intent = SaveIntent::SaveAll,
1864 Ok(1) => save_intent = SaveIntent::Skip,
1865 Ok(2) => return Ok(()),
1866 _ => {}
1867 }
1868 }
1869
1870 for item_to_close in items_to_close {
1871 let mut should_close = true;
1872 let mut should_save = true;
1873 if save_intent == SaveIntent::Close {
1874 workspace.update(cx, |workspace, cx| {
1875 if Self::skip_save_on_close(item_to_close.as_ref(), workspace, cx) {
1876 should_save = false;
1877 }
1878 })?;
1879 }
1880
1881 if should_save {
1882 match Self::save_item(project.clone(), &pane, &*item_to_close, save_intent, cx)
1883 .await
1884 {
1885 Ok(success) => {
1886 if !success {
1887 should_close = false;
1888 }
1889 }
1890 Err(err) => {
1891 let answer = pane.update_in(cx, |_, window, cx| {
1892 let detail = Self::file_names_for_prompt(
1893 &mut [&item_to_close].into_iter(),
1894 cx,
1895 );
1896 window.prompt(
1897 PromptLevel::Warning,
1898 &format!("Unable to save file: {}", &err),
1899 Some(&detail),
1900 &["Close Without Saving", "Cancel"],
1901 cx,
1902 )
1903 })?;
1904 match answer.await {
1905 Ok(0) => {}
1906 Ok(1..) | Err(_) => should_close = false,
1907 }
1908 }
1909 }
1910 }
1911
1912 // Remove the item from the pane.
1913 if should_close {
1914 pane.update_in(cx, |pane, window, cx| {
1915 pane.remove_item(
1916 item_to_close.item_id(),
1917 false,
1918 pane.close_pane_if_empty,
1919 window,
1920 cx,
1921 );
1922 })
1923 .ok();
1924 }
1925 }
1926
1927 pane.update(cx, |_, cx| cx.notify()).ok();
1928 Ok(())
1929 })
1930 }
1931
1932 pub fn take_active_item(
1933 &mut self,
1934 window: &mut Window,
1935 cx: &mut Context<Self>,
1936 ) -> Option<Box<dyn ItemHandle>> {
1937 let item = self.active_item()?;
1938 self.remove_item(item.item_id(), false, false, window, cx);
1939 Some(item)
1940 }
1941
1942 pub fn remove_item(
1943 &mut self,
1944 item_id: EntityId,
1945 activate_pane: bool,
1946 close_pane_if_empty: bool,
1947 window: &mut Window,
1948 cx: &mut Context<Self>,
1949 ) {
1950 let Some(item_index) = self.index_for_item_id(item_id) else {
1951 return;
1952 };
1953 self._remove_item(
1954 item_index,
1955 activate_pane,
1956 close_pane_if_empty,
1957 None,
1958 window,
1959 cx,
1960 )
1961 }
1962
1963 pub fn remove_item_and_focus_on_pane(
1964 &mut self,
1965 item_index: usize,
1966 activate_pane: bool,
1967 focus_on_pane_if_closed: Entity<Pane>,
1968 window: &mut Window,
1969 cx: &mut Context<Self>,
1970 ) {
1971 self._remove_item(
1972 item_index,
1973 activate_pane,
1974 true,
1975 Some(focus_on_pane_if_closed),
1976 window,
1977 cx,
1978 )
1979 }
1980
1981 fn _remove_item(
1982 &mut self,
1983 item_index: usize,
1984 activate_pane: bool,
1985 close_pane_if_empty: bool,
1986 focus_on_pane_if_closed: Option<Entity<Pane>>,
1987 window: &mut Window,
1988 cx: &mut Context<Self>,
1989 ) {
1990 let activate_on_close = &ItemSettings::get_global(cx).activate_on_close;
1991 self.activation_history
1992 .retain(|entry| entry.entity_id != self.items[item_index].item_id());
1993
1994 if self.is_tab_pinned(item_index) {
1995 self.pinned_tab_count -= 1;
1996 }
1997 if item_index == self.active_item_index {
1998 let left_neighbour_index = || item_index.min(self.items.len()).saturating_sub(1);
1999 let index_to_activate = match activate_on_close {
2000 ActivateOnClose::History => self
2001 .activation_history
2002 .pop()
2003 .and_then(|last_activated_item| {
2004 self.items.iter().enumerate().find_map(|(index, item)| {
2005 (item.item_id() == last_activated_item.entity_id).then_some(index)
2006 })
2007 })
2008 // We didn't have a valid activation history entry, so fallback
2009 // to activating the item to the left
2010 .unwrap_or_else(left_neighbour_index),
2011 ActivateOnClose::Neighbour => {
2012 self.activation_history.pop();
2013 if item_index + 1 < self.items.len() {
2014 item_index + 1
2015 } else {
2016 item_index.saturating_sub(1)
2017 }
2018 }
2019 ActivateOnClose::LeftNeighbour => {
2020 self.activation_history.pop();
2021 left_neighbour_index()
2022 }
2023 };
2024
2025 let should_activate = activate_pane || self.has_focus(window, cx);
2026 if self.items.len() == 1 && should_activate {
2027 self.focus_handle.focus(window, cx);
2028 } else {
2029 self.activate_item(
2030 index_to_activate,
2031 should_activate,
2032 should_activate,
2033 window,
2034 cx,
2035 );
2036 }
2037 }
2038
2039 let item = self.items.remove(item_index);
2040
2041 cx.emit(Event::RemovedItem { item: item.clone() });
2042 if self.items.is_empty() {
2043 item.deactivated(window, cx);
2044 if close_pane_if_empty {
2045 self.update_toolbar(window, cx);
2046 cx.emit(Event::Remove {
2047 focus_on_pane: focus_on_pane_if_closed,
2048 });
2049 }
2050 }
2051
2052 if item_index < self.active_item_index {
2053 self.active_item_index -= 1;
2054 }
2055
2056 let mode = self.nav_history.mode();
2057 self.nav_history.set_mode(NavigationMode::ClosingItem);
2058 item.deactivated(window, cx);
2059 item.on_removed(cx);
2060 self.nav_history.set_mode(mode);
2061
2062 self.unpreview_item_if_preview(item.item_id());
2063
2064 if let Some(path) = item.project_path(cx) {
2065 let abs_path = self
2066 .nav_history
2067 .0
2068 .lock()
2069 .paths_by_item
2070 .get(&item.item_id())
2071 .and_then(|(_, abs_path)| abs_path.clone());
2072
2073 self.nav_history
2074 .0
2075 .lock()
2076 .paths_by_item
2077 .insert(item.item_id(), (path, abs_path));
2078 } else {
2079 self.nav_history
2080 .0
2081 .lock()
2082 .paths_by_item
2083 .remove(&item.item_id());
2084 }
2085
2086 if self.zoom_out_on_close && self.items.is_empty() && close_pane_if_empty && self.zoomed {
2087 cx.emit(Event::ZoomOut);
2088 }
2089
2090 cx.notify();
2091 }
2092
2093 pub async fn save_item(
2094 project: Entity<Project>,
2095 pane: &WeakEntity<Pane>,
2096 item: &dyn ItemHandle,
2097 save_intent: SaveIntent,
2098 cx: &mut AsyncWindowContext,
2099 ) -> Result<bool> {
2100 const CONFLICT_MESSAGE: &str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
2101
2102 const DELETED_MESSAGE: &str = "This file has been deleted on disk since you started editing it. Do you want to recreate it?";
2103
2104 let path_style = project.read_with(cx, |project, cx| project.path_style(cx));
2105 if save_intent == SaveIntent::Skip {
2106 return Ok(true);
2107 };
2108 let Some(item_ix) = pane
2109 .read_with(cx, |pane, _| pane.index_for_item(item))
2110 .ok()
2111 .flatten()
2112 else {
2113 return Ok(true);
2114 };
2115
2116 let (
2117 mut has_conflict,
2118 mut is_dirty,
2119 mut can_save,
2120 can_save_as,
2121 is_singleton,
2122 has_deleted_file,
2123 ) = cx.update(|_window, cx| {
2124 (
2125 item.has_conflict(cx),
2126 item.is_dirty(cx),
2127 item.can_save(cx),
2128 item.can_save_as(cx),
2129 item.buffer_kind(cx) == ItemBufferKind::Singleton,
2130 item.has_deleted_file(cx),
2131 )
2132 })?;
2133
2134 // when saving a single buffer, we ignore whether or not it's dirty.
2135 if save_intent == SaveIntent::Save || save_intent == SaveIntent::SaveWithoutFormat {
2136 is_dirty = true;
2137 }
2138
2139 if save_intent == SaveIntent::SaveAs {
2140 is_dirty = true;
2141 has_conflict = false;
2142 can_save = false;
2143 }
2144
2145 if save_intent == SaveIntent::Overwrite {
2146 has_conflict = false;
2147 }
2148
2149 let should_format = save_intent != SaveIntent::SaveWithoutFormat;
2150
2151 if has_conflict && can_save {
2152 if has_deleted_file && is_singleton {
2153 let answer = pane.update_in(cx, |pane, window, cx| {
2154 pane.activate_item(item_ix, true, true, window, cx);
2155 window.prompt(
2156 PromptLevel::Warning,
2157 DELETED_MESSAGE,
2158 None,
2159 &["Save", "Close", "Cancel"],
2160 cx,
2161 )
2162 })?;
2163 match answer.await {
2164 Ok(0) => {
2165 pane.update_in(cx, |_, window, cx| {
2166 item.save(
2167 SaveOptions {
2168 format: should_format,
2169 autosave: false,
2170 },
2171 project,
2172 window,
2173 cx,
2174 )
2175 })?
2176 .await?
2177 }
2178 Ok(1) => {
2179 pane.update_in(cx, |pane, window, cx| {
2180 pane.remove_item(item.item_id(), false, true, window, cx)
2181 })?;
2182 }
2183 _ => return Ok(false),
2184 }
2185 return Ok(true);
2186 } else {
2187 let answer = pane.update_in(cx, |pane, window, cx| {
2188 pane.activate_item(item_ix, true, true, window, cx);
2189 window.prompt(
2190 PromptLevel::Warning,
2191 CONFLICT_MESSAGE,
2192 None,
2193 &["Overwrite", "Discard", "Cancel"],
2194 cx,
2195 )
2196 })?;
2197 match answer.await {
2198 Ok(0) => {
2199 pane.update_in(cx, |_, window, cx| {
2200 item.save(
2201 SaveOptions {
2202 format: should_format,
2203 autosave: false,
2204 },
2205 project,
2206 window,
2207 cx,
2208 )
2209 })?
2210 .await?
2211 }
2212 Ok(1) => {
2213 pane.update_in(cx, |_, window, cx| item.reload(project, window, cx))?
2214 .await?
2215 }
2216 _ => return Ok(false),
2217 }
2218 }
2219 } else if is_dirty && (can_save || can_save_as) {
2220 if save_intent == SaveIntent::Close {
2221 let will_autosave = cx.update(|_window, cx| {
2222 item.can_autosave(cx)
2223 && item.workspace_settings(cx).autosave.should_save_on_close()
2224 })?;
2225 if !will_autosave {
2226 let item_id = item.item_id();
2227 let answer_task = pane.update_in(cx, |pane, window, cx| {
2228 if pane.save_modals_spawned.insert(item_id) {
2229 pane.activate_item(item_ix, true, true, window, cx);
2230 let prompt = dirty_message_for(item.project_path(cx), path_style);
2231 Some(window.prompt(
2232 PromptLevel::Warning,
2233 &prompt,
2234 None,
2235 &["Save", "Don't Save", "Cancel"],
2236 cx,
2237 ))
2238 } else {
2239 None
2240 }
2241 })?;
2242 if let Some(answer_task) = answer_task {
2243 let answer = answer_task.await;
2244 pane.update(cx, |pane, _| {
2245 if !pane.save_modals_spawned.remove(&item_id) {
2246 debug_panic!(
2247 "save modal was not present in spawned modals after awaiting for its answer"
2248 )
2249 }
2250 })?;
2251 match answer {
2252 Ok(0) => {}
2253 Ok(1) => {
2254 // Don't save this file
2255 pane.update_in(cx, |pane, _, cx| {
2256 if pane.is_tab_pinned(item_ix) && !item.can_save(cx) {
2257 pane.pinned_tab_count -= 1;
2258 }
2259 })
2260 .log_err();
2261 return Ok(true);
2262 }
2263 _ => return Ok(false), // Cancel
2264 }
2265 } else {
2266 return Ok(false);
2267 }
2268 }
2269 }
2270
2271 if can_save {
2272 pane.update_in(cx, |pane, window, cx| {
2273 pane.unpreview_item_if_preview(item.item_id());
2274 item.save(
2275 SaveOptions {
2276 format: should_format,
2277 autosave: false,
2278 },
2279 project,
2280 window,
2281 cx,
2282 )
2283 })?
2284 .await?;
2285 } else if can_save_as && is_singleton {
2286 let suggested_name =
2287 cx.update(|_window, cx| item.suggested_filename(cx).to_string())?;
2288 let new_path = pane.update_in(cx, |pane, window, cx| {
2289 pane.activate_item(item_ix, true, true, window, cx);
2290 pane.workspace.update(cx, |workspace, cx| {
2291 let lister = if workspace.project().read(cx).is_local() {
2292 DirectoryLister::Local(
2293 workspace.project().clone(),
2294 workspace.app_state().fs.clone(),
2295 )
2296 } else {
2297 DirectoryLister::Project(workspace.project().clone())
2298 };
2299 workspace.prompt_for_new_path(lister, Some(suggested_name), window, cx)
2300 })
2301 })??;
2302 let Some(new_path) = new_path.await.ok().flatten().into_iter().flatten().next()
2303 else {
2304 return Ok(false);
2305 };
2306
2307 let project_path = pane
2308 .update(cx, |pane, cx| {
2309 pane.project
2310 .update(cx, |project, cx| {
2311 project.find_or_create_worktree(new_path, true, cx)
2312 })
2313 .ok()
2314 })
2315 .ok()
2316 .flatten();
2317 let save_task = if let Some(project_path) = project_path {
2318 let (worktree, path) = project_path.await?;
2319 let worktree_id = worktree.read_with(cx, |worktree, _| worktree.id());
2320 let new_path = ProjectPath { worktree_id, path };
2321
2322 pane.update_in(cx, |pane, window, cx| {
2323 if let Some(item) = pane.item_for_path(new_path.clone(), cx) {
2324 pane.remove_item(item.item_id(), false, false, window, cx);
2325 }
2326
2327 item.save_as(project, new_path, window, cx)
2328 })?
2329 } else {
2330 return Ok(false);
2331 };
2332
2333 save_task.await?;
2334 return Ok(true);
2335 }
2336 }
2337
2338 pane.update(cx, |_, cx| {
2339 cx.emit(Event::UserSavedItem {
2340 item: item.downgrade_item(),
2341 save_intent,
2342 });
2343 true
2344 })
2345 }
2346
2347 pub fn autosave_item(
2348 item: &dyn ItemHandle,
2349 project: Entity<Project>,
2350 window: &mut Window,
2351 cx: &mut App,
2352 ) -> Task<Result<()>> {
2353 let format = !matches!(
2354 item.workspace_settings(cx).autosave,
2355 AutosaveSetting::AfterDelay { .. }
2356 );
2357 if item.can_autosave(cx) {
2358 item.save(
2359 SaveOptions {
2360 format,
2361 autosave: true,
2362 },
2363 project,
2364 window,
2365 cx,
2366 )
2367 } else {
2368 Task::ready(Ok(()))
2369 }
2370 }
2371
2372 pub fn focus_active_item(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2373 if let Some(active_item) = self.active_item() {
2374 let focus_handle = active_item.item_focus_handle(cx);
2375 window.focus(&focus_handle, cx);
2376 }
2377 }
2378
2379 pub fn split(
2380 &mut self,
2381 direction: SplitDirection,
2382 mode: SplitMode,
2383 window: &mut Window,
2384 cx: &mut Context<Self>,
2385 ) {
2386 if self.items.len() <= 1 && mode == SplitMode::MovePane {
2387 // MovePane with only one pane present behaves like a SplitEmpty in the opposite direction
2388 let active_item = self.active_item();
2389 cx.emit(Event::Split {
2390 direction: direction.opposite(),
2391 mode: SplitMode::EmptyPane,
2392 });
2393 // ensure that we focus the moved pane
2394 // in this case we know that the window is the same as the active_item
2395 if let Some(active_item) = active_item {
2396 cx.defer_in(window, move |_, window, cx| {
2397 let focus_handle = active_item.item_focus_handle(cx);
2398 window.focus(&focus_handle, cx);
2399 });
2400 }
2401 } else {
2402 cx.emit(Event::Split { direction, mode });
2403 }
2404 }
2405
2406 pub fn toolbar(&self) -> &Entity<Toolbar> {
2407 &self.toolbar
2408 }
2409
2410 pub fn handle_deleted_project_item(
2411 &mut self,
2412 entry_id: ProjectEntryId,
2413 window: &mut Window,
2414 cx: &mut Context<Pane>,
2415 ) -> Option<()> {
2416 let item_id = self.items().find_map(|item| {
2417 if item.buffer_kind(cx) == ItemBufferKind::Singleton
2418 && item.project_entry_ids(cx).as_slice() == [entry_id]
2419 {
2420 Some(item.item_id())
2421 } else {
2422 None
2423 }
2424 })?;
2425
2426 self.remove_item(item_id, false, true, window, cx);
2427 self.nav_history.remove_item(item_id);
2428
2429 Some(())
2430 }
2431
2432 fn update_toolbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2433 let active_item = self
2434 .items
2435 .get(self.active_item_index)
2436 .map(|item| item.as_ref());
2437 self.toolbar.update(cx, |toolbar, cx| {
2438 toolbar.set_active_item(active_item, window, cx);
2439 });
2440 }
2441
2442 fn update_status_bar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2443 let workspace = self.workspace.clone();
2444 let pane = cx.entity();
2445
2446 window.defer(cx, move |window, cx| {
2447 let Ok(status_bar) =
2448 workspace.read_with(cx, |workspace, _| workspace.status_bar.clone())
2449 else {
2450 return;
2451 };
2452
2453 status_bar.update(cx, move |status_bar, cx| {
2454 status_bar.set_active_pane(&pane, window, cx);
2455 });
2456 });
2457 }
2458
2459 fn entry_abs_path(&self, entry: ProjectEntryId, cx: &App) -> Option<PathBuf> {
2460 let worktree = self
2461 .workspace
2462 .upgrade()?
2463 .read(cx)
2464 .project()
2465 .read(cx)
2466 .worktree_for_entry(entry, cx)?
2467 .read(cx);
2468 let entry = worktree.entry_for_id(entry)?;
2469 Some(match &entry.canonical_path {
2470 Some(canonical_path) => canonical_path.to_path_buf(),
2471 None => worktree.absolutize(&entry.path),
2472 })
2473 }
2474
2475 pub fn icon_color(selected: bool) -> Color {
2476 if selected {
2477 Color::Default
2478 } else {
2479 Color::Muted
2480 }
2481 }
2482
2483 fn toggle_pin_tab(&mut self, _: &TogglePinTab, window: &mut Window, cx: &mut Context<Self>) {
2484 if self.items.is_empty() {
2485 return;
2486 }
2487 let active_tab_ix = self.active_item_index();
2488 if self.is_tab_pinned(active_tab_ix) {
2489 self.unpin_tab_at(active_tab_ix, window, cx);
2490 } else {
2491 self.pin_tab_at(active_tab_ix, window, cx);
2492 }
2493 }
2494
2495 fn unpin_all_tabs(&mut self, _: &UnpinAllTabs, window: &mut Window, cx: &mut Context<Self>) {
2496 if self.items.is_empty() {
2497 return;
2498 }
2499
2500 let pinned_item_ids = self.pinned_item_ids().into_iter().rev();
2501
2502 for pinned_item_id in pinned_item_ids {
2503 if let Some(ix) = self.index_for_item_id(pinned_item_id) {
2504 self.unpin_tab_at(ix, window, cx);
2505 }
2506 }
2507 }
2508
2509 fn pin_tab_at(&mut self, ix: usize, window: &mut Window, cx: &mut Context<Self>) {
2510 self.change_tab_pin_state(ix, PinOperation::Pin, window, cx);
2511 }
2512
2513 fn unpin_tab_at(&mut self, ix: usize, window: &mut Window, cx: &mut Context<Self>) {
2514 self.change_tab_pin_state(ix, PinOperation::Unpin, window, cx);
2515 }
2516
2517 fn change_tab_pin_state(
2518 &mut self,
2519 ix: usize,
2520 operation: PinOperation,
2521 window: &mut Window,
2522 cx: &mut Context<Self>,
2523 ) {
2524 maybe!({
2525 let pane = cx.entity();
2526
2527 let destination_index = match operation {
2528 PinOperation::Pin => self.pinned_tab_count.min(ix),
2529 PinOperation::Unpin => self.pinned_tab_count.checked_sub(1)?,
2530 };
2531
2532 let id = self.item_for_index(ix)?.item_id();
2533 let should_activate = ix == self.active_item_index;
2534
2535 if matches!(operation, PinOperation::Pin) {
2536 self.unpreview_item_if_preview(id);
2537 }
2538
2539 match operation {
2540 PinOperation::Pin => self.pinned_tab_count += 1,
2541 PinOperation::Unpin => self.pinned_tab_count -= 1,
2542 }
2543
2544 if ix == destination_index {
2545 cx.notify();
2546 } else {
2547 self.workspace
2548 .update(cx, |_, cx| {
2549 cx.defer_in(window, move |_, window, cx| {
2550 move_item(
2551 &pane,
2552 &pane,
2553 id,
2554 destination_index,
2555 should_activate,
2556 window,
2557 cx,
2558 );
2559 });
2560 })
2561 .ok()?;
2562 }
2563
2564 let event = match operation {
2565 PinOperation::Pin => Event::ItemPinned,
2566 PinOperation::Unpin => Event::ItemUnpinned,
2567 };
2568
2569 cx.emit(event);
2570
2571 Some(())
2572 });
2573 }
2574
2575 fn is_tab_pinned(&self, ix: usize) -> bool {
2576 self.pinned_tab_count > ix
2577 }
2578
2579 fn has_unpinned_tabs(&self) -> bool {
2580 self.pinned_tab_count < self.items.len()
2581 }
2582
2583 fn activate_unpinned_tab(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2584 if self.items.is_empty() {
2585 return;
2586 }
2587 let Some(index) = self
2588 .items()
2589 .enumerate()
2590 .find_map(|(index, _item)| (!self.is_tab_pinned(index)).then_some(index))
2591 else {
2592 return;
2593 };
2594 self.activate_item(index, true, true, window, cx);
2595 }
2596
2597 fn render_tab(
2598 &self,
2599 ix: usize,
2600 item: &dyn ItemHandle,
2601 detail: usize,
2602 focus_handle: &FocusHandle,
2603 window: &mut Window,
2604 cx: &mut Context<Pane>,
2605 ) -> impl IntoElement + use<> {
2606 let is_active = ix == self.active_item_index;
2607 let is_preview = self
2608 .preview_item_id
2609 .map(|id| id == item.item_id())
2610 .unwrap_or(false);
2611
2612 let label = item.tab_content(
2613 TabContentParams {
2614 detail: Some(detail),
2615 selected: is_active,
2616 preview: is_preview,
2617 deemphasized: !self.has_focus(window, cx),
2618 },
2619 window,
2620 cx,
2621 );
2622
2623 let item_diagnostic = item
2624 .project_path(cx)
2625 .map_or(None, |project_path| self.diagnostics.get(&project_path));
2626
2627 let decorated_icon = item_diagnostic.map_or(None, |diagnostic| {
2628 let icon = match item.tab_icon(window, cx) {
2629 Some(icon) => icon,
2630 None => return None,
2631 };
2632
2633 let knockout_item_color = if is_active {
2634 cx.theme().colors().tab_active_background
2635 } else {
2636 cx.theme().colors().tab_bar_background
2637 };
2638
2639 let (icon_decoration, icon_color) = if matches!(diagnostic, &DiagnosticSeverity::ERROR)
2640 {
2641 (IconDecorationKind::X, Color::Error)
2642 } else {
2643 (IconDecorationKind::Triangle, Color::Warning)
2644 };
2645
2646 Some(DecoratedIcon::new(
2647 icon.size(IconSize::Small).color(Color::Muted),
2648 Some(
2649 IconDecoration::new(icon_decoration, knockout_item_color, cx)
2650 .color(icon_color.color(cx))
2651 .position(Point {
2652 x: px(-2.),
2653 y: px(-2.),
2654 }),
2655 ),
2656 ))
2657 });
2658
2659 let icon = if decorated_icon.is_none() {
2660 match item_diagnostic {
2661 Some(&DiagnosticSeverity::ERROR) => None,
2662 Some(&DiagnosticSeverity::WARNING) => None,
2663 _ => item
2664 .tab_icon(window, cx)
2665 .map(|icon| icon.color(Color::Muted)),
2666 }
2667 .map(|icon| icon.size(IconSize::Small))
2668 } else {
2669 None
2670 };
2671
2672 let settings = ItemSettings::get_global(cx);
2673 let close_side = &settings.close_position;
2674 let show_close_button = &settings.show_close_button;
2675 let indicator = render_item_indicator(item.boxed_clone(), cx);
2676 let tab_tooltip_content = item.tab_tooltip_content(cx);
2677 let item_id = item.item_id();
2678 let is_first_item = ix == 0;
2679 let is_last_item = ix == self.items.len() - 1;
2680 let is_pinned = self.is_tab_pinned(ix);
2681 let position_relative_to_active_item = ix.cmp(&self.active_item_index);
2682
2683 let read_only_toggle = |toggleable: bool| {
2684 IconButton::new("toggle_read_only", IconName::FileLock)
2685 .size(ButtonSize::None)
2686 .shape(IconButtonShape::Square)
2687 .icon_color(Color::Muted)
2688 .icon_size(IconSize::Small)
2689 .disabled(!toggleable)
2690 .tooltip(move |_, cx| {
2691 Tooltip::with_meta("Unlock File", None, "This will make this file editable", cx)
2692 })
2693 .on_click(cx.listener(move |pane, _, window, cx| {
2694 if let Some(item) = pane.item_for_index(ix) {
2695 item.toggle_read_only(window, cx);
2696 }
2697 }))
2698 };
2699
2700 let has_file_icon = icon.is_some() | decorated_icon.is_some();
2701
2702 let capability = item.capability(cx);
2703 let tab = Tab::new(ix)
2704 .position(if is_first_item {
2705 TabPosition::First
2706 } else if is_last_item {
2707 TabPosition::Last
2708 } else {
2709 TabPosition::Middle(position_relative_to_active_item)
2710 })
2711 .close_side(match close_side {
2712 ClosePosition::Left => ui::TabCloseSide::Start,
2713 ClosePosition::Right => ui::TabCloseSide::End,
2714 })
2715 .toggle_state(is_active)
2716 .on_click(cx.listener(move |pane: &mut Self, _, window, cx| {
2717 pane.activate_item(ix, true, true, window, cx)
2718 }))
2719 // TODO: This should be a click listener with the middle mouse button instead of a mouse down listener.
2720 .on_mouse_down(
2721 MouseButton::Middle,
2722 cx.listener(move |pane, _event, window, cx| {
2723 pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2724 .detach_and_log_err(cx);
2725 }),
2726 )
2727 .on_mouse_down(
2728 MouseButton::Left,
2729 cx.listener(move |pane, event: &MouseDownEvent, _, _| {
2730 if event.click_count > 1 {
2731 pane.unpreview_item_if_preview(item_id);
2732 }
2733 }),
2734 )
2735 .on_drag(
2736 DraggedTab {
2737 item: item.boxed_clone(),
2738 pane: cx.entity(),
2739 detail,
2740 is_active,
2741 ix,
2742 },
2743 |tab, _, _, cx| cx.new(|_| tab.clone()),
2744 )
2745 .drag_over::<DraggedTab>(move |tab, dragged_tab: &DraggedTab, _, cx| {
2746 let mut styled_tab = tab
2747 .bg(cx.theme().colors().drop_target_background)
2748 .border_color(cx.theme().colors().drop_target_border)
2749 .border_0();
2750
2751 if ix < dragged_tab.ix {
2752 styled_tab = styled_tab.border_l_2();
2753 } else if ix > dragged_tab.ix {
2754 styled_tab = styled_tab.border_r_2();
2755 }
2756
2757 styled_tab
2758 })
2759 .drag_over::<DraggedSelection>(|tab, _, _, cx| {
2760 tab.bg(cx.theme().colors().drop_target_background)
2761 })
2762 .when_some(self.can_drop_predicate.clone(), |this, p| {
2763 this.can_drop(move |a, window, cx| p(a, window, cx))
2764 })
2765 .on_drop(
2766 cx.listener(move |this, dragged_tab: &DraggedTab, window, cx| {
2767 this.drag_split_direction = None;
2768 this.handle_tab_drop(dragged_tab, ix, window, cx)
2769 }),
2770 )
2771 .on_drop(
2772 cx.listener(move |this, selection: &DraggedSelection, window, cx| {
2773 this.drag_split_direction = None;
2774 this.handle_dragged_selection_drop(selection, Some(ix), window, cx)
2775 }),
2776 )
2777 .on_drop(cx.listener(move |this, paths, window, cx| {
2778 this.drag_split_direction = None;
2779 this.handle_external_paths_drop(paths, window, cx)
2780 }))
2781 .start_slot::<Indicator>(indicator)
2782 .map(|this| {
2783 let end_slot_action: &'static dyn Action;
2784 let end_slot_tooltip_text: &'static str;
2785 let end_slot = if is_pinned {
2786 end_slot_action = &TogglePinTab;
2787 end_slot_tooltip_text = "Unpin Tab";
2788 IconButton::new("unpin tab", IconName::Pin)
2789 .shape(IconButtonShape::Square)
2790 .icon_color(Color::Muted)
2791 .size(ButtonSize::None)
2792 .icon_size(IconSize::Small)
2793 .on_click(cx.listener(move |pane, _, window, cx| {
2794 pane.unpin_tab_at(ix, window, cx);
2795 }))
2796 } else {
2797 end_slot_action = &CloseActiveItem {
2798 save_intent: None,
2799 close_pinned: false,
2800 };
2801 end_slot_tooltip_text = "Close Tab";
2802 match show_close_button {
2803 ShowCloseButton::Always => IconButton::new("close tab", IconName::Close),
2804 ShowCloseButton::Hover => {
2805 IconButton::new("close tab", IconName::Close).visible_on_hover("")
2806 }
2807 ShowCloseButton::Hidden => return this,
2808 }
2809 .shape(IconButtonShape::Square)
2810 .icon_color(Color::Muted)
2811 .size(ButtonSize::None)
2812 .icon_size(IconSize::Small)
2813 .on_click(cx.listener(move |pane, _, window, cx| {
2814 pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2815 .detach_and_log_err(cx);
2816 }))
2817 }
2818 .map(|this| {
2819 if is_active {
2820 let focus_handle = focus_handle.clone();
2821 this.tooltip(move |window, cx| {
2822 Tooltip::for_action_in(
2823 end_slot_tooltip_text,
2824 end_slot_action,
2825 &window.focused(cx).unwrap_or_else(|| focus_handle.clone()),
2826 cx,
2827 )
2828 })
2829 } else {
2830 this.tooltip(Tooltip::text(end_slot_tooltip_text))
2831 }
2832 });
2833 this.end_slot(end_slot)
2834 })
2835 .child(
2836 h_flex()
2837 .id(("pane-tab-content", ix))
2838 .gap_1()
2839 .children(if let Some(decorated_icon) = decorated_icon {
2840 Some(decorated_icon.into_any_element())
2841 } else if let Some(icon) = icon {
2842 Some(icon.into_any_element())
2843 } else if !capability.editable() {
2844 Some(read_only_toggle(capability == Capability::Read).into_any_element())
2845 } else {
2846 None
2847 })
2848 .child(label)
2849 .map(|this| match tab_tooltip_content {
2850 Some(TabTooltipContent::Text(text)) => {
2851 if capability.editable() {
2852 this.tooltip(Tooltip::text(text))
2853 } else {
2854 this.tooltip(move |_, cx| {
2855 let text = text.clone();
2856 Tooltip::with_meta(text, None, "Read-Only File", cx)
2857 })
2858 }
2859 }
2860 Some(TabTooltipContent::Custom(element_fn)) => {
2861 this.tooltip(move |window, cx| element_fn(window, cx))
2862 }
2863 None => this,
2864 })
2865 .when(capability == Capability::Read && has_file_icon, |this| {
2866 this.child(read_only_toggle(true))
2867 }),
2868 );
2869
2870 let single_entry_to_resolve = (self.items[ix].buffer_kind(cx) == ItemBufferKind::Singleton)
2871 .then(|| self.items[ix].project_entry_ids(cx).get(0).copied())
2872 .flatten();
2873
2874 let total_items = self.items.len();
2875 let has_multibuffer_items = self
2876 .items
2877 .iter()
2878 .any(|item| item.buffer_kind(cx) == ItemBufferKind::Multibuffer);
2879 let has_items_to_left = ix > 0;
2880 let has_items_to_right = ix < total_items - 1;
2881 let has_clean_items = self.items.iter().any(|item| !item.is_dirty(cx));
2882 let is_pinned = self.is_tab_pinned(ix);
2883
2884 let pane = cx.entity().downgrade();
2885 let menu_context = item.item_focus_handle(cx);
2886
2887 right_click_menu(ix)
2888 .trigger(|_, _, _| tab)
2889 .menu(move |window, cx| {
2890 let pane = pane.clone();
2891 let menu_context = menu_context.clone();
2892 ContextMenu::build(window, cx, move |mut menu, window, cx| {
2893 let close_active_item_action = CloseActiveItem {
2894 save_intent: None,
2895 close_pinned: true,
2896 };
2897 let close_inactive_items_action = CloseOtherItems {
2898 save_intent: None,
2899 close_pinned: false,
2900 };
2901 let close_multibuffers_action = CloseMultibufferItems {
2902 save_intent: None,
2903 close_pinned: false,
2904 };
2905 let close_items_to_the_left_action = CloseItemsToTheLeft {
2906 close_pinned: false,
2907 };
2908 let close_items_to_the_right_action = CloseItemsToTheRight {
2909 close_pinned: false,
2910 };
2911 let close_clean_items_action = CloseCleanItems {
2912 close_pinned: false,
2913 };
2914 let close_all_items_action = CloseAllItems {
2915 save_intent: None,
2916 close_pinned: false,
2917 };
2918 if let Some(pane) = pane.upgrade() {
2919 menu = menu
2920 .entry(
2921 "Close",
2922 Some(Box::new(close_active_item_action)),
2923 window.handler_for(&pane, move |pane, window, cx| {
2924 pane.close_item_by_id(item_id, SaveIntent::Close, window, cx)
2925 .detach_and_log_err(cx);
2926 }),
2927 )
2928 .item(ContextMenuItem::Entry(
2929 ContextMenuEntry::new("Close Others")
2930 .action(Box::new(close_inactive_items_action.clone()))
2931 .disabled(total_items == 1)
2932 .handler(window.handler_for(&pane, move |pane, window, cx| {
2933 pane.close_other_items(
2934 &close_inactive_items_action,
2935 Some(item_id),
2936 window,
2937 cx,
2938 )
2939 .detach_and_log_err(cx);
2940 })),
2941 ))
2942 // We make this optional, instead of using disabled as to not overwhelm the context menu unnecessarily
2943 .extend(has_multibuffer_items.then(|| {
2944 ContextMenuItem::Entry(
2945 ContextMenuEntry::new("Close Multibuffers")
2946 .action(Box::new(close_multibuffers_action.clone()))
2947 .handler(window.handler_for(
2948 &pane,
2949 move |pane, window, cx| {
2950 pane.close_multibuffer_items(
2951 &close_multibuffers_action,
2952 window,
2953 cx,
2954 )
2955 .detach_and_log_err(cx);
2956 },
2957 )),
2958 )
2959 }))
2960 .separator()
2961 .item(ContextMenuItem::Entry(
2962 ContextMenuEntry::new("Close Left")
2963 .action(Box::new(close_items_to_the_left_action.clone()))
2964 .disabled(!has_items_to_left)
2965 .handler(window.handler_for(&pane, move |pane, window, cx| {
2966 pane.close_items_to_the_left_by_id(
2967 Some(item_id),
2968 &close_items_to_the_left_action,
2969 window,
2970 cx,
2971 )
2972 .detach_and_log_err(cx);
2973 })),
2974 ))
2975 .item(ContextMenuItem::Entry(
2976 ContextMenuEntry::new("Close Right")
2977 .action(Box::new(close_items_to_the_right_action.clone()))
2978 .disabled(!has_items_to_right)
2979 .handler(window.handler_for(&pane, move |pane, window, cx| {
2980 pane.close_items_to_the_right_by_id(
2981 Some(item_id),
2982 &close_items_to_the_right_action,
2983 window,
2984 cx,
2985 )
2986 .detach_and_log_err(cx);
2987 })),
2988 ))
2989 .separator()
2990 .item(ContextMenuItem::Entry(
2991 ContextMenuEntry::new("Close Clean")
2992 .action(Box::new(close_clean_items_action.clone()))
2993 .disabled(!has_clean_items)
2994 .handler(window.handler_for(&pane, move |pane, window, cx| {
2995 pane.close_clean_items(
2996 &close_clean_items_action,
2997 window,
2998 cx,
2999 )
3000 .detach_and_log_err(cx)
3001 })),
3002 ))
3003 .entry(
3004 "Close All",
3005 Some(Box::new(close_all_items_action.clone())),
3006 window.handler_for(&pane, move |pane, window, cx| {
3007 pane.close_all_items(&close_all_items_action, window, cx)
3008 .detach_and_log_err(cx)
3009 }),
3010 );
3011
3012 let pin_tab_entries = |menu: ContextMenu| {
3013 menu.separator().map(|this| {
3014 if is_pinned {
3015 this.entry(
3016 "Unpin Tab",
3017 Some(TogglePinTab.boxed_clone()),
3018 window.handler_for(&pane, move |pane, window, cx| {
3019 pane.unpin_tab_at(ix, window, cx);
3020 }),
3021 )
3022 } else {
3023 this.entry(
3024 "Pin Tab",
3025 Some(TogglePinTab.boxed_clone()),
3026 window.handler_for(&pane, move |pane, window, cx| {
3027 pane.pin_tab_at(ix, window, cx);
3028 }),
3029 )
3030 }
3031 })
3032 };
3033
3034 if capability != Capability::ReadOnly {
3035 let read_only_label = if capability.editable() {
3036 "Make File Read-Only"
3037 } else {
3038 "Make File Editable"
3039 };
3040 menu = menu.separator().entry(
3041 read_only_label,
3042 None,
3043 window.handler_for(&pane, move |pane, window, cx| {
3044 if let Some(item) = pane.item_for_index(ix) {
3045 item.toggle_read_only(window, cx);
3046 }
3047 }),
3048 );
3049 }
3050
3051 if let Some(entry) = single_entry_to_resolve {
3052 let project_path = pane
3053 .read(cx)
3054 .item_for_entry(entry, cx)
3055 .and_then(|item| item.project_path(cx));
3056 let worktree = project_path.as_ref().and_then(|project_path| {
3057 pane.read(cx)
3058 .project
3059 .upgrade()?
3060 .read(cx)
3061 .worktree_for_id(project_path.worktree_id, cx)
3062 });
3063 let has_relative_path = worktree.as_ref().is_some_and(|worktree| {
3064 worktree
3065 .read(cx)
3066 .root_entry()
3067 .is_some_and(|entry| entry.is_dir())
3068 });
3069
3070 let entry_abs_path = pane.read(cx).entry_abs_path(entry, cx);
3071 let parent_abs_path = entry_abs_path
3072 .as_deref()
3073 .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
3074 let relative_path = project_path
3075 .map(|project_path| project_path.path)
3076 .filter(|_| has_relative_path);
3077
3078 let visible_in_project_panel = relative_path.is_some()
3079 && worktree.is_some_and(|worktree| worktree.read(cx).is_visible());
3080
3081 let entry_id = entry.to_proto();
3082
3083 menu = menu
3084 .separator()
3085 .when_some(entry_abs_path, |menu, abs_path| {
3086 menu.entry(
3087 "Copy Path",
3088 Some(Box::new(zed_actions::workspace::CopyPath)),
3089 window.handler_for(&pane, move |_, _, cx| {
3090 cx.write_to_clipboard(ClipboardItem::new_string(
3091 abs_path.to_string_lossy().into_owned(),
3092 ));
3093 }),
3094 )
3095 })
3096 .when_some(relative_path, |menu, relative_path| {
3097 menu.entry(
3098 "Copy Relative Path",
3099 Some(Box::new(zed_actions::workspace::CopyRelativePath)),
3100 window.handler_for(&pane, move |this, _, cx| {
3101 let Some(project) = this.project.upgrade() else {
3102 return;
3103 };
3104 let path_style = project
3105 .update(cx, |project, cx| project.path_style(cx));
3106 cx.write_to_clipboard(ClipboardItem::new_string(
3107 relative_path.display(path_style).to_string(),
3108 ));
3109 }),
3110 )
3111 })
3112 .map(pin_tab_entries)
3113 .separator()
3114 .when(visible_in_project_panel, |menu| {
3115 menu.entry(
3116 "Reveal In Project Panel",
3117 Some(Box::new(RevealInProjectPanel::default())),
3118 window.handler_for(&pane, move |pane, _, cx| {
3119 pane.project
3120 .update(cx, |_, cx| {
3121 cx.emit(project::Event::RevealInProjectPanel(
3122 ProjectEntryId::from_proto(entry_id),
3123 ))
3124 })
3125 .ok();
3126 }),
3127 )
3128 })
3129 .when_some(parent_abs_path, |menu, parent_abs_path| {
3130 menu.entry(
3131 "Open in Terminal",
3132 Some(Box::new(OpenInTerminal)),
3133 window.handler_for(&pane, move |_, window, cx| {
3134 window.dispatch_action(
3135 OpenTerminal {
3136 working_directory: parent_abs_path.clone(),
3137 }
3138 .boxed_clone(),
3139 cx,
3140 );
3141 }),
3142 )
3143 });
3144 } else {
3145 menu = menu.map(pin_tab_entries);
3146 }
3147 };
3148
3149 menu.context(menu_context)
3150 })
3151 })
3152 }
3153
3154 fn render_tab_bar(&mut self, window: &mut Window, cx: &mut Context<Pane>) -> AnyElement {
3155 let Some(workspace) = self.workspace.upgrade() else {
3156 return gpui::Empty.into_any();
3157 };
3158
3159 let focus_handle = self.focus_handle.clone();
3160 let is_pane_focused = self.has_focus(window, cx);
3161
3162 let navigate_backward = IconButton::new("navigate_backward", IconName::ArrowLeft)
3163 .icon_size(IconSize::Small)
3164 .on_click({
3165 let entity = cx.entity();
3166 move |_, window, cx| {
3167 entity.update(cx, |pane, cx| {
3168 pane.navigate_backward(&Default::default(), window, cx)
3169 })
3170 }
3171 })
3172 .disabled(!self.can_navigate_backward())
3173 .tooltip({
3174 let focus_handle = focus_handle.clone();
3175 move |window, cx| {
3176 Tooltip::for_action_in(
3177 "Go Back",
3178 &GoBack,
3179 &window.focused(cx).unwrap_or_else(|| focus_handle.clone()),
3180 cx,
3181 )
3182 }
3183 });
3184
3185 let open_aside_left = {
3186 let workspace = workspace.read(cx);
3187 workspace.utility_pane(UtilityPaneSlot::Left).map(|pane| {
3188 let toggle_icon = pane.toggle_icon(cx);
3189 let workspace_handle = self.workspace.clone();
3190
3191 h_flex()
3192 .h_full()
3193 .pr_1p5()
3194 .border_r_1()
3195 .border_color(cx.theme().colors().border)
3196 .child(
3197 IconButton::new("open_aside_left", toggle_icon)
3198 .icon_size(IconSize::Small)
3199 .tooltip(Tooltip::text("Toggle Agent Pane")) // TODO: Probably want to make this generic
3200 .on_click(move |_, window, cx| {
3201 workspace_handle
3202 .update(cx, |workspace, cx| {
3203 workspace.toggle_utility_pane(
3204 UtilityPaneSlot::Left,
3205 window,
3206 cx,
3207 )
3208 })
3209 .ok();
3210 }),
3211 )
3212 .into_any_element()
3213 })
3214 };
3215
3216 let open_aside_right = {
3217 let workspace = workspace.read(cx);
3218 workspace.utility_pane(UtilityPaneSlot::Right).map(|pane| {
3219 let toggle_icon = pane.toggle_icon(cx);
3220 let workspace_handle = self.workspace.clone();
3221
3222 h_flex()
3223 .h_full()
3224 .when(is_pane_focused, |this| {
3225 this.pl(DynamicSpacing::Base04.rems(cx))
3226 .border_l_1()
3227 .border_color(cx.theme().colors().border)
3228 })
3229 .child(
3230 IconButton::new("open_aside_right", toggle_icon)
3231 .icon_size(IconSize::Small)
3232 .tooltip(Tooltip::text("Toggle Agent Pane")) // TODO: Probably want to make this generic
3233 .on_click(move |_, window, cx| {
3234 workspace_handle
3235 .update(cx, |workspace, cx| {
3236 workspace.toggle_utility_pane(
3237 UtilityPaneSlot::Right,
3238 window,
3239 cx,
3240 )
3241 })
3242 .ok();
3243 }),
3244 )
3245 .into_any_element()
3246 })
3247 };
3248
3249 let navigate_forward = IconButton::new("navigate_forward", IconName::ArrowRight)
3250 .icon_size(IconSize::Small)
3251 .on_click({
3252 let entity = cx.entity();
3253 move |_, window, cx| {
3254 entity.update(cx, |pane, cx| {
3255 pane.navigate_forward(&Default::default(), window, cx)
3256 })
3257 }
3258 })
3259 .disabled(!self.can_navigate_forward())
3260 .tooltip({
3261 let focus_handle = focus_handle.clone();
3262 move |window, cx| {
3263 Tooltip::for_action_in(
3264 "Go Forward",
3265 &GoForward,
3266 &window.focused(cx).unwrap_or_else(|| focus_handle.clone()),
3267 cx,
3268 )
3269 }
3270 });
3271
3272 let mut tab_items = self
3273 .items
3274 .iter()
3275 .enumerate()
3276 .zip(tab_details(&self.items, window, cx))
3277 .map(|((ix, item), detail)| {
3278 self.render_tab(ix, &**item, detail, &focus_handle, window, cx)
3279 })
3280 .collect::<Vec<_>>();
3281 let tab_count = tab_items.len();
3282 if self.is_tab_pinned(tab_count) {
3283 log::warn!(
3284 "Pinned tab count ({}) exceeds actual tab count ({}). \
3285 This should not happen. If possible, add reproduction steps, \
3286 in a comment, to https://github.com/zed-industries/zed/issues/33342",
3287 self.pinned_tab_count,
3288 tab_count
3289 );
3290 self.pinned_tab_count = tab_count;
3291 }
3292 let unpinned_tabs = tab_items.split_off(self.pinned_tab_count);
3293 let pinned_tabs = tab_items;
3294
3295 let render_aside_toggle_left = cx.has_flag::<AgentV2FeatureFlag>()
3296 && self
3297 .is_upper_left
3298 .then(|| {
3299 self.workspace.upgrade().and_then(|entity| {
3300 let workspace = entity.read(cx);
3301 workspace
3302 .utility_pane(UtilityPaneSlot::Left)
3303 .map(|pane| !pane.expanded(cx))
3304 })
3305 })
3306 .flatten()
3307 .unwrap_or(false);
3308
3309 let render_aside_toggle_right = cx.has_flag::<AgentV2FeatureFlag>()
3310 && self
3311 .is_upper_right
3312 .then(|| {
3313 self.workspace.upgrade().and_then(|entity| {
3314 let workspace = entity.read(cx);
3315 workspace
3316 .utility_pane(UtilityPaneSlot::Right)
3317 .map(|pane| !pane.expanded(cx))
3318 })
3319 })
3320 .flatten()
3321 .unwrap_or(false);
3322
3323 TabBar::new("tab_bar")
3324 .map(|tab_bar| {
3325 if let Some(open_aside_left) = open_aside_left
3326 && render_aside_toggle_left
3327 {
3328 tab_bar.start_child(open_aside_left)
3329 } else {
3330 tab_bar
3331 }
3332 })
3333 .when(
3334 self.display_nav_history_buttons.unwrap_or_default(),
3335 |tab_bar| {
3336 tab_bar
3337 .start_child(navigate_backward)
3338 .start_child(navigate_forward)
3339 },
3340 )
3341 .map(|tab_bar| {
3342 if self.show_tab_bar_buttons {
3343 let render_tab_buttons = self.render_tab_bar_buttons.clone();
3344 let (left_children, right_children) = render_tab_buttons(self, window, cx);
3345 tab_bar
3346 .start_children(left_children)
3347 .end_children(right_children)
3348 } else {
3349 tab_bar
3350 }
3351 })
3352 .children(pinned_tabs.len().ne(&0).then(|| {
3353 let max_scroll = self.tab_bar_scroll_handle.max_offset().width;
3354 // We need to check both because offset returns delta values even when the scroll handle is not scrollable
3355 let is_scrolled = self.tab_bar_scroll_handle.offset().x < px(0.);
3356 // Avoid flickering when max_offset is very small (< 2px).
3357 // The border adds 1-2px which can push max_offset back to 0, creating a loop.
3358 let is_scrollable = max_scroll > px(2.0);
3359 let has_active_unpinned_tab = self.active_item_index >= self.pinned_tab_count;
3360 h_flex()
3361 .children(pinned_tabs)
3362 .when(is_scrollable && is_scrolled, |this| {
3363 this.when(has_active_unpinned_tab, |this| this.border_r_2())
3364 .when(!has_active_unpinned_tab, |this| this.border_r_1())
3365 .border_color(cx.theme().colors().border)
3366 })
3367 }))
3368 .child(
3369 h_flex()
3370 .id("unpinned tabs")
3371 .overflow_x_scroll()
3372 .w_full()
3373 .track_scroll(&self.tab_bar_scroll_handle)
3374 .on_scroll_wheel(cx.listener(|this, _, _, _| {
3375 this.suppress_scroll = true;
3376 }))
3377 .children(unpinned_tabs)
3378 .child(
3379 div()
3380 .id("tab_bar_drop_target")
3381 .min_w_6()
3382 // HACK: This empty child is currently necessary to force the drop target to appear
3383 // despite us setting a min width above.
3384 .child("")
3385 // HACK: h_full doesn't occupy the complete height, using fixed height instead
3386 .h(Tab::container_height(cx))
3387 .flex_grow()
3388 .drag_over::<DraggedTab>(|bar, _, _, cx| {
3389 bar.bg(cx.theme().colors().drop_target_background)
3390 })
3391 .drag_over::<DraggedSelection>(|bar, _, _, cx| {
3392 bar.bg(cx.theme().colors().drop_target_background)
3393 })
3394 .on_drop(cx.listener(
3395 move |this, dragged_tab: &DraggedTab, window, cx| {
3396 this.drag_split_direction = None;
3397 this.handle_tab_drop(dragged_tab, this.items.len(), window, cx)
3398 },
3399 ))
3400 .on_drop(cx.listener(
3401 move |this, selection: &DraggedSelection, window, cx| {
3402 this.drag_split_direction = None;
3403 this.handle_project_entry_drop(
3404 &selection.active_selection.entry_id,
3405 Some(tab_count),
3406 window,
3407 cx,
3408 )
3409 },
3410 ))
3411 .on_drop(cx.listener(move |this, paths, window, cx| {
3412 this.drag_split_direction = None;
3413 this.handle_external_paths_drop(paths, window, cx)
3414 }))
3415 .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
3416 if event.click_count() == 2 {
3417 window.dispatch_action(
3418 this.double_click_dispatch_action.boxed_clone(),
3419 cx,
3420 );
3421 }
3422 })),
3423 ),
3424 )
3425 .map(|tab_bar| {
3426 if let Some(open_aside_right) = open_aside_right
3427 && render_aside_toggle_right
3428 {
3429 tab_bar.end_child(open_aside_right)
3430 } else {
3431 tab_bar
3432 }
3433 })
3434 .into_any_element()
3435 }
3436
3437 pub fn render_menu_overlay(menu: &Entity<ContextMenu>) -> Div {
3438 div().absolute().bottom_0().right_0().size_0().child(
3439 deferred(anchored().anchor(Corner::TopRight).child(menu.clone())).with_priority(1),
3440 )
3441 }
3442
3443 pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut Context<Self>) {
3444 self.zoomed = zoomed;
3445 cx.notify();
3446 }
3447
3448 pub fn is_zoomed(&self) -> bool {
3449 self.zoomed
3450 }
3451
3452 fn handle_drag_move<T: 'static>(
3453 &mut self,
3454 event: &DragMoveEvent<T>,
3455 window: &mut Window,
3456 cx: &mut Context<Self>,
3457 ) {
3458 let can_split_predicate = self.can_split_predicate.take();
3459 let can_split = match &can_split_predicate {
3460 Some(can_split_predicate) => {
3461 can_split_predicate(self, event.dragged_item(), window, cx)
3462 }
3463 None => false,
3464 };
3465 self.can_split_predicate = can_split_predicate;
3466 if !can_split {
3467 return;
3468 }
3469
3470 let rect = event.bounds.size;
3471
3472 let size = event.bounds.size.width.min(event.bounds.size.height)
3473 * WorkspaceSettings::get_global(cx).drop_target_size;
3474
3475 let relative_cursor = Point::new(
3476 event.event.position.x - event.bounds.left(),
3477 event.event.position.y - event.bounds.top(),
3478 );
3479
3480 let direction = if relative_cursor.x < size
3481 || relative_cursor.x > rect.width - size
3482 || relative_cursor.y < size
3483 || relative_cursor.y > rect.height - size
3484 {
3485 [
3486 SplitDirection::Up,
3487 SplitDirection::Right,
3488 SplitDirection::Down,
3489 SplitDirection::Left,
3490 ]
3491 .iter()
3492 .min_by_key(|side| match side {
3493 SplitDirection::Up => relative_cursor.y,
3494 SplitDirection::Right => rect.width - relative_cursor.x,
3495 SplitDirection::Down => rect.height - relative_cursor.y,
3496 SplitDirection::Left => relative_cursor.x,
3497 })
3498 .cloned()
3499 } else {
3500 None
3501 };
3502
3503 if direction != self.drag_split_direction {
3504 self.drag_split_direction = direction;
3505 }
3506 }
3507
3508 pub fn handle_tab_drop(
3509 &mut self,
3510 dragged_tab: &DraggedTab,
3511 ix: usize,
3512 window: &mut Window,
3513 cx: &mut Context<Self>,
3514 ) {
3515 if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3516 && let ControlFlow::Break(()) = custom_drop_handle(self, dragged_tab, window, cx)
3517 {
3518 return;
3519 }
3520 let mut to_pane = cx.entity();
3521 let split_direction = self.drag_split_direction;
3522 let item_id = dragged_tab.item.item_id();
3523 self.unpreview_item_if_preview(item_id);
3524
3525 let is_clone = cfg!(target_os = "macos") && window.modifiers().alt
3526 || cfg!(not(target_os = "macos")) && window.modifiers().control;
3527
3528 let from_pane = dragged_tab.pane.clone();
3529
3530 self.workspace
3531 .update(cx, |_, cx| {
3532 cx.defer_in(window, move |workspace, window, cx| {
3533 if let Some(split_direction) = split_direction {
3534 to_pane = workspace.split_pane(to_pane, split_direction, window, cx);
3535 }
3536 let database_id = workspace.database_id();
3537 let was_pinned_in_from_pane = from_pane.read_with(cx, |pane, _| {
3538 pane.index_for_item_id(item_id)
3539 .is_some_and(|ix| pane.is_tab_pinned(ix))
3540 });
3541 let to_pane_old_length = to_pane.read(cx).items.len();
3542 if is_clone {
3543 let Some(item) = from_pane
3544 .read(cx)
3545 .items()
3546 .find(|item| item.item_id() == item_id)
3547 .cloned()
3548 else {
3549 return;
3550 };
3551 if item.can_split(cx) {
3552 let task = item.clone_on_split(database_id, window, cx);
3553 let to_pane = to_pane.downgrade();
3554 cx.spawn_in(window, async move |_, cx| {
3555 if let Some(item) = task.await {
3556 to_pane
3557 .update_in(cx, |pane, window, cx| {
3558 pane.add_item(item, true, true, None, window, cx)
3559 })
3560 .ok();
3561 }
3562 })
3563 .detach();
3564 } else {
3565 move_item(&from_pane, &to_pane, item_id, ix, true, window, cx);
3566 }
3567 } else {
3568 move_item(&from_pane, &to_pane, item_id, ix, true, window, cx);
3569 }
3570 to_pane.update(cx, |this, _| {
3571 if to_pane == from_pane {
3572 let actual_ix = this
3573 .items
3574 .iter()
3575 .position(|item| item.item_id() == item_id)
3576 .unwrap_or(0);
3577
3578 let is_pinned_in_to_pane = this.is_tab_pinned(actual_ix);
3579
3580 if !was_pinned_in_from_pane && is_pinned_in_to_pane {
3581 this.pinned_tab_count += 1;
3582 } else if was_pinned_in_from_pane && !is_pinned_in_to_pane {
3583 this.pinned_tab_count -= 1;
3584 }
3585 } else if this.items.len() >= to_pane_old_length {
3586 let is_pinned_in_to_pane = this.is_tab_pinned(ix);
3587 let item_created_pane = to_pane_old_length == 0;
3588 let is_first_position = ix == 0;
3589 let was_dropped_at_beginning = item_created_pane || is_first_position;
3590 let should_remain_pinned = is_pinned_in_to_pane
3591 || (was_pinned_in_from_pane && was_dropped_at_beginning);
3592
3593 if should_remain_pinned {
3594 this.pinned_tab_count += 1;
3595 }
3596 }
3597 });
3598 });
3599 })
3600 .log_err();
3601 }
3602
3603 fn handle_dragged_selection_drop(
3604 &mut self,
3605 dragged_selection: &DraggedSelection,
3606 dragged_onto: Option<usize>,
3607 window: &mut Window,
3608 cx: &mut Context<Self>,
3609 ) {
3610 if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3611 && let ControlFlow::Break(()) = custom_drop_handle(self, dragged_selection, window, cx)
3612 {
3613 return;
3614 }
3615 self.handle_project_entry_drop(
3616 &dragged_selection.active_selection.entry_id,
3617 dragged_onto,
3618 window,
3619 cx,
3620 );
3621 }
3622
3623 fn handle_project_entry_drop(
3624 &mut self,
3625 project_entry_id: &ProjectEntryId,
3626 target: Option<usize>,
3627 window: &mut Window,
3628 cx: &mut Context<Self>,
3629 ) {
3630 if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3631 && let ControlFlow::Break(()) = custom_drop_handle(self, project_entry_id, window, cx)
3632 {
3633 return;
3634 }
3635 let mut to_pane = cx.entity();
3636 let split_direction = self.drag_split_direction;
3637 let project_entry_id = *project_entry_id;
3638 self.workspace
3639 .update(cx, |_, cx| {
3640 cx.defer_in(window, move |workspace, window, cx| {
3641 if let Some(project_path) = workspace
3642 .project()
3643 .read(cx)
3644 .path_for_entry(project_entry_id, cx)
3645 {
3646 let load_path_task = workspace.load_path(project_path.clone(), window, cx);
3647 cx.spawn_in(window, async move |workspace, cx| {
3648 if let Some((project_entry_id, build_item)) =
3649 load_path_task.await.notify_async_err(cx)
3650 {
3651 let (to_pane, new_item_handle) = workspace
3652 .update_in(cx, |workspace, window, cx| {
3653 if let Some(split_direction) = split_direction {
3654 to_pane = workspace.split_pane(
3655 to_pane,
3656 split_direction,
3657 window,
3658 cx,
3659 );
3660 }
3661 let new_item_handle = to_pane.update(cx, |pane, cx| {
3662 pane.open_item(
3663 project_entry_id,
3664 project_path,
3665 true,
3666 false,
3667 true,
3668 target,
3669 window,
3670 cx,
3671 build_item,
3672 )
3673 });
3674 (to_pane, new_item_handle)
3675 })
3676 .log_err()?;
3677 to_pane
3678 .update_in(cx, |this, window, cx| {
3679 let Some(index) = this.index_for_item(&*new_item_handle)
3680 else {
3681 return;
3682 };
3683
3684 if target.is_some_and(|target| this.is_tab_pinned(target)) {
3685 this.pin_tab_at(index, window, cx);
3686 }
3687 })
3688 .ok()?
3689 }
3690 Some(())
3691 })
3692 .detach();
3693 };
3694 });
3695 })
3696 .log_err();
3697 }
3698
3699 fn handle_external_paths_drop(
3700 &mut self,
3701 paths: &ExternalPaths,
3702 window: &mut Window,
3703 cx: &mut Context<Self>,
3704 ) {
3705 if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3706 && let ControlFlow::Break(()) = custom_drop_handle(self, paths, window, cx)
3707 {
3708 return;
3709 }
3710 let mut to_pane = cx.entity();
3711 let mut split_direction = self.drag_split_direction;
3712 let paths = paths.paths().to_vec();
3713 let is_remote = self
3714 .workspace
3715 .update(cx, |workspace, cx| {
3716 if workspace.project().read(cx).is_via_collab() {
3717 workspace.show_error(
3718 &anyhow::anyhow!("Cannot drop files on a remote project"),
3719 cx,
3720 );
3721 true
3722 } else {
3723 false
3724 }
3725 })
3726 .unwrap_or(true);
3727 if is_remote {
3728 return;
3729 }
3730
3731 self.workspace
3732 .update(cx, |workspace, cx| {
3733 let fs = Arc::clone(workspace.project().read(cx).fs());
3734 cx.spawn_in(window, async move |workspace, cx| {
3735 let mut is_file_checks = FuturesUnordered::new();
3736 for path in &paths {
3737 is_file_checks.push(fs.is_file(path))
3738 }
3739 let mut has_files_to_open = false;
3740 while let Some(is_file) = is_file_checks.next().await {
3741 if is_file {
3742 has_files_to_open = true;
3743 break;
3744 }
3745 }
3746 drop(is_file_checks);
3747 if !has_files_to_open {
3748 split_direction = None;
3749 }
3750
3751 if let Ok((open_task, to_pane)) =
3752 workspace.update_in(cx, |workspace, window, cx| {
3753 if let Some(split_direction) = split_direction {
3754 to_pane =
3755 workspace.split_pane(to_pane, split_direction, window, cx);
3756 }
3757 (
3758 workspace.open_paths(
3759 paths,
3760 OpenOptions {
3761 visible: Some(OpenVisible::OnlyDirectories),
3762 ..Default::default()
3763 },
3764 Some(to_pane.downgrade()),
3765 window,
3766 cx,
3767 ),
3768 to_pane,
3769 )
3770 })
3771 {
3772 let opened_items: Vec<_> = open_task.await;
3773 _ = workspace.update_in(cx, |workspace, window, cx| {
3774 for item in opened_items.into_iter().flatten() {
3775 if let Err(e) = item {
3776 workspace.show_error(&e, cx);
3777 }
3778 }
3779 if to_pane.read(cx).items_len() == 0 {
3780 workspace.remove_pane(to_pane, None, window, cx);
3781 }
3782 });
3783 }
3784 })
3785 .detach();
3786 })
3787 .log_err();
3788 }
3789
3790 pub fn display_nav_history_buttons(&mut self, display: Option<bool>) {
3791 self.display_nav_history_buttons = display;
3792 }
3793
3794 fn pinned_item_ids(&self) -> Vec<EntityId> {
3795 self.items
3796 .iter()
3797 .enumerate()
3798 .filter_map(|(index, item)| {
3799 if self.is_tab_pinned(index) {
3800 return Some(item.item_id());
3801 }
3802
3803 None
3804 })
3805 .collect()
3806 }
3807
3808 fn clean_item_ids(&self, cx: &mut Context<Pane>) -> Vec<EntityId> {
3809 self.items()
3810 .filter_map(|item| {
3811 if !item.is_dirty(cx) {
3812 return Some(item.item_id());
3813 }
3814
3815 None
3816 })
3817 .collect()
3818 }
3819
3820 fn to_the_side_item_ids(&self, item_id: EntityId, side: Side) -> Vec<EntityId> {
3821 match side {
3822 Side::Left => self
3823 .items()
3824 .take_while(|item| item.item_id() != item_id)
3825 .map(|item| item.item_id())
3826 .collect(),
3827 Side::Right => self
3828 .items()
3829 .rev()
3830 .take_while(|item| item.item_id() != item_id)
3831 .map(|item| item.item_id())
3832 .collect(),
3833 }
3834 }
3835
3836 fn multibuffer_item_ids(&self, cx: &mut Context<Pane>) -> Vec<EntityId> {
3837 self.items()
3838 .filter(|item| item.buffer_kind(cx) == ItemBufferKind::Multibuffer)
3839 .map(|item| item.item_id())
3840 .collect()
3841 }
3842
3843 pub fn drag_split_direction(&self) -> Option<SplitDirection> {
3844 self.drag_split_direction
3845 }
3846
3847 pub fn set_zoom_out_on_close(&mut self, zoom_out_on_close: bool) {
3848 self.zoom_out_on_close = zoom_out_on_close;
3849 }
3850}
3851
3852fn default_render_tab_bar_buttons(
3853 pane: &mut Pane,
3854 window: &mut Window,
3855 cx: &mut Context<Pane>,
3856) -> (Option<AnyElement>, Option<AnyElement>) {
3857 if !pane.has_focus(window, cx) && !pane.context_menu_focused(window, cx) {
3858 return (None, None);
3859 }
3860 let (can_clone, can_split_move) = match pane.active_item() {
3861 Some(active_item) if active_item.can_split(cx) => (true, false),
3862 Some(_) => (false, pane.items_len() > 1),
3863 None => (false, false),
3864 };
3865 // Ideally we would return a vec of elements here to pass directly to the [TabBar]'s
3866 // `end_slot`, but due to needing a view here that isn't possible.
3867 let right_children = h_flex()
3868 // Instead we need to replicate the spacing from the [TabBar]'s `end_slot` here.
3869 .gap(DynamicSpacing::Base04.rems(cx))
3870 .child(
3871 PopoverMenu::new("pane-tab-bar-popover-menu")
3872 .trigger_with_tooltip(
3873 IconButton::new("plus", IconName::Plus).icon_size(IconSize::Small),
3874 Tooltip::text("New..."),
3875 )
3876 .anchor(Corner::TopRight)
3877 .with_handle(pane.new_item_context_menu_handle.clone())
3878 .menu(move |window, cx| {
3879 Some(ContextMenu::build(window, cx, |menu, _, _| {
3880 menu.action("New File", NewFile.boxed_clone())
3881 .action("Open File", ToggleFileFinder::default().boxed_clone())
3882 .separator()
3883 .action(
3884 "Search Project",
3885 DeploySearch {
3886 replace_enabled: false,
3887 included_files: None,
3888 excluded_files: None,
3889 }
3890 .boxed_clone(),
3891 )
3892 .action("Search Symbols", ToggleProjectSymbols.boxed_clone())
3893 .separator()
3894 .action("New Terminal", NewTerminal.boxed_clone())
3895 }))
3896 }),
3897 )
3898 .child(
3899 PopoverMenu::new("pane-tab-bar-split")
3900 .trigger_with_tooltip(
3901 IconButton::new("split", IconName::Split)
3902 .icon_size(IconSize::Small)
3903 .disabled(!can_clone && !can_split_move),
3904 Tooltip::text("Split Pane"),
3905 )
3906 .anchor(Corner::TopRight)
3907 .with_handle(pane.split_item_context_menu_handle.clone())
3908 .menu(move |window, cx| {
3909 ContextMenu::build(window, cx, |menu, _, _| {
3910 let mode = SplitMode::MovePane;
3911 if can_split_move {
3912 menu.action("Split Right", SplitRight { mode }.boxed_clone())
3913 .action("Split Left", SplitLeft { mode }.boxed_clone())
3914 .action("Split Up", SplitUp { mode }.boxed_clone())
3915 .action("Split Down", SplitDown { mode }.boxed_clone())
3916 } else {
3917 menu.action("Split Right", SplitRight::default().boxed_clone())
3918 .action("Split Left", SplitLeft::default().boxed_clone())
3919 .action("Split Up", SplitUp::default().boxed_clone())
3920 .action("Split Down", SplitDown::default().boxed_clone())
3921 }
3922 })
3923 .into()
3924 }),
3925 )
3926 .child({
3927 let zoomed = pane.is_zoomed();
3928 IconButton::new("toggle_zoom", IconName::Maximize)
3929 .icon_size(IconSize::Small)
3930 .toggle_state(zoomed)
3931 .selected_icon(IconName::Minimize)
3932 .on_click(cx.listener(|pane, _, window, cx| {
3933 pane.toggle_zoom(&crate::ToggleZoom, window, cx);
3934 }))
3935 .tooltip(move |_window, cx| {
3936 Tooltip::for_action(
3937 if zoomed { "Zoom Out" } else { "Zoom In" },
3938 &ToggleZoom,
3939 cx,
3940 )
3941 })
3942 })
3943 .into_any_element()
3944 .into();
3945 (None, right_children)
3946}
3947
3948impl Focusable for Pane {
3949 fn focus_handle(&self, _cx: &App) -> FocusHandle {
3950 self.focus_handle.clone()
3951 }
3952}
3953
3954impl Render for Pane {
3955 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3956 let mut key_context = KeyContext::new_with_defaults();
3957 key_context.add("Pane");
3958 if self.active_item().is_none() {
3959 key_context.add("EmptyPane");
3960 }
3961
3962 self.toolbar
3963 .read(cx)
3964 .contribute_context(&mut key_context, cx);
3965
3966 let should_display_tab_bar = self.should_display_tab_bar.clone();
3967 let display_tab_bar = should_display_tab_bar(window, cx);
3968 let Some(project) = self.project.upgrade() else {
3969 return div().track_focus(&self.focus_handle(cx));
3970 };
3971 let is_local = project.read(cx).is_local();
3972
3973 v_flex()
3974 .key_context(key_context)
3975 .track_focus(&self.focus_handle(cx))
3976 .size_full()
3977 .flex_none()
3978 .overflow_hidden()
3979 .on_action(cx.listener(|pane, split: &SplitLeft, window, cx| {
3980 pane.split(SplitDirection::Left, split.mode, window, cx)
3981 }))
3982 .on_action(cx.listener(|pane, split: &SplitUp, window, cx| {
3983 pane.split(SplitDirection::Up, split.mode, window, cx)
3984 }))
3985 .on_action(cx.listener(|pane, split: &SplitHorizontal, window, cx| {
3986 pane.split(SplitDirection::horizontal(cx), split.mode, window, cx)
3987 }))
3988 .on_action(cx.listener(|pane, split: &SplitVertical, window, cx| {
3989 pane.split(SplitDirection::vertical(cx), split.mode, window, cx)
3990 }))
3991 .on_action(cx.listener(|pane, split: &SplitRight, window, cx| {
3992 pane.split(SplitDirection::Right, split.mode, window, cx)
3993 }))
3994 .on_action(cx.listener(|pane, split: &SplitDown, window, cx| {
3995 pane.split(SplitDirection::Down, split.mode, window, cx)
3996 }))
3997 .on_action(cx.listener(|pane, _: &SplitAndMoveUp, window, cx| {
3998 pane.split(SplitDirection::Up, SplitMode::MovePane, window, cx)
3999 }))
4000 .on_action(cx.listener(|pane, _: &SplitAndMoveDown, window, cx| {
4001 pane.split(SplitDirection::Down, SplitMode::MovePane, window, cx)
4002 }))
4003 .on_action(cx.listener(|pane, _: &SplitAndMoveLeft, window, cx| {
4004 pane.split(SplitDirection::Left, SplitMode::MovePane, window, cx)
4005 }))
4006 .on_action(cx.listener(|pane, _: &SplitAndMoveRight, window, cx| {
4007 pane.split(SplitDirection::Right, SplitMode::MovePane, window, cx)
4008 }))
4009 .on_action(cx.listener(|_, _: &JoinIntoNext, _, cx| {
4010 cx.emit(Event::JoinIntoNext);
4011 }))
4012 .on_action(cx.listener(|_, _: &JoinAll, _, cx| {
4013 cx.emit(Event::JoinAll);
4014 }))
4015 .on_action(cx.listener(Pane::toggle_zoom))
4016 .on_action(cx.listener(Pane::zoom_in))
4017 .on_action(cx.listener(Pane::zoom_out))
4018 .on_action(cx.listener(Self::navigate_backward))
4019 .on_action(cx.listener(Self::navigate_forward))
4020 .on_action(
4021 cx.listener(|pane: &mut Pane, action: &ActivateItem, window, cx| {
4022 pane.activate_item(
4023 action.0.min(pane.items.len().saturating_sub(1)),
4024 true,
4025 true,
4026 window,
4027 cx,
4028 );
4029 }),
4030 )
4031 .on_action(cx.listener(Self::alternate_file))
4032 .on_action(cx.listener(Self::activate_last_item))
4033 .on_action(cx.listener(Self::activate_previous_item))
4034 .on_action(cx.listener(Self::activate_next_item))
4035 .on_action(cx.listener(Self::swap_item_left))
4036 .on_action(cx.listener(Self::swap_item_right))
4037 .on_action(cx.listener(Self::toggle_pin_tab))
4038 .on_action(cx.listener(Self::unpin_all_tabs))
4039 .when(PreviewTabsSettings::get_global(cx).enabled, |this| {
4040 this.on_action(
4041 cx.listener(|pane: &mut Pane, _: &TogglePreviewTab, window, cx| {
4042 if let Some(active_item_id) = pane.active_item().map(|i| i.item_id()) {
4043 if pane.is_active_preview_item(active_item_id) {
4044 pane.unpreview_item_if_preview(active_item_id);
4045 } else {
4046 pane.replace_preview_item_id(active_item_id, window, cx);
4047 }
4048 }
4049 }),
4050 )
4051 })
4052 .on_action(
4053 cx.listener(|pane: &mut Self, action: &CloseActiveItem, window, cx| {
4054 pane.close_active_item(action, window, cx)
4055 .detach_and_log_err(cx)
4056 }),
4057 )
4058 .on_action(
4059 cx.listener(|pane: &mut Self, action: &CloseOtherItems, window, cx| {
4060 pane.close_other_items(action, None, window, cx)
4061 .detach_and_log_err(cx);
4062 }),
4063 )
4064 .on_action(
4065 cx.listener(|pane: &mut Self, action: &CloseCleanItems, window, cx| {
4066 pane.close_clean_items(action, window, cx)
4067 .detach_and_log_err(cx)
4068 }),
4069 )
4070 .on_action(cx.listener(
4071 |pane: &mut Self, action: &CloseItemsToTheLeft, window, cx| {
4072 pane.close_items_to_the_left_by_id(None, action, window, cx)
4073 .detach_and_log_err(cx)
4074 },
4075 ))
4076 .on_action(cx.listener(
4077 |pane: &mut Self, action: &CloseItemsToTheRight, window, cx| {
4078 pane.close_items_to_the_right_by_id(None, action, window, cx)
4079 .detach_and_log_err(cx)
4080 },
4081 ))
4082 .on_action(
4083 cx.listener(|pane: &mut Self, action: &CloseAllItems, window, cx| {
4084 pane.close_all_items(action, window, cx)
4085 .detach_and_log_err(cx)
4086 }),
4087 )
4088 .on_action(cx.listener(
4089 |pane: &mut Self, action: &CloseMultibufferItems, window, cx| {
4090 pane.close_multibuffer_items(action, window, cx)
4091 .detach_and_log_err(cx)
4092 },
4093 ))
4094 .on_action(
4095 cx.listener(|pane: &mut Self, action: &RevealInProjectPanel, _, cx| {
4096 let entry_id = action
4097 .entry_id
4098 .map(ProjectEntryId::from_proto)
4099 .or_else(|| pane.active_item()?.project_entry_ids(cx).first().copied());
4100 if let Some(entry_id) = entry_id {
4101 pane.project
4102 .update(cx, |_, cx| {
4103 cx.emit(project::Event::RevealInProjectPanel(entry_id))
4104 })
4105 .ok();
4106 }
4107 }),
4108 )
4109 .on_action(cx.listener(|_, _: &menu::Cancel, window, cx| {
4110 if cx.stop_active_drag(window) {
4111 } else {
4112 cx.propagate();
4113 }
4114 }))
4115 .when(self.active_item().is_some() && display_tab_bar, |pane| {
4116 pane.child((self.render_tab_bar.clone())(self, window, cx))
4117 })
4118 .child({
4119 let has_worktrees = project.read(cx).visible_worktrees(cx).next().is_some();
4120 // main content
4121 div()
4122 .flex_1()
4123 .relative()
4124 .group("")
4125 .overflow_hidden()
4126 .on_drag_move::<DraggedTab>(cx.listener(Self::handle_drag_move))
4127 .on_drag_move::<DraggedSelection>(cx.listener(Self::handle_drag_move))
4128 .when(is_local, |div| {
4129 div.on_drag_move::<ExternalPaths>(cx.listener(Self::handle_drag_move))
4130 })
4131 .map(|div| {
4132 if let Some(item) = self.active_item() {
4133 div.id("pane_placeholder")
4134 .v_flex()
4135 .size_full()
4136 .overflow_hidden()
4137 .child(self.toolbar.clone())
4138 .child(item.to_any_view())
4139 } else {
4140 let placeholder = div
4141 .id("pane_placeholder")
4142 .h_flex()
4143 .size_full()
4144 .justify_center()
4145 .on_click(cx.listener(
4146 move |this, event: &ClickEvent, window, cx| {
4147 if event.click_count() == 2 {
4148 window.dispatch_action(
4149 this.double_click_dispatch_action.boxed_clone(),
4150 cx,
4151 );
4152 }
4153 },
4154 ));
4155 if has_worktrees {
4156 placeholder
4157 } else {
4158 if self.welcome_page.is_none() {
4159 let workspace = self.workspace.clone();
4160 self.welcome_page = Some(cx.new(|cx| {
4161 crate::welcome::WelcomePage::new(
4162 workspace, true, window, cx,
4163 )
4164 }));
4165 }
4166 placeholder.child(self.welcome_page.clone().unwrap())
4167 }
4168 }
4169 })
4170 .child(
4171 // drag target
4172 div()
4173 .invisible()
4174 .absolute()
4175 .bg(cx.theme().colors().drop_target_background)
4176 .group_drag_over::<DraggedTab>("", |style| style.visible())
4177 .group_drag_over::<DraggedSelection>("", |style| style.visible())
4178 .when(is_local, |div| {
4179 div.group_drag_over::<ExternalPaths>("", |style| style.visible())
4180 })
4181 .when_some(self.can_drop_predicate.clone(), |this, p| {
4182 this.can_drop(move |a, window, cx| p(a, window, cx))
4183 })
4184 .on_drop(cx.listener(move |this, dragged_tab, window, cx| {
4185 this.handle_tab_drop(
4186 dragged_tab,
4187 this.active_item_index(),
4188 window,
4189 cx,
4190 )
4191 }))
4192 .on_drop(cx.listener(
4193 move |this, selection: &DraggedSelection, window, cx| {
4194 this.handle_dragged_selection_drop(selection, None, window, cx)
4195 },
4196 ))
4197 .on_drop(cx.listener(move |this, paths, window, cx| {
4198 this.handle_external_paths_drop(paths, window, cx)
4199 }))
4200 .map(|div| {
4201 let size = DefiniteLength::Fraction(0.5);
4202 match self.drag_split_direction {
4203 None => div.top_0().right_0().bottom_0().left_0(),
4204 Some(SplitDirection::Up) => {
4205 div.top_0().left_0().right_0().h(size)
4206 }
4207 Some(SplitDirection::Down) => {
4208 div.left_0().bottom_0().right_0().h(size)
4209 }
4210 Some(SplitDirection::Left) => {
4211 div.top_0().left_0().bottom_0().w(size)
4212 }
4213 Some(SplitDirection::Right) => {
4214 div.top_0().bottom_0().right_0().w(size)
4215 }
4216 }
4217 }),
4218 )
4219 })
4220 .on_mouse_down(
4221 MouseButton::Navigate(NavigationDirection::Back),
4222 cx.listener(|pane, _, window, cx| {
4223 if let Some(workspace) = pane.workspace.upgrade() {
4224 let pane = cx.entity().downgrade();
4225 window.defer(cx, move |window, cx| {
4226 workspace.update(cx, |workspace, cx| {
4227 workspace.go_back(pane, window, cx).detach_and_log_err(cx)
4228 })
4229 })
4230 }
4231 }),
4232 )
4233 .on_mouse_down(
4234 MouseButton::Navigate(NavigationDirection::Forward),
4235 cx.listener(|pane, _, window, cx| {
4236 if let Some(workspace) = pane.workspace.upgrade() {
4237 let pane = cx.entity().downgrade();
4238 window.defer(cx, move |window, cx| {
4239 workspace.update(cx, |workspace, cx| {
4240 workspace
4241 .go_forward(pane, window, cx)
4242 .detach_and_log_err(cx)
4243 })
4244 })
4245 }
4246 }),
4247 )
4248 }
4249}
4250
4251impl ItemNavHistory {
4252 pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut App) {
4253 if self
4254 .item
4255 .upgrade()
4256 .is_some_and(|item| item.include_in_nav_history())
4257 {
4258 self.history
4259 .push(data, self.item.clone(), self.is_preview, cx);
4260 }
4261 }
4262
4263 pub fn pop_backward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
4264 self.history.pop(NavigationMode::GoingBack, cx)
4265 }
4266
4267 pub fn pop_forward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
4268 self.history.pop(NavigationMode::GoingForward, cx)
4269 }
4270}
4271
4272impl NavHistory {
4273 pub fn for_each_entry(
4274 &self,
4275 cx: &App,
4276 mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
4277 ) {
4278 let borrowed_history = self.0.lock();
4279 borrowed_history
4280 .forward_stack
4281 .iter()
4282 .chain(borrowed_history.backward_stack.iter())
4283 .chain(borrowed_history.closed_stack.iter())
4284 .for_each(|entry| {
4285 if let Some(project_and_abs_path) =
4286 borrowed_history.paths_by_item.get(&entry.item.id())
4287 {
4288 f(entry, project_and_abs_path.clone());
4289 } else if let Some(item) = entry.item.upgrade()
4290 && let Some(path) = item.project_path(cx)
4291 {
4292 f(entry, (path, None));
4293 }
4294 })
4295 }
4296
4297 pub fn set_mode(&mut self, mode: NavigationMode) {
4298 self.0.lock().mode = mode;
4299 }
4300
4301 pub fn mode(&self) -> NavigationMode {
4302 self.0.lock().mode
4303 }
4304
4305 pub fn disable(&mut self) {
4306 self.0.lock().mode = NavigationMode::Disabled;
4307 }
4308
4309 pub fn enable(&mut self) {
4310 self.0.lock().mode = NavigationMode::Normal;
4311 }
4312
4313 pub fn clear(&mut self, cx: &mut App) {
4314 let mut state = self.0.lock();
4315
4316 if state.backward_stack.is_empty()
4317 && state.forward_stack.is_empty()
4318 && state.closed_stack.is_empty()
4319 && state.paths_by_item.is_empty()
4320 {
4321 return;
4322 }
4323
4324 state.mode = NavigationMode::Normal;
4325 state.backward_stack.clear();
4326 state.forward_stack.clear();
4327 state.closed_stack.clear();
4328 state.paths_by_item.clear();
4329 state.did_update(cx);
4330 }
4331
4332 pub fn pop(&mut self, mode: NavigationMode, cx: &mut App) -> Option<NavigationEntry> {
4333 let mut state = self.0.lock();
4334 let entry = match mode {
4335 NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
4336 return None;
4337 }
4338 NavigationMode::GoingBack => &mut state.backward_stack,
4339 NavigationMode::GoingForward => &mut state.forward_stack,
4340 NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
4341 }
4342 .pop_back();
4343 if entry.is_some() {
4344 state.did_update(cx);
4345 }
4346 entry
4347 }
4348
4349 pub fn push<D: 'static + Send + Any>(
4350 &mut self,
4351 data: Option<D>,
4352 item: Arc<dyn WeakItemHandle>,
4353 is_preview: bool,
4354 cx: &mut App,
4355 ) {
4356 let state = &mut *self.0.lock();
4357 match state.mode {
4358 NavigationMode::Disabled => {}
4359 NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
4360 if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4361 state.backward_stack.pop_front();
4362 }
4363 state.backward_stack.push_back(NavigationEntry {
4364 item,
4365 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4366 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4367 is_preview,
4368 });
4369 state.forward_stack.clear();
4370 }
4371 NavigationMode::GoingBack => {
4372 if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4373 state.forward_stack.pop_front();
4374 }
4375 state.forward_stack.push_back(NavigationEntry {
4376 item,
4377 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4378 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4379 is_preview,
4380 });
4381 }
4382 NavigationMode::GoingForward => {
4383 if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4384 state.backward_stack.pop_front();
4385 }
4386 state.backward_stack.push_back(NavigationEntry {
4387 item,
4388 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4389 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4390 is_preview,
4391 });
4392 }
4393 NavigationMode::ClosingItem if is_preview => return,
4394 NavigationMode::ClosingItem => {
4395 if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4396 state.closed_stack.pop_front();
4397 }
4398 state.closed_stack.push_back(NavigationEntry {
4399 item,
4400 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4401 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4402 is_preview,
4403 });
4404 }
4405 }
4406 state.did_update(cx);
4407 }
4408
4409 pub fn remove_item(&mut self, item_id: EntityId) {
4410 let mut state = self.0.lock();
4411 state.paths_by_item.remove(&item_id);
4412 state
4413 .backward_stack
4414 .retain(|entry| entry.item.id() != item_id);
4415 state
4416 .forward_stack
4417 .retain(|entry| entry.item.id() != item_id);
4418 state
4419 .closed_stack
4420 .retain(|entry| entry.item.id() != item_id);
4421 }
4422
4423 pub fn rename_item(
4424 &mut self,
4425 item_id: EntityId,
4426 project_path: ProjectPath,
4427 abs_path: Option<PathBuf>,
4428 ) {
4429 let mut state = self.0.lock();
4430 let path_for_item = state.paths_by_item.get_mut(&item_id);
4431 if let Some(path_for_item) = path_for_item {
4432 path_for_item.0 = project_path;
4433 path_for_item.1 = abs_path;
4434 }
4435 }
4436
4437 pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
4438 self.0.lock().paths_by_item.get(&item_id).cloned()
4439 }
4440}
4441
4442impl NavHistoryState {
4443 pub fn did_update(&self, cx: &mut App) {
4444 if let Some(pane) = self.pane.upgrade() {
4445 cx.defer(move |cx| {
4446 pane.update(cx, |pane, cx| pane.history_updated(cx));
4447 });
4448 }
4449 }
4450}
4451
4452fn dirty_message_for(buffer_path: Option<ProjectPath>, path_style: PathStyle) -> String {
4453 let path = buffer_path
4454 .as_ref()
4455 .and_then(|p| {
4456 let path = p.path.display(path_style);
4457 if path.is_empty() { None } else { Some(path) }
4458 })
4459 .unwrap_or("This buffer".into());
4460 let path = truncate_and_remove_front(&path, 80);
4461 format!("{path} contains unsaved edits. Do you want to save it?")
4462}
4463
4464pub fn tab_details(items: &[Box<dyn ItemHandle>], _window: &Window, cx: &App) -> Vec<usize> {
4465 let mut tab_details = items.iter().map(|_| 0).collect::<Vec<_>>();
4466 let mut tab_descriptions = HashMap::default();
4467 let mut done = false;
4468 while !done {
4469 done = true;
4470
4471 // Store item indices by their tab description.
4472 for (ix, (item, detail)) in items.iter().zip(&tab_details).enumerate() {
4473 let description = item.tab_content_text(*detail, cx);
4474 if *detail == 0 || description != item.tab_content_text(detail - 1, cx) {
4475 tab_descriptions
4476 .entry(description)
4477 .or_insert(Vec::new())
4478 .push(ix);
4479 }
4480 }
4481
4482 // If two or more items have the same tab description, increase their level
4483 // of detail and try again.
4484 for (_, item_ixs) in tab_descriptions.drain() {
4485 if item_ixs.len() > 1 {
4486 done = false;
4487 for ix in item_ixs {
4488 tab_details[ix] += 1;
4489 }
4490 }
4491 }
4492 }
4493
4494 tab_details
4495}
4496
4497pub fn render_item_indicator(item: Box<dyn ItemHandle>, cx: &App) -> Option<Indicator> {
4498 maybe!({
4499 let indicator_color = match (item.has_conflict(cx), item.is_dirty(cx)) {
4500 (true, _) => Color::Warning,
4501 (_, true) => Color::Accent,
4502 (false, false) => return None,
4503 };
4504
4505 Some(Indicator::dot().color(indicator_color))
4506 })
4507}
4508
4509impl Render for DraggedTab {
4510 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4511 let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
4512 let label = self.item.tab_content(
4513 TabContentParams {
4514 detail: Some(self.detail),
4515 selected: false,
4516 preview: false,
4517 deemphasized: false,
4518 },
4519 window,
4520 cx,
4521 );
4522 Tab::new("")
4523 .toggle_state(self.is_active)
4524 .child(label)
4525 .render(window, cx)
4526 .font(ui_font)
4527 }
4528}
4529
4530#[cfg(test)]
4531mod tests {
4532 use std::{iter::zip, num::NonZero};
4533
4534 use super::*;
4535 use crate::{
4536 Member,
4537 item::test::{TestItem, TestProjectItem},
4538 };
4539 use gpui::{AppContext, Axis, TestAppContext, VisualTestContext, size};
4540 use project::FakeFs;
4541 use settings::SettingsStore;
4542 use theme::LoadThemes;
4543 use util::TryFutureExt;
4544
4545 #[gpui::test]
4546 async fn test_add_item_capped_to_max_tabs(cx: &mut TestAppContext) {
4547 init_test(cx);
4548 let fs = FakeFs::new(cx.executor());
4549
4550 let project = Project::test(fs, None, cx).await;
4551 let (workspace, cx) =
4552 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4553 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4554
4555 for i in 0..7 {
4556 add_labeled_item(&pane, format!("{}", i).as_str(), false, cx);
4557 }
4558
4559 set_max_tabs(cx, Some(5));
4560 add_labeled_item(&pane, "7", false, cx);
4561 // Remove items to respect the max tab cap.
4562 assert_item_labels(&pane, ["3", "4", "5", "6", "7*"], cx);
4563 pane.update_in(cx, |pane, window, cx| {
4564 pane.activate_item(0, false, false, window, cx);
4565 });
4566 add_labeled_item(&pane, "X", false, cx);
4567 // Respect activation order.
4568 assert_item_labels(&pane, ["3", "X*", "5", "6", "7"], cx);
4569
4570 for i in 0..7 {
4571 add_labeled_item(&pane, format!("D{}", i).as_str(), true, cx);
4572 }
4573 // Keeps dirty items, even over max tab cap.
4574 assert_item_labels(
4575 &pane,
4576 ["D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6*^"],
4577 cx,
4578 );
4579
4580 set_max_tabs(cx, None);
4581 for i in 0..7 {
4582 add_labeled_item(&pane, format!("N{}", i).as_str(), false, cx);
4583 }
4584 // No cap when max tabs is None.
4585 assert_item_labels(
4586 &pane,
4587 [
4588 "D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6^", "N0", "N1", "N2", "N3", "N4",
4589 "N5", "N6*",
4590 ],
4591 cx,
4592 );
4593 }
4594
4595 #[gpui::test]
4596 async fn test_reduce_max_tabs_closes_existing_items(cx: &mut TestAppContext) {
4597 init_test(cx);
4598 let fs = FakeFs::new(cx.executor());
4599
4600 let project = Project::test(fs, None, cx).await;
4601 let (workspace, cx) =
4602 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4603 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4604
4605 add_labeled_item(&pane, "A", false, cx);
4606 add_labeled_item(&pane, "B", false, cx);
4607 let item_c = add_labeled_item(&pane, "C", false, cx);
4608 let item_d = add_labeled_item(&pane, "D", false, cx);
4609 add_labeled_item(&pane, "E", false, cx);
4610 add_labeled_item(&pane, "Settings", false, cx);
4611 assert_item_labels(&pane, ["A", "B", "C", "D", "E", "Settings*"], cx);
4612
4613 set_max_tabs(cx, Some(5));
4614 assert_item_labels(&pane, ["B", "C", "D", "E", "Settings*"], cx);
4615
4616 set_max_tabs(cx, Some(4));
4617 assert_item_labels(&pane, ["C", "D", "E", "Settings*"], cx);
4618
4619 pane.update_in(cx, |pane, window, cx| {
4620 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4621 pane.pin_tab_at(ix, window, cx);
4622
4623 let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4624 pane.pin_tab_at(ix, window, cx);
4625 });
4626 assert_item_labels(&pane, ["C!", "D!", "E", "Settings*"], cx);
4627
4628 set_max_tabs(cx, Some(2));
4629 assert_item_labels(&pane, ["C!", "D!", "Settings*"], cx);
4630 }
4631
4632 #[gpui::test]
4633 async fn test_allow_pinning_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
4634 init_test(cx);
4635 let fs = FakeFs::new(cx.executor());
4636
4637 let project = Project::test(fs, None, cx).await;
4638 let (workspace, cx) =
4639 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4640 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4641
4642 set_max_tabs(cx, Some(1));
4643 let item_a = add_labeled_item(&pane, "A", true, cx);
4644
4645 pane.update_in(cx, |pane, window, cx| {
4646 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4647 pane.pin_tab_at(ix, window, cx);
4648 });
4649 assert_item_labels(&pane, ["A*^!"], cx);
4650 }
4651
4652 #[gpui::test]
4653 async fn test_allow_pinning_non_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
4654 init_test(cx);
4655 let fs = FakeFs::new(cx.executor());
4656
4657 let project = Project::test(fs, None, cx).await;
4658 let (workspace, cx) =
4659 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4660 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4661
4662 set_max_tabs(cx, Some(1));
4663 let item_a = add_labeled_item(&pane, "A", false, cx);
4664
4665 pane.update_in(cx, |pane, window, cx| {
4666 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4667 pane.pin_tab_at(ix, window, cx);
4668 });
4669 assert_item_labels(&pane, ["A*!"], cx);
4670 }
4671
4672 #[gpui::test]
4673 async fn test_pin_tabs_incrementally_at_max_capacity(cx: &mut TestAppContext) {
4674 init_test(cx);
4675 let fs = FakeFs::new(cx.executor());
4676
4677 let project = Project::test(fs, None, cx).await;
4678 let (workspace, cx) =
4679 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4680 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4681
4682 set_max_tabs(cx, Some(3));
4683
4684 let item_a = add_labeled_item(&pane, "A", false, cx);
4685 assert_item_labels(&pane, ["A*"], cx);
4686
4687 pane.update_in(cx, |pane, window, cx| {
4688 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4689 pane.pin_tab_at(ix, window, cx);
4690 });
4691 assert_item_labels(&pane, ["A*!"], cx);
4692
4693 let item_b = add_labeled_item(&pane, "B", false, cx);
4694 assert_item_labels(&pane, ["A!", "B*"], cx);
4695
4696 pane.update_in(cx, |pane, window, cx| {
4697 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4698 pane.pin_tab_at(ix, window, cx);
4699 });
4700 assert_item_labels(&pane, ["A!", "B*!"], cx);
4701
4702 let item_c = add_labeled_item(&pane, "C", false, cx);
4703 assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4704
4705 pane.update_in(cx, |pane, window, cx| {
4706 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4707 pane.pin_tab_at(ix, window, cx);
4708 });
4709 assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4710 }
4711
4712 #[gpui::test]
4713 async fn test_pin_tabs_left_to_right_after_opening_at_max_capacity(cx: &mut TestAppContext) {
4714 init_test(cx);
4715 let fs = FakeFs::new(cx.executor());
4716
4717 let project = Project::test(fs, None, cx).await;
4718 let (workspace, cx) =
4719 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4720 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4721
4722 set_max_tabs(cx, Some(3));
4723
4724 let item_a = add_labeled_item(&pane, "A", false, cx);
4725 assert_item_labels(&pane, ["A*"], cx);
4726
4727 let item_b = add_labeled_item(&pane, "B", false, cx);
4728 assert_item_labels(&pane, ["A", "B*"], cx);
4729
4730 let item_c = add_labeled_item(&pane, "C", false, cx);
4731 assert_item_labels(&pane, ["A", "B", "C*"], cx);
4732
4733 pane.update_in(cx, |pane, window, cx| {
4734 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4735 pane.pin_tab_at(ix, window, cx);
4736 });
4737 assert_item_labels(&pane, ["A!", "B", "C*"], cx);
4738
4739 pane.update_in(cx, |pane, window, cx| {
4740 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4741 pane.pin_tab_at(ix, window, cx);
4742 });
4743 assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4744
4745 pane.update_in(cx, |pane, window, cx| {
4746 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4747 pane.pin_tab_at(ix, window, cx);
4748 });
4749 assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4750 }
4751
4752 #[gpui::test]
4753 async fn test_pin_tabs_right_to_left_after_opening_at_max_capacity(cx: &mut TestAppContext) {
4754 init_test(cx);
4755 let fs = FakeFs::new(cx.executor());
4756
4757 let project = Project::test(fs, None, cx).await;
4758 let (workspace, cx) =
4759 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4760 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4761
4762 set_max_tabs(cx, Some(3));
4763
4764 let item_a = add_labeled_item(&pane, "A", false, cx);
4765 assert_item_labels(&pane, ["A*"], cx);
4766
4767 let item_b = add_labeled_item(&pane, "B", false, cx);
4768 assert_item_labels(&pane, ["A", "B*"], cx);
4769
4770 let item_c = add_labeled_item(&pane, "C", false, cx);
4771 assert_item_labels(&pane, ["A", "B", "C*"], cx);
4772
4773 pane.update_in(cx, |pane, window, cx| {
4774 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4775 pane.pin_tab_at(ix, window, cx);
4776 });
4777 assert_item_labels(&pane, ["C*!", "A", "B"], cx);
4778
4779 pane.update_in(cx, |pane, window, cx| {
4780 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4781 pane.pin_tab_at(ix, window, cx);
4782 });
4783 assert_item_labels(&pane, ["C*!", "B!", "A"], cx);
4784
4785 pane.update_in(cx, |pane, window, cx| {
4786 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4787 pane.pin_tab_at(ix, window, cx);
4788 });
4789 assert_item_labels(&pane, ["C*!", "B!", "A!"], cx);
4790 }
4791
4792 #[gpui::test]
4793 async fn test_pinned_tabs_never_closed_at_max_tabs(cx: &mut TestAppContext) {
4794 init_test(cx);
4795 let fs = FakeFs::new(cx.executor());
4796
4797 let project = Project::test(fs, None, cx).await;
4798 let (workspace, cx) =
4799 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4800 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4801
4802 let item_a = add_labeled_item(&pane, "A", false, cx);
4803 pane.update_in(cx, |pane, window, cx| {
4804 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4805 pane.pin_tab_at(ix, window, cx);
4806 });
4807
4808 let item_b = add_labeled_item(&pane, "B", false, cx);
4809 pane.update_in(cx, |pane, window, cx| {
4810 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4811 pane.pin_tab_at(ix, window, cx);
4812 });
4813
4814 add_labeled_item(&pane, "C", false, cx);
4815 add_labeled_item(&pane, "D", false, cx);
4816 add_labeled_item(&pane, "E", false, cx);
4817 assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
4818
4819 set_max_tabs(cx, Some(3));
4820 add_labeled_item(&pane, "F", false, cx);
4821 assert_item_labels(&pane, ["A!", "B!", "F*"], cx);
4822
4823 add_labeled_item(&pane, "G", false, cx);
4824 assert_item_labels(&pane, ["A!", "B!", "G*"], cx);
4825
4826 add_labeled_item(&pane, "H", false, cx);
4827 assert_item_labels(&pane, ["A!", "B!", "H*"], cx);
4828 }
4829
4830 #[gpui::test]
4831 async fn test_always_allows_one_unpinned_item_over_max_tabs_regardless_of_pinned_count(
4832 cx: &mut TestAppContext,
4833 ) {
4834 init_test(cx);
4835 let fs = FakeFs::new(cx.executor());
4836
4837 let project = Project::test(fs, None, cx).await;
4838 let (workspace, cx) =
4839 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4840 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4841
4842 set_max_tabs(cx, Some(3));
4843
4844 let item_a = add_labeled_item(&pane, "A", false, cx);
4845 pane.update_in(cx, |pane, window, cx| {
4846 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4847 pane.pin_tab_at(ix, window, cx);
4848 });
4849
4850 let item_b = add_labeled_item(&pane, "B", false, cx);
4851 pane.update_in(cx, |pane, window, cx| {
4852 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4853 pane.pin_tab_at(ix, window, cx);
4854 });
4855
4856 let item_c = add_labeled_item(&pane, "C", false, cx);
4857 pane.update_in(cx, |pane, window, cx| {
4858 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4859 pane.pin_tab_at(ix, window, cx);
4860 });
4861
4862 assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4863
4864 let item_d = add_labeled_item(&pane, "D", false, cx);
4865 assert_item_labels(&pane, ["A!", "B!", "C!", "D*"], cx);
4866
4867 pane.update_in(cx, |pane, window, cx| {
4868 let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4869 pane.pin_tab_at(ix, window, cx);
4870 });
4871 assert_item_labels(&pane, ["A!", "B!", "C!", "D*!"], cx);
4872
4873 add_labeled_item(&pane, "E", false, cx);
4874 assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "E*"], cx);
4875
4876 add_labeled_item(&pane, "F", false, cx);
4877 assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "F*"], cx);
4878 }
4879
4880 #[gpui::test]
4881 async fn test_can_open_one_item_when_all_tabs_are_dirty_at_max(cx: &mut TestAppContext) {
4882 init_test(cx);
4883 let fs = FakeFs::new(cx.executor());
4884
4885 let project = Project::test(fs, None, cx).await;
4886 let (workspace, cx) =
4887 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4888 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4889
4890 set_max_tabs(cx, Some(3));
4891
4892 add_labeled_item(&pane, "A", true, cx);
4893 assert_item_labels(&pane, ["A*^"], cx);
4894
4895 add_labeled_item(&pane, "B", true, cx);
4896 assert_item_labels(&pane, ["A^", "B*^"], cx);
4897
4898 add_labeled_item(&pane, "C", true, cx);
4899 assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
4900
4901 add_labeled_item(&pane, "D", false, cx);
4902 assert_item_labels(&pane, ["A^", "B^", "C^", "D*"], cx);
4903
4904 add_labeled_item(&pane, "E", false, cx);
4905 assert_item_labels(&pane, ["A^", "B^", "C^", "E*"], cx);
4906
4907 add_labeled_item(&pane, "F", false, cx);
4908 assert_item_labels(&pane, ["A^", "B^", "C^", "F*"], cx);
4909
4910 add_labeled_item(&pane, "G", true, cx);
4911 assert_item_labels(&pane, ["A^", "B^", "C^", "G*^"], cx);
4912 }
4913
4914 #[gpui::test]
4915 async fn test_toggle_pin_tab(cx: &mut TestAppContext) {
4916 init_test(cx);
4917 let fs = FakeFs::new(cx.executor());
4918
4919 let project = Project::test(fs, None, cx).await;
4920 let (workspace, cx) =
4921 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4922 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4923
4924 set_labeled_items(&pane, ["A", "B*", "C"], cx);
4925 assert_item_labels(&pane, ["A", "B*", "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 pane.update_in(cx, |pane, window, cx| {
4933 pane.toggle_pin_tab(&TogglePinTab, window, cx);
4934 });
4935 assert_item_labels(&pane, ["B*", "A", "C"], cx);
4936 }
4937
4938 #[gpui::test]
4939 async fn test_unpin_all_tabs(cx: &mut TestAppContext) {
4940 init_test(cx);
4941 let fs = FakeFs::new(cx.executor());
4942
4943 let project = Project::test(fs, None, cx).await;
4944 let (workspace, cx) =
4945 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4946 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4947
4948 // Unpin all, in an empty pane
4949 pane.update_in(cx, |pane, window, cx| {
4950 pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4951 });
4952
4953 assert_item_labels(&pane, [], cx);
4954
4955 let item_a = add_labeled_item(&pane, "A", false, cx);
4956 let item_b = add_labeled_item(&pane, "B", false, cx);
4957 let item_c = add_labeled_item(&pane, "C", false, cx);
4958 assert_item_labels(&pane, ["A", "B", "C*"], cx);
4959
4960 // Unpin all, when no tabs are pinned
4961 pane.update_in(cx, |pane, window, cx| {
4962 pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4963 });
4964
4965 assert_item_labels(&pane, ["A", "B", "C*"], cx);
4966
4967 // Pin inactive tabs only
4968 pane.update_in(cx, |pane, window, cx| {
4969 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4970 pane.pin_tab_at(ix, window, cx);
4971
4972 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4973 pane.pin_tab_at(ix, window, cx);
4974 });
4975 assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4976
4977 pane.update_in(cx, |pane, window, cx| {
4978 pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4979 });
4980
4981 assert_item_labels(&pane, ["A", "B", "C*"], cx);
4982
4983 // Pin all tabs
4984 pane.update_in(cx, |pane, window, cx| {
4985 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4986 pane.pin_tab_at(ix, window, cx);
4987
4988 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4989 pane.pin_tab_at(ix, window, cx);
4990
4991 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4992 pane.pin_tab_at(ix, window, cx);
4993 });
4994 assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4995
4996 // Activate middle tab
4997 pane.update_in(cx, |pane, window, cx| {
4998 pane.activate_item(1, false, false, window, cx);
4999 });
5000 assert_item_labels(&pane, ["A!", "B*!", "C!"], cx);
5001
5002 pane.update_in(cx, |pane, window, cx| {
5003 pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
5004 });
5005
5006 // Order has not changed
5007 assert_item_labels(&pane, ["A", "B*", "C"], cx);
5008 }
5009
5010 #[gpui::test]
5011 async fn test_pinning_active_tab_without_position_change_maintains_focus(
5012 cx: &mut TestAppContext,
5013 ) {
5014 init_test(cx);
5015 let fs = FakeFs::new(cx.executor());
5016
5017 let project = Project::test(fs, None, cx).await;
5018 let (workspace, cx) =
5019 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5020 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5021
5022 // Add A
5023 let item_a = add_labeled_item(&pane, "A", false, cx);
5024 assert_item_labels(&pane, ["A*"], cx);
5025
5026 // Add B
5027 add_labeled_item(&pane, "B", false, cx);
5028 assert_item_labels(&pane, ["A", "B*"], cx);
5029
5030 // Activate A again
5031 pane.update_in(cx, |pane, window, cx| {
5032 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5033 pane.activate_item(ix, true, true, window, cx);
5034 });
5035 assert_item_labels(&pane, ["A*", "B"], cx);
5036
5037 // Pin A - remains active
5038 pane.update_in(cx, |pane, window, cx| {
5039 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5040 pane.pin_tab_at(ix, window, cx);
5041 });
5042 assert_item_labels(&pane, ["A*!", "B"], cx);
5043
5044 // Unpin A - remain active
5045 pane.update_in(cx, |pane, window, cx| {
5046 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5047 pane.unpin_tab_at(ix, window, cx);
5048 });
5049 assert_item_labels(&pane, ["A*", "B"], cx);
5050 }
5051
5052 #[gpui::test]
5053 async fn test_pinning_active_tab_with_position_change_maintains_focus(cx: &mut TestAppContext) {
5054 init_test(cx);
5055 let fs = FakeFs::new(cx.executor());
5056
5057 let project = Project::test(fs, None, cx).await;
5058 let (workspace, cx) =
5059 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5060 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5061
5062 // Add A, B, C
5063 add_labeled_item(&pane, "A", false, cx);
5064 add_labeled_item(&pane, "B", false, cx);
5065 let item_c = add_labeled_item(&pane, "C", false, cx);
5066 assert_item_labels(&pane, ["A", "B", "C*"], cx);
5067
5068 // Pin C - moves to pinned area, remains active
5069 pane.update_in(cx, |pane, window, cx| {
5070 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5071 pane.pin_tab_at(ix, window, cx);
5072 });
5073 assert_item_labels(&pane, ["C*!", "A", "B"], cx);
5074
5075 // Unpin C - moves after pinned area, remains active
5076 pane.update_in(cx, |pane, window, cx| {
5077 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5078 pane.unpin_tab_at(ix, window, cx);
5079 });
5080 assert_item_labels(&pane, ["C*", "A", "B"], cx);
5081 }
5082
5083 #[gpui::test]
5084 async fn test_pinning_inactive_tab_without_position_change_preserves_existing_focus(
5085 cx: &mut TestAppContext,
5086 ) {
5087 init_test(cx);
5088 let fs = FakeFs::new(cx.executor());
5089
5090 let project = Project::test(fs, None, cx).await;
5091 let (workspace, cx) =
5092 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5093 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5094
5095 // Add A, B
5096 let item_a = add_labeled_item(&pane, "A", false, cx);
5097 add_labeled_item(&pane, "B", false, cx);
5098 assert_item_labels(&pane, ["A", "B*"], cx);
5099
5100 // Pin A - already in pinned area, B remains active
5101 pane.update_in(cx, |pane, window, cx| {
5102 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5103 pane.pin_tab_at(ix, window, cx);
5104 });
5105 assert_item_labels(&pane, ["A!", "B*"], cx);
5106
5107 // Unpin A - stays in place, B remains active
5108 pane.update_in(cx, |pane, window, cx| {
5109 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5110 pane.unpin_tab_at(ix, window, cx);
5111 });
5112 assert_item_labels(&pane, ["A", "B*"], cx);
5113 }
5114
5115 #[gpui::test]
5116 async fn test_pinning_inactive_tab_with_position_change_preserves_existing_focus(
5117 cx: &mut TestAppContext,
5118 ) {
5119 init_test(cx);
5120 let fs = FakeFs::new(cx.executor());
5121
5122 let project = Project::test(fs, None, cx).await;
5123 let (workspace, cx) =
5124 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5125 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5126
5127 // Add A, B, C
5128 add_labeled_item(&pane, "A", false, cx);
5129 let item_b = add_labeled_item(&pane, "B", false, cx);
5130 let item_c = add_labeled_item(&pane, "C", false, cx);
5131 assert_item_labels(&pane, ["A", "B", "C*"], cx);
5132
5133 // Activate B
5134 pane.update_in(cx, |pane, window, cx| {
5135 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5136 pane.activate_item(ix, true, true, window, cx);
5137 });
5138 assert_item_labels(&pane, ["A", "B*", "C"], cx);
5139
5140 // Pin C - moves to pinned area, B remains active
5141 pane.update_in(cx, |pane, window, cx| {
5142 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5143 pane.pin_tab_at(ix, window, cx);
5144 });
5145 assert_item_labels(&pane, ["C!", "A", "B*"], cx);
5146
5147 // Unpin C - moves after pinned area, B remains active
5148 pane.update_in(cx, |pane, window, cx| {
5149 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5150 pane.unpin_tab_at(ix, window, cx);
5151 });
5152 assert_item_labels(&pane, ["C", "A", "B*"], cx);
5153 }
5154
5155 #[gpui::test]
5156 async fn test_drag_unpinned_tab_to_split_creates_pane_with_unpinned_tab(
5157 cx: &mut TestAppContext,
5158 ) {
5159 init_test(cx);
5160 let fs = FakeFs::new(cx.executor());
5161
5162 let project = Project::test(fs, None, cx).await;
5163 let (workspace, cx) =
5164 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5165 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5166
5167 // Add A, B. Pin B. Activate A
5168 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5169 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5170
5171 pane_a.update_in(cx, |pane, window, cx| {
5172 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5173 pane.pin_tab_at(ix, window, cx);
5174
5175 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5176 pane.activate_item(ix, true, true, window, cx);
5177 });
5178
5179 // Drag A to create new split
5180 pane_a.update_in(cx, |pane, window, cx| {
5181 pane.drag_split_direction = Some(SplitDirection::Right);
5182
5183 let dragged_tab = DraggedTab {
5184 pane: pane_a.clone(),
5185 item: item_a.boxed_clone(),
5186 ix: 0,
5187 detail: 0,
5188 is_active: true,
5189 };
5190 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5191 });
5192
5193 // A should be moved to new pane. B should remain pinned, A should not be pinned
5194 let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
5195 let panes = workspace.panes();
5196 (panes[0].clone(), panes[1].clone())
5197 });
5198 assert_item_labels(&pane_a, ["B*!"], cx);
5199 assert_item_labels(&pane_b, ["A*"], cx);
5200 }
5201
5202 #[gpui::test]
5203 async fn test_drag_pinned_tab_to_split_creates_pane_with_pinned_tab(cx: &mut TestAppContext) {
5204 init_test(cx);
5205 let fs = FakeFs::new(cx.executor());
5206
5207 let project = Project::test(fs, None, cx).await;
5208 let (workspace, cx) =
5209 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5210 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5211
5212 // Add A, B. Pin both. Activate A
5213 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5214 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5215
5216 pane_a.update_in(cx, |pane, window, cx| {
5217 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5218 pane.pin_tab_at(ix, window, cx);
5219
5220 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5221 pane.pin_tab_at(ix, window, cx);
5222
5223 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5224 pane.activate_item(ix, true, true, window, cx);
5225 });
5226 assert_item_labels(&pane_a, ["A*!", "B!"], cx);
5227
5228 // Drag A to create new split
5229 pane_a.update_in(cx, |pane, window, cx| {
5230 pane.drag_split_direction = Some(SplitDirection::Right);
5231
5232 let dragged_tab = DraggedTab {
5233 pane: pane_a.clone(),
5234 item: item_a.boxed_clone(),
5235 ix: 0,
5236 detail: 0,
5237 is_active: true,
5238 };
5239 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5240 });
5241
5242 // A should be moved to new pane. Both A and B should still be pinned
5243 let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
5244 let panes = workspace.panes();
5245 (panes[0].clone(), panes[1].clone())
5246 });
5247 assert_item_labels(&pane_a, ["B*!"], cx);
5248 assert_item_labels(&pane_b, ["A*!"], cx);
5249 }
5250
5251 #[gpui::test]
5252 async fn test_drag_pinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
5253 init_test(cx);
5254 let fs = FakeFs::new(cx.executor());
5255
5256 let project = Project::test(fs, None, cx).await;
5257 let (workspace, cx) =
5258 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5259 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5260
5261 // Add A to pane A and pin
5262 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5263 pane_a.update_in(cx, |pane, window, cx| {
5264 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5265 pane.pin_tab_at(ix, window, cx);
5266 });
5267 assert_item_labels(&pane_a, ["A*!"], cx);
5268
5269 // Add B to pane B and pin
5270 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5271 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5272 });
5273 let item_b = add_labeled_item(&pane_b, "B", false, cx);
5274 pane_b.update_in(cx, |pane, window, cx| {
5275 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5276 pane.pin_tab_at(ix, window, cx);
5277 });
5278 assert_item_labels(&pane_b, ["B*!"], cx);
5279
5280 // Move A from pane A to pane B's pinned region
5281 pane_b.update_in(cx, |pane, window, cx| {
5282 let dragged_tab = DraggedTab {
5283 pane: pane_a.clone(),
5284 item: item_a.boxed_clone(),
5285 ix: 0,
5286 detail: 0,
5287 is_active: true,
5288 };
5289 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5290 });
5291
5292 // A should stay pinned
5293 assert_item_labels(&pane_a, [], cx);
5294 assert_item_labels(&pane_b, ["A*!", "B!"], cx);
5295 }
5296
5297 #[gpui::test]
5298 async fn test_drag_pinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
5299 init_test(cx);
5300 let fs = FakeFs::new(cx.executor());
5301
5302 let project = Project::test(fs, None, cx).await;
5303 let (workspace, cx) =
5304 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5305 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5306
5307 // Add A to pane A and pin
5308 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5309 pane_a.update_in(cx, |pane, window, cx| {
5310 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5311 pane.pin_tab_at(ix, window, cx);
5312 });
5313 assert_item_labels(&pane_a, ["A*!"], cx);
5314
5315 // Create pane B with pinned item B
5316 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5317 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5318 });
5319 let item_b = add_labeled_item(&pane_b, "B", false, cx);
5320 assert_item_labels(&pane_b, ["B*"], cx);
5321
5322 pane_b.update_in(cx, |pane, window, cx| {
5323 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5324 pane.pin_tab_at(ix, window, cx);
5325 });
5326 assert_item_labels(&pane_b, ["B*!"], cx);
5327
5328 // Move A from pane A to pane B's unpinned region
5329 pane_b.update_in(cx, |pane, window, cx| {
5330 let dragged_tab = DraggedTab {
5331 pane: pane_a.clone(),
5332 item: item_a.boxed_clone(),
5333 ix: 0,
5334 detail: 0,
5335 is_active: true,
5336 };
5337 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5338 });
5339
5340 // A should become pinned
5341 assert_item_labels(&pane_a, [], cx);
5342 assert_item_labels(&pane_b, ["B!", "A*"], cx);
5343 }
5344
5345 #[gpui::test]
5346 async fn test_drag_pinned_tab_into_existing_panes_first_position_with_no_pinned_tabs(
5347 cx: &mut TestAppContext,
5348 ) {
5349 init_test(cx);
5350 let fs = FakeFs::new(cx.executor());
5351
5352 let project = Project::test(fs, None, cx).await;
5353 let (workspace, cx) =
5354 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5355 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5356
5357 // Add A to pane A and pin
5358 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5359 pane_a.update_in(cx, |pane, window, cx| {
5360 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5361 pane.pin_tab_at(ix, window, cx);
5362 });
5363 assert_item_labels(&pane_a, ["A*!"], cx);
5364
5365 // Add B to pane B
5366 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5367 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5368 });
5369 add_labeled_item(&pane_b, "B", false, cx);
5370 assert_item_labels(&pane_b, ["B*"], cx);
5371
5372 // Move A from pane A to position 0 in pane B, indicating it should stay pinned
5373 pane_b.update_in(cx, |pane, window, cx| {
5374 let dragged_tab = DraggedTab {
5375 pane: pane_a.clone(),
5376 item: item_a.boxed_clone(),
5377 ix: 0,
5378 detail: 0,
5379 is_active: true,
5380 };
5381 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5382 });
5383
5384 // A should stay pinned
5385 assert_item_labels(&pane_a, [], cx);
5386 assert_item_labels(&pane_b, ["A*!", "B"], cx);
5387 }
5388
5389 #[gpui::test]
5390 async fn test_drag_pinned_tab_into_existing_pane_at_max_capacity_closes_unpinned_tabs(
5391 cx: &mut TestAppContext,
5392 ) {
5393 init_test(cx);
5394 let fs = FakeFs::new(cx.executor());
5395
5396 let project = Project::test(fs, None, cx).await;
5397 let (workspace, cx) =
5398 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5399 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5400 set_max_tabs(cx, Some(2));
5401
5402 // Add A, B to pane A. Pin both
5403 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5404 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5405 pane_a.update_in(cx, |pane, window, cx| {
5406 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5407 pane.pin_tab_at(ix, window, cx);
5408
5409 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5410 pane.pin_tab_at(ix, window, cx);
5411 });
5412 assert_item_labels(&pane_a, ["A!", "B*!"], cx);
5413
5414 // Add C, D to pane B. Pin both
5415 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5416 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5417 });
5418 let item_c = add_labeled_item(&pane_b, "C", false, cx);
5419 let item_d = add_labeled_item(&pane_b, "D", false, cx);
5420 pane_b.update_in(cx, |pane, window, cx| {
5421 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5422 pane.pin_tab_at(ix, window, cx);
5423
5424 let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
5425 pane.pin_tab_at(ix, window, cx);
5426 });
5427 assert_item_labels(&pane_b, ["C!", "D*!"], cx);
5428
5429 // Add a third unpinned item to pane B (exceeds max tabs), but is allowed,
5430 // as we allow 1 tab over max if the others are pinned or dirty
5431 add_labeled_item(&pane_b, "E", false, cx);
5432 assert_item_labels(&pane_b, ["C!", "D!", "E*"], cx);
5433
5434 // Drag pinned A from pane A to position 0 in pane B
5435 pane_b.update_in(cx, |pane, window, cx| {
5436 let dragged_tab = DraggedTab {
5437 pane: pane_a.clone(),
5438 item: item_a.boxed_clone(),
5439 ix: 0,
5440 detail: 0,
5441 is_active: true,
5442 };
5443 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5444 });
5445
5446 // E (unpinned) should be closed, leaving 3 pinned items
5447 assert_item_labels(&pane_a, ["B*!"], cx);
5448 assert_item_labels(&pane_b, ["A*!", "C!", "D!"], cx);
5449 }
5450
5451 #[gpui::test]
5452 async fn test_drag_last_pinned_tab_to_same_position_stays_pinned(cx: &mut TestAppContext) {
5453 init_test(cx);
5454 let fs = FakeFs::new(cx.executor());
5455
5456 let project = Project::test(fs, None, cx).await;
5457 let (workspace, cx) =
5458 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5459 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5460
5461 // Add A to pane A and pin it
5462 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5463 pane_a.update_in(cx, |pane, window, cx| {
5464 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5465 pane.pin_tab_at(ix, window, cx);
5466 });
5467 assert_item_labels(&pane_a, ["A*!"], cx);
5468
5469 // Drag pinned A to position 1 (directly to the right) in the same pane
5470 pane_a.update_in(cx, |pane, window, cx| {
5471 let dragged_tab = DraggedTab {
5472 pane: pane_a.clone(),
5473 item: item_a.boxed_clone(),
5474 ix: 0,
5475 detail: 0,
5476 is_active: true,
5477 };
5478 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5479 });
5480
5481 // A should still be pinned and active
5482 assert_item_labels(&pane_a, ["A*!"], cx);
5483 }
5484
5485 #[gpui::test]
5486 async fn test_drag_pinned_tab_beyond_last_pinned_tab_in_same_pane_stays_pinned(
5487 cx: &mut TestAppContext,
5488 ) {
5489 init_test(cx);
5490 let fs = FakeFs::new(cx.executor());
5491
5492 let project = Project::test(fs, None, cx).await;
5493 let (workspace, cx) =
5494 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5495 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5496
5497 // Add A, B to pane A and pin both
5498 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5499 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5500 pane_a.update_in(cx, |pane, window, cx| {
5501 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5502 pane.pin_tab_at(ix, window, cx);
5503
5504 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5505 pane.pin_tab_at(ix, window, cx);
5506 });
5507 assert_item_labels(&pane_a, ["A!", "B*!"], cx);
5508
5509 // Drag pinned A right of B in the same pane
5510 pane_a.update_in(cx, |pane, window, cx| {
5511 let dragged_tab = DraggedTab {
5512 pane: pane_a.clone(),
5513 item: item_a.boxed_clone(),
5514 ix: 0,
5515 detail: 0,
5516 is_active: true,
5517 };
5518 pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5519 });
5520
5521 // A stays pinned
5522 assert_item_labels(&pane_a, ["B!", "A*!"], cx);
5523 }
5524
5525 #[gpui::test]
5526 async fn test_dragging_pinned_tab_onto_unpinned_tab_reduces_unpinned_tab_count(
5527 cx: &mut TestAppContext,
5528 ) {
5529 init_test(cx);
5530 let fs = FakeFs::new(cx.executor());
5531
5532 let project = Project::test(fs, None, cx).await;
5533 let (workspace, cx) =
5534 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5535 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5536
5537 // Add A, B to pane A and pin A
5538 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5539 add_labeled_item(&pane_a, "B", false, cx);
5540 pane_a.update_in(cx, |pane, window, cx| {
5541 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5542 pane.pin_tab_at(ix, window, cx);
5543 });
5544 assert_item_labels(&pane_a, ["A!", "B*"], cx);
5545
5546 // Drag pinned A on top of B in the same pane, which changes tab order to B, A
5547 pane_a.update_in(cx, |pane, window, cx| {
5548 let dragged_tab = DraggedTab {
5549 pane: pane_a.clone(),
5550 item: item_a.boxed_clone(),
5551 ix: 0,
5552 detail: 0,
5553 is_active: true,
5554 };
5555 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5556 });
5557
5558 // Neither are pinned
5559 assert_item_labels(&pane_a, ["B", "A*"], cx);
5560 }
5561
5562 #[gpui::test]
5563 async fn test_drag_pinned_tab_beyond_unpinned_tab_in_same_pane_becomes_unpinned(
5564 cx: &mut TestAppContext,
5565 ) {
5566 init_test(cx);
5567 let fs = FakeFs::new(cx.executor());
5568
5569 let project = Project::test(fs, None, cx).await;
5570 let (workspace, cx) =
5571 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5572 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5573
5574 // Add A, B to pane A and pin A
5575 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5576 add_labeled_item(&pane_a, "B", false, cx);
5577 pane_a.update_in(cx, |pane, window, cx| {
5578 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5579 pane.pin_tab_at(ix, window, cx);
5580 });
5581 assert_item_labels(&pane_a, ["A!", "B*"], cx);
5582
5583 // Drag pinned A right of B in the same pane
5584 pane_a.update_in(cx, |pane, window, cx| {
5585 let dragged_tab = DraggedTab {
5586 pane: pane_a.clone(),
5587 item: item_a.boxed_clone(),
5588 ix: 0,
5589 detail: 0,
5590 is_active: true,
5591 };
5592 pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5593 });
5594
5595 // A becomes unpinned
5596 assert_item_labels(&pane_a, ["B", "A*"], cx);
5597 }
5598
5599 #[gpui::test]
5600 async fn test_drag_unpinned_tab_in_front_of_pinned_tab_in_same_pane_becomes_pinned(
5601 cx: &mut TestAppContext,
5602 ) {
5603 init_test(cx);
5604 let fs = FakeFs::new(cx.executor());
5605
5606 let project = Project::test(fs, None, cx).await;
5607 let (workspace, cx) =
5608 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5609 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5610
5611 // Add A, B to pane A and pin A
5612 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5613 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5614 pane_a.update_in(cx, |pane, window, cx| {
5615 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5616 pane.pin_tab_at(ix, window, cx);
5617 });
5618 assert_item_labels(&pane_a, ["A!", "B*"], cx);
5619
5620 // Drag pinned B left of A in the same pane
5621 pane_a.update_in(cx, |pane, window, cx| {
5622 let dragged_tab = DraggedTab {
5623 pane: pane_a.clone(),
5624 item: item_b.boxed_clone(),
5625 ix: 1,
5626 detail: 0,
5627 is_active: true,
5628 };
5629 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5630 });
5631
5632 // A becomes unpinned
5633 assert_item_labels(&pane_a, ["B*!", "A!"], cx);
5634 }
5635
5636 #[gpui::test]
5637 async fn test_drag_unpinned_tab_to_the_pinned_region_stays_pinned(cx: &mut TestAppContext) {
5638 init_test(cx);
5639 let fs = FakeFs::new(cx.executor());
5640
5641 let project = Project::test(fs, None, cx).await;
5642 let (workspace, cx) =
5643 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5644 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5645
5646 // Add A, B, C to pane A and pin A
5647 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5648 add_labeled_item(&pane_a, "B", false, cx);
5649 let item_c = add_labeled_item(&pane_a, "C", false, cx);
5650 pane_a.update_in(cx, |pane, window, cx| {
5651 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5652 pane.pin_tab_at(ix, window, cx);
5653 });
5654 assert_item_labels(&pane_a, ["A!", "B", "C*"], cx);
5655
5656 // Drag pinned C left of B in the same pane
5657 pane_a.update_in(cx, |pane, window, cx| {
5658 let dragged_tab = DraggedTab {
5659 pane: pane_a.clone(),
5660 item: item_c.boxed_clone(),
5661 ix: 2,
5662 detail: 0,
5663 is_active: true,
5664 };
5665 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5666 });
5667
5668 // A stays pinned, B and C remain unpinned
5669 assert_item_labels(&pane_a, ["A!", "C*", "B"], cx);
5670 }
5671
5672 #[gpui::test]
5673 async fn test_drag_unpinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
5674 init_test(cx);
5675 let fs = FakeFs::new(cx.executor());
5676
5677 let project = Project::test(fs, None, cx).await;
5678 let (workspace, cx) =
5679 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5680 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5681
5682 // Add unpinned item A to pane A
5683 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5684 assert_item_labels(&pane_a, ["A*"], cx);
5685
5686 // Create pane B with pinned item B
5687 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5688 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5689 });
5690 let item_b = add_labeled_item(&pane_b, "B", false, cx);
5691 pane_b.update_in(cx, |pane, window, cx| {
5692 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5693 pane.pin_tab_at(ix, window, cx);
5694 });
5695 assert_item_labels(&pane_b, ["B*!"], cx);
5696
5697 // Move A from pane A to pane B's pinned region
5698 pane_b.update_in(cx, |pane, window, cx| {
5699 let dragged_tab = DraggedTab {
5700 pane: pane_a.clone(),
5701 item: item_a.boxed_clone(),
5702 ix: 0,
5703 detail: 0,
5704 is_active: true,
5705 };
5706 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5707 });
5708
5709 // A should become pinned since it was dropped in the pinned region
5710 assert_item_labels(&pane_a, [], cx);
5711 assert_item_labels(&pane_b, ["A*!", "B!"], cx);
5712 }
5713
5714 #[gpui::test]
5715 async fn test_drag_unpinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
5716 init_test(cx);
5717 let fs = FakeFs::new(cx.executor());
5718
5719 let project = Project::test(fs, None, cx).await;
5720 let (workspace, cx) =
5721 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5722 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5723
5724 // Add unpinned item A to pane A
5725 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5726 assert_item_labels(&pane_a, ["A*"], cx);
5727
5728 // Create pane B with one pinned item B
5729 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5730 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5731 });
5732 let item_b = add_labeled_item(&pane_b, "B", false, cx);
5733 pane_b.update_in(cx, |pane, window, cx| {
5734 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5735 pane.pin_tab_at(ix, window, cx);
5736 });
5737 assert_item_labels(&pane_b, ["B*!"], cx);
5738
5739 // Move A from pane A to pane B's unpinned region
5740 pane_b.update_in(cx, |pane, window, cx| {
5741 let dragged_tab = DraggedTab {
5742 pane: pane_a.clone(),
5743 item: item_a.boxed_clone(),
5744 ix: 0,
5745 detail: 0,
5746 is_active: true,
5747 };
5748 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5749 });
5750
5751 // A should remain unpinned since it was dropped outside the pinned region
5752 assert_item_labels(&pane_a, [], cx);
5753 assert_item_labels(&pane_b, ["B!", "A*"], cx);
5754 }
5755
5756 #[gpui::test]
5757 async fn test_drag_pinned_tab_throughout_entire_range_of_pinned_tabs_both_directions(
5758 cx: &mut TestAppContext,
5759 ) {
5760 init_test(cx);
5761 let fs = FakeFs::new(cx.executor());
5762
5763 let project = Project::test(fs, None, cx).await;
5764 let (workspace, cx) =
5765 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5766 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5767
5768 // Add A, B, C and pin all
5769 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5770 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5771 let item_c = add_labeled_item(&pane_a, "C", false, cx);
5772 assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5773
5774 pane_a.update_in(cx, |pane, window, cx| {
5775 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5776 pane.pin_tab_at(ix, window, cx);
5777
5778 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5779 pane.pin_tab_at(ix, window, cx);
5780
5781 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5782 pane.pin_tab_at(ix, window, cx);
5783 });
5784 assert_item_labels(&pane_a, ["A!", "B!", "C*!"], cx);
5785
5786 // Move A to right of B
5787 pane_a.update_in(cx, |pane, window, cx| {
5788 let dragged_tab = DraggedTab {
5789 pane: pane_a.clone(),
5790 item: item_a.boxed_clone(),
5791 ix: 0,
5792 detail: 0,
5793 is_active: true,
5794 };
5795 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5796 });
5797
5798 // A should be after B and all are pinned
5799 assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
5800
5801 // Move A to right of C
5802 pane_a.update_in(cx, |pane, window, cx| {
5803 let dragged_tab = DraggedTab {
5804 pane: pane_a.clone(),
5805 item: item_a.boxed_clone(),
5806 ix: 1,
5807 detail: 0,
5808 is_active: true,
5809 };
5810 pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5811 });
5812
5813 // A should be after C and all are pinned
5814 assert_item_labels(&pane_a, ["B!", "C!", "A*!"], cx);
5815
5816 // Move A to left of C
5817 pane_a.update_in(cx, |pane, window, cx| {
5818 let dragged_tab = DraggedTab {
5819 pane: pane_a.clone(),
5820 item: item_a.boxed_clone(),
5821 ix: 2,
5822 detail: 0,
5823 is_active: true,
5824 };
5825 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5826 });
5827
5828 // A should be before C and all are pinned
5829 assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
5830
5831 // Move A to left of B
5832 pane_a.update_in(cx, |pane, window, cx| {
5833 let dragged_tab = DraggedTab {
5834 pane: pane_a.clone(),
5835 item: item_a.boxed_clone(),
5836 ix: 1,
5837 detail: 0,
5838 is_active: true,
5839 };
5840 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5841 });
5842
5843 // A should be before B and all are pinned
5844 assert_item_labels(&pane_a, ["A*!", "B!", "C!"], cx);
5845 }
5846
5847 #[gpui::test]
5848 async fn test_drag_first_tab_to_last_position(cx: &mut TestAppContext) {
5849 init_test(cx);
5850 let fs = FakeFs::new(cx.executor());
5851
5852 let project = Project::test(fs, None, cx).await;
5853 let (workspace, cx) =
5854 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5855 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5856
5857 // Add A, B, C
5858 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5859 add_labeled_item(&pane_a, "B", false, cx);
5860 add_labeled_item(&pane_a, "C", false, cx);
5861 assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5862
5863 // Move A to the end
5864 pane_a.update_in(cx, |pane, window, cx| {
5865 let dragged_tab = DraggedTab {
5866 pane: pane_a.clone(),
5867 item: item_a.boxed_clone(),
5868 ix: 0,
5869 detail: 0,
5870 is_active: true,
5871 };
5872 pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5873 });
5874
5875 // A should be at the end
5876 assert_item_labels(&pane_a, ["B", "C", "A*"], cx);
5877 }
5878
5879 #[gpui::test]
5880 async fn test_drag_last_tab_to_first_position(cx: &mut TestAppContext) {
5881 init_test(cx);
5882 let fs = FakeFs::new(cx.executor());
5883
5884 let project = Project::test(fs, None, cx).await;
5885 let (workspace, cx) =
5886 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5887 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5888
5889 // Add A, B, C
5890 add_labeled_item(&pane_a, "A", false, cx);
5891 add_labeled_item(&pane_a, "B", false, cx);
5892 let item_c = add_labeled_item(&pane_a, "C", false, cx);
5893 assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5894
5895 // Move C to the beginning
5896 pane_a.update_in(cx, |pane, window, cx| {
5897 let dragged_tab = DraggedTab {
5898 pane: pane_a.clone(),
5899 item: item_c.boxed_clone(),
5900 ix: 2,
5901 detail: 0,
5902 is_active: true,
5903 };
5904 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5905 });
5906
5907 // C should be at the beginning
5908 assert_item_labels(&pane_a, ["C*", "A", "B"], cx);
5909 }
5910
5911 #[gpui::test]
5912 async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
5913 init_test(cx);
5914 let fs = FakeFs::new(cx.executor());
5915
5916 let project = Project::test(fs, None, cx).await;
5917 let (workspace, cx) =
5918 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5919 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5920
5921 // 1. Add with a destination index
5922 // a. Add before the active item
5923 set_labeled_items(&pane, ["A", "B*", "C"], cx);
5924 pane.update_in(cx, |pane, window, cx| {
5925 pane.add_item(
5926 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5927 false,
5928 false,
5929 Some(0),
5930 window,
5931 cx,
5932 );
5933 });
5934 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
5935
5936 // b. Add after the active item
5937 set_labeled_items(&pane, ["A", "B*", "C"], cx);
5938 pane.update_in(cx, |pane, window, cx| {
5939 pane.add_item(
5940 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5941 false,
5942 false,
5943 Some(2),
5944 window,
5945 cx,
5946 );
5947 });
5948 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
5949
5950 // c. Add at the end of the item list (including off the length)
5951 set_labeled_items(&pane, ["A", "B*", "C"], cx);
5952 pane.update_in(cx, |pane, window, cx| {
5953 pane.add_item(
5954 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5955 false,
5956 false,
5957 Some(5),
5958 window,
5959 cx,
5960 );
5961 });
5962 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5963
5964 // 2. Add without a destination index
5965 // a. Add with active item at the start of the item list
5966 set_labeled_items(&pane, ["A*", "B", "C"], cx);
5967 pane.update_in(cx, |pane, window, cx| {
5968 pane.add_item(
5969 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5970 false,
5971 false,
5972 None,
5973 window,
5974 cx,
5975 );
5976 });
5977 set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
5978
5979 // b. Add with active item at the end of the item list
5980 set_labeled_items(&pane, ["A", "B", "C*"], cx);
5981 pane.update_in(cx, |pane, window, cx| {
5982 pane.add_item(
5983 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5984 false,
5985 false,
5986 None,
5987 window,
5988 cx,
5989 );
5990 });
5991 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5992 }
5993
5994 #[gpui::test]
5995 async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
5996 init_test(cx);
5997 let fs = FakeFs::new(cx.executor());
5998
5999 let project = Project::test(fs, None, cx).await;
6000 let (workspace, cx) =
6001 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6002 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6003
6004 // 1. Add with a destination index
6005 // 1a. Add before the active item
6006 let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
6007 pane.update_in(cx, |pane, window, cx| {
6008 pane.add_item(d, false, false, Some(0), window, cx);
6009 });
6010 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
6011
6012 // 1b. Add after the active item
6013 let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
6014 pane.update_in(cx, |pane, window, cx| {
6015 pane.add_item(d, false, false, Some(2), window, cx);
6016 });
6017 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
6018
6019 // 1c. Add at the end of the item list (including off the length)
6020 let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
6021 pane.update_in(cx, |pane, window, cx| {
6022 pane.add_item(a, false, false, Some(5), window, cx);
6023 });
6024 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
6025
6026 // 1d. Add same item to active index
6027 let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
6028 pane.update_in(cx, |pane, window, cx| {
6029 pane.add_item(b, false, false, Some(1), window, cx);
6030 });
6031 assert_item_labels(&pane, ["A", "B*", "C"], cx);
6032
6033 // 1e. Add item to index after same item in last position
6034 let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
6035 pane.update_in(cx, |pane, window, cx| {
6036 pane.add_item(c, false, false, Some(2), window, cx);
6037 });
6038 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6039
6040 // 2. Add without a destination index
6041 // 2a. Add with active item at the start of the item list
6042 let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
6043 pane.update_in(cx, |pane, window, cx| {
6044 pane.add_item(d, false, false, None, window, cx);
6045 });
6046 assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
6047
6048 // 2b. Add with active item at the end of the item list
6049 let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
6050 pane.update_in(cx, |pane, window, cx| {
6051 pane.add_item(a, false, false, None, window, cx);
6052 });
6053 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
6054
6055 // 2c. Add active item to active item at end of list
6056 let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
6057 pane.update_in(cx, |pane, window, cx| {
6058 pane.add_item(c, false, false, None, window, cx);
6059 });
6060 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6061
6062 // 2d. Add active item to active item at start of list
6063 let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
6064 pane.update_in(cx, |pane, window, cx| {
6065 pane.add_item(a, false, false, None, window, cx);
6066 });
6067 assert_item_labels(&pane, ["A*", "B", "C"], cx);
6068 }
6069
6070 #[gpui::test]
6071 async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
6072 init_test(cx);
6073 let fs = FakeFs::new(cx.executor());
6074
6075 let project = Project::test(fs, None, cx).await;
6076 let (workspace, cx) =
6077 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6078 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6079
6080 // singleton view
6081 pane.update_in(cx, |pane, window, cx| {
6082 pane.add_item(
6083 Box::new(cx.new(|cx| {
6084 TestItem::new(cx)
6085 .with_buffer_kind(ItemBufferKind::Singleton)
6086 .with_label("buffer 1")
6087 .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
6088 })),
6089 false,
6090 false,
6091 None,
6092 window,
6093 cx,
6094 );
6095 });
6096 assert_item_labels(&pane, ["buffer 1*"], cx);
6097
6098 // new singleton view with the same project entry
6099 pane.update_in(cx, |pane, window, cx| {
6100 pane.add_item(
6101 Box::new(cx.new(|cx| {
6102 TestItem::new(cx)
6103 .with_buffer_kind(ItemBufferKind::Singleton)
6104 .with_label("buffer 1")
6105 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
6106 })),
6107 false,
6108 false,
6109 None,
6110 window,
6111 cx,
6112 );
6113 });
6114 assert_item_labels(&pane, ["buffer 1*"], cx);
6115
6116 // new singleton view with different project entry
6117 pane.update_in(cx, |pane, window, cx| {
6118 pane.add_item(
6119 Box::new(cx.new(|cx| {
6120 TestItem::new(cx)
6121 .with_buffer_kind(ItemBufferKind::Singleton)
6122 .with_label("buffer 2")
6123 .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
6124 })),
6125 false,
6126 false,
6127 None,
6128 window,
6129 cx,
6130 );
6131 });
6132 assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
6133
6134 // new multibuffer view with the same project entry
6135 pane.update_in(cx, |pane, window, cx| {
6136 pane.add_item(
6137 Box::new(cx.new(|cx| {
6138 TestItem::new(cx)
6139 .with_buffer_kind(ItemBufferKind::Multibuffer)
6140 .with_label("multibuffer 1")
6141 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
6142 })),
6143 false,
6144 false,
6145 None,
6146 window,
6147 cx,
6148 );
6149 });
6150 assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
6151
6152 // another multibuffer view with the same project entry
6153 pane.update_in(cx, |pane, window, cx| {
6154 pane.add_item(
6155 Box::new(cx.new(|cx| {
6156 TestItem::new(cx)
6157 .with_buffer_kind(ItemBufferKind::Multibuffer)
6158 .with_label("multibuffer 1b")
6159 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
6160 })),
6161 false,
6162 false,
6163 None,
6164 window,
6165 cx,
6166 );
6167 });
6168 assert_item_labels(
6169 &pane,
6170 ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
6171 cx,
6172 );
6173 }
6174
6175 #[gpui::test]
6176 async fn test_remove_item_ordering_history(cx: &mut TestAppContext) {
6177 init_test(cx);
6178 let fs = FakeFs::new(cx.executor());
6179
6180 let project = Project::test(fs, None, cx).await;
6181 let (workspace, cx) =
6182 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6183 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6184
6185 add_labeled_item(&pane, "A", false, cx);
6186 add_labeled_item(&pane, "B", false, cx);
6187 add_labeled_item(&pane, "C", false, cx);
6188 add_labeled_item(&pane, "D", false, cx);
6189 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6190
6191 pane.update_in(cx, |pane, window, cx| {
6192 pane.activate_item(1, false, false, window, cx)
6193 });
6194 add_labeled_item(&pane, "1", false, cx);
6195 assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
6196
6197 pane.update_in(cx, |pane, window, cx| {
6198 pane.close_active_item(
6199 &CloseActiveItem {
6200 save_intent: None,
6201 close_pinned: false,
6202 },
6203 window,
6204 cx,
6205 )
6206 })
6207 .await
6208 .unwrap();
6209 assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
6210
6211 pane.update_in(cx, |pane, window, cx| {
6212 pane.activate_item(3, false, false, window, cx)
6213 });
6214 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6215
6216 pane.update_in(cx, |pane, window, cx| {
6217 pane.close_active_item(
6218 &CloseActiveItem {
6219 save_intent: None,
6220 close_pinned: false,
6221 },
6222 window,
6223 cx,
6224 )
6225 })
6226 .await
6227 .unwrap();
6228 assert_item_labels(&pane, ["A", "B*", "C"], cx);
6229
6230 pane.update_in(cx, |pane, window, cx| {
6231 pane.close_active_item(
6232 &CloseActiveItem {
6233 save_intent: None,
6234 close_pinned: false,
6235 },
6236 window,
6237 cx,
6238 )
6239 })
6240 .await
6241 .unwrap();
6242 assert_item_labels(&pane, ["A", "C*"], cx);
6243
6244 pane.update_in(cx, |pane, window, cx| {
6245 pane.close_active_item(
6246 &CloseActiveItem {
6247 save_intent: None,
6248 close_pinned: false,
6249 },
6250 window,
6251 cx,
6252 )
6253 })
6254 .await
6255 .unwrap();
6256 assert_item_labels(&pane, ["A*"], cx);
6257 }
6258
6259 #[gpui::test]
6260 async fn test_remove_item_ordering_neighbour(cx: &mut TestAppContext) {
6261 init_test(cx);
6262 cx.update_global::<SettingsStore, ()>(|s, cx| {
6263 s.update_user_settings(cx, |s| {
6264 s.tabs.get_or_insert_default().activate_on_close = Some(ActivateOnClose::Neighbour);
6265 });
6266 });
6267 let fs = FakeFs::new(cx.executor());
6268
6269 let project = Project::test(fs, None, cx).await;
6270 let (workspace, cx) =
6271 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6272 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6273
6274 add_labeled_item(&pane, "A", false, cx);
6275 add_labeled_item(&pane, "B", false, cx);
6276 add_labeled_item(&pane, "C", false, cx);
6277 add_labeled_item(&pane, "D", false, cx);
6278 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6279
6280 pane.update_in(cx, |pane, window, cx| {
6281 pane.activate_item(1, false, false, window, cx)
6282 });
6283 add_labeled_item(&pane, "1", false, cx);
6284 assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
6285
6286 pane.update_in(cx, |pane, window, cx| {
6287 pane.close_active_item(
6288 &CloseActiveItem {
6289 save_intent: None,
6290 close_pinned: false,
6291 },
6292 window,
6293 cx,
6294 )
6295 })
6296 .await
6297 .unwrap();
6298 assert_item_labels(&pane, ["A", "B", "C*", "D"], cx);
6299
6300 pane.update_in(cx, |pane, window, cx| {
6301 pane.activate_item(3, false, false, window, cx)
6302 });
6303 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6304
6305 pane.update_in(cx, |pane, window, cx| {
6306 pane.close_active_item(
6307 &CloseActiveItem {
6308 save_intent: None,
6309 close_pinned: false,
6310 },
6311 window,
6312 cx,
6313 )
6314 })
6315 .await
6316 .unwrap();
6317 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6318
6319 pane.update_in(cx, |pane, window, cx| {
6320 pane.close_active_item(
6321 &CloseActiveItem {
6322 save_intent: None,
6323 close_pinned: false,
6324 },
6325 window,
6326 cx,
6327 )
6328 })
6329 .await
6330 .unwrap();
6331 assert_item_labels(&pane, ["A", "B*"], cx);
6332
6333 pane.update_in(cx, |pane, window, cx| {
6334 pane.close_active_item(
6335 &CloseActiveItem {
6336 save_intent: None,
6337 close_pinned: false,
6338 },
6339 window,
6340 cx,
6341 )
6342 })
6343 .await
6344 .unwrap();
6345 assert_item_labels(&pane, ["A*"], cx);
6346 }
6347
6348 #[gpui::test]
6349 async fn test_remove_item_ordering_left_neighbour(cx: &mut TestAppContext) {
6350 init_test(cx);
6351 cx.update_global::<SettingsStore, ()>(|s, cx| {
6352 s.update_user_settings(cx, |s| {
6353 s.tabs.get_or_insert_default().activate_on_close =
6354 Some(ActivateOnClose::LeftNeighbour);
6355 });
6356 });
6357 let fs = FakeFs::new(cx.executor());
6358
6359 let project = Project::test(fs, None, cx).await;
6360 let (workspace, cx) =
6361 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6362 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6363
6364 add_labeled_item(&pane, "A", false, cx);
6365 add_labeled_item(&pane, "B", false, cx);
6366 add_labeled_item(&pane, "C", false, cx);
6367 add_labeled_item(&pane, "D", false, cx);
6368 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6369
6370 pane.update_in(cx, |pane, window, cx| {
6371 pane.activate_item(1, false, false, window, cx)
6372 });
6373 add_labeled_item(&pane, "1", false, cx);
6374 assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
6375
6376 pane.update_in(cx, |pane, window, cx| {
6377 pane.close_active_item(
6378 &CloseActiveItem {
6379 save_intent: None,
6380 close_pinned: false,
6381 },
6382 window,
6383 cx,
6384 )
6385 })
6386 .await
6387 .unwrap();
6388 assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
6389
6390 pane.update_in(cx, |pane, window, cx| {
6391 pane.activate_item(3, false, false, window, cx)
6392 });
6393 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6394
6395 pane.update_in(cx, |pane, window, cx| {
6396 pane.close_active_item(
6397 &CloseActiveItem {
6398 save_intent: None,
6399 close_pinned: false,
6400 },
6401 window,
6402 cx,
6403 )
6404 })
6405 .await
6406 .unwrap();
6407 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6408
6409 pane.update_in(cx, |pane, window, cx| {
6410 pane.activate_item(0, false, false, window, cx)
6411 });
6412 assert_item_labels(&pane, ["A*", "B", "C"], cx);
6413
6414 pane.update_in(cx, |pane, window, cx| {
6415 pane.close_active_item(
6416 &CloseActiveItem {
6417 save_intent: None,
6418 close_pinned: false,
6419 },
6420 window,
6421 cx,
6422 )
6423 })
6424 .await
6425 .unwrap();
6426 assert_item_labels(&pane, ["B*", "C"], cx);
6427
6428 pane.update_in(cx, |pane, window, cx| {
6429 pane.close_active_item(
6430 &CloseActiveItem {
6431 save_intent: None,
6432 close_pinned: false,
6433 },
6434 window,
6435 cx,
6436 )
6437 })
6438 .await
6439 .unwrap();
6440 assert_item_labels(&pane, ["C*"], cx);
6441 }
6442
6443 #[gpui::test]
6444 async fn test_close_inactive_items(cx: &mut TestAppContext) {
6445 init_test(cx);
6446 let fs = FakeFs::new(cx.executor());
6447
6448 let project = Project::test(fs, None, cx).await;
6449 let (workspace, cx) =
6450 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6451 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6452
6453 let item_a = add_labeled_item(&pane, "A", false, cx);
6454 pane.update_in(cx, |pane, window, cx| {
6455 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6456 pane.pin_tab_at(ix, window, cx);
6457 });
6458 assert_item_labels(&pane, ["A*!"], cx);
6459
6460 let item_b = add_labeled_item(&pane, "B", false, cx);
6461 pane.update_in(cx, |pane, window, cx| {
6462 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6463 pane.pin_tab_at(ix, window, cx);
6464 });
6465 assert_item_labels(&pane, ["A!", "B*!"], cx);
6466
6467 add_labeled_item(&pane, "C", false, cx);
6468 assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
6469
6470 add_labeled_item(&pane, "D", false, cx);
6471 add_labeled_item(&pane, "E", false, cx);
6472 assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
6473
6474 pane.update_in(cx, |pane, window, cx| {
6475 pane.close_other_items(
6476 &CloseOtherItems {
6477 save_intent: None,
6478 close_pinned: false,
6479 },
6480 None,
6481 window,
6482 cx,
6483 )
6484 })
6485 .await
6486 .unwrap();
6487 assert_item_labels(&pane, ["A!", "B!", "E*"], cx);
6488 }
6489
6490 #[gpui::test]
6491 async fn test_running_close_inactive_items_via_an_inactive_item(cx: &mut TestAppContext) {
6492 init_test(cx);
6493 let fs = FakeFs::new(cx.executor());
6494
6495 let project = Project::test(fs, None, cx).await;
6496 let (workspace, cx) =
6497 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6498 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6499
6500 add_labeled_item(&pane, "A", false, cx);
6501 assert_item_labels(&pane, ["A*"], cx);
6502
6503 let item_b = add_labeled_item(&pane, "B", false, cx);
6504 assert_item_labels(&pane, ["A", "B*"], cx);
6505
6506 add_labeled_item(&pane, "C", false, cx);
6507 add_labeled_item(&pane, "D", false, cx);
6508 add_labeled_item(&pane, "E", false, cx);
6509 assert_item_labels(&pane, ["A", "B", "C", "D", "E*"], cx);
6510
6511 pane.update_in(cx, |pane, window, cx| {
6512 pane.close_other_items(
6513 &CloseOtherItems {
6514 save_intent: None,
6515 close_pinned: false,
6516 },
6517 Some(item_b.item_id()),
6518 window,
6519 cx,
6520 )
6521 })
6522 .await
6523 .unwrap();
6524 assert_item_labels(&pane, ["B*"], cx);
6525 }
6526
6527 #[gpui::test]
6528 async fn test_close_other_items_unpreviews_active_item(cx: &mut TestAppContext) {
6529 init_test(cx);
6530 let fs = FakeFs::new(cx.executor());
6531
6532 let project = Project::test(fs, None, cx).await;
6533 let (workspace, cx) =
6534 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6535 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6536
6537 add_labeled_item(&pane, "A", false, cx);
6538 add_labeled_item(&pane, "B", false, cx);
6539 let item_c = add_labeled_item(&pane, "C", false, cx);
6540 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6541
6542 pane.update(cx, |pane, cx| {
6543 pane.set_preview_item_id(Some(item_c.item_id()), cx);
6544 });
6545 assert!(pane.read_with(cx, |pane, _| pane.preview_item_id()
6546 == Some(item_c.item_id())));
6547
6548 pane.update_in(cx, |pane, window, cx| {
6549 pane.close_other_items(
6550 &CloseOtherItems {
6551 save_intent: None,
6552 close_pinned: false,
6553 },
6554 Some(item_c.item_id()),
6555 window,
6556 cx,
6557 )
6558 })
6559 .await
6560 .unwrap();
6561
6562 assert!(pane.read_with(cx, |pane, _| pane.preview_item_id().is_none()));
6563 assert_item_labels(&pane, ["C*"], cx);
6564 }
6565
6566 #[gpui::test]
6567 async fn test_close_clean_items(cx: &mut TestAppContext) {
6568 init_test(cx);
6569 let fs = FakeFs::new(cx.executor());
6570
6571 let project = Project::test(fs, None, cx).await;
6572 let (workspace, cx) =
6573 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6574 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6575
6576 add_labeled_item(&pane, "A", true, cx);
6577 add_labeled_item(&pane, "B", false, cx);
6578 add_labeled_item(&pane, "C", true, cx);
6579 add_labeled_item(&pane, "D", false, cx);
6580 add_labeled_item(&pane, "E", false, cx);
6581 assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
6582
6583 pane.update_in(cx, |pane, window, cx| {
6584 pane.close_clean_items(
6585 &CloseCleanItems {
6586 close_pinned: false,
6587 },
6588 window,
6589 cx,
6590 )
6591 })
6592 .await
6593 .unwrap();
6594 assert_item_labels(&pane, ["A^", "C*^"], cx);
6595 }
6596
6597 #[gpui::test]
6598 async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
6599 init_test(cx);
6600 let fs = FakeFs::new(cx.executor());
6601
6602 let project = Project::test(fs, None, cx).await;
6603 let (workspace, cx) =
6604 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6605 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6606
6607 set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
6608
6609 pane.update_in(cx, |pane, window, cx| {
6610 pane.close_items_to_the_left_by_id(
6611 None,
6612 &CloseItemsToTheLeft {
6613 close_pinned: false,
6614 },
6615 window,
6616 cx,
6617 )
6618 })
6619 .await
6620 .unwrap();
6621 assert_item_labels(&pane, ["C*", "D", "E"], cx);
6622 }
6623
6624 #[gpui::test]
6625 async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
6626 init_test(cx);
6627 let fs = FakeFs::new(cx.executor());
6628
6629 let project = Project::test(fs, None, cx).await;
6630 let (workspace, cx) =
6631 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6632 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6633
6634 set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
6635
6636 pane.update_in(cx, |pane, window, cx| {
6637 pane.close_items_to_the_right_by_id(
6638 None,
6639 &CloseItemsToTheRight {
6640 close_pinned: false,
6641 },
6642 window,
6643 cx,
6644 )
6645 })
6646 .await
6647 .unwrap();
6648 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6649 }
6650
6651 #[gpui::test]
6652 async fn test_close_all_items(cx: &mut TestAppContext) {
6653 init_test(cx);
6654 let fs = FakeFs::new(cx.executor());
6655
6656 let project = Project::test(fs, None, cx).await;
6657 let (workspace, cx) =
6658 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6659 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6660
6661 let item_a = add_labeled_item(&pane, "A", false, cx);
6662 add_labeled_item(&pane, "B", false, cx);
6663 add_labeled_item(&pane, "C", false, cx);
6664 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6665
6666 pane.update_in(cx, |pane, window, cx| {
6667 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6668 pane.pin_tab_at(ix, window, cx);
6669 pane.close_all_items(
6670 &CloseAllItems {
6671 save_intent: None,
6672 close_pinned: false,
6673 },
6674 window,
6675 cx,
6676 )
6677 })
6678 .await
6679 .unwrap();
6680 assert_item_labels(&pane, ["A*!"], cx);
6681
6682 pane.update_in(cx, |pane, window, cx| {
6683 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6684 pane.unpin_tab_at(ix, window, cx);
6685 pane.close_all_items(
6686 &CloseAllItems {
6687 save_intent: None,
6688 close_pinned: false,
6689 },
6690 window,
6691 cx,
6692 )
6693 })
6694 .await
6695 .unwrap();
6696
6697 assert_item_labels(&pane, [], cx);
6698
6699 add_labeled_item(&pane, "A", true, cx).update(cx, |item, cx| {
6700 item.project_items
6701 .push(TestProjectItem::new_dirty(1, "A.txt", cx))
6702 });
6703 add_labeled_item(&pane, "B", true, cx).update(cx, |item, cx| {
6704 item.project_items
6705 .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6706 });
6707 add_labeled_item(&pane, "C", true, cx).update(cx, |item, cx| {
6708 item.project_items
6709 .push(TestProjectItem::new_dirty(3, "C.txt", cx))
6710 });
6711 assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6712
6713 let save = pane.update_in(cx, |pane, window, cx| {
6714 pane.close_all_items(
6715 &CloseAllItems {
6716 save_intent: None,
6717 close_pinned: false,
6718 },
6719 window,
6720 cx,
6721 )
6722 });
6723
6724 cx.executor().run_until_parked();
6725 cx.simulate_prompt_answer("Save all");
6726 save.await.unwrap();
6727 assert_item_labels(&pane, [], cx);
6728
6729 add_labeled_item(&pane, "A", true, cx);
6730 add_labeled_item(&pane, "B", true, cx);
6731 add_labeled_item(&pane, "C", true, cx);
6732 assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6733 let save = pane.update_in(cx, |pane, window, cx| {
6734 pane.close_all_items(
6735 &CloseAllItems {
6736 save_intent: None,
6737 close_pinned: false,
6738 },
6739 window,
6740 cx,
6741 )
6742 });
6743
6744 cx.executor().run_until_parked();
6745 cx.simulate_prompt_answer("Discard all");
6746 save.await.unwrap();
6747 assert_item_labels(&pane, [], cx);
6748
6749 add_labeled_item(&pane, "A", true, cx).update(cx, |item, cx| {
6750 item.project_items
6751 .push(TestProjectItem::new_dirty(1, "A.txt", cx))
6752 });
6753 add_labeled_item(&pane, "B", true, cx).update(cx, |item, cx| {
6754 item.project_items
6755 .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6756 });
6757 add_labeled_item(&pane, "C", true, cx).update(cx, |item, cx| {
6758 item.project_items
6759 .push(TestProjectItem::new_dirty(3, "C.txt", cx))
6760 });
6761 assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6762
6763 let close_task = pane.update_in(cx, |pane, window, cx| {
6764 pane.close_all_items(
6765 &CloseAllItems {
6766 save_intent: None,
6767 close_pinned: false,
6768 },
6769 window,
6770 cx,
6771 )
6772 });
6773
6774 cx.executor().run_until_parked();
6775 cx.simulate_prompt_answer("Discard all");
6776 close_task.await.unwrap();
6777 assert_item_labels(&pane, [], cx);
6778
6779 add_labeled_item(&pane, "Clean1", false, cx);
6780 add_labeled_item(&pane, "Dirty", true, cx).update(cx, |item, cx| {
6781 item.project_items
6782 .push(TestProjectItem::new_dirty(1, "Dirty.txt", cx))
6783 });
6784 add_labeled_item(&pane, "Clean2", false, cx);
6785 assert_item_labels(&pane, ["Clean1", "Dirty^", "Clean2*"], cx);
6786
6787 let close_task = pane.update_in(cx, |pane, window, cx| {
6788 pane.close_all_items(
6789 &CloseAllItems {
6790 save_intent: None,
6791 close_pinned: false,
6792 },
6793 window,
6794 cx,
6795 )
6796 });
6797
6798 cx.executor().run_until_parked();
6799 cx.simulate_prompt_answer("Cancel");
6800 close_task.await.unwrap();
6801 assert_item_labels(&pane, ["Dirty*^"], cx);
6802 }
6803
6804 #[gpui::test]
6805 async fn test_close_multibuffer_items(cx: &mut TestAppContext) {
6806 init_test(cx);
6807 let fs = FakeFs::new(cx.executor());
6808
6809 let project = Project::test(fs, None, cx).await;
6810 let (workspace, cx) =
6811 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6812 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6813
6814 let add_labeled_item = |pane: &Entity<Pane>,
6815 label,
6816 is_dirty,
6817 kind: ItemBufferKind,
6818 cx: &mut VisualTestContext| {
6819 pane.update_in(cx, |pane, window, cx| {
6820 let labeled_item = Box::new(cx.new(|cx| {
6821 TestItem::new(cx)
6822 .with_label(label)
6823 .with_dirty(is_dirty)
6824 .with_buffer_kind(kind)
6825 }));
6826 pane.add_item(labeled_item.clone(), false, false, None, window, cx);
6827 labeled_item
6828 })
6829 };
6830
6831 let item_a = add_labeled_item(&pane, "A", false, ItemBufferKind::Multibuffer, cx);
6832 add_labeled_item(&pane, "B", false, ItemBufferKind::Multibuffer, cx);
6833 add_labeled_item(&pane, "C", false, ItemBufferKind::Singleton, cx);
6834 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6835
6836 pane.update_in(cx, |pane, window, cx| {
6837 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6838 pane.pin_tab_at(ix, window, cx);
6839 pane.close_multibuffer_items(
6840 &CloseMultibufferItems {
6841 save_intent: None,
6842 close_pinned: false,
6843 },
6844 window,
6845 cx,
6846 )
6847 })
6848 .await
6849 .unwrap();
6850 assert_item_labels(&pane, ["A!", "C*"], cx);
6851
6852 pane.update_in(cx, |pane, window, cx| {
6853 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6854 pane.unpin_tab_at(ix, window, cx);
6855 pane.close_multibuffer_items(
6856 &CloseMultibufferItems {
6857 save_intent: None,
6858 close_pinned: false,
6859 },
6860 window,
6861 cx,
6862 )
6863 })
6864 .await
6865 .unwrap();
6866
6867 assert_item_labels(&pane, ["C*"], cx);
6868
6869 add_labeled_item(&pane, "A", true, ItemBufferKind::Singleton, cx).update(cx, |item, cx| {
6870 item.project_items
6871 .push(TestProjectItem::new_dirty(1, "A.txt", cx))
6872 });
6873 add_labeled_item(&pane, "B", true, ItemBufferKind::Multibuffer, cx).update(
6874 cx,
6875 |item, cx| {
6876 item.project_items
6877 .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6878 },
6879 );
6880 add_labeled_item(&pane, "D", true, ItemBufferKind::Multibuffer, cx).update(
6881 cx,
6882 |item, cx| {
6883 item.project_items
6884 .push(TestProjectItem::new_dirty(3, "D.txt", cx))
6885 },
6886 );
6887 assert_item_labels(&pane, ["C", "A^", "B^", "D*^"], cx);
6888
6889 let save = pane.update_in(cx, |pane, window, cx| {
6890 pane.close_multibuffer_items(
6891 &CloseMultibufferItems {
6892 save_intent: None,
6893 close_pinned: false,
6894 },
6895 window,
6896 cx,
6897 )
6898 });
6899
6900 cx.executor().run_until_parked();
6901 cx.simulate_prompt_answer("Save all");
6902 save.await.unwrap();
6903 assert_item_labels(&pane, ["C", "A*^"], cx);
6904
6905 add_labeled_item(&pane, "B", true, ItemBufferKind::Multibuffer, cx).update(
6906 cx,
6907 |item, cx| {
6908 item.project_items
6909 .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6910 },
6911 );
6912 add_labeled_item(&pane, "D", true, ItemBufferKind::Multibuffer, cx).update(
6913 cx,
6914 |item, cx| {
6915 item.project_items
6916 .push(TestProjectItem::new_dirty(3, "D.txt", cx))
6917 },
6918 );
6919 assert_item_labels(&pane, ["C", "A^", "B^", "D*^"], cx);
6920 let save = pane.update_in(cx, |pane, window, cx| {
6921 pane.close_multibuffer_items(
6922 &CloseMultibufferItems {
6923 save_intent: None,
6924 close_pinned: false,
6925 },
6926 window,
6927 cx,
6928 )
6929 });
6930
6931 cx.executor().run_until_parked();
6932 cx.simulate_prompt_answer("Discard all");
6933 save.await.unwrap();
6934 assert_item_labels(&pane, ["C", "A*^"], cx);
6935 }
6936
6937 #[gpui::test]
6938 async fn test_close_with_save_intent(cx: &mut TestAppContext) {
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 let a = cx.update(|_, cx| TestProjectItem::new_dirty(1, "A.txt", cx));
6948 let b = cx.update(|_, cx| TestProjectItem::new_dirty(1, "B.txt", cx));
6949 let c = cx.update(|_, cx| TestProjectItem::new_dirty(1, "C.txt", cx));
6950
6951 add_labeled_item(&pane, "AB", true, cx).update(cx, |item, _| {
6952 item.project_items.push(a.clone());
6953 item.project_items.push(b.clone());
6954 });
6955 add_labeled_item(&pane, "C", true, cx)
6956 .update(cx, |item, _| item.project_items.push(c.clone()));
6957 assert_item_labels(&pane, ["AB^", "C*^"], cx);
6958
6959 pane.update_in(cx, |pane, window, cx| {
6960 pane.close_all_items(
6961 &CloseAllItems {
6962 save_intent: Some(SaveIntent::Save),
6963 close_pinned: false,
6964 },
6965 window,
6966 cx,
6967 )
6968 })
6969 .await
6970 .unwrap();
6971
6972 assert_item_labels(&pane, [], cx);
6973 cx.update(|_, cx| {
6974 assert!(!a.read(cx).is_dirty);
6975 assert!(!b.read(cx).is_dirty);
6976 assert!(!c.read(cx).is_dirty);
6977 });
6978 }
6979
6980 #[gpui::test]
6981 async fn test_new_tab_scrolls_into_view_completely(cx: &mut TestAppContext) {
6982 // Arrange
6983 init_test(cx);
6984 let fs = FakeFs::new(cx.executor());
6985
6986 let project = Project::test(fs, None, cx).await;
6987 let (workspace, cx) =
6988 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6989 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6990
6991 cx.simulate_resize(size(px(300.), px(300.)));
6992
6993 add_labeled_item(&pane, "untitled", false, cx);
6994 add_labeled_item(&pane, "untitled", false, cx);
6995 add_labeled_item(&pane, "untitled", false, cx);
6996 add_labeled_item(&pane, "untitled", false, cx);
6997 // Act: this should trigger a scroll
6998 add_labeled_item(&pane, "untitled", false, cx);
6999 // Assert
7000 let tab_bar_scroll_handle =
7001 pane.update_in(cx, |pane, _window, _cx| pane.tab_bar_scroll_handle.clone());
7002 assert_eq!(tab_bar_scroll_handle.children_count(), 6);
7003 let tab_bounds = cx.debug_bounds("TAB-4").unwrap();
7004 let new_tab_button_bounds = cx.debug_bounds("ICON-Plus").unwrap();
7005 let scroll_bounds = tab_bar_scroll_handle.bounds();
7006 let scroll_offset = tab_bar_scroll_handle.offset();
7007 assert!(tab_bounds.right() <= scroll_bounds.right());
7008 // -43.0 is the magic number for this setup
7009 assert_eq!(scroll_offset.x, px(-43.0));
7010 assert!(
7011 !tab_bounds.intersects(&new_tab_button_bounds),
7012 "Tab should not overlap with the new tab button, if this is failing check if there's been a redesign!"
7013 );
7014 }
7015
7016 #[gpui::test]
7017 async fn test_close_all_items_including_pinned(cx: &mut TestAppContext) {
7018 init_test(cx);
7019 let fs = FakeFs::new(cx.executor());
7020
7021 let project = Project::test(fs, None, cx).await;
7022 let (workspace, cx) =
7023 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
7024 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7025
7026 let item_a = add_labeled_item(&pane, "A", false, cx);
7027 add_labeled_item(&pane, "B", false, cx);
7028 add_labeled_item(&pane, "C", false, cx);
7029 assert_item_labels(&pane, ["A", "B", "C*"], cx);
7030
7031 pane.update_in(cx, |pane, window, cx| {
7032 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
7033 pane.pin_tab_at(ix, window, cx);
7034 pane.close_all_items(
7035 &CloseAllItems {
7036 save_intent: None,
7037 close_pinned: true,
7038 },
7039 window,
7040 cx,
7041 )
7042 })
7043 .await
7044 .unwrap();
7045 assert_item_labels(&pane, [], cx);
7046 }
7047
7048 #[gpui::test]
7049 async fn test_close_pinned_tab_with_non_pinned_in_same_pane(cx: &mut TestAppContext) {
7050 init_test(cx);
7051 let fs = FakeFs::new(cx.executor());
7052 let project = Project::test(fs, None, cx).await;
7053 let (workspace, cx) =
7054 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
7055
7056 // Non-pinned tabs in same pane
7057 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7058 add_labeled_item(&pane, "A", false, cx);
7059 add_labeled_item(&pane, "B", false, cx);
7060 add_labeled_item(&pane, "C", false, cx);
7061 pane.update_in(cx, |pane, window, cx| {
7062 pane.pin_tab_at(0, window, cx);
7063 });
7064 set_labeled_items(&pane, ["A*", "B", "C"], cx);
7065 pane.update_in(cx, |pane, window, cx| {
7066 pane.close_active_item(
7067 &CloseActiveItem {
7068 save_intent: None,
7069 close_pinned: false,
7070 },
7071 window,
7072 cx,
7073 )
7074 .unwrap();
7075 });
7076 // Non-pinned tab should be active
7077 assert_item_labels(&pane, ["A!", "B*", "C"], cx);
7078 }
7079
7080 #[gpui::test]
7081 async fn test_close_pinned_tab_with_non_pinned_in_different_pane(cx: &mut TestAppContext) {
7082 init_test(cx);
7083 let fs = FakeFs::new(cx.executor());
7084 let project = Project::test(fs, None, cx).await;
7085 let (workspace, cx) =
7086 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
7087
7088 // No non-pinned tabs in same pane, non-pinned tabs in another pane
7089 let pane1 = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7090 let pane2 = workspace.update_in(cx, |workspace, window, cx| {
7091 workspace.split_pane(pane1.clone(), SplitDirection::Right, window, cx)
7092 });
7093 add_labeled_item(&pane1, "A", false, cx);
7094 pane1.update_in(cx, |pane, window, cx| {
7095 pane.pin_tab_at(0, window, cx);
7096 });
7097 set_labeled_items(&pane1, ["A*"], cx);
7098 add_labeled_item(&pane2, "B", false, cx);
7099 set_labeled_items(&pane2, ["B"], cx);
7100 pane1.update_in(cx, |pane, window, cx| {
7101 pane.close_active_item(
7102 &CloseActiveItem {
7103 save_intent: None,
7104 close_pinned: false,
7105 },
7106 window,
7107 cx,
7108 )
7109 .unwrap();
7110 });
7111 // Non-pinned tab of other pane should be active
7112 assert_item_labels(&pane2, ["B*"], cx);
7113 }
7114
7115 #[gpui::test]
7116 async fn ensure_item_closing_actions_do_not_panic_when_no_items_exist(cx: &mut TestAppContext) {
7117 init_test(cx);
7118 let fs = FakeFs::new(cx.executor());
7119 let project = Project::test(fs, None, cx).await;
7120 let (workspace, cx) =
7121 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
7122
7123 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7124 assert_item_labels(&pane, [], cx);
7125
7126 pane.update_in(cx, |pane, window, cx| {
7127 pane.close_active_item(
7128 &CloseActiveItem {
7129 save_intent: None,
7130 close_pinned: false,
7131 },
7132 window,
7133 cx,
7134 )
7135 })
7136 .await
7137 .unwrap();
7138
7139 pane.update_in(cx, |pane, window, cx| {
7140 pane.close_other_items(
7141 &CloseOtherItems {
7142 save_intent: None,
7143 close_pinned: false,
7144 },
7145 None,
7146 window,
7147 cx,
7148 )
7149 })
7150 .await
7151 .unwrap();
7152
7153 pane.update_in(cx, |pane, window, cx| {
7154 pane.close_all_items(
7155 &CloseAllItems {
7156 save_intent: None,
7157 close_pinned: false,
7158 },
7159 window,
7160 cx,
7161 )
7162 })
7163 .await
7164 .unwrap();
7165
7166 pane.update_in(cx, |pane, window, cx| {
7167 pane.close_clean_items(
7168 &CloseCleanItems {
7169 close_pinned: false,
7170 },
7171 window,
7172 cx,
7173 )
7174 })
7175 .await
7176 .unwrap();
7177
7178 pane.update_in(cx, |pane, window, cx| {
7179 pane.close_items_to_the_right_by_id(
7180 None,
7181 &CloseItemsToTheRight {
7182 close_pinned: false,
7183 },
7184 window,
7185 cx,
7186 )
7187 })
7188 .await
7189 .unwrap();
7190
7191 pane.update_in(cx, |pane, window, cx| {
7192 pane.close_items_to_the_left_by_id(
7193 None,
7194 &CloseItemsToTheLeft {
7195 close_pinned: false,
7196 },
7197 window,
7198 cx,
7199 )
7200 })
7201 .await
7202 .unwrap();
7203 }
7204
7205 #[gpui::test]
7206 async fn test_item_swapping_actions(cx: &mut TestAppContext) {
7207 init_test(cx);
7208 let fs = FakeFs::new(cx.executor());
7209 let project = Project::test(fs, None, cx).await;
7210 let (workspace, cx) =
7211 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
7212
7213 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7214 assert_item_labels(&pane, [], cx);
7215
7216 // Test that these actions do not panic
7217 pane.update_in(cx, |pane, window, cx| {
7218 pane.swap_item_right(&Default::default(), window, cx);
7219 });
7220
7221 pane.update_in(cx, |pane, window, cx| {
7222 pane.swap_item_left(&Default::default(), window, cx);
7223 });
7224
7225 add_labeled_item(&pane, "A", false, cx);
7226 add_labeled_item(&pane, "B", false, cx);
7227 add_labeled_item(&pane, "C", false, cx);
7228 assert_item_labels(&pane, ["A", "B", "C*"], cx);
7229
7230 pane.update_in(cx, |pane, window, cx| {
7231 pane.swap_item_right(&Default::default(), window, cx);
7232 });
7233 assert_item_labels(&pane, ["A", "B", "C*"], cx);
7234
7235 pane.update_in(cx, |pane, window, cx| {
7236 pane.swap_item_left(&Default::default(), window, cx);
7237 });
7238 assert_item_labels(&pane, ["A", "C*", "B"], cx);
7239
7240 pane.update_in(cx, |pane, window, cx| {
7241 pane.swap_item_left(&Default::default(), window, cx);
7242 });
7243 assert_item_labels(&pane, ["C*", "A", "B"], cx);
7244
7245 pane.update_in(cx, |pane, window, cx| {
7246 pane.swap_item_left(&Default::default(), window, cx);
7247 });
7248 assert_item_labels(&pane, ["C*", "A", "B"], cx);
7249
7250 pane.update_in(cx, |pane, window, cx| {
7251 pane.swap_item_right(&Default::default(), window, cx);
7252 });
7253 assert_item_labels(&pane, ["A", "C*", "B"], cx);
7254 }
7255
7256 #[gpui::test]
7257 async fn test_split_empty(cx: &mut TestAppContext) {
7258 for split_direction in SplitDirection::all() {
7259 test_single_pane_split(["A"], split_direction, SplitMode::EmptyPane, cx).await;
7260 }
7261 }
7262
7263 #[gpui::test]
7264 async fn test_split_clone(cx: &mut TestAppContext) {
7265 for split_direction in SplitDirection::all() {
7266 test_single_pane_split(["A"], split_direction, SplitMode::ClonePane, cx).await;
7267 }
7268 }
7269
7270 #[gpui::test]
7271 async fn test_split_move_right_on_single_pane(cx: &mut TestAppContext) {
7272 test_single_pane_split(["A"], SplitDirection::Right, SplitMode::MovePane, cx).await;
7273 }
7274
7275 #[gpui::test]
7276 async fn test_split_move(cx: &mut TestAppContext) {
7277 for split_direction in SplitDirection::all() {
7278 test_single_pane_split(["A", "B"], split_direction, SplitMode::MovePane, cx).await;
7279 }
7280 }
7281
7282 fn init_test(cx: &mut TestAppContext) {
7283 cx.update(|cx| {
7284 let settings_store = SettingsStore::test(cx);
7285 cx.set_global(settings_store);
7286 theme::init(LoadThemes::JustBase, cx);
7287 });
7288 }
7289
7290 fn set_max_tabs(cx: &mut TestAppContext, value: Option<usize>) {
7291 cx.update_global(|store: &mut SettingsStore, cx| {
7292 store.update_user_settings(cx, |settings| {
7293 settings.workspace.max_tabs = value.map(|v| NonZero::new(v).unwrap())
7294 });
7295 });
7296 }
7297
7298 fn add_labeled_item(
7299 pane: &Entity<Pane>,
7300 label: &str,
7301 is_dirty: bool,
7302 cx: &mut VisualTestContext,
7303 ) -> Box<Entity<TestItem>> {
7304 pane.update_in(cx, |pane, window, cx| {
7305 let labeled_item =
7306 Box::new(cx.new(|cx| TestItem::new(cx).with_label(label).with_dirty(is_dirty)));
7307 pane.add_item(labeled_item.clone(), false, false, None, window, cx);
7308 labeled_item
7309 })
7310 }
7311
7312 fn set_labeled_items<const COUNT: usize>(
7313 pane: &Entity<Pane>,
7314 labels: [&str; COUNT],
7315 cx: &mut VisualTestContext,
7316 ) -> [Box<Entity<TestItem>>; COUNT] {
7317 pane.update_in(cx, |pane, window, cx| {
7318 pane.items.clear();
7319 let mut active_item_index = 0;
7320
7321 let mut index = 0;
7322 let items = labels.map(|mut label| {
7323 if label.ends_with('*') {
7324 label = label.trim_end_matches('*');
7325 active_item_index = index;
7326 }
7327
7328 let labeled_item = Box::new(cx.new(|cx| TestItem::new(cx).with_label(label)));
7329 pane.add_item(labeled_item.clone(), false, false, None, window, cx);
7330 index += 1;
7331 labeled_item
7332 });
7333
7334 pane.activate_item(active_item_index, false, false, window, cx);
7335
7336 items
7337 })
7338 }
7339
7340 // Assert the item label, with the active item label suffixed with a '*'
7341 #[track_caller]
7342 fn assert_item_labels<const COUNT: usize>(
7343 pane: &Entity<Pane>,
7344 expected_states: [&str; COUNT],
7345 cx: &mut VisualTestContext,
7346 ) {
7347 let actual_states = pane.update(cx, |pane, cx| {
7348 pane.items
7349 .iter()
7350 .enumerate()
7351 .map(|(ix, item)| {
7352 let mut state = item
7353 .to_any_view()
7354 .downcast::<TestItem>()
7355 .unwrap()
7356 .read(cx)
7357 .label
7358 .clone();
7359 if ix == pane.active_item_index {
7360 state.push('*');
7361 }
7362 if item.is_dirty(cx) {
7363 state.push('^');
7364 }
7365 if pane.is_tab_pinned(ix) {
7366 state.push('!');
7367 }
7368 state
7369 })
7370 .collect::<Vec<_>>()
7371 });
7372 assert_eq!(
7373 actual_states, expected_states,
7374 "pane items do not match expectation"
7375 );
7376 }
7377
7378 // Assert the item label, with the active item label expected active index
7379 #[track_caller]
7380 fn assert_item_labels_active_index(
7381 pane: &Entity<Pane>,
7382 expected_states: &[&str],
7383 expected_active_idx: usize,
7384 cx: &mut VisualTestContext,
7385 ) {
7386 let actual_states = pane.update(cx, |pane, cx| {
7387 pane.items
7388 .iter()
7389 .enumerate()
7390 .map(|(ix, item)| {
7391 let mut state = item
7392 .to_any_view()
7393 .downcast::<TestItem>()
7394 .unwrap()
7395 .read(cx)
7396 .label
7397 .clone();
7398 if ix == pane.active_item_index {
7399 assert_eq!(ix, expected_active_idx);
7400 }
7401 if item.is_dirty(cx) {
7402 state.push('^');
7403 }
7404 if pane.is_tab_pinned(ix) {
7405 state.push('!');
7406 }
7407 state
7408 })
7409 .collect::<Vec<_>>()
7410 });
7411 assert_eq!(
7412 actual_states, expected_states,
7413 "pane items do not match expectation"
7414 );
7415 }
7416
7417 #[track_caller]
7418 fn assert_pane_ids_on_axis<const COUNT: usize>(
7419 workspace: &Entity<Workspace>,
7420 expected_ids: [&EntityId; COUNT],
7421 expected_axis: Axis,
7422 cx: &mut VisualTestContext,
7423 ) {
7424 workspace.read_with(cx, |workspace, _| match &workspace.center.root {
7425 Member::Axis(axis) => {
7426 assert_eq!(axis.axis, expected_axis);
7427 assert_eq!(axis.members.len(), expected_ids.len());
7428 assert!(
7429 zip(expected_ids, &axis.members).all(|(e, a)| {
7430 if let Member::Pane(p) = a {
7431 p.entity_id() == *e
7432 } else {
7433 false
7434 }
7435 }),
7436 "pane ids do not match expectation: {expected_ids:?} != {actual_ids:?}",
7437 actual_ids = axis.members
7438 );
7439 }
7440 Member::Pane(_) => panic!("expected axis"),
7441 });
7442 }
7443
7444 async fn test_single_pane_split<const COUNT: usize>(
7445 pane_labels: [&str; COUNT],
7446 direction: SplitDirection,
7447 operation: SplitMode,
7448 cx: &mut TestAppContext,
7449 ) {
7450 init_test(cx);
7451 let fs = FakeFs::new(cx.executor());
7452 let project = Project::test(fs, None, cx).await;
7453 let (workspace, cx) =
7454 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
7455
7456 let mut pane_before =
7457 workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7458 for label in pane_labels {
7459 add_labeled_item(&pane_before, label, false, cx);
7460 }
7461 pane_before.update_in(cx, |pane, window, cx| {
7462 pane.split(direction, operation, window, cx)
7463 });
7464 cx.executor().run_until_parked();
7465 let pane_after = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
7466
7467 let num_labels = pane_labels.len();
7468 let last_as_active = format!("{}*", String::from(pane_labels[num_labels - 1]));
7469
7470 // check labels for all split operations
7471 match operation {
7472 SplitMode::EmptyPane => {
7473 assert_item_labels_active_index(&pane_before, &pane_labels, num_labels - 1, cx);
7474 assert_item_labels(&pane_after, [], cx);
7475 }
7476 SplitMode::ClonePane => {
7477 assert_item_labels_active_index(&pane_before, &pane_labels, num_labels - 1, cx);
7478 assert_item_labels(&pane_after, [&last_as_active], cx);
7479 }
7480 SplitMode::MovePane => {
7481 let head = &pane_labels[..(num_labels - 1)];
7482 if num_labels == 1 {
7483 // We special-case this behavior and actually execute an empty pane command
7484 // followed by a refocus of the old pane for this case.
7485 pane_before = workspace.read_with(cx, |workspace, _cx| {
7486 workspace
7487 .panes()
7488 .into_iter()
7489 .find(|pane| *pane != &pane_after)
7490 .unwrap()
7491 .clone()
7492 });
7493 };
7494
7495 assert_item_labels_active_index(
7496 &pane_before,
7497 &head,
7498 head.len().saturating_sub(1),
7499 cx,
7500 );
7501 assert_item_labels(&pane_after, [&last_as_active], cx);
7502 pane_after.update_in(cx, |pane, window, cx| {
7503 window.focused(cx).is_some_and(|focus_handle| {
7504 focus_handle == pane.active_item().unwrap().item_focus_handle(cx)
7505 })
7506 });
7507 }
7508 }
7509
7510 // expected axis depends on split direction
7511 let expected_axis = match direction {
7512 SplitDirection::Right | SplitDirection::Left => Axis::Horizontal,
7513 SplitDirection::Up | SplitDirection::Down => Axis::Vertical,
7514 };
7515
7516 // expected ids depends on split direction
7517 let expected_ids = match direction {
7518 SplitDirection::Right | SplitDirection::Down => {
7519 [&pane_before.entity_id(), &pane_after.entity_id()]
7520 }
7521 SplitDirection::Left | SplitDirection::Up => {
7522 [&pane_after.entity_id(), &pane_before.entity_id()]
7523 }
7524 };
7525
7526 // check pane axes for all operations
7527 match operation {
7528 SplitMode::EmptyPane | SplitMode::ClonePane => {
7529 assert_pane_ids_on_axis(&workspace, expected_ids, expected_axis, cx);
7530 }
7531 SplitMode::MovePane => {
7532 assert_pane_ids_on_axis(&workspace, expected_ids, expected_axis, cx);
7533 }
7534 }
7535 }
7536}