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