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