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