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