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