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, 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
3078 TabBar::new("tab_bar")
3079 .when(
3080 self.display_nav_history_buttons.unwrap_or_default(),
3081 |tab_bar| {
3082 tab_bar
3083 .start_child(navigate_backward)
3084 .start_child(navigate_forward)
3085 },
3086 )
3087 .map(|tab_bar| {
3088 if self.show_tab_bar_buttons {
3089 let render_tab_buttons = self.render_tab_bar_buttons.clone();
3090 let (left_children, right_children) = render_tab_buttons(self, window, cx);
3091 tab_bar
3092 .start_children(left_children)
3093 .end_children(right_children)
3094 } else {
3095 tab_bar
3096 }
3097 })
3098 .children(pinned_tabs.len().ne(&0).then(|| {
3099 let max_scroll = self.tab_bar_scroll_handle.max_offset().width;
3100 // We need to check both because offset returns delta values even when the scroll handle is not scrollable
3101 let is_scrolled = self.tab_bar_scroll_handle.offset().x < px(0.);
3102 // Avoid flickering when max_offset is very small (< 2px).
3103 // The border adds 1-2px which can push max_offset back to 0, creating a loop.
3104 let is_scrollable = max_scroll > px(2.0);
3105 let has_active_unpinned_tab = self.active_item_index >= self.pinned_tab_count;
3106 h_flex()
3107 .children(pinned_tabs)
3108 .when(is_scrollable && is_scrolled, |this| {
3109 this.when(has_active_unpinned_tab, |this| this.border_r_2())
3110 .when(!has_active_unpinned_tab, |this| this.border_r_1())
3111 .border_color(cx.theme().colors().border)
3112 })
3113 }))
3114 .child(
3115 h_flex()
3116 .id("unpinned tabs")
3117 .overflow_x_scroll()
3118 .w_full()
3119 .track_scroll(&self.tab_bar_scroll_handle)
3120 .on_scroll_wheel(cx.listener(|this, _, _, _| {
3121 this.suppress_scroll = true;
3122 }))
3123 .children(unpinned_tabs)
3124 .child(
3125 div()
3126 .id("tab_bar_drop_target")
3127 .min_w_6()
3128 // HACK: This empty child is currently necessary to force the drop target to appear
3129 // despite us setting a min width above.
3130 .child("")
3131 // HACK: h_full doesn't occupy the complete height, using fixed height instead
3132 .h(Tab::container_height(cx))
3133 .flex_grow()
3134 .drag_over::<DraggedTab>(|bar, _, _, cx| {
3135 bar.bg(cx.theme().colors().drop_target_background)
3136 })
3137 .drag_over::<DraggedSelection>(|bar, _, _, cx| {
3138 bar.bg(cx.theme().colors().drop_target_background)
3139 })
3140 .on_drop(cx.listener(
3141 move |this, dragged_tab: &DraggedTab, window, cx| {
3142 this.drag_split_direction = None;
3143 this.handle_tab_drop(dragged_tab, this.items.len(), window, cx)
3144 },
3145 ))
3146 .on_drop(cx.listener(
3147 move |this, selection: &DraggedSelection, window, cx| {
3148 this.drag_split_direction = None;
3149 this.handle_project_entry_drop(
3150 &selection.active_selection.entry_id,
3151 Some(tab_count),
3152 window,
3153 cx,
3154 )
3155 },
3156 ))
3157 .on_drop(cx.listener(move |this, paths, window, cx| {
3158 this.drag_split_direction = None;
3159 this.handle_external_paths_drop(paths, window, cx)
3160 }))
3161 .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
3162 if event.click_count() == 2 {
3163 window.dispatch_action(
3164 this.double_click_dispatch_action.boxed_clone(),
3165 cx,
3166 );
3167 }
3168 })),
3169 ),
3170 )
3171 .into_any_element()
3172 }
3173
3174 pub fn render_menu_overlay(menu: &Entity<ContextMenu>) -> Div {
3175 div().absolute().bottom_0().right_0().size_0().child(
3176 deferred(anchored().anchor(Corner::TopRight).child(menu.clone())).with_priority(1),
3177 )
3178 }
3179
3180 pub fn set_zoomed(&mut self, zoomed: bool, cx: &mut Context<Self>) {
3181 self.zoomed = zoomed;
3182 cx.notify();
3183 }
3184
3185 pub fn is_zoomed(&self) -> bool {
3186 self.zoomed
3187 }
3188
3189 fn handle_drag_move<T: 'static>(
3190 &mut self,
3191 event: &DragMoveEvent<T>,
3192 window: &mut Window,
3193 cx: &mut Context<Self>,
3194 ) {
3195 let can_split_predicate = self.can_split_predicate.take();
3196 let can_split = match &can_split_predicate {
3197 Some(can_split_predicate) => {
3198 can_split_predicate(self, event.dragged_item(), window, cx)
3199 }
3200 None => false,
3201 };
3202 self.can_split_predicate = can_split_predicate;
3203 if !can_split {
3204 return;
3205 }
3206
3207 let rect = event.bounds.size;
3208
3209 let size = event.bounds.size.width.min(event.bounds.size.height)
3210 * WorkspaceSettings::get_global(cx).drop_target_size;
3211
3212 let relative_cursor = Point::new(
3213 event.event.position.x - event.bounds.left(),
3214 event.event.position.y - event.bounds.top(),
3215 );
3216
3217 let direction = if relative_cursor.x < size
3218 || relative_cursor.x > rect.width - size
3219 || relative_cursor.y < size
3220 || relative_cursor.y > rect.height - size
3221 {
3222 [
3223 SplitDirection::Up,
3224 SplitDirection::Right,
3225 SplitDirection::Down,
3226 SplitDirection::Left,
3227 ]
3228 .iter()
3229 .min_by_key(|side| match side {
3230 SplitDirection::Up => relative_cursor.y,
3231 SplitDirection::Right => rect.width - relative_cursor.x,
3232 SplitDirection::Down => rect.height - relative_cursor.y,
3233 SplitDirection::Left => relative_cursor.x,
3234 })
3235 .cloned()
3236 } else {
3237 None
3238 };
3239
3240 if direction != self.drag_split_direction {
3241 self.drag_split_direction = direction;
3242 }
3243 }
3244
3245 pub fn handle_tab_drop(
3246 &mut self,
3247 dragged_tab: &DraggedTab,
3248 ix: usize,
3249 window: &mut Window,
3250 cx: &mut Context<Self>,
3251 ) {
3252 if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3253 && let ControlFlow::Break(()) = custom_drop_handle(self, dragged_tab, window, cx)
3254 {
3255 return;
3256 }
3257 let mut to_pane = cx.entity();
3258 let split_direction = self.drag_split_direction;
3259 let item_id = dragged_tab.item.item_id();
3260 if let Some(preview_item_id) = self.preview_item_id
3261 && item_id == preview_item_id
3262 {
3263 self.set_preview_item_id(None, cx);
3264 }
3265
3266 let is_clone = cfg!(target_os = "macos") && window.modifiers().alt
3267 || cfg!(not(target_os = "macos")) && window.modifiers().control;
3268
3269 let from_pane = dragged_tab.pane.clone();
3270
3271 self.workspace
3272 .update(cx, |_, cx| {
3273 cx.defer_in(window, move |workspace, window, cx| {
3274 if let Some(split_direction) = split_direction {
3275 to_pane = workspace.split_pane(to_pane, split_direction, window, cx);
3276 }
3277 let database_id = workspace.database_id();
3278 let was_pinned_in_from_pane = from_pane.read_with(cx, |pane, _| {
3279 pane.index_for_item_id(item_id)
3280 .is_some_and(|ix| pane.is_tab_pinned(ix))
3281 });
3282 let to_pane_old_length = to_pane.read(cx).items.len();
3283 if is_clone {
3284 let Some(item) = from_pane
3285 .read(cx)
3286 .items()
3287 .find(|item| item.item_id() == item_id)
3288 .cloned()
3289 else {
3290 return;
3291 };
3292 if item.can_split(cx) {
3293 let task = item.clone_on_split(database_id, window, cx);
3294 let to_pane = to_pane.downgrade();
3295 cx.spawn_in(window, async move |_, cx| {
3296 if let Some(item) = task.await {
3297 to_pane
3298 .update_in(cx, |pane, window, cx| {
3299 pane.add_item(item, true, true, None, window, cx)
3300 })
3301 .ok();
3302 }
3303 })
3304 .detach();
3305 } else {
3306 move_item(&from_pane, &to_pane, item_id, ix, true, window, cx);
3307 }
3308 } else {
3309 move_item(&from_pane, &to_pane, item_id, ix, true, window, cx);
3310 }
3311 to_pane.update(cx, |this, _| {
3312 if to_pane == from_pane {
3313 let actual_ix = this
3314 .items
3315 .iter()
3316 .position(|item| item.item_id() == item_id)
3317 .unwrap_or(0);
3318
3319 let is_pinned_in_to_pane = this.is_tab_pinned(actual_ix);
3320
3321 if !was_pinned_in_from_pane && is_pinned_in_to_pane {
3322 this.pinned_tab_count += 1;
3323 } else if was_pinned_in_from_pane && !is_pinned_in_to_pane {
3324 this.pinned_tab_count -= 1;
3325 }
3326 } else if this.items.len() >= to_pane_old_length {
3327 let is_pinned_in_to_pane = this.is_tab_pinned(ix);
3328 let item_created_pane = to_pane_old_length == 0;
3329 let is_first_position = ix == 0;
3330 let was_dropped_at_beginning = item_created_pane || is_first_position;
3331 let should_remain_pinned = is_pinned_in_to_pane
3332 || (was_pinned_in_from_pane && was_dropped_at_beginning);
3333
3334 if should_remain_pinned {
3335 this.pinned_tab_count += 1;
3336 }
3337 }
3338 });
3339 });
3340 })
3341 .log_err();
3342 }
3343
3344 fn handle_dragged_selection_drop(
3345 &mut self,
3346 dragged_selection: &DraggedSelection,
3347 dragged_onto: Option<usize>,
3348 window: &mut Window,
3349 cx: &mut Context<Self>,
3350 ) {
3351 if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3352 && let ControlFlow::Break(()) = custom_drop_handle(self, dragged_selection, window, cx)
3353 {
3354 return;
3355 }
3356 self.handle_project_entry_drop(
3357 &dragged_selection.active_selection.entry_id,
3358 dragged_onto,
3359 window,
3360 cx,
3361 );
3362 }
3363
3364 fn handle_project_entry_drop(
3365 &mut self,
3366 project_entry_id: &ProjectEntryId,
3367 target: Option<usize>,
3368 window: &mut Window,
3369 cx: &mut Context<Self>,
3370 ) {
3371 if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3372 && let ControlFlow::Break(()) = custom_drop_handle(self, project_entry_id, window, cx)
3373 {
3374 return;
3375 }
3376 let mut to_pane = cx.entity();
3377 let split_direction = self.drag_split_direction;
3378 let project_entry_id = *project_entry_id;
3379 self.workspace
3380 .update(cx, |_, cx| {
3381 cx.defer_in(window, move |workspace, window, cx| {
3382 if let Some(project_path) = workspace
3383 .project()
3384 .read(cx)
3385 .path_for_entry(project_entry_id, cx)
3386 {
3387 let load_path_task = workspace.load_path(project_path.clone(), window, cx);
3388 cx.spawn_in(window, async move |workspace, cx| {
3389 if let Some((project_entry_id, build_item)) =
3390 load_path_task.await.notify_async_err(cx)
3391 {
3392 let (to_pane, new_item_handle) = workspace
3393 .update_in(cx, |workspace, window, cx| {
3394 if let Some(split_direction) = split_direction {
3395 to_pane = workspace.split_pane(
3396 to_pane,
3397 split_direction,
3398 window,
3399 cx,
3400 );
3401 }
3402 let new_item_handle = to_pane.update(cx, |pane, cx| {
3403 pane.open_item(
3404 project_entry_id,
3405 project_path,
3406 true,
3407 false,
3408 true,
3409 target,
3410 window,
3411 cx,
3412 build_item,
3413 )
3414 });
3415 (to_pane, new_item_handle)
3416 })
3417 .log_err()?;
3418 to_pane
3419 .update_in(cx, |this, window, cx| {
3420 let Some(index) = this.index_for_item(&*new_item_handle)
3421 else {
3422 return;
3423 };
3424
3425 if target.is_some_and(|target| this.is_tab_pinned(target)) {
3426 this.pin_tab_at(index, window, cx);
3427 }
3428 })
3429 .ok()?
3430 }
3431 Some(())
3432 })
3433 .detach();
3434 };
3435 });
3436 })
3437 .log_err();
3438 }
3439
3440 fn handle_external_paths_drop(
3441 &mut self,
3442 paths: &ExternalPaths,
3443 window: &mut Window,
3444 cx: &mut Context<Self>,
3445 ) {
3446 if let Some(custom_drop_handle) = self.custom_drop_handle.clone()
3447 && let ControlFlow::Break(()) = custom_drop_handle(self, paths, window, cx)
3448 {
3449 return;
3450 }
3451 let mut to_pane = cx.entity();
3452 let mut split_direction = self.drag_split_direction;
3453 let paths = paths.paths().to_vec();
3454 let is_remote = self
3455 .workspace
3456 .update(cx, |workspace, cx| {
3457 if workspace.project().read(cx).is_via_collab() {
3458 workspace.show_error(
3459 &anyhow::anyhow!("Cannot drop files on a remote project"),
3460 cx,
3461 );
3462 true
3463 } else {
3464 false
3465 }
3466 })
3467 .unwrap_or(true);
3468 if is_remote {
3469 return;
3470 }
3471
3472 self.workspace
3473 .update(cx, |workspace, cx| {
3474 let fs = Arc::clone(workspace.project().read(cx).fs());
3475 cx.spawn_in(window, async move |workspace, cx| {
3476 let mut is_file_checks = FuturesUnordered::new();
3477 for path in &paths {
3478 is_file_checks.push(fs.is_file(path))
3479 }
3480 let mut has_files_to_open = false;
3481 while let Some(is_file) = is_file_checks.next().await {
3482 if is_file {
3483 has_files_to_open = true;
3484 break;
3485 }
3486 }
3487 drop(is_file_checks);
3488 if !has_files_to_open {
3489 split_direction = None;
3490 }
3491
3492 if let Ok((open_task, to_pane)) =
3493 workspace.update_in(cx, |workspace, window, cx| {
3494 if let Some(split_direction) = split_direction {
3495 to_pane =
3496 workspace.split_pane(to_pane, split_direction, window, cx);
3497 }
3498 (
3499 workspace.open_paths(
3500 paths,
3501 OpenOptions {
3502 visible: Some(OpenVisible::OnlyDirectories),
3503 ..Default::default()
3504 },
3505 Some(to_pane.downgrade()),
3506 window,
3507 cx,
3508 ),
3509 to_pane,
3510 )
3511 })
3512 {
3513 let opened_items: Vec<_> = open_task.await;
3514 _ = workspace.update_in(cx, |workspace, window, cx| {
3515 for item in opened_items.into_iter().flatten() {
3516 if let Err(e) = item {
3517 workspace.show_error(&e, cx);
3518 }
3519 }
3520 if to_pane.read(cx).items_len() == 0 {
3521 workspace.remove_pane(to_pane, None, window, cx);
3522 }
3523 });
3524 }
3525 })
3526 .detach();
3527 })
3528 .log_err();
3529 }
3530
3531 pub fn display_nav_history_buttons(&mut self, display: Option<bool>) {
3532 self.display_nav_history_buttons = display;
3533 }
3534
3535 fn pinned_item_ids(&self) -> Vec<EntityId> {
3536 self.items
3537 .iter()
3538 .enumerate()
3539 .filter_map(|(index, item)| {
3540 if self.is_tab_pinned(index) {
3541 return Some(item.item_id());
3542 }
3543
3544 None
3545 })
3546 .collect()
3547 }
3548
3549 fn clean_item_ids(&self, cx: &mut Context<Pane>) -> Vec<EntityId> {
3550 self.items()
3551 .filter_map(|item| {
3552 if !item.is_dirty(cx) {
3553 return Some(item.item_id());
3554 }
3555
3556 None
3557 })
3558 .collect()
3559 }
3560
3561 fn to_the_side_item_ids(&self, item_id: EntityId, side: Side) -> Vec<EntityId> {
3562 match side {
3563 Side::Left => self
3564 .items()
3565 .take_while(|item| item.item_id() != item_id)
3566 .map(|item| item.item_id())
3567 .collect(),
3568 Side::Right => self
3569 .items()
3570 .rev()
3571 .take_while(|item| item.item_id() != item_id)
3572 .map(|item| item.item_id())
3573 .collect(),
3574 }
3575 }
3576
3577 fn multibuffer_item_ids(&self, cx: &mut Context<Pane>) -> Vec<EntityId> {
3578 self.items()
3579 .filter(|item| item.buffer_kind(cx) == ItemBufferKind::Multibuffer)
3580 .map(|item| item.item_id())
3581 .collect()
3582 }
3583
3584 pub fn drag_split_direction(&self) -> Option<SplitDirection> {
3585 self.drag_split_direction
3586 }
3587
3588 pub fn set_zoom_out_on_close(&mut self, zoom_out_on_close: bool) {
3589 self.zoom_out_on_close = zoom_out_on_close;
3590 }
3591}
3592
3593fn default_render_tab_bar_buttons(
3594 pane: &mut Pane,
3595 window: &mut Window,
3596 cx: &mut Context<Pane>,
3597) -> (Option<AnyElement>, Option<AnyElement>) {
3598 if !pane.has_focus(window, cx) && !pane.context_menu_focused(window, cx) {
3599 return (None, None);
3600 }
3601 let (can_clone, can_split_move) = match pane.active_item() {
3602 Some(active_item) if active_item.can_split(cx) => (true, false),
3603 Some(_) => (false, pane.items_len() > 1),
3604 None => (false, false),
3605 };
3606 // Ideally we would return a vec of elements here to pass directly to the [TabBar]'s
3607 // `end_slot`, but due to needing a view here that isn't possible.
3608 let right_children = h_flex()
3609 // Instead we need to replicate the spacing from the [TabBar]'s `end_slot` here.
3610 .gap(DynamicSpacing::Base04.rems(cx))
3611 .child(
3612 PopoverMenu::new("pane-tab-bar-popover-menu")
3613 .trigger_with_tooltip(
3614 IconButton::new("plus", IconName::Plus).icon_size(IconSize::Small),
3615 Tooltip::text("New..."),
3616 )
3617 .anchor(Corner::TopRight)
3618 .with_handle(pane.new_item_context_menu_handle.clone())
3619 .menu(move |window, cx| {
3620 Some(ContextMenu::build(window, cx, |menu, _, _| {
3621 menu.action("New File", NewFile.boxed_clone())
3622 .action("Open File", ToggleFileFinder::default().boxed_clone())
3623 .separator()
3624 .action(
3625 "Search Project",
3626 DeploySearch {
3627 replace_enabled: false,
3628 included_files: None,
3629 excluded_files: None,
3630 }
3631 .boxed_clone(),
3632 )
3633 .action("Search Symbols", ToggleProjectSymbols.boxed_clone())
3634 .separator()
3635 .action("New Terminal", NewTerminal.boxed_clone())
3636 }))
3637 }),
3638 )
3639 .child(
3640 PopoverMenu::new("pane-tab-bar-split")
3641 .trigger_with_tooltip(
3642 IconButton::new("split", IconName::Split)
3643 .icon_size(IconSize::Small)
3644 .disabled(!can_clone && !can_split_move),
3645 Tooltip::text("Split Pane"),
3646 )
3647 .anchor(Corner::TopRight)
3648 .with_handle(pane.split_item_context_menu_handle.clone())
3649 .menu(move |window, cx| {
3650 ContextMenu::build(window, cx, |menu, _, _| {
3651 if can_split_move {
3652 menu.action("Split Right", SplitAndMoveRight.boxed_clone())
3653 .action("Split Left", SplitAndMoveLeft.boxed_clone())
3654 .action("Split Up", SplitAndMoveUp.boxed_clone())
3655 .action("Split Down", SplitAndMoveDown.boxed_clone())
3656 } else {
3657 menu.action("Split Right", SplitRight.boxed_clone())
3658 .action("Split Left", SplitLeft.boxed_clone())
3659 .action("Split Up", SplitUp.boxed_clone())
3660 .action("Split Down", SplitDown.boxed_clone())
3661 }
3662 })
3663 .into()
3664 }),
3665 )
3666 .child({
3667 let zoomed = pane.is_zoomed();
3668 IconButton::new("toggle_zoom", IconName::Maximize)
3669 .icon_size(IconSize::Small)
3670 .toggle_state(zoomed)
3671 .selected_icon(IconName::Minimize)
3672 .on_click(cx.listener(|pane, _, window, cx| {
3673 pane.toggle_zoom(&crate::ToggleZoom, window, cx);
3674 }))
3675 .tooltip(move |_window, cx| {
3676 Tooltip::for_action(
3677 if zoomed { "Zoom Out" } else { "Zoom In" },
3678 &ToggleZoom,
3679 cx,
3680 )
3681 })
3682 })
3683 .into_any_element()
3684 .into();
3685 (None, right_children)
3686}
3687
3688impl Focusable for Pane {
3689 fn focus_handle(&self, _cx: &App) -> FocusHandle {
3690 self.focus_handle.clone()
3691 }
3692}
3693
3694impl Render for Pane {
3695 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3696 let mut key_context = KeyContext::new_with_defaults();
3697 key_context.add("Pane");
3698 if self.active_item().is_none() {
3699 key_context.add("EmptyPane");
3700 }
3701
3702 self.toolbar
3703 .read(cx)
3704 .contribute_context(&mut key_context, cx);
3705
3706 let should_display_tab_bar = self.should_display_tab_bar.clone();
3707 let display_tab_bar = should_display_tab_bar(window, cx);
3708 let Some(project) = self.project.upgrade() else {
3709 return div().track_focus(&self.focus_handle(cx));
3710 };
3711 let is_local = project.read(cx).is_local();
3712
3713 v_flex()
3714 .key_context(key_context)
3715 .track_focus(&self.focus_handle(cx))
3716 .size_full()
3717 .flex_none()
3718 .overflow_hidden()
3719 .on_action(
3720 cx.listener(|pane, _: &SplitLeft, _, cx| pane.split(SplitDirection::Left, cx)),
3721 )
3722 .on_action(cx.listener(|pane, _: &SplitUp, _, cx| pane.split(SplitDirection::Up, cx)))
3723 .on_action(cx.listener(|pane, _: &SplitHorizontal, _, cx| {
3724 pane.split(SplitDirection::horizontal(cx), cx)
3725 }))
3726 .on_action(cx.listener(|pane, _: &SplitVertical, _, cx| {
3727 pane.split(SplitDirection::vertical(cx), cx)
3728 }))
3729 .on_action(
3730 cx.listener(|pane, _: &SplitRight, _, cx| pane.split(SplitDirection::Right, cx)),
3731 )
3732 .on_action(
3733 cx.listener(|pane, _: &SplitDown, _, cx| pane.split(SplitDirection::Down, cx)),
3734 )
3735 .on_action(cx.listener(|pane, _: &SplitAndMoveUp, _, cx| {
3736 pane.split_and_move(SplitDirection::Up, cx)
3737 }))
3738 .on_action(cx.listener(|pane, _: &SplitAndMoveDown, _, cx| {
3739 pane.split_and_move(SplitDirection::Down, cx)
3740 }))
3741 .on_action(cx.listener(|pane, _: &SplitAndMoveLeft, _, cx| {
3742 pane.split_and_move(SplitDirection::Left, cx)
3743 }))
3744 .on_action(cx.listener(|pane, _: &SplitAndMoveRight, _, cx| {
3745 pane.split_and_move(SplitDirection::Right, cx)
3746 }))
3747 .on_action(cx.listener(|_, _: &JoinIntoNext, _, cx| {
3748 cx.emit(Event::JoinIntoNext);
3749 }))
3750 .on_action(cx.listener(|_, _: &JoinAll, _, cx| {
3751 cx.emit(Event::JoinAll);
3752 }))
3753 .on_action(cx.listener(Pane::toggle_zoom))
3754 .on_action(cx.listener(Self::navigate_backward))
3755 .on_action(cx.listener(Self::navigate_forward))
3756 .on_action(
3757 cx.listener(|pane: &mut Pane, action: &ActivateItem, window, cx| {
3758 pane.activate_item(
3759 action.0.min(pane.items.len().saturating_sub(1)),
3760 true,
3761 true,
3762 window,
3763 cx,
3764 );
3765 }),
3766 )
3767 .on_action(cx.listener(Self::alternate_file))
3768 .on_action(cx.listener(Self::activate_last_item))
3769 .on_action(cx.listener(Self::activate_previous_item))
3770 .on_action(cx.listener(Self::activate_next_item))
3771 .on_action(cx.listener(Self::swap_item_left))
3772 .on_action(cx.listener(Self::swap_item_right))
3773 .on_action(cx.listener(Self::toggle_pin_tab))
3774 .on_action(cx.listener(Self::unpin_all_tabs))
3775 .when(PreviewTabsSettings::get_global(cx).enabled, |this| {
3776 this.on_action(cx.listener(|pane: &mut Pane, _: &TogglePreviewTab, _, cx| {
3777 if let Some(active_item_id) = pane.active_item().map(|i| i.item_id()) {
3778 if pane.is_active_preview_item(active_item_id) {
3779 pane.set_preview_item_id(None, cx);
3780 } else {
3781 pane.set_preview_item_id(Some(active_item_id), cx);
3782 }
3783 }
3784 }))
3785 })
3786 .on_action(
3787 cx.listener(|pane: &mut Self, action: &CloseActiveItem, window, cx| {
3788 pane.close_active_item(action, window, cx)
3789 .detach_and_log_err(cx)
3790 }),
3791 )
3792 .on_action(
3793 cx.listener(|pane: &mut Self, action: &CloseOtherItems, window, cx| {
3794 pane.close_other_items(action, None, window, cx)
3795 .detach_and_log_err(cx);
3796 }),
3797 )
3798 .on_action(
3799 cx.listener(|pane: &mut Self, action: &CloseCleanItems, window, cx| {
3800 pane.close_clean_items(action, window, cx)
3801 .detach_and_log_err(cx)
3802 }),
3803 )
3804 .on_action(cx.listener(
3805 |pane: &mut Self, action: &CloseItemsToTheLeft, window, cx| {
3806 pane.close_items_to_the_left_by_id(None, action, window, cx)
3807 .detach_and_log_err(cx)
3808 },
3809 ))
3810 .on_action(cx.listener(
3811 |pane: &mut Self, action: &CloseItemsToTheRight, window, cx| {
3812 pane.close_items_to_the_right_by_id(None, action, window, cx)
3813 .detach_and_log_err(cx)
3814 },
3815 ))
3816 .on_action(
3817 cx.listener(|pane: &mut Self, action: &CloseAllItems, window, cx| {
3818 pane.close_all_items(action, window, cx)
3819 .detach_and_log_err(cx)
3820 }),
3821 )
3822 .on_action(cx.listener(
3823 |pane: &mut Self, action: &CloseMultibufferItems, window, cx| {
3824 pane.close_multibuffer_items(action, window, cx)
3825 .detach_and_log_err(cx)
3826 },
3827 ))
3828 .on_action(
3829 cx.listener(|pane: &mut Self, action: &RevealInProjectPanel, _, cx| {
3830 let entry_id = action
3831 .entry_id
3832 .map(ProjectEntryId::from_proto)
3833 .or_else(|| pane.active_item()?.project_entry_ids(cx).first().copied());
3834 if let Some(entry_id) = entry_id {
3835 pane.project
3836 .update(cx, |_, cx| {
3837 cx.emit(project::Event::RevealInProjectPanel(entry_id))
3838 })
3839 .ok();
3840 }
3841 }),
3842 )
3843 .on_action(cx.listener(|_, _: &menu::Cancel, window, cx| {
3844 if cx.stop_active_drag(window) {
3845 } else {
3846 cx.propagate();
3847 }
3848 }))
3849 .when(self.active_item().is_some() && display_tab_bar, |pane| {
3850 pane.child((self.render_tab_bar.clone())(self, window, cx))
3851 })
3852 .child({
3853 let has_worktrees = project.read(cx).visible_worktrees(cx).next().is_some();
3854 // main content
3855 div()
3856 .flex_1()
3857 .relative()
3858 .group("")
3859 .overflow_hidden()
3860 .on_drag_move::<DraggedTab>(cx.listener(Self::handle_drag_move))
3861 .on_drag_move::<DraggedSelection>(cx.listener(Self::handle_drag_move))
3862 .when(is_local, |div| {
3863 div.on_drag_move::<ExternalPaths>(cx.listener(Self::handle_drag_move))
3864 })
3865 .map(|div| {
3866 if let Some(item) = self.active_item() {
3867 div.id("pane_placeholder")
3868 .v_flex()
3869 .size_full()
3870 .overflow_hidden()
3871 .child(self.toolbar.clone())
3872 .child(item.to_any())
3873 } else {
3874 let placeholder = div
3875 .id("pane_placeholder")
3876 .h_flex()
3877 .size_full()
3878 .justify_center()
3879 .on_click(cx.listener(
3880 move |this, event: &ClickEvent, window, cx| {
3881 if event.click_count() == 2 {
3882 window.dispatch_action(
3883 this.double_click_dispatch_action.boxed_clone(),
3884 cx,
3885 );
3886 }
3887 },
3888 ));
3889 if has_worktrees {
3890 placeholder
3891 } else {
3892 placeholder.child(
3893 Label::new("Open a file or project to get started.")
3894 .color(Color::Muted),
3895 )
3896 }
3897 }
3898 })
3899 .child(
3900 // drag target
3901 div()
3902 .invisible()
3903 .absolute()
3904 .bg(cx.theme().colors().drop_target_background)
3905 .group_drag_over::<DraggedTab>("", |style| style.visible())
3906 .group_drag_over::<DraggedSelection>("", |style| style.visible())
3907 .when(is_local, |div| {
3908 div.group_drag_over::<ExternalPaths>("", |style| style.visible())
3909 })
3910 .when_some(self.can_drop_predicate.clone(), |this, p| {
3911 this.can_drop(move |a, window, cx| p(a, window, cx))
3912 })
3913 .on_drop(cx.listener(move |this, dragged_tab, window, cx| {
3914 this.handle_tab_drop(
3915 dragged_tab,
3916 this.active_item_index(),
3917 window,
3918 cx,
3919 )
3920 }))
3921 .on_drop(cx.listener(
3922 move |this, selection: &DraggedSelection, window, cx| {
3923 this.handle_dragged_selection_drop(selection, None, window, cx)
3924 },
3925 ))
3926 .on_drop(cx.listener(move |this, paths, window, cx| {
3927 this.handle_external_paths_drop(paths, window, cx)
3928 }))
3929 .map(|div| {
3930 let size = DefiniteLength::Fraction(0.5);
3931 match self.drag_split_direction {
3932 None => div.top_0().right_0().bottom_0().left_0(),
3933 Some(SplitDirection::Up) => {
3934 div.top_0().left_0().right_0().h(size)
3935 }
3936 Some(SplitDirection::Down) => {
3937 div.left_0().bottom_0().right_0().h(size)
3938 }
3939 Some(SplitDirection::Left) => {
3940 div.top_0().left_0().bottom_0().w(size)
3941 }
3942 Some(SplitDirection::Right) => {
3943 div.top_0().bottom_0().right_0().w(size)
3944 }
3945 }
3946 }),
3947 )
3948 })
3949 .on_mouse_down(
3950 MouseButton::Navigate(NavigationDirection::Back),
3951 cx.listener(|pane, _, window, cx| {
3952 if let Some(workspace) = pane.workspace.upgrade() {
3953 let pane = cx.entity().downgrade();
3954 window.defer(cx, move |window, cx| {
3955 workspace.update(cx, |workspace, cx| {
3956 workspace.go_back(pane, window, cx).detach_and_log_err(cx)
3957 })
3958 })
3959 }
3960 }),
3961 )
3962 .on_mouse_down(
3963 MouseButton::Navigate(NavigationDirection::Forward),
3964 cx.listener(|pane, _, window, cx| {
3965 if let Some(workspace) = pane.workspace.upgrade() {
3966 let pane = cx.entity().downgrade();
3967 window.defer(cx, move |window, cx| {
3968 workspace.update(cx, |workspace, cx| {
3969 workspace
3970 .go_forward(pane, window, cx)
3971 .detach_and_log_err(cx)
3972 })
3973 })
3974 }
3975 }),
3976 )
3977 }
3978}
3979
3980impl ItemNavHistory {
3981 pub fn push<D: 'static + Send + Any>(&mut self, data: Option<D>, cx: &mut App) {
3982 if self
3983 .item
3984 .upgrade()
3985 .is_some_and(|item| item.include_in_nav_history())
3986 {
3987 self.history
3988 .push(data, self.item.clone(), self.is_preview, cx);
3989 }
3990 }
3991
3992 pub fn pop_backward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
3993 self.history.pop(NavigationMode::GoingBack, cx)
3994 }
3995
3996 pub fn pop_forward(&mut self, cx: &mut App) -> Option<NavigationEntry> {
3997 self.history.pop(NavigationMode::GoingForward, cx)
3998 }
3999}
4000
4001impl NavHistory {
4002 pub fn for_each_entry(
4003 &self,
4004 cx: &App,
4005 mut f: impl FnMut(&NavigationEntry, (ProjectPath, Option<PathBuf>)),
4006 ) {
4007 let borrowed_history = self.0.lock();
4008 borrowed_history
4009 .forward_stack
4010 .iter()
4011 .chain(borrowed_history.backward_stack.iter())
4012 .chain(borrowed_history.closed_stack.iter())
4013 .for_each(|entry| {
4014 if let Some(project_and_abs_path) =
4015 borrowed_history.paths_by_item.get(&entry.item.id())
4016 {
4017 f(entry, project_and_abs_path.clone());
4018 } else if let Some(item) = entry.item.upgrade()
4019 && let Some(path) = item.project_path(cx)
4020 {
4021 f(entry, (path, None));
4022 }
4023 })
4024 }
4025
4026 pub fn set_mode(&mut self, mode: NavigationMode) {
4027 self.0.lock().mode = mode;
4028 }
4029
4030 pub fn mode(&self) -> NavigationMode {
4031 self.0.lock().mode
4032 }
4033
4034 pub fn disable(&mut self) {
4035 self.0.lock().mode = NavigationMode::Disabled;
4036 }
4037
4038 pub fn enable(&mut self) {
4039 self.0.lock().mode = NavigationMode::Normal;
4040 }
4041
4042 pub fn clear(&mut self, cx: &mut App) {
4043 let mut state = self.0.lock();
4044
4045 if state.backward_stack.is_empty()
4046 && state.forward_stack.is_empty()
4047 && state.closed_stack.is_empty()
4048 && state.paths_by_item.is_empty()
4049 {
4050 return;
4051 }
4052
4053 state.mode = NavigationMode::Normal;
4054 state.backward_stack.clear();
4055 state.forward_stack.clear();
4056 state.closed_stack.clear();
4057 state.paths_by_item.clear();
4058 state.did_update(cx);
4059 }
4060
4061 pub fn pop(&mut self, mode: NavigationMode, cx: &mut App) -> Option<NavigationEntry> {
4062 let mut state = self.0.lock();
4063 let entry = match mode {
4064 NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
4065 return None;
4066 }
4067 NavigationMode::GoingBack => &mut state.backward_stack,
4068 NavigationMode::GoingForward => &mut state.forward_stack,
4069 NavigationMode::ReopeningClosedItem => &mut state.closed_stack,
4070 }
4071 .pop_back();
4072 if entry.is_some() {
4073 state.did_update(cx);
4074 }
4075 entry
4076 }
4077
4078 pub fn push<D: 'static + Send + Any>(
4079 &mut self,
4080 data: Option<D>,
4081 item: Arc<dyn WeakItemHandle>,
4082 is_preview: bool,
4083 cx: &mut App,
4084 ) {
4085 let state = &mut *self.0.lock();
4086 match state.mode {
4087 NavigationMode::Disabled => {}
4088 NavigationMode::Normal | NavigationMode::ReopeningClosedItem => {
4089 if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4090 state.backward_stack.pop_front();
4091 }
4092 state.backward_stack.push_back(NavigationEntry {
4093 item,
4094 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4095 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4096 is_preview,
4097 });
4098 state.forward_stack.clear();
4099 }
4100 NavigationMode::GoingBack => {
4101 if state.forward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4102 state.forward_stack.pop_front();
4103 }
4104 state.forward_stack.push_back(NavigationEntry {
4105 item,
4106 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4107 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4108 is_preview,
4109 });
4110 }
4111 NavigationMode::GoingForward => {
4112 if state.backward_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4113 state.backward_stack.pop_front();
4114 }
4115 state.backward_stack.push_back(NavigationEntry {
4116 item,
4117 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4118 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4119 is_preview,
4120 });
4121 }
4122 NavigationMode::ClosingItem if is_preview => return,
4123 NavigationMode::ClosingItem => {
4124 if state.closed_stack.len() >= MAX_NAVIGATION_HISTORY_LEN {
4125 state.closed_stack.pop_front();
4126 }
4127 state.closed_stack.push_back(NavigationEntry {
4128 item,
4129 data: data.map(|data| Box::new(data) as Box<dyn Any + Send>),
4130 timestamp: state.next_timestamp.fetch_add(1, Ordering::SeqCst),
4131 is_preview,
4132 });
4133 }
4134 }
4135 state.did_update(cx);
4136 }
4137
4138 pub fn remove_item(&mut self, item_id: EntityId) {
4139 let mut state = self.0.lock();
4140 state.paths_by_item.remove(&item_id);
4141 state
4142 .backward_stack
4143 .retain(|entry| entry.item.id() != item_id);
4144 state
4145 .forward_stack
4146 .retain(|entry| entry.item.id() != item_id);
4147 state
4148 .closed_stack
4149 .retain(|entry| entry.item.id() != item_id);
4150 }
4151
4152 pub fn rename_item(
4153 &mut self,
4154 item_id: EntityId,
4155 project_path: ProjectPath,
4156 abs_path: Option<PathBuf>,
4157 ) {
4158 let mut state = self.0.lock();
4159 let path_for_item = state.paths_by_item.get_mut(&item_id);
4160 if let Some(path_for_item) = path_for_item {
4161 path_for_item.0 = project_path;
4162 path_for_item.1 = abs_path;
4163 }
4164 }
4165
4166 pub fn path_for_item(&self, item_id: EntityId) -> Option<(ProjectPath, Option<PathBuf>)> {
4167 self.0.lock().paths_by_item.get(&item_id).cloned()
4168 }
4169}
4170
4171impl NavHistoryState {
4172 pub fn did_update(&self, cx: &mut App) {
4173 if let Some(pane) = self.pane.upgrade() {
4174 cx.defer(move |cx| {
4175 pane.update(cx, |pane, cx| pane.history_updated(cx));
4176 });
4177 }
4178 }
4179}
4180
4181fn dirty_message_for(buffer_path: Option<ProjectPath>, path_style: PathStyle) -> String {
4182 let path = buffer_path
4183 .as_ref()
4184 .and_then(|p| {
4185 let path = p.path.display(path_style);
4186 if path.is_empty() { None } else { Some(path) }
4187 })
4188 .unwrap_or("This buffer".into());
4189 let path = truncate_and_remove_front(&path, 80);
4190 format!("{path} contains unsaved edits. Do you want to save it?")
4191}
4192
4193pub fn tab_details(items: &[Box<dyn ItemHandle>], _window: &Window, cx: &App) -> Vec<usize> {
4194 let mut tab_details = items.iter().map(|_| 0).collect::<Vec<_>>();
4195 let mut tab_descriptions = HashMap::default();
4196 let mut done = false;
4197 while !done {
4198 done = true;
4199
4200 // Store item indices by their tab description.
4201 for (ix, (item, detail)) in items.iter().zip(&tab_details).enumerate() {
4202 let description = item.tab_content_text(*detail, cx);
4203 if *detail == 0 || description != item.tab_content_text(detail - 1, cx) {
4204 tab_descriptions
4205 .entry(description)
4206 .or_insert(Vec::new())
4207 .push(ix);
4208 }
4209 }
4210
4211 // If two or more items have the same tab description, increase their level
4212 // of detail and try again.
4213 for (_, item_ixs) in tab_descriptions.drain() {
4214 if item_ixs.len() > 1 {
4215 done = false;
4216 for ix in item_ixs {
4217 tab_details[ix] += 1;
4218 }
4219 }
4220 }
4221 }
4222
4223 tab_details
4224}
4225
4226pub fn render_item_indicator(item: Box<dyn ItemHandle>, cx: &App) -> Option<Indicator> {
4227 maybe!({
4228 let indicator_color = match (item.has_conflict(cx), item.is_dirty(cx)) {
4229 (true, _) => Color::Warning,
4230 (_, true) => Color::Accent,
4231 (false, false) => return None,
4232 };
4233
4234 Some(Indicator::dot().color(indicator_color))
4235 })
4236}
4237
4238impl Render for DraggedTab {
4239 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4240 let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
4241 let label = self.item.tab_content(
4242 TabContentParams {
4243 detail: Some(self.detail),
4244 selected: false,
4245 preview: false,
4246 deemphasized: false,
4247 },
4248 window,
4249 cx,
4250 );
4251 Tab::new("")
4252 .toggle_state(self.is_active)
4253 .child(label)
4254 .render(window, cx)
4255 .font(ui_font)
4256 }
4257}
4258
4259#[cfg(test)]
4260mod tests {
4261 use std::num::NonZero;
4262
4263 use super::*;
4264 use crate::item::test::{TestItem, TestProjectItem};
4265 use gpui::{TestAppContext, VisualTestContext, size};
4266 use project::FakeFs;
4267 use settings::SettingsStore;
4268 use theme::LoadThemes;
4269 use util::TryFutureExt;
4270
4271 #[gpui::test]
4272 async fn test_add_item_capped_to_max_tabs(cx: &mut TestAppContext) {
4273 init_test(cx);
4274 let fs = FakeFs::new(cx.executor());
4275
4276 let project = Project::test(fs, None, cx).await;
4277 let (workspace, cx) =
4278 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4279 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4280
4281 for i in 0..7 {
4282 add_labeled_item(&pane, format!("{}", i).as_str(), false, cx);
4283 }
4284
4285 set_max_tabs(cx, Some(5));
4286 add_labeled_item(&pane, "7", false, cx);
4287 // Remove items to respect the max tab cap.
4288 assert_item_labels(&pane, ["3", "4", "5", "6", "7*"], cx);
4289 pane.update_in(cx, |pane, window, cx| {
4290 pane.activate_item(0, false, false, window, cx);
4291 });
4292 add_labeled_item(&pane, "X", false, cx);
4293 // Respect activation order.
4294 assert_item_labels(&pane, ["3", "X*", "5", "6", "7"], cx);
4295
4296 for i in 0..7 {
4297 add_labeled_item(&pane, format!("D{}", i).as_str(), true, cx);
4298 }
4299 // Keeps dirty items, even over max tab cap.
4300 assert_item_labels(
4301 &pane,
4302 ["D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6*^"],
4303 cx,
4304 );
4305
4306 set_max_tabs(cx, None);
4307 for i in 0..7 {
4308 add_labeled_item(&pane, format!("N{}", i).as_str(), false, cx);
4309 }
4310 // No cap when max tabs is None.
4311 assert_item_labels(
4312 &pane,
4313 [
4314 "D0^", "D1^", "D2^", "D3^", "D4^", "D5^", "D6^", "N0", "N1", "N2", "N3", "N4",
4315 "N5", "N6*",
4316 ],
4317 cx,
4318 );
4319 }
4320
4321 #[gpui::test]
4322 async fn test_reduce_max_tabs_closes_existing_items(cx: &mut TestAppContext) {
4323 init_test(cx);
4324 let fs = FakeFs::new(cx.executor());
4325
4326 let project = Project::test(fs, None, cx).await;
4327 let (workspace, cx) =
4328 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4329 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4330
4331 add_labeled_item(&pane, "A", false, cx);
4332 add_labeled_item(&pane, "B", false, cx);
4333 let item_c = add_labeled_item(&pane, "C", false, cx);
4334 let item_d = add_labeled_item(&pane, "D", false, cx);
4335 add_labeled_item(&pane, "E", false, cx);
4336 add_labeled_item(&pane, "Settings", false, cx);
4337 assert_item_labels(&pane, ["A", "B", "C", "D", "E", "Settings*"], cx);
4338
4339 set_max_tabs(cx, Some(5));
4340 assert_item_labels(&pane, ["B", "C", "D", "E", "Settings*"], cx);
4341
4342 set_max_tabs(cx, Some(4));
4343 assert_item_labels(&pane, ["C", "D", "E", "Settings*"], cx);
4344
4345 pane.update_in(cx, |pane, window, cx| {
4346 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4347 pane.pin_tab_at(ix, window, cx);
4348
4349 let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4350 pane.pin_tab_at(ix, window, cx);
4351 });
4352 assert_item_labels(&pane, ["C!", "D!", "E", "Settings*"], cx);
4353
4354 set_max_tabs(cx, Some(2));
4355 assert_item_labels(&pane, ["C!", "D!", "Settings*"], cx);
4356 }
4357
4358 #[gpui::test]
4359 async fn test_allow_pinning_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
4360 init_test(cx);
4361 let fs = FakeFs::new(cx.executor());
4362
4363 let project = Project::test(fs, None, cx).await;
4364 let (workspace, cx) =
4365 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4366 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4367
4368 set_max_tabs(cx, Some(1));
4369 let item_a = add_labeled_item(&pane, "A", true, cx);
4370
4371 pane.update_in(cx, |pane, window, cx| {
4372 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4373 pane.pin_tab_at(ix, window, cx);
4374 });
4375 assert_item_labels(&pane, ["A*^!"], cx);
4376 }
4377
4378 #[gpui::test]
4379 async fn test_allow_pinning_non_dirty_item_at_max_tabs(cx: &mut TestAppContext) {
4380 init_test(cx);
4381 let fs = FakeFs::new(cx.executor());
4382
4383 let project = Project::test(fs, None, cx).await;
4384 let (workspace, cx) =
4385 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4386 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4387
4388 set_max_tabs(cx, Some(1));
4389 let item_a = add_labeled_item(&pane, "A", false, cx);
4390
4391 pane.update_in(cx, |pane, window, cx| {
4392 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4393 pane.pin_tab_at(ix, window, cx);
4394 });
4395 assert_item_labels(&pane, ["A*!"], cx);
4396 }
4397
4398 #[gpui::test]
4399 async fn test_pin_tabs_incrementally_at_max_capacity(cx: &mut TestAppContext) {
4400 init_test(cx);
4401 let fs = FakeFs::new(cx.executor());
4402
4403 let project = Project::test(fs, None, cx).await;
4404 let (workspace, cx) =
4405 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4406 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4407
4408 set_max_tabs(cx, Some(3));
4409
4410 let item_a = add_labeled_item(&pane, "A", false, cx);
4411 assert_item_labels(&pane, ["A*"], cx);
4412
4413 pane.update_in(cx, |pane, window, cx| {
4414 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4415 pane.pin_tab_at(ix, window, cx);
4416 });
4417 assert_item_labels(&pane, ["A*!"], cx);
4418
4419 let item_b = add_labeled_item(&pane, "B", false, cx);
4420 assert_item_labels(&pane, ["A!", "B*"], cx);
4421
4422 pane.update_in(cx, |pane, window, cx| {
4423 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4424 pane.pin_tab_at(ix, window, cx);
4425 });
4426 assert_item_labels(&pane, ["A!", "B*!"], cx);
4427
4428 let item_c = add_labeled_item(&pane, "C", false, cx);
4429 assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4430
4431 pane.update_in(cx, |pane, window, cx| {
4432 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4433 pane.pin_tab_at(ix, window, cx);
4434 });
4435 assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4436 }
4437
4438 #[gpui::test]
4439 async fn test_pin_tabs_left_to_right_after_opening_at_max_capacity(cx: &mut TestAppContext) {
4440 init_test(cx);
4441 let fs = FakeFs::new(cx.executor());
4442
4443 let project = Project::test(fs, None, cx).await;
4444 let (workspace, cx) =
4445 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4446 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4447
4448 set_max_tabs(cx, Some(3));
4449
4450 let item_a = add_labeled_item(&pane, "A", false, cx);
4451 assert_item_labels(&pane, ["A*"], cx);
4452
4453 let item_b = add_labeled_item(&pane, "B", false, cx);
4454 assert_item_labels(&pane, ["A", "B*"], cx);
4455
4456 let item_c = add_labeled_item(&pane, "C", false, cx);
4457 assert_item_labels(&pane, ["A", "B", "C*"], cx);
4458
4459 pane.update_in(cx, |pane, window, cx| {
4460 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4461 pane.pin_tab_at(ix, window, cx);
4462 });
4463 assert_item_labels(&pane, ["A!", "B", "C*"], cx);
4464
4465 pane.update_in(cx, |pane, window, cx| {
4466 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4467 pane.pin_tab_at(ix, window, cx);
4468 });
4469 assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4470
4471 pane.update_in(cx, |pane, window, cx| {
4472 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4473 pane.pin_tab_at(ix, window, cx);
4474 });
4475 assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4476 }
4477
4478 #[gpui::test]
4479 async fn test_pin_tabs_right_to_left_after_opening_at_max_capacity(cx: &mut TestAppContext) {
4480 init_test(cx);
4481 let fs = FakeFs::new(cx.executor());
4482
4483 let project = Project::test(fs, None, cx).await;
4484 let (workspace, cx) =
4485 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4486 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4487
4488 set_max_tabs(cx, Some(3));
4489
4490 let item_a = add_labeled_item(&pane, "A", false, cx);
4491 assert_item_labels(&pane, ["A*"], cx);
4492
4493 let item_b = add_labeled_item(&pane, "B", false, cx);
4494 assert_item_labels(&pane, ["A", "B*"], cx);
4495
4496 let item_c = add_labeled_item(&pane, "C", false, cx);
4497 assert_item_labels(&pane, ["A", "B", "C*"], cx);
4498
4499 pane.update_in(cx, |pane, window, cx| {
4500 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4501 pane.pin_tab_at(ix, window, cx);
4502 });
4503 assert_item_labels(&pane, ["C*!", "A", "B"], cx);
4504
4505 pane.update_in(cx, |pane, window, cx| {
4506 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4507 pane.pin_tab_at(ix, window, cx);
4508 });
4509 assert_item_labels(&pane, ["C*!", "B!", "A"], cx);
4510
4511 pane.update_in(cx, |pane, window, cx| {
4512 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4513 pane.pin_tab_at(ix, window, cx);
4514 });
4515 assert_item_labels(&pane, ["C*!", "B!", "A!"], cx);
4516 }
4517
4518 #[gpui::test]
4519 async fn test_pinned_tabs_never_closed_at_max_tabs(cx: &mut TestAppContext) {
4520 init_test(cx);
4521 let fs = FakeFs::new(cx.executor());
4522
4523 let project = Project::test(fs, None, cx).await;
4524 let (workspace, cx) =
4525 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4526 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4527
4528 let item_a = add_labeled_item(&pane, "A", false, cx);
4529 pane.update_in(cx, |pane, window, cx| {
4530 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4531 pane.pin_tab_at(ix, window, cx);
4532 });
4533
4534 let item_b = add_labeled_item(&pane, "B", false, cx);
4535 pane.update_in(cx, |pane, window, cx| {
4536 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4537 pane.pin_tab_at(ix, window, cx);
4538 });
4539
4540 add_labeled_item(&pane, "C", false, cx);
4541 add_labeled_item(&pane, "D", false, cx);
4542 add_labeled_item(&pane, "E", false, cx);
4543 assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
4544
4545 set_max_tabs(cx, Some(3));
4546 add_labeled_item(&pane, "F", false, cx);
4547 assert_item_labels(&pane, ["A!", "B!", "F*"], cx);
4548
4549 add_labeled_item(&pane, "G", false, cx);
4550 assert_item_labels(&pane, ["A!", "B!", "G*"], cx);
4551
4552 add_labeled_item(&pane, "H", false, cx);
4553 assert_item_labels(&pane, ["A!", "B!", "H*"], cx);
4554 }
4555
4556 #[gpui::test]
4557 async fn test_always_allows_one_unpinned_item_over_max_tabs_regardless_of_pinned_count(
4558 cx: &mut TestAppContext,
4559 ) {
4560 init_test(cx);
4561 let fs = FakeFs::new(cx.executor());
4562
4563 let project = Project::test(fs, None, cx).await;
4564 let (workspace, cx) =
4565 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4566 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4567
4568 set_max_tabs(cx, Some(3));
4569
4570 let item_a = add_labeled_item(&pane, "A", false, cx);
4571 pane.update_in(cx, |pane, window, cx| {
4572 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4573 pane.pin_tab_at(ix, window, cx);
4574 });
4575
4576 let item_b = add_labeled_item(&pane, "B", false, cx);
4577 pane.update_in(cx, |pane, window, cx| {
4578 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4579 pane.pin_tab_at(ix, window, cx);
4580 });
4581
4582 let item_c = add_labeled_item(&pane, "C", false, cx);
4583 pane.update_in(cx, |pane, window, cx| {
4584 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4585 pane.pin_tab_at(ix, window, cx);
4586 });
4587
4588 assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4589
4590 let item_d = add_labeled_item(&pane, "D", false, cx);
4591 assert_item_labels(&pane, ["A!", "B!", "C!", "D*"], cx);
4592
4593 pane.update_in(cx, |pane, window, cx| {
4594 let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
4595 pane.pin_tab_at(ix, window, cx);
4596 });
4597 assert_item_labels(&pane, ["A!", "B!", "C!", "D*!"], cx);
4598
4599 add_labeled_item(&pane, "E", false, cx);
4600 assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "E*"], cx);
4601
4602 add_labeled_item(&pane, "F", false, cx);
4603 assert_item_labels(&pane, ["A!", "B!", "C!", "D!", "F*"], cx);
4604 }
4605
4606 #[gpui::test]
4607 async fn test_can_open_one_item_when_all_tabs_are_dirty_at_max(cx: &mut TestAppContext) {
4608 init_test(cx);
4609 let fs = FakeFs::new(cx.executor());
4610
4611 let project = Project::test(fs, None, cx).await;
4612 let (workspace, cx) =
4613 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4614 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4615
4616 set_max_tabs(cx, Some(3));
4617
4618 add_labeled_item(&pane, "A", true, cx);
4619 assert_item_labels(&pane, ["A*^"], cx);
4620
4621 add_labeled_item(&pane, "B", true, cx);
4622 assert_item_labels(&pane, ["A^", "B*^"], cx);
4623
4624 add_labeled_item(&pane, "C", true, cx);
4625 assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
4626
4627 add_labeled_item(&pane, "D", false, cx);
4628 assert_item_labels(&pane, ["A^", "B^", "C^", "D*"], cx);
4629
4630 add_labeled_item(&pane, "E", false, cx);
4631 assert_item_labels(&pane, ["A^", "B^", "C^", "E*"], cx);
4632
4633 add_labeled_item(&pane, "F", false, cx);
4634 assert_item_labels(&pane, ["A^", "B^", "C^", "F*"], cx);
4635
4636 add_labeled_item(&pane, "G", true, cx);
4637 assert_item_labels(&pane, ["A^", "B^", "C^", "G*^"], cx);
4638 }
4639
4640 #[gpui::test]
4641 async fn test_toggle_pin_tab(cx: &mut TestAppContext) {
4642 init_test(cx);
4643 let fs = FakeFs::new(cx.executor());
4644
4645 let project = Project::test(fs, None, cx).await;
4646 let (workspace, cx) =
4647 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4648 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4649
4650 set_labeled_items(&pane, ["A", "B*", "C"], cx);
4651 assert_item_labels(&pane, ["A", "B*", "C"], cx);
4652
4653 pane.update_in(cx, |pane, window, cx| {
4654 pane.toggle_pin_tab(&TogglePinTab, window, cx);
4655 });
4656 assert_item_labels(&pane, ["B*!", "A", "C"], cx);
4657
4658 pane.update_in(cx, |pane, window, cx| {
4659 pane.toggle_pin_tab(&TogglePinTab, window, cx);
4660 });
4661 assert_item_labels(&pane, ["B*", "A", "C"], cx);
4662 }
4663
4664 #[gpui::test]
4665 async fn test_unpin_all_tabs(cx: &mut TestAppContext) {
4666 init_test(cx);
4667 let fs = FakeFs::new(cx.executor());
4668
4669 let project = Project::test(fs, None, cx).await;
4670 let (workspace, cx) =
4671 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4672 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4673
4674 // Unpin all, in an empty pane
4675 pane.update_in(cx, |pane, window, cx| {
4676 pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4677 });
4678
4679 assert_item_labels(&pane, [], cx);
4680
4681 let item_a = add_labeled_item(&pane, "A", false, cx);
4682 let item_b = add_labeled_item(&pane, "B", false, cx);
4683 let item_c = add_labeled_item(&pane, "C", false, cx);
4684 assert_item_labels(&pane, ["A", "B", "C*"], cx);
4685
4686 // Unpin all, when no tabs are pinned
4687 pane.update_in(cx, |pane, window, cx| {
4688 pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4689 });
4690
4691 assert_item_labels(&pane, ["A", "B", "C*"], cx);
4692
4693 // Pin inactive tabs only
4694 pane.update_in(cx, |pane, window, cx| {
4695 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4696 pane.pin_tab_at(ix, window, cx);
4697
4698 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4699 pane.pin_tab_at(ix, window, cx);
4700 });
4701 assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
4702
4703 pane.update_in(cx, |pane, window, cx| {
4704 pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4705 });
4706
4707 assert_item_labels(&pane, ["A", "B", "C*"], cx);
4708
4709 // Pin all tabs
4710 pane.update_in(cx, |pane, window, cx| {
4711 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4712 pane.pin_tab_at(ix, window, cx);
4713
4714 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4715 pane.pin_tab_at(ix, window, cx);
4716
4717 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4718 pane.pin_tab_at(ix, window, cx);
4719 });
4720 assert_item_labels(&pane, ["A!", "B!", "C*!"], cx);
4721
4722 // Activate middle tab
4723 pane.update_in(cx, |pane, window, cx| {
4724 pane.activate_item(1, false, false, window, cx);
4725 });
4726 assert_item_labels(&pane, ["A!", "B*!", "C!"], cx);
4727
4728 pane.update_in(cx, |pane, window, cx| {
4729 pane.unpin_all_tabs(&UnpinAllTabs, window, cx);
4730 });
4731
4732 // Order has not changed
4733 assert_item_labels(&pane, ["A", "B*", "C"], cx);
4734 }
4735
4736 #[gpui::test]
4737 async fn test_pinning_active_tab_without_position_change_maintains_focus(
4738 cx: &mut TestAppContext,
4739 ) {
4740 init_test(cx);
4741 let fs = FakeFs::new(cx.executor());
4742
4743 let project = Project::test(fs, None, cx).await;
4744 let (workspace, cx) =
4745 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4746 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4747
4748 // Add A
4749 let item_a = add_labeled_item(&pane, "A", false, cx);
4750 assert_item_labels(&pane, ["A*"], cx);
4751
4752 // Add B
4753 add_labeled_item(&pane, "B", false, cx);
4754 assert_item_labels(&pane, ["A", "B*"], cx);
4755
4756 // Activate A again
4757 pane.update_in(cx, |pane, window, cx| {
4758 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4759 pane.activate_item(ix, true, true, window, cx);
4760 });
4761 assert_item_labels(&pane, ["A*", "B"], cx);
4762
4763 // Pin A - remains active
4764 pane.update_in(cx, |pane, window, cx| {
4765 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4766 pane.pin_tab_at(ix, window, cx);
4767 });
4768 assert_item_labels(&pane, ["A*!", "B"], cx);
4769
4770 // Unpin A - remain active
4771 pane.update_in(cx, |pane, window, cx| {
4772 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4773 pane.unpin_tab_at(ix, window, cx);
4774 });
4775 assert_item_labels(&pane, ["A*", "B"], cx);
4776 }
4777
4778 #[gpui::test]
4779 async fn test_pinning_active_tab_with_position_change_maintains_focus(cx: &mut TestAppContext) {
4780 init_test(cx);
4781 let fs = FakeFs::new(cx.executor());
4782
4783 let project = Project::test(fs, None, cx).await;
4784 let (workspace, cx) =
4785 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4786 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4787
4788 // Add A, B, C
4789 add_labeled_item(&pane, "A", false, cx);
4790 add_labeled_item(&pane, "B", false, cx);
4791 let item_c = add_labeled_item(&pane, "C", false, cx);
4792 assert_item_labels(&pane, ["A", "B", "C*"], cx);
4793
4794 // Pin C - moves to pinned area, remains active
4795 pane.update_in(cx, |pane, window, cx| {
4796 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4797 pane.pin_tab_at(ix, window, cx);
4798 });
4799 assert_item_labels(&pane, ["C*!", "A", "B"], cx);
4800
4801 // Unpin C - moves after pinned area, remains active
4802 pane.update_in(cx, |pane, window, cx| {
4803 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4804 pane.unpin_tab_at(ix, window, cx);
4805 });
4806 assert_item_labels(&pane, ["C*", "A", "B"], cx);
4807 }
4808
4809 #[gpui::test]
4810 async fn test_pinning_inactive_tab_without_position_change_preserves_existing_focus(
4811 cx: &mut TestAppContext,
4812 ) {
4813 init_test(cx);
4814 let fs = FakeFs::new(cx.executor());
4815
4816 let project = Project::test(fs, None, cx).await;
4817 let (workspace, cx) =
4818 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4819 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4820
4821 // Add A, B
4822 let item_a = add_labeled_item(&pane, "A", false, cx);
4823 add_labeled_item(&pane, "B", false, cx);
4824 assert_item_labels(&pane, ["A", "B*"], cx);
4825
4826 // Pin A - already in pinned area, B remains active
4827 pane.update_in(cx, |pane, window, cx| {
4828 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4829 pane.pin_tab_at(ix, window, cx);
4830 });
4831 assert_item_labels(&pane, ["A!", "B*"], cx);
4832
4833 // Unpin A - stays in place, B remains active
4834 pane.update_in(cx, |pane, window, cx| {
4835 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4836 pane.unpin_tab_at(ix, window, cx);
4837 });
4838 assert_item_labels(&pane, ["A", "B*"], cx);
4839 }
4840
4841 #[gpui::test]
4842 async fn test_pinning_inactive_tab_with_position_change_preserves_existing_focus(
4843 cx: &mut TestAppContext,
4844 ) {
4845 init_test(cx);
4846 let fs = FakeFs::new(cx.executor());
4847
4848 let project = Project::test(fs, None, cx).await;
4849 let (workspace, cx) =
4850 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4851 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4852
4853 // Add A, B, C
4854 add_labeled_item(&pane, "A", false, cx);
4855 let item_b = add_labeled_item(&pane, "B", false, cx);
4856 let item_c = add_labeled_item(&pane, "C", false, cx);
4857 assert_item_labels(&pane, ["A", "B", "C*"], cx);
4858
4859 // Activate B
4860 pane.update_in(cx, |pane, window, cx| {
4861 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4862 pane.activate_item(ix, true, true, window, cx);
4863 });
4864 assert_item_labels(&pane, ["A", "B*", "C"], cx);
4865
4866 // Pin C - moves to pinned area, B remains active
4867 pane.update_in(cx, |pane, window, cx| {
4868 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4869 pane.pin_tab_at(ix, window, cx);
4870 });
4871 assert_item_labels(&pane, ["C!", "A", "B*"], cx);
4872
4873 // Unpin C - moves after pinned area, B remains active
4874 pane.update_in(cx, |pane, window, cx| {
4875 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
4876 pane.unpin_tab_at(ix, window, cx);
4877 });
4878 assert_item_labels(&pane, ["C", "A", "B*"], cx);
4879 }
4880
4881 #[gpui::test]
4882 async fn test_drag_unpinned_tab_to_split_creates_pane_with_unpinned_tab(
4883 cx: &mut TestAppContext,
4884 ) {
4885 init_test(cx);
4886 let fs = FakeFs::new(cx.executor());
4887
4888 let project = Project::test(fs, None, cx).await;
4889 let (workspace, cx) =
4890 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4891 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4892
4893 // Add A, B. Pin B. Activate A
4894 let item_a = add_labeled_item(&pane_a, "A", false, cx);
4895 let item_b = add_labeled_item(&pane_a, "B", false, cx);
4896
4897 pane_a.update_in(cx, |pane, window, cx| {
4898 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4899 pane.pin_tab_at(ix, window, cx);
4900
4901 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4902 pane.activate_item(ix, true, true, window, cx);
4903 });
4904
4905 // Drag A to create new split
4906 pane_a.update_in(cx, |pane, window, cx| {
4907 pane.drag_split_direction = Some(SplitDirection::Right);
4908
4909 let dragged_tab = DraggedTab {
4910 pane: pane_a.clone(),
4911 item: item_a.boxed_clone(),
4912 ix: 0,
4913 detail: 0,
4914 is_active: true,
4915 };
4916 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4917 });
4918
4919 // A should be moved to new pane. B should remain pinned, A should not be pinned
4920 let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
4921 let panes = workspace.panes();
4922 (panes[0].clone(), panes[1].clone())
4923 });
4924 assert_item_labels(&pane_a, ["B*!"], cx);
4925 assert_item_labels(&pane_b, ["A*"], cx);
4926 }
4927
4928 #[gpui::test]
4929 async fn test_drag_pinned_tab_to_split_creates_pane_with_pinned_tab(cx: &mut TestAppContext) {
4930 init_test(cx);
4931 let fs = FakeFs::new(cx.executor());
4932
4933 let project = Project::test(fs, None, cx).await;
4934 let (workspace, cx) =
4935 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4936 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4937
4938 // Add A, B. Pin both. Activate A
4939 let item_a = add_labeled_item(&pane_a, "A", false, cx);
4940 let item_b = add_labeled_item(&pane_a, "B", false, cx);
4941
4942 pane_a.update_in(cx, |pane, window, cx| {
4943 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4944 pane.pin_tab_at(ix, window, cx);
4945
4946 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
4947 pane.pin_tab_at(ix, window, cx);
4948
4949 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4950 pane.activate_item(ix, true, true, window, cx);
4951 });
4952 assert_item_labels(&pane_a, ["A*!", "B!"], cx);
4953
4954 // Drag A to create new split
4955 pane_a.update_in(cx, |pane, window, cx| {
4956 pane.drag_split_direction = Some(SplitDirection::Right);
4957
4958 let dragged_tab = DraggedTab {
4959 pane: pane_a.clone(),
4960 item: item_a.boxed_clone(),
4961 ix: 0,
4962 detail: 0,
4963 is_active: true,
4964 };
4965 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
4966 });
4967
4968 // A should be moved to new pane. Both A and B should still be pinned
4969 let (pane_a, pane_b) = workspace.read_with(cx, |workspace, _| {
4970 let panes = workspace.panes();
4971 (panes[0].clone(), panes[1].clone())
4972 });
4973 assert_item_labels(&pane_a, ["B*!"], cx);
4974 assert_item_labels(&pane_b, ["A*!"], cx);
4975 }
4976
4977 #[gpui::test]
4978 async fn test_drag_pinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
4979 init_test(cx);
4980 let fs = FakeFs::new(cx.executor());
4981
4982 let project = Project::test(fs, None, cx).await;
4983 let (workspace, cx) =
4984 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
4985 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
4986
4987 // Add A to pane A and pin
4988 let item_a = add_labeled_item(&pane_a, "A", false, cx);
4989 pane_a.update_in(cx, |pane, window, cx| {
4990 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
4991 pane.pin_tab_at(ix, window, cx);
4992 });
4993 assert_item_labels(&pane_a, ["A*!"], cx);
4994
4995 // Add B to pane B and pin
4996 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
4997 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
4998 });
4999 let item_b = add_labeled_item(&pane_b, "B", false, cx);
5000 pane_b.update_in(cx, |pane, window, cx| {
5001 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5002 pane.pin_tab_at(ix, window, cx);
5003 });
5004 assert_item_labels(&pane_b, ["B*!"], cx);
5005
5006 // Move A from pane A to pane B's pinned region
5007 pane_b.update_in(cx, |pane, window, cx| {
5008 let dragged_tab = DraggedTab {
5009 pane: pane_a.clone(),
5010 item: item_a.boxed_clone(),
5011 ix: 0,
5012 detail: 0,
5013 is_active: true,
5014 };
5015 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5016 });
5017
5018 // A should stay pinned
5019 assert_item_labels(&pane_a, [], cx);
5020 assert_item_labels(&pane_b, ["A*!", "B!"], cx);
5021 }
5022
5023 #[gpui::test]
5024 async fn test_drag_pinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
5025 init_test(cx);
5026 let fs = FakeFs::new(cx.executor());
5027
5028 let project = Project::test(fs, None, cx).await;
5029 let (workspace, cx) =
5030 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5031 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5032
5033 // Add A to pane A and pin
5034 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5035 pane_a.update_in(cx, |pane, window, cx| {
5036 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5037 pane.pin_tab_at(ix, window, cx);
5038 });
5039 assert_item_labels(&pane_a, ["A*!"], cx);
5040
5041 // Create pane B with pinned item B
5042 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5043 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5044 });
5045 let item_b = add_labeled_item(&pane_b, "B", false, cx);
5046 assert_item_labels(&pane_b, ["B*"], cx);
5047
5048 pane_b.update_in(cx, |pane, window, cx| {
5049 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5050 pane.pin_tab_at(ix, window, cx);
5051 });
5052 assert_item_labels(&pane_b, ["B*!"], cx);
5053
5054 // Move A from pane A to pane B's unpinned region
5055 pane_b.update_in(cx, |pane, window, cx| {
5056 let dragged_tab = DraggedTab {
5057 pane: pane_a.clone(),
5058 item: item_a.boxed_clone(),
5059 ix: 0,
5060 detail: 0,
5061 is_active: true,
5062 };
5063 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5064 });
5065
5066 // A should become pinned
5067 assert_item_labels(&pane_a, [], cx);
5068 assert_item_labels(&pane_b, ["B!", "A*"], cx);
5069 }
5070
5071 #[gpui::test]
5072 async fn test_drag_pinned_tab_into_existing_panes_first_position_with_no_pinned_tabs(
5073 cx: &mut TestAppContext,
5074 ) {
5075 init_test(cx);
5076 let fs = FakeFs::new(cx.executor());
5077
5078 let project = Project::test(fs, None, cx).await;
5079 let (workspace, cx) =
5080 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5081 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5082
5083 // Add A to pane A and pin
5084 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5085 pane_a.update_in(cx, |pane, window, cx| {
5086 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5087 pane.pin_tab_at(ix, window, cx);
5088 });
5089 assert_item_labels(&pane_a, ["A*!"], cx);
5090
5091 // Add B to pane B
5092 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5093 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5094 });
5095 add_labeled_item(&pane_b, "B", false, cx);
5096 assert_item_labels(&pane_b, ["B*"], cx);
5097
5098 // Move A from pane A to position 0 in pane B, indicating it should stay pinned
5099 pane_b.update_in(cx, |pane, window, cx| {
5100 let dragged_tab = DraggedTab {
5101 pane: pane_a.clone(),
5102 item: item_a.boxed_clone(),
5103 ix: 0,
5104 detail: 0,
5105 is_active: true,
5106 };
5107 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5108 });
5109
5110 // A should stay pinned
5111 assert_item_labels(&pane_a, [], cx);
5112 assert_item_labels(&pane_b, ["A*!", "B"], cx);
5113 }
5114
5115 #[gpui::test]
5116 async fn test_drag_pinned_tab_into_existing_pane_at_max_capacity_closes_unpinned_tabs(
5117 cx: &mut TestAppContext,
5118 ) {
5119 init_test(cx);
5120 let fs = FakeFs::new(cx.executor());
5121
5122 let project = Project::test(fs, None, cx).await;
5123 let (workspace, cx) =
5124 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5125 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5126 set_max_tabs(cx, Some(2));
5127
5128 // Add A, B to pane A. Pin both
5129 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5130 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5131 pane_a.update_in(cx, |pane, window, cx| {
5132 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5133 pane.pin_tab_at(ix, window, cx);
5134
5135 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5136 pane.pin_tab_at(ix, window, cx);
5137 });
5138 assert_item_labels(&pane_a, ["A!", "B*!"], cx);
5139
5140 // Add C, D to pane B. Pin both
5141 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5142 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5143 });
5144 let item_c = add_labeled_item(&pane_b, "C", false, cx);
5145 let item_d = add_labeled_item(&pane_b, "D", false, cx);
5146 pane_b.update_in(cx, |pane, window, cx| {
5147 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5148 pane.pin_tab_at(ix, window, cx);
5149
5150 let ix = pane.index_for_item_id(item_d.item_id()).unwrap();
5151 pane.pin_tab_at(ix, window, cx);
5152 });
5153 assert_item_labels(&pane_b, ["C!", "D*!"], cx);
5154
5155 // Add a third unpinned item to pane B (exceeds max tabs), but is allowed,
5156 // as we allow 1 tab over max if the others are pinned or dirty
5157 add_labeled_item(&pane_b, "E", false, cx);
5158 assert_item_labels(&pane_b, ["C!", "D!", "E*"], cx);
5159
5160 // Drag pinned A from pane A to position 0 in pane B
5161 pane_b.update_in(cx, |pane, window, cx| {
5162 let dragged_tab = DraggedTab {
5163 pane: pane_a.clone(),
5164 item: item_a.boxed_clone(),
5165 ix: 0,
5166 detail: 0,
5167 is_active: true,
5168 };
5169 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5170 });
5171
5172 // E (unpinned) should be closed, leaving 3 pinned items
5173 assert_item_labels(&pane_a, ["B*!"], cx);
5174 assert_item_labels(&pane_b, ["A*!", "C!", "D!"], cx);
5175 }
5176
5177 #[gpui::test]
5178 async fn test_drag_last_pinned_tab_to_same_position_stays_pinned(cx: &mut TestAppContext) {
5179 init_test(cx);
5180 let fs = FakeFs::new(cx.executor());
5181
5182 let project = Project::test(fs, None, cx).await;
5183 let (workspace, cx) =
5184 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5185 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5186
5187 // Add A to pane A and pin it
5188 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5189 pane_a.update_in(cx, |pane, window, cx| {
5190 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5191 pane.pin_tab_at(ix, window, cx);
5192 });
5193 assert_item_labels(&pane_a, ["A*!"], cx);
5194
5195 // Drag pinned A to position 1 (directly to the right) in the same pane
5196 pane_a.update_in(cx, |pane, window, cx| {
5197 let dragged_tab = DraggedTab {
5198 pane: pane_a.clone(),
5199 item: item_a.boxed_clone(),
5200 ix: 0,
5201 detail: 0,
5202 is_active: true,
5203 };
5204 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5205 });
5206
5207 // A should still be pinned and active
5208 assert_item_labels(&pane_a, ["A*!"], cx);
5209 }
5210
5211 #[gpui::test]
5212 async fn test_drag_pinned_tab_beyond_last_pinned_tab_in_same_pane_stays_pinned(
5213 cx: &mut TestAppContext,
5214 ) {
5215 init_test(cx);
5216 let fs = FakeFs::new(cx.executor());
5217
5218 let project = Project::test(fs, None, cx).await;
5219 let (workspace, cx) =
5220 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5221 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5222
5223 // Add A, B to pane A and pin both
5224 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5225 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5226 pane_a.update_in(cx, |pane, window, cx| {
5227 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5228 pane.pin_tab_at(ix, window, cx);
5229
5230 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5231 pane.pin_tab_at(ix, window, cx);
5232 });
5233 assert_item_labels(&pane_a, ["A!", "B*!"], cx);
5234
5235 // Drag pinned A right of B in the same pane
5236 pane_a.update_in(cx, |pane, window, cx| {
5237 let dragged_tab = DraggedTab {
5238 pane: pane_a.clone(),
5239 item: item_a.boxed_clone(),
5240 ix: 0,
5241 detail: 0,
5242 is_active: true,
5243 };
5244 pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5245 });
5246
5247 // A stays pinned
5248 assert_item_labels(&pane_a, ["B!", "A*!"], cx);
5249 }
5250
5251 #[gpui::test]
5252 async fn test_dragging_pinned_tab_onto_unpinned_tab_reduces_unpinned_tab_count(
5253 cx: &mut TestAppContext,
5254 ) {
5255 init_test(cx);
5256 let fs = FakeFs::new(cx.executor());
5257
5258 let project = Project::test(fs, None, cx).await;
5259 let (workspace, cx) =
5260 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5261 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5262
5263 // Add A, B to pane A and pin A
5264 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5265 add_labeled_item(&pane_a, "B", false, cx);
5266 pane_a.update_in(cx, |pane, window, cx| {
5267 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5268 pane.pin_tab_at(ix, window, cx);
5269 });
5270 assert_item_labels(&pane_a, ["A!", "B*"], cx);
5271
5272 // Drag pinned A on top of B in the same pane, which changes tab order to B, A
5273 pane_a.update_in(cx, |pane, window, cx| {
5274 let dragged_tab = DraggedTab {
5275 pane: pane_a.clone(),
5276 item: item_a.boxed_clone(),
5277 ix: 0,
5278 detail: 0,
5279 is_active: true,
5280 };
5281 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5282 });
5283
5284 // Neither are pinned
5285 assert_item_labels(&pane_a, ["B", "A*"], cx);
5286 }
5287
5288 #[gpui::test]
5289 async fn test_drag_pinned_tab_beyond_unpinned_tab_in_same_pane_becomes_unpinned(
5290 cx: &mut TestAppContext,
5291 ) {
5292 init_test(cx);
5293 let fs = FakeFs::new(cx.executor());
5294
5295 let project = Project::test(fs, None, cx).await;
5296 let (workspace, cx) =
5297 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5298 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5299
5300 // Add A, B to pane A and pin A
5301 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5302 add_labeled_item(&pane_a, "B", false, cx);
5303 pane_a.update_in(cx, |pane, window, cx| {
5304 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5305 pane.pin_tab_at(ix, window, cx);
5306 });
5307 assert_item_labels(&pane_a, ["A!", "B*"], cx);
5308
5309 // Drag pinned A right of B in the same pane
5310 pane_a.update_in(cx, |pane, window, cx| {
5311 let dragged_tab = DraggedTab {
5312 pane: pane_a.clone(),
5313 item: item_a.boxed_clone(),
5314 ix: 0,
5315 detail: 0,
5316 is_active: true,
5317 };
5318 pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5319 });
5320
5321 // A becomes unpinned
5322 assert_item_labels(&pane_a, ["B", "A*"], cx);
5323 }
5324
5325 #[gpui::test]
5326 async fn test_drag_unpinned_tab_in_front_of_pinned_tab_in_same_pane_becomes_pinned(
5327 cx: &mut TestAppContext,
5328 ) {
5329 init_test(cx);
5330 let fs = FakeFs::new(cx.executor());
5331
5332 let project = Project::test(fs, None, cx).await;
5333 let (workspace, cx) =
5334 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5335 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5336
5337 // Add A, B to pane A and pin A
5338 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5339 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5340 pane_a.update_in(cx, |pane, window, cx| {
5341 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5342 pane.pin_tab_at(ix, window, cx);
5343 });
5344 assert_item_labels(&pane_a, ["A!", "B*"], cx);
5345
5346 // Drag pinned B left of A in the same pane
5347 pane_a.update_in(cx, |pane, window, cx| {
5348 let dragged_tab = DraggedTab {
5349 pane: pane_a.clone(),
5350 item: item_b.boxed_clone(),
5351 ix: 1,
5352 detail: 0,
5353 is_active: true,
5354 };
5355 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5356 });
5357
5358 // A becomes unpinned
5359 assert_item_labels(&pane_a, ["B*!", "A!"], cx);
5360 }
5361
5362 #[gpui::test]
5363 async fn test_drag_unpinned_tab_to_the_pinned_region_stays_pinned(cx: &mut TestAppContext) {
5364 init_test(cx);
5365 let fs = FakeFs::new(cx.executor());
5366
5367 let project = Project::test(fs, None, cx).await;
5368 let (workspace, cx) =
5369 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5370 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5371
5372 // Add A, B, C to pane A and pin A
5373 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5374 add_labeled_item(&pane_a, "B", false, cx);
5375 let item_c = add_labeled_item(&pane_a, "C", false, cx);
5376 pane_a.update_in(cx, |pane, window, cx| {
5377 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5378 pane.pin_tab_at(ix, window, cx);
5379 });
5380 assert_item_labels(&pane_a, ["A!", "B", "C*"], cx);
5381
5382 // Drag pinned C left of B in the same pane
5383 pane_a.update_in(cx, |pane, window, cx| {
5384 let dragged_tab = DraggedTab {
5385 pane: pane_a.clone(),
5386 item: item_c.boxed_clone(),
5387 ix: 2,
5388 detail: 0,
5389 is_active: true,
5390 };
5391 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5392 });
5393
5394 // A stays pinned, B and C remain unpinned
5395 assert_item_labels(&pane_a, ["A!", "C*", "B"], cx);
5396 }
5397
5398 #[gpui::test]
5399 async fn test_drag_unpinned_tab_into_existing_panes_pinned_region(cx: &mut TestAppContext) {
5400 init_test(cx);
5401 let fs = FakeFs::new(cx.executor());
5402
5403 let project = Project::test(fs, None, cx).await;
5404 let (workspace, cx) =
5405 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5406 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5407
5408 // Add unpinned item A to pane A
5409 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5410 assert_item_labels(&pane_a, ["A*"], cx);
5411
5412 // Create pane B with pinned item B
5413 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5414 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5415 });
5416 let item_b = add_labeled_item(&pane_b, "B", false, cx);
5417 pane_b.update_in(cx, |pane, window, cx| {
5418 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5419 pane.pin_tab_at(ix, window, cx);
5420 });
5421 assert_item_labels(&pane_b, ["B*!"], cx);
5422
5423 // Move A from pane A to pane B's pinned region
5424 pane_b.update_in(cx, |pane, window, cx| {
5425 let dragged_tab = DraggedTab {
5426 pane: pane_a.clone(),
5427 item: item_a.boxed_clone(),
5428 ix: 0,
5429 detail: 0,
5430 is_active: true,
5431 };
5432 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5433 });
5434
5435 // A should become pinned since it was dropped in the pinned region
5436 assert_item_labels(&pane_a, [], cx);
5437 assert_item_labels(&pane_b, ["A*!", "B!"], cx);
5438 }
5439
5440 #[gpui::test]
5441 async fn test_drag_unpinned_tab_into_existing_panes_unpinned_region(cx: &mut TestAppContext) {
5442 init_test(cx);
5443 let fs = FakeFs::new(cx.executor());
5444
5445 let project = Project::test(fs, None, cx).await;
5446 let (workspace, cx) =
5447 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5448 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5449
5450 // Add unpinned item A to pane A
5451 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5452 assert_item_labels(&pane_a, ["A*"], cx);
5453
5454 // Create pane B with one pinned item B
5455 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
5456 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
5457 });
5458 let item_b = add_labeled_item(&pane_b, "B", false, cx);
5459 pane_b.update_in(cx, |pane, window, cx| {
5460 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5461 pane.pin_tab_at(ix, window, cx);
5462 });
5463 assert_item_labels(&pane_b, ["B*!"], cx);
5464
5465 // Move A from pane A to pane B's unpinned region
5466 pane_b.update_in(cx, |pane, window, cx| {
5467 let dragged_tab = DraggedTab {
5468 pane: pane_a.clone(),
5469 item: item_a.boxed_clone(),
5470 ix: 0,
5471 detail: 0,
5472 is_active: true,
5473 };
5474 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5475 });
5476
5477 // A should remain unpinned since it was dropped outside the pinned region
5478 assert_item_labels(&pane_a, [], cx);
5479 assert_item_labels(&pane_b, ["B!", "A*"], cx);
5480 }
5481
5482 #[gpui::test]
5483 async fn test_drag_pinned_tab_throughout_entire_range_of_pinned_tabs_both_directions(
5484 cx: &mut TestAppContext,
5485 ) {
5486 init_test(cx);
5487 let fs = FakeFs::new(cx.executor());
5488
5489 let project = Project::test(fs, None, cx).await;
5490 let (workspace, cx) =
5491 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5492 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5493
5494 // Add A, B, C and pin all
5495 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5496 let item_b = add_labeled_item(&pane_a, "B", false, cx);
5497 let item_c = add_labeled_item(&pane_a, "C", false, cx);
5498 assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5499
5500 pane_a.update_in(cx, |pane, window, cx| {
5501 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
5502 pane.pin_tab_at(ix, window, cx);
5503
5504 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
5505 pane.pin_tab_at(ix, window, cx);
5506
5507 let ix = pane.index_for_item_id(item_c.item_id()).unwrap();
5508 pane.pin_tab_at(ix, window, cx);
5509 });
5510 assert_item_labels(&pane_a, ["A!", "B!", "C*!"], cx);
5511
5512 // Move A to right of B
5513 pane_a.update_in(cx, |pane, window, cx| {
5514 let dragged_tab = DraggedTab {
5515 pane: pane_a.clone(),
5516 item: item_a.boxed_clone(),
5517 ix: 0,
5518 detail: 0,
5519 is_active: true,
5520 };
5521 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5522 });
5523
5524 // A should be after B and all are pinned
5525 assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
5526
5527 // Move A to right of C
5528 pane_a.update_in(cx, |pane, window, cx| {
5529 let dragged_tab = DraggedTab {
5530 pane: pane_a.clone(),
5531 item: item_a.boxed_clone(),
5532 ix: 1,
5533 detail: 0,
5534 is_active: true,
5535 };
5536 pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5537 });
5538
5539 // A should be after C and all are pinned
5540 assert_item_labels(&pane_a, ["B!", "C!", "A*!"], cx);
5541
5542 // Move A to left of C
5543 pane_a.update_in(cx, |pane, window, cx| {
5544 let dragged_tab = DraggedTab {
5545 pane: pane_a.clone(),
5546 item: item_a.boxed_clone(),
5547 ix: 2,
5548 detail: 0,
5549 is_active: true,
5550 };
5551 pane.handle_tab_drop(&dragged_tab, 1, window, cx);
5552 });
5553
5554 // A should be before C and all are pinned
5555 assert_item_labels(&pane_a, ["B!", "A*!", "C!"], cx);
5556
5557 // Move A to left of B
5558 pane_a.update_in(cx, |pane, window, cx| {
5559 let dragged_tab = DraggedTab {
5560 pane: pane_a.clone(),
5561 item: item_a.boxed_clone(),
5562 ix: 1,
5563 detail: 0,
5564 is_active: true,
5565 };
5566 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5567 });
5568
5569 // A should be before B and all are pinned
5570 assert_item_labels(&pane_a, ["A*!", "B!", "C!"], cx);
5571 }
5572
5573 #[gpui::test]
5574 async fn test_drag_first_tab_to_last_position(cx: &mut TestAppContext) {
5575 init_test(cx);
5576 let fs = FakeFs::new(cx.executor());
5577
5578 let project = Project::test(fs, None, cx).await;
5579 let (workspace, cx) =
5580 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5581 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5582
5583 // Add A, B, C
5584 let item_a = add_labeled_item(&pane_a, "A", false, cx);
5585 add_labeled_item(&pane_a, "B", false, cx);
5586 add_labeled_item(&pane_a, "C", false, cx);
5587 assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5588
5589 // Move A to the end
5590 pane_a.update_in(cx, |pane, window, cx| {
5591 let dragged_tab = DraggedTab {
5592 pane: pane_a.clone(),
5593 item: item_a.boxed_clone(),
5594 ix: 0,
5595 detail: 0,
5596 is_active: true,
5597 };
5598 pane.handle_tab_drop(&dragged_tab, 2, window, cx);
5599 });
5600
5601 // A should be at the end
5602 assert_item_labels(&pane_a, ["B", "C", "A*"], cx);
5603 }
5604
5605 #[gpui::test]
5606 async fn test_drag_last_tab_to_first_position(cx: &mut TestAppContext) {
5607 init_test(cx);
5608 let fs = FakeFs::new(cx.executor());
5609
5610 let project = Project::test(fs, None, cx).await;
5611 let (workspace, cx) =
5612 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5613 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5614
5615 // Add A, B, C
5616 add_labeled_item(&pane_a, "A", false, cx);
5617 add_labeled_item(&pane_a, "B", false, cx);
5618 let item_c = add_labeled_item(&pane_a, "C", false, cx);
5619 assert_item_labels(&pane_a, ["A", "B", "C*"], cx);
5620
5621 // Move C to the beginning
5622 pane_a.update_in(cx, |pane, window, cx| {
5623 let dragged_tab = DraggedTab {
5624 pane: pane_a.clone(),
5625 item: item_c.boxed_clone(),
5626 ix: 2,
5627 detail: 0,
5628 is_active: true,
5629 };
5630 pane.handle_tab_drop(&dragged_tab, 0, window, cx);
5631 });
5632
5633 // C should be at the beginning
5634 assert_item_labels(&pane_a, ["C*", "A", "B"], cx);
5635 }
5636
5637 #[gpui::test]
5638 async fn test_add_item_with_new_item(cx: &mut TestAppContext) {
5639 init_test(cx);
5640 let fs = FakeFs::new(cx.executor());
5641
5642 let project = Project::test(fs, None, cx).await;
5643 let (workspace, cx) =
5644 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5645 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5646
5647 // 1. Add with a destination index
5648 // a. Add before the active item
5649 set_labeled_items(&pane, ["A", "B*", "C"], cx);
5650 pane.update_in(cx, |pane, window, cx| {
5651 pane.add_item(
5652 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5653 false,
5654 false,
5655 Some(0),
5656 window,
5657 cx,
5658 );
5659 });
5660 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
5661
5662 // b. Add after the active item
5663 set_labeled_items(&pane, ["A", "B*", "C"], cx);
5664 pane.update_in(cx, |pane, window, cx| {
5665 pane.add_item(
5666 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5667 false,
5668 false,
5669 Some(2),
5670 window,
5671 cx,
5672 );
5673 });
5674 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
5675
5676 // c. Add at the end of the item list (including off the length)
5677 set_labeled_items(&pane, ["A", "B*", "C"], cx);
5678 pane.update_in(cx, |pane, window, cx| {
5679 pane.add_item(
5680 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5681 false,
5682 false,
5683 Some(5),
5684 window,
5685 cx,
5686 );
5687 });
5688 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5689
5690 // 2. Add without a destination index
5691 // a. Add with active item at the start of the item list
5692 set_labeled_items(&pane, ["A*", "B", "C"], cx);
5693 pane.update_in(cx, |pane, window, cx| {
5694 pane.add_item(
5695 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5696 false,
5697 false,
5698 None,
5699 window,
5700 cx,
5701 );
5702 });
5703 set_labeled_items(&pane, ["A", "D*", "B", "C"], cx);
5704
5705 // b. Add with active item at the end of the item list
5706 set_labeled_items(&pane, ["A", "B", "C*"], cx);
5707 pane.update_in(cx, |pane, window, cx| {
5708 pane.add_item(
5709 Box::new(cx.new(|cx| TestItem::new(cx).with_label("D"))),
5710 false,
5711 false,
5712 None,
5713 window,
5714 cx,
5715 );
5716 });
5717 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5718 }
5719
5720 #[gpui::test]
5721 async fn test_add_item_with_existing_item(cx: &mut TestAppContext) {
5722 init_test(cx);
5723 let fs = FakeFs::new(cx.executor());
5724
5725 let project = Project::test(fs, None, cx).await;
5726 let (workspace, cx) =
5727 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5728 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5729
5730 // 1. Add with a destination index
5731 // 1a. Add before the active item
5732 let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5733 pane.update_in(cx, |pane, window, cx| {
5734 pane.add_item(d, false, false, Some(0), window, cx);
5735 });
5736 assert_item_labels(&pane, ["D*", "A", "B", "C"], cx);
5737
5738 // 1b. Add after the active item
5739 let [_, _, _, d] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5740 pane.update_in(cx, |pane, window, cx| {
5741 pane.add_item(d, false, false, Some(2), window, cx);
5742 });
5743 assert_item_labels(&pane, ["A", "B", "D*", "C"], cx);
5744
5745 // 1c. Add at the end of the item list (including off the length)
5746 let [a, _, _, _] = set_labeled_items(&pane, ["A", "B*", "C", "D"], cx);
5747 pane.update_in(cx, |pane, window, cx| {
5748 pane.add_item(a, false, false, Some(5), window, cx);
5749 });
5750 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
5751
5752 // 1d. Add same item to active index
5753 let [_, b, _] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
5754 pane.update_in(cx, |pane, window, cx| {
5755 pane.add_item(b, false, false, Some(1), window, cx);
5756 });
5757 assert_item_labels(&pane, ["A", "B*", "C"], cx);
5758
5759 // 1e. Add item to index after same item in last position
5760 let [_, _, c] = set_labeled_items(&pane, ["A", "B*", "C"], cx);
5761 pane.update_in(cx, |pane, window, cx| {
5762 pane.add_item(c, false, false, Some(2), window, cx);
5763 });
5764 assert_item_labels(&pane, ["A", "B", "C*"], cx);
5765
5766 // 2. Add without a destination index
5767 // 2a. Add with active item at the start of the item list
5768 let [_, _, _, d] = set_labeled_items(&pane, ["A*", "B", "C", "D"], cx);
5769 pane.update_in(cx, |pane, window, cx| {
5770 pane.add_item(d, false, false, None, window, cx);
5771 });
5772 assert_item_labels(&pane, ["A", "D*", "B", "C"], cx);
5773
5774 // 2b. Add with active item at the end of the item list
5775 let [a, _, _, _] = set_labeled_items(&pane, ["A", "B", "C", "D*"], cx);
5776 pane.update_in(cx, |pane, window, cx| {
5777 pane.add_item(a, false, false, None, window, cx);
5778 });
5779 assert_item_labels(&pane, ["B", "C", "D", "A*"], cx);
5780
5781 // 2c. Add active item to active item at end of list
5782 let [_, _, c] = set_labeled_items(&pane, ["A", "B", "C*"], cx);
5783 pane.update_in(cx, |pane, window, cx| {
5784 pane.add_item(c, false, false, None, window, cx);
5785 });
5786 assert_item_labels(&pane, ["A", "B", "C*"], cx);
5787
5788 // 2d. Add active item to active item at start of list
5789 let [a, _, _] = set_labeled_items(&pane, ["A*", "B", "C"], cx);
5790 pane.update_in(cx, |pane, window, cx| {
5791 pane.add_item(a, false, false, None, window, cx);
5792 });
5793 assert_item_labels(&pane, ["A*", "B", "C"], cx);
5794 }
5795
5796 #[gpui::test]
5797 async fn test_add_item_with_same_project_entries(cx: &mut TestAppContext) {
5798 init_test(cx);
5799 let fs = FakeFs::new(cx.executor());
5800
5801 let project = Project::test(fs, None, cx).await;
5802 let (workspace, cx) =
5803 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5804 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5805
5806 // singleton view
5807 pane.update_in(cx, |pane, window, cx| {
5808 pane.add_item(
5809 Box::new(cx.new(|cx| {
5810 TestItem::new(cx)
5811 .with_buffer_kind(ItemBufferKind::Singleton)
5812 .with_label("buffer 1")
5813 .with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
5814 })),
5815 false,
5816 false,
5817 None,
5818 window,
5819 cx,
5820 );
5821 });
5822 assert_item_labels(&pane, ["buffer 1*"], cx);
5823
5824 // new singleton view with the same project entry
5825 pane.update_in(cx, |pane, window, cx| {
5826 pane.add_item(
5827 Box::new(cx.new(|cx| {
5828 TestItem::new(cx)
5829 .with_buffer_kind(ItemBufferKind::Singleton)
5830 .with_label("buffer 1")
5831 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5832 })),
5833 false,
5834 false,
5835 None,
5836 window,
5837 cx,
5838 );
5839 });
5840 assert_item_labels(&pane, ["buffer 1*"], cx);
5841
5842 // new singleton view with different project entry
5843 pane.update_in(cx, |pane, window, cx| {
5844 pane.add_item(
5845 Box::new(cx.new(|cx| {
5846 TestItem::new(cx)
5847 .with_buffer_kind(ItemBufferKind::Singleton)
5848 .with_label("buffer 2")
5849 .with_project_items(&[TestProjectItem::new(2, "2.txt", cx)])
5850 })),
5851 false,
5852 false,
5853 None,
5854 window,
5855 cx,
5856 );
5857 });
5858 assert_item_labels(&pane, ["buffer 1", "buffer 2*"], cx);
5859
5860 // new multibuffer view with the same project entry
5861 pane.update_in(cx, |pane, window, cx| {
5862 pane.add_item(
5863 Box::new(cx.new(|cx| {
5864 TestItem::new(cx)
5865 .with_buffer_kind(ItemBufferKind::Multibuffer)
5866 .with_label("multibuffer 1")
5867 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5868 })),
5869 false,
5870 false,
5871 None,
5872 window,
5873 cx,
5874 );
5875 });
5876 assert_item_labels(&pane, ["buffer 1", "buffer 2", "multibuffer 1*"], cx);
5877
5878 // another multibuffer view with the same project entry
5879 pane.update_in(cx, |pane, window, cx| {
5880 pane.add_item(
5881 Box::new(cx.new(|cx| {
5882 TestItem::new(cx)
5883 .with_buffer_kind(ItemBufferKind::Multibuffer)
5884 .with_label("multibuffer 1b")
5885 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
5886 })),
5887 false,
5888 false,
5889 None,
5890 window,
5891 cx,
5892 );
5893 });
5894 assert_item_labels(
5895 &pane,
5896 ["buffer 1", "buffer 2", "multibuffer 1", "multibuffer 1b*"],
5897 cx,
5898 );
5899 }
5900
5901 #[gpui::test]
5902 async fn test_remove_item_ordering_history(cx: &mut TestAppContext) {
5903 init_test(cx);
5904 let fs = FakeFs::new(cx.executor());
5905
5906 let project = Project::test(fs, None, cx).await;
5907 let (workspace, cx) =
5908 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5909 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5910
5911 add_labeled_item(&pane, "A", false, cx);
5912 add_labeled_item(&pane, "B", false, cx);
5913 add_labeled_item(&pane, "C", false, cx);
5914 add_labeled_item(&pane, "D", false, cx);
5915 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5916
5917 pane.update_in(cx, |pane, window, cx| {
5918 pane.activate_item(1, false, false, window, cx)
5919 });
5920 add_labeled_item(&pane, "1", false, cx);
5921 assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
5922
5923 pane.update_in(cx, |pane, window, cx| {
5924 pane.close_active_item(
5925 &CloseActiveItem {
5926 save_intent: None,
5927 close_pinned: false,
5928 },
5929 window,
5930 cx,
5931 )
5932 })
5933 .await
5934 .unwrap();
5935 assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
5936
5937 pane.update_in(cx, |pane, window, cx| {
5938 pane.activate_item(3, false, false, window, cx)
5939 });
5940 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
5941
5942 pane.update_in(cx, |pane, window, cx| {
5943 pane.close_active_item(
5944 &CloseActiveItem {
5945 save_intent: None,
5946 close_pinned: false,
5947 },
5948 window,
5949 cx,
5950 )
5951 })
5952 .await
5953 .unwrap();
5954 assert_item_labels(&pane, ["A", "B*", "C"], cx);
5955
5956 pane.update_in(cx, |pane, window, cx| {
5957 pane.close_active_item(
5958 &CloseActiveItem {
5959 save_intent: None,
5960 close_pinned: false,
5961 },
5962 window,
5963 cx,
5964 )
5965 })
5966 .await
5967 .unwrap();
5968 assert_item_labels(&pane, ["A", "C*"], cx);
5969
5970 pane.update_in(cx, |pane, window, cx| {
5971 pane.close_active_item(
5972 &CloseActiveItem {
5973 save_intent: None,
5974 close_pinned: false,
5975 },
5976 window,
5977 cx,
5978 )
5979 })
5980 .await
5981 .unwrap();
5982 assert_item_labels(&pane, ["A*"], cx);
5983 }
5984
5985 #[gpui::test]
5986 async fn test_remove_item_ordering_neighbour(cx: &mut TestAppContext) {
5987 init_test(cx);
5988 cx.update_global::<SettingsStore, ()>(|s, cx| {
5989 s.update_user_settings(cx, |s| {
5990 s.tabs.get_or_insert_default().activate_on_close = Some(ActivateOnClose::Neighbour);
5991 });
5992 });
5993 let fs = FakeFs::new(cx.executor());
5994
5995 let project = Project::test(fs, None, cx).await;
5996 let (workspace, cx) =
5997 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
5998 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
5999
6000 add_labeled_item(&pane, "A", false, cx);
6001 add_labeled_item(&pane, "B", false, cx);
6002 add_labeled_item(&pane, "C", false, cx);
6003 add_labeled_item(&pane, "D", false, cx);
6004 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6005
6006 pane.update_in(cx, |pane, window, cx| {
6007 pane.activate_item(1, false, false, window, cx)
6008 });
6009 add_labeled_item(&pane, "1", false, cx);
6010 assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
6011
6012 pane.update_in(cx, |pane, window, cx| {
6013 pane.close_active_item(
6014 &CloseActiveItem {
6015 save_intent: None,
6016 close_pinned: false,
6017 },
6018 window,
6019 cx,
6020 )
6021 })
6022 .await
6023 .unwrap();
6024 assert_item_labels(&pane, ["A", "B", "C*", "D"], cx);
6025
6026 pane.update_in(cx, |pane, window, cx| {
6027 pane.activate_item(3, false, false, window, cx)
6028 });
6029 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6030
6031 pane.update_in(cx, |pane, window, cx| {
6032 pane.close_active_item(
6033 &CloseActiveItem {
6034 save_intent: None,
6035 close_pinned: false,
6036 },
6037 window,
6038 cx,
6039 )
6040 })
6041 .await
6042 .unwrap();
6043 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6044
6045 pane.update_in(cx, |pane, window, cx| {
6046 pane.close_active_item(
6047 &CloseActiveItem {
6048 save_intent: None,
6049 close_pinned: false,
6050 },
6051 window,
6052 cx,
6053 )
6054 })
6055 .await
6056 .unwrap();
6057 assert_item_labels(&pane, ["A", "B*"], cx);
6058
6059 pane.update_in(cx, |pane, window, cx| {
6060 pane.close_active_item(
6061 &CloseActiveItem {
6062 save_intent: None,
6063 close_pinned: false,
6064 },
6065 window,
6066 cx,
6067 )
6068 })
6069 .await
6070 .unwrap();
6071 assert_item_labels(&pane, ["A*"], cx);
6072 }
6073
6074 #[gpui::test]
6075 async fn test_remove_item_ordering_left_neighbour(cx: &mut TestAppContext) {
6076 init_test(cx);
6077 cx.update_global::<SettingsStore, ()>(|s, cx| {
6078 s.update_user_settings(cx, |s| {
6079 s.tabs.get_or_insert_default().activate_on_close =
6080 Some(ActivateOnClose::LeftNeighbour);
6081 });
6082 });
6083 let fs = FakeFs::new(cx.executor());
6084
6085 let project = Project::test(fs, None, cx).await;
6086 let (workspace, cx) =
6087 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6088 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6089
6090 add_labeled_item(&pane, "A", false, cx);
6091 add_labeled_item(&pane, "B", false, cx);
6092 add_labeled_item(&pane, "C", false, cx);
6093 add_labeled_item(&pane, "D", false, cx);
6094 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6095
6096 pane.update_in(cx, |pane, window, cx| {
6097 pane.activate_item(1, false, false, window, cx)
6098 });
6099 add_labeled_item(&pane, "1", false, cx);
6100 assert_item_labels(&pane, ["A", "B", "1*", "C", "D"], cx);
6101
6102 pane.update_in(cx, |pane, window, cx| {
6103 pane.close_active_item(
6104 &CloseActiveItem {
6105 save_intent: None,
6106 close_pinned: false,
6107 },
6108 window,
6109 cx,
6110 )
6111 })
6112 .await
6113 .unwrap();
6114 assert_item_labels(&pane, ["A", "B*", "C", "D"], cx);
6115
6116 pane.update_in(cx, |pane, window, cx| {
6117 pane.activate_item(3, false, false, window, cx)
6118 });
6119 assert_item_labels(&pane, ["A", "B", "C", "D*"], cx);
6120
6121 pane.update_in(cx, |pane, window, cx| {
6122 pane.close_active_item(
6123 &CloseActiveItem {
6124 save_intent: None,
6125 close_pinned: false,
6126 },
6127 window,
6128 cx,
6129 )
6130 })
6131 .await
6132 .unwrap();
6133 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6134
6135 pane.update_in(cx, |pane, window, cx| {
6136 pane.activate_item(0, false, false, window, cx)
6137 });
6138 assert_item_labels(&pane, ["A*", "B", "C"], cx);
6139
6140 pane.update_in(cx, |pane, window, cx| {
6141 pane.close_active_item(
6142 &CloseActiveItem {
6143 save_intent: None,
6144 close_pinned: false,
6145 },
6146 window,
6147 cx,
6148 )
6149 })
6150 .await
6151 .unwrap();
6152 assert_item_labels(&pane, ["B*", "C"], cx);
6153
6154 pane.update_in(cx, |pane, window, cx| {
6155 pane.close_active_item(
6156 &CloseActiveItem {
6157 save_intent: None,
6158 close_pinned: false,
6159 },
6160 window,
6161 cx,
6162 )
6163 })
6164 .await
6165 .unwrap();
6166 assert_item_labels(&pane, ["C*"], cx);
6167 }
6168
6169 #[gpui::test]
6170 async fn test_close_inactive_items(cx: &mut TestAppContext) {
6171 init_test(cx);
6172 let fs = FakeFs::new(cx.executor());
6173
6174 let project = Project::test(fs, None, cx).await;
6175 let (workspace, cx) =
6176 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6177 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6178
6179 let item_a = add_labeled_item(&pane, "A", false, cx);
6180 pane.update_in(cx, |pane, window, cx| {
6181 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6182 pane.pin_tab_at(ix, window, cx);
6183 });
6184 assert_item_labels(&pane, ["A*!"], cx);
6185
6186 let item_b = add_labeled_item(&pane, "B", false, cx);
6187 pane.update_in(cx, |pane, window, cx| {
6188 let ix = pane.index_for_item_id(item_b.item_id()).unwrap();
6189 pane.pin_tab_at(ix, window, cx);
6190 });
6191 assert_item_labels(&pane, ["A!", "B*!"], cx);
6192
6193 add_labeled_item(&pane, "C", false, cx);
6194 assert_item_labels(&pane, ["A!", "B!", "C*"], cx);
6195
6196 add_labeled_item(&pane, "D", false, cx);
6197 add_labeled_item(&pane, "E", false, cx);
6198 assert_item_labels(&pane, ["A!", "B!", "C", "D", "E*"], cx);
6199
6200 pane.update_in(cx, |pane, window, cx| {
6201 pane.close_other_items(
6202 &CloseOtherItems {
6203 save_intent: None,
6204 close_pinned: false,
6205 },
6206 None,
6207 window,
6208 cx,
6209 )
6210 })
6211 .await
6212 .unwrap();
6213 assert_item_labels(&pane, ["A!", "B!", "E*"], cx);
6214 }
6215
6216 #[gpui::test]
6217 async fn test_running_close_inactive_items_via_an_inactive_item(cx: &mut TestAppContext) {
6218 init_test(cx);
6219 let fs = FakeFs::new(cx.executor());
6220
6221 let project = Project::test(fs, None, cx).await;
6222 let (workspace, cx) =
6223 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6224 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6225
6226 add_labeled_item(&pane, "A", false, cx);
6227 assert_item_labels(&pane, ["A*"], cx);
6228
6229 let item_b = add_labeled_item(&pane, "B", false, cx);
6230 assert_item_labels(&pane, ["A", "B*"], cx);
6231
6232 add_labeled_item(&pane, "C", false, cx);
6233 add_labeled_item(&pane, "D", false, cx);
6234 add_labeled_item(&pane, "E", false, cx);
6235 assert_item_labels(&pane, ["A", "B", "C", "D", "E*"], cx);
6236
6237 pane.update_in(cx, |pane, window, cx| {
6238 pane.close_other_items(
6239 &CloseOtherItems {
6240 save_intent: None,
6241 close_pinned: false,
6242 },
6243 Some(item_b.item_id()),
6244 window,
6245 cx,
6246 )
6247 })
6248 .await
6249 .unwrap();
6250 assert_item_labels(&pane, ["B*"], cx);
6251 }
6252
6253 #[gpui::test]
6254 async fn test_close_clean_items(cx: &mut TestAppContext) {
6255 init_test(cx);
6256 let fs = FakeFs::new(cx.executor());
6257
6258 let project = Project::test(fs, None, cx).await;
6259 let (workspace, cx) =
6260 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6261 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6262
6263 add_labeled_item(&pane, "A", true, cx);
6264 add_labeled_item(&pane, "B", false, cx);
6265 add_labeled_item(&pane, "C", true, cx);
6266 add_labeled_item(&pane, "D", false, cx);
6267 add_labeled_item(&pane, "E", false, cx);
6268 assert_item_labels(&pane, ["A^", "B", "C^", "D", "E*"], cx);
6269
6270 pane.update_in(cx, |pane, window, cx| {
6271 pane.close_clean_items(
6272 &CloseCleanItems {
6273 close_pinned: false,
6274 },
6275 window,
6276 cx,
6277 )
6278 })
6279 .await
6280 .unwrap();
6281 assert_item_labels(&pane, ["A^", "C*^"], cx);
6282 }
6283
6284 #[gpui::test]
6285 async fn test_close_items_to_the_left(cx: &mut TestAppContext) {
6286 init_test(cx);
6287 let fs = FakeFs::new(cx.executor());
6288
6289 let project = Project::test(fs, None, cx).await;
6290 let (workspace, cx) =
6291 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6292 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6293
6294 set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
6295
6296 pane.update_in(cx, |pane, window, cx| {
6297 pane.close_items_to_the_left_by_id(
6298 None,
6299 &CloseItemsToTheLeft {
6300 close_pinned: false,
6301 },
6302 window,
6303 cx,
6304 )
6305 })
6306 .await
6307 .unwrap();
6308 assert_item_labels(&pane, ["C*", "D", "E"], cx);
6309 }
6310
6311 #[gpui::test]
6312 async fn test_close_items_to_the_right(cx: &mut TestAppContext) {
6313 init_test(cx);
6314 let fs = FakeFs::new(cx.executor());
6315
6316 let project = Project::test(fs, None, cx).await;
6317 let (workspace, cx) =
6318 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6319 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6320
6321 set_labeled_items(&pane, ["A", "B", "C*", "D", "E"], cx);
6322
6323 pane.update_in(cx, |pane, window, cx| {
6324 pane.close_items_to_the_right_by_id(
6325 None,
6326 &CloseItemsToTheRight {
6327 close_pinned: false,
6328 },
6329 window,
6330 cx,
6331 )
6332 })
6333 .await
6334 .unwrap();
6335 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6336 }
6337
6338 #[gpui::test]
6339 async fn test_close_all_items(cx: &mut TestAppContext) {
6340 init_test(cx);
6341 let fs = FakeFs::new(cx.executor());
6342
6343 let project = Project::test(fs, None, cx).await;
6344 let (workspace, cx) =
6345 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6346 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6347
6348 let item_a = add_labeled_item(&pane, "A", false, cx);
6349 add_labeled_item(&pane, "B", false, cx);
6350 add_labeled_item(&pane, "C", false, cx);
6351 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6352
6353 pane.update_in(cx, |pane, window, cx| {
6354 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6355 pane.pin_tab_at(ix, window, cx);
6356 pane.close_all_items(
6357 &CloseAllItems {
6358 save_intent: None,
6359 close_pinned: false,
6360 },
6361 window,
6362 cx,
6363 )
6364 })
6365 .await
6366 .unwrap();
6367 assert_item_labels(&pane, ["A*!"], cx);
6368
6369 pane.update_in(cx, |pane, window, cx| {
6370 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6371 pane.unpin_tab_at(ix, window, cx);
6372 pane.close_all_items(
6373 &CloseAllItems {
6374 save_intent: None,
6375 close_pinned: false,
6376 },
6377 window,
6378 cx,
6379 )
6380 })
6381 .await
6382 .unwrap();
6383
6384 assert_item_labels(&pane, [], cx);
6385
6386 add_labeled_item(&pane, "A", true, cx).update(cx, |item, cx| {
6387 item.project_items
6388 .push(TestProjectItem::new_dirty(1, "A.txt", cx))
6389 });
6390 add_labeled_item(&pane, "B", true, cx).update(cx, |item, cx| {
6391 item.project_items
6392 .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6393 });
6394 add_labeled_item(&pane, "C", true, cx).update(cx, |item, cx| {
6395 item.project_items
6396 .push(TestProjectItem::new_dirty(3, "C.txt", cx))
6397 });
6398 assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6399
6400 let save = pane.update_in(cx, |pane, window, cx| {
6401 pane.close_all_items(
6402 &CloseAllItems {
6403 save_intent: None,
6404 close_pinned: false,
6405 },
6406 window,
6407 cx,
6408 )
6409 });
6410
6411 cx.executor().run_until_parked();
6412 cx.simulate_prompt_answer("Save all");
6413 save.await.unwrap();
6414 assert_item_labels(&pane, [], cx);
6415
6416 add_labeled_item(&pane, "A", true, cx);
6417 add_labeled_item(&pane, "B", true, cx);
6418 add_labeled_item(&pane, "C", true, cx);
6419 assert_item_labels(&pane, ["A^", "B^", "C*^"], cx);
6420 let save = pane.update_in(cx, |pane, window, cx| {
6421 pane.close_all_items(
6422 &CloseAllItems {
6423 save_intent: None,
6424 close_pinned: false,
6425 },
6426 window,
6427 cx,
6428 )
6429 });
6430
6431 cx.executor().run_until_parked();
6432 cx.simulate_prompt_answer("Discard all");
6433 save.await.unwrap();
6434 assert_item_labels(&pane, [], cx);
6435 }
6436
6437 #[gpui::test]
6438 async fn test_close_multibuffer_items(cx: &mut TestAppContext) {
6439 init_test(cx);
6440 let fs = FakeFs::new(cx.executor());
6441
6442 let project = Project::test(fs, None, cx).await;
6443 let (workspace, cx) =
6444 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
6445 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6446
6447 let add_labeled_item = |pane: &Entity<Pane>,
6448 label,
6449 is_dirty,
6450 kind: ItemBufferKind,
6451 cx: &mut VisualTestContext| {
6452 pane.update_in(cx, |pane, window, cx| {
6453 let labeled_item = Box::new(cx.new(|cx| {
6454 TestItem::new(cx)
6455 .with_label(label)
6456 .with_dirty(is_dirty)
6457 .with_buffer_kind(kind)
6458 }));
6459 pane.add_item(labeled_item.clone(), false, false, None, window, cx);
6460 labeled_item
6461 })
6462 };
6463
6464 let item_a = add_labeled_item(&pane, "A", false, ItemBufferKind::Multibuffer, cx);
6465 add_labeled_item(&pane, "B", false, ItemBufferKind::Multibuffer, cx);
6466 add_labeled_item(&pane, "C", false, ItemBufferKind::Singleton, cx);
6467 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6468
6469 pane.update_in(cx, |pane, window, cx| {
6470 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6471 pane.pin_tab_at(ix, window, cx);
6472 pane.close_multibuffer_items(
6473 &CloseMultibufferItems {
6474 save_intent: None,
6475 close_pinned: false,
6476 },
6477 window,
6478 cx,
6479 )
6480 })
6481 .await
6482 .unwrap();
6483 assert_item_labels(&pane, ["A!", "C*"], cx);
6484
6485 pane.update_in(cx, |pane, window, cx| {
6486 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6487 pane.unpin_tab_at(ix, window, cx);
6488 pane.close_multibuffer_items(
6489 &CloseMultibufferItems {
6490 save_intent: None,
6491 close_pinned: false,
6492 },
6493 window,
6494 cx,
6495 )
6496 })
6497 .await
6498 .unwrap();
6499
6500 assert_item_labels(&pane, ["C*"], cx);
6501
6502 add_labeled_item(&pane, "A", true, ItemBufferKind::Singleton, cx).update(cx, |item, cx| {
6503 item.project_items
6504 .push(TestProjectItem::new_dirty(1, "A.txt", cx))
6505 });
6506 add_labeled_item(&pane, "B", true, ItemBufferKind::Multibuffer, cx).update(
6507 cx,
6508 |item, cx| {
6509 item.project_items
6510 .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6511 },
6512 );
6513 add_labeled_item(&pane, "D", true, ItemBufferKind::Multibuffer, cx).update(
6514 cx,
6515 |item, cx| {
6516 item.project_items
6517 .push(TestProjectItem::new_dirty(3, "D.txt", cx))
6518 },
6519 );
6520 assert_item_labels(&pane, ["C", "A^", "B^", "D*^"], cx);
6521
6522 let save = pane.update_in(cx, |pane, window, cx| {
6523 pane.close_multibuffer_items(
6524 &CloseMultibufferItems {
6525 save_intent: None,
6526 close_pinned: false,
6527 },
6528 window,
6529 cx,
6530 )
6531 });
6532
6533 cx.executor().run_until_parked();
6534 cx.simulate_prompt_answer("Save all");
6535 save.await.unwrap();
6536 assert_item_labels(&pane, ["C", "A*^"], cx);
6537
6538 add_labeled_item(&pane, "B", true, ItemBufferKind::Multibuffer, cx).update(
6539 cx,
6540 |item, cx| {
6541 item.project_items
6542 .push(TestProjectItem::new_dirty(2, "B.txt", cx))
6543 },
6544 );
6545 add_labeled_item(&pane, "D", true, ItemBufferKind::Multibuffer, cx).update(
6546 cx,
6547 |item, cx| {
6548 item.project_items
6549 .push(TestProjectItem::new_dirty(3, "D.txt", cx))
6550 },
6551 );
6552 assert_item_labels(&pane, ["C", "A^", "B^", "D*^"], cx);
6553 let save = pane.update_in(cx, |pane, window, cx| {
6554 pane.close_multibuffer_items(
6555 &CloseMultibufferItems {
6556 save_intent: None,
6557 close_pinned: false,
6558 },
6559 window,
6560 cx,
6561 )
6562 });
6563
6564 cx.executor().run_until_parked();
6565 cx.simulate_prompt_answer("Discard all");
6566 save.await.unwrap();
6567 assert_item_labels(&pane, ["C", "A*^"], cx);
6568 }
6569
6570 #[gpui::test]
6571 async fn test_close_with_save_intent(cx: &mut TestAppContext) {
6572 init_test(cx);
6573 let fs = FakeFs::new(cx.executor());
6574
6575 let project = Project::test(fs, None, cx).await;
6576 let (workspace, cx) =
6577 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6578 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6579
6580 let a = cx.update(|_, cx| TestProjectItem::new_dirty(1, "A.txt", cx));
6581 let b = cx.update(|_, cx| TestProjectItem::new_dirty(1, "B.txt", cx));
6582 let c = cx.update(|_, cx| TestProjectItem::new_dirty(1, "C.txt", cx));
6583
6584 add_labeled_item(&pane, "AB", true, cx).update(cx, |item, _| {
6585 item.project_items.push(a.clone());
6586 item.project_items.push(b.clone());
6587 });
6588 add_labeled_item(&pane, "C", true, cx)
6589 .update(cx, |item, _| item.project_items.push(c.clone()));
6590 assert_item_labels(&pane, ["AB^", "C*^"], cx);
6591
6592 pane.update_in(cx, |pane, window, cx| {
6593 pane.close_all_items(
6594 &CloseAllItems {
6595 save_intent: Some(SaveIntent::Save),
6596 close_pinned: false,
6597 },
6598 window,
6599 cx,
6600 )
6601 })
6602 .await
6603 .unwrap();
6604
6605 assert_item_labels(&pane, [], cx);
6606 cx.update(|_, cx| {
6607 assert!(!a.read(cx).is_dirty);
6608 assert!(!b.read(cx).is_dirty);
6609 assert!(!c.read(cx).is_dirty);
6610 });
6611 }
6612
6613 #[gpui::test]
6614 async fn test_new_tab_scrolls_into_view_completely(cx: &mut TestAppContext) {
6615 // Arrange
6616 init_test(cx);
6617 let fs = FakeFs::new(cx.executor());
6618
6619 let project = Project::test(fs, None, cx).await;
6620 let (workspace, cx) =
6621 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6622 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6623
6624 cx.simulate_resize(size(px(300.), px(300.)));
6625
6626 add_labeled_item(&pane, "untitled", false, cx);
6627 add_labeled_item(&pane, "untitled", false, cx);
6628 add_labeled_item(&pane, "untitled", false, cx);
6629 add_labeled_item(&pane, "untitled", false, cx);
6630 // Act: this should trigger a scroll
6631 add_labeled_item(&pane, "untitled", false, cx);
6632 // Assert
6633 let tab_bar_scroll_handle =
6634 pane.update_in(cx, |pane, _window, _cx| pane.tab_bar_scroll_handle.clone());
6635 assert_eq!(tab_bar_scroll_handle.children_count(), 6);
6636 let tab_bounds = cx.debug_bounds("TAB-3").unwrap();
6637 let new_tab_button_bounds = cx.debug_bounds("ICON-Plus").unwrap();
6638 let scroll_bounds = tab_bar_scroll_handle.bounds();
6639 let scroll_offset = tab_bar_scroll_handle.offset();
6640 assert!(tab_bounds.right() <= scroll_bounds.right() + scroll_offset.x);
6641 // -39.5 is the magic number for this setup
6642 assert_eq!(scroll_offset.x, px(-39.5));
6643 assert!(
6644 !tab_bounds.intersects(&new_tab_button_bounds),
6645 "Tab should not overlap with the new tab button, if this is failing check if there's been a redesign!"
6646 );
6647 }
6648
6649 #[gpui::test]
6650 async fn test_close_all_items_including_pinned(cx: &mut TestAppContext) {
6651 init_test(cx);
6652 let fs = FakeFs::new(cx.executor());
6653
6654 let project = Project::test(fs, None, cx).await;
6655 let (workspace, cx) =
6656 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6657 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6658
6659 let item_a = add_labeled_item(&pane, "A", false, cx);
6660 add_labeled_item(&pane, "B", false, cx);
6661 add_labeled_item(&pane, "C", false, cx);
6662 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6663
6664 pane.update_in(cx, |pane, window, cx| {
6665 let ix = pane.index_for_item_id(item_a.item_id()).unwrap();
6666 pane.pin_tab_at(ix, window, cx);
6667 pane.close_all_items(
6668 &CloseAllItems {
6669 save_intent: None,
6670 close_pinned: true,
6671 },
6672 window,
6673 cx,
6674 )
6675 })
6676 .await
6677 .unwrap();
6678 assert_item_labels(&pane, [], cx);
6679 }
6680
6681 #[gpui::test]
6682 async fn test_close_pinned_tab_with_non_pinned_in_same_pane(cx: &mut TestAppContext) {
6683 init_test(cx);
6684 let fs = FakeFs::new(cx.executor());
6685 let project = Project::test(fs, None, cx).await;
6686 let (workspace, cx) =
6687 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6688
6689 // Non-pinned tabs in same pane
6690 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6691 add_labeled_item(&pane, "A", false, cx);
6692 add_labeled_item(&pane, "B", false, cx);
6693 add_labeled_item(&pane, "C", false, cx);
6694 pane.update_in(cx, |pane, window, cx| {
6695 pane.pin_tab_at(0, window, cx);
6696 });
6697 set_labeled_items(&pane, ["A*", "B", "C"], cx);
6698 pane.update_in(cx, |pane, window, cx| {
6699 pane.close_active_item(
6700 &CloseActiveItem {
6701 save_intent: None,
6702 close_pinned: false,
6703 },
6704 window,
6705 cx,
6706 )
6707 .unwrap();
6708 });
6709 // Non-pinned tab should be active
6710 assert_item_labels(&pane, ["A!", "B*", "C"], cx);
6711 }
6712
6713 #[gpui::test]
6714 async fn test_close_pinned_tab_with_non_pinned_in_different_pane(cx: &mut TestAppContext) {
6715 init_test(cx);
6716 let fs = FakeFs::new(cx.executor());
6717 let project = Project::test(fs, None, cx).await;
6718 let (workspace, cx) =
6719 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6720
6721 // No non-pinned tabs in same pane, non-pinned tabs in another pane
6722 let pane1 = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6723 let pane2 = workspace.update_in(cx, |workspace, window, cx| {
6724 workspace.split_pane(pane1.clone(), SplitDirection::Right, window, cx)
6725 });
6726 add_labeled_item(&pane1, "A", false, cx);
6727 pane1.update_in(cx, |pane, window, cx| {
6728 pane.pin_tab_at(0, window, cx);
6729 });
6730 set_labeled_items(&pane1, ["A*"], cx);
6731 add_labeled_item(&pane2, "B", false, cx);
6732 set_labeled_items(&pane2, ["B"], cx);
6733 pane1.update_in(cx, |pane, window, cx| {
6734 pane.close_active_item(
6735 &CloseActiveItem {
6736 save_intent: None,
6737 close_pinned: false,
6738 },
6739 window,
6740 cx,
6741 )
6742 .unwrap();
6743 });
6744 // Non-pinned tab of other pane should be active
6745 assert_item_labels(&pane2, ["B*"], cx);
6746 }
6747
6748 #[gpui::test]
6749 async fn ensure_item_closing_actions_do_not_panic_when_no_items_exist(cx: &mut TestAppContext) {
6750 init_test(cx);
6751 let fs = FakeFs::new(cx.executor());
6752 let project = Project::test(fs, None, cx).await;
6753 let (workspace, cx) =
6754 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6755
6756 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6757 assert_item_labels(&pane, [], cx);
6758
6759 pane.update_in(cx, |pane, window, cx| {
6760 pane.close_active_item(
6761 &CloseActiveItem {
6762 save_intent: None,
6763 close_pinned: false,
6764 },
6765 window,
6766 cx,
6767 )
6768 })
6769 .await
6770 .unwrap();
6771
6772 pane.update_in(cx, |pane, window, cx| {
6773 pane.close_other_items(
6774 &CloseOtherItems {
6775 save_intent: None,
6776 close_pinned: false,
6777 },
6778 None,
6779 window,
6780 cx,
6781 )
6782 })
6783 .await
6784 .unwrap();
6785
6786 pane.update_in(cx, |pane, window, cx| {
6787 pane.close_all_items(
6788 &CloseAllItems {
6789 save_intent: None,
6790 close_pinned: false,
6791 },
6792 window,
6793 cx,
6794 )
6795 })
6796 .await
6797 .unwrap();
6798
6799 pane.update_in(cx, |pane, window, cx| {
6800 pane.close_clean_items(
6801 &CloseCleanItems {
6802 close_pinned: false,
6803 },
6804 window,
6805 cx,
6806 )
6807 })
6808 .await
6809 .unwrap();
6810
6811 pane.update_in(cx, |pane, window, cx| {
6812 pane.close_items_to_the_right_by_id(
6813 None,
6814 &CloseItemsToTheRight {
6815 close_pinned: false,
6816 },
6817 window,
6818 cx,
6819 )
6820 })
6821 .await
6822 .unwrap();
6823
6824 pane.update_in(cx, |pane, window, cx| {
6825 pane.close_items_to_the_left_by_id(
6826 None,
6827 &CloseItemsToTheLeft {
6828 close_pinned: false,
6829 },
6830 window,
6831 cx,
6832 )
6833 })
6834 .await
6835 .unwrap();
6836 }
6837
6838 #[gpui::test]
6839 async fn test_item_swapping_actions(cx: &mut TestAppContext) {
6840 init_test(cx);
6841 let fs = FakeFs::new(cx.executor());
6842 let project = Project::test(fs, None, cx).await;
6843 let (workspace, cx) =
6844 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
6845
6846 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
6847 assert_item_labels(&pane, [], cx);
6848
6849 // Test that these actions do not panic
6850 pane.update_in(cx, |pane, window, cx| {
6851 pane.swap_item_right(&Default::default(), window, cx);
6852 });
6853
6854 pane.update_in(cx, |pane, window, cx| {
6855 pane.swap_item_left(&Default::default(), window, cx);
6856 });
6857
6858 add_labeled_item(&pane, "A", false, cx);
6859 add_labeled_item(&pane, "B", false, cx);
6860 add_labeled_item(&pane, "C", false, cx);
6861 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6862
6863 pane.update_in(cx, |pane, window, cx| {
6864 pane.swap_item_right(&Default::default(), window, cx);
6865 });
6866 assert_item_labels(&pane, ["A", "B", "C*"], cx);
6867
6868 pane.update_in(cx, |pane, window, cx| {
6869 pane.swap_item_left(&Default::default(), window, cx);
6870 });
6871 assert_item_labels(&pane, ["A", "C*", "B"], cx);
6872
6873 pane.update_in(cx, |pane, window, cx| {
6874 pane.swap_item_left(&Default::default(), window, cx);
6875 });
6876 assert_item_labels(&pane, ["C*", "A", "B"], cx);
6877
6878 pane.update_in(cx, |pane, window, cx| {
6879 pane.swap_item_left(&Default::default(), window, cx);
6880 });
6881 assert_item_labels(&pane, ["C*", "A", "B"], cx);
6882
6883 pane.update_in(cx, |pane, window, cx| {
6884 pane.swap_item_right(&Default::default(), window, cx);
6885 });
6886 assert_item_labels(&pane, ["A", "C*", "B"], cx);
6887 }
6888
6889 fn init_test(cx: &mut TestAppContext) {
6890 cx.update(|cx| {
6891 let settings_store = SettingsStore::test(cx);
6892 cx.set_global(settings_store);
6893 theme::init(LoadThemes::JustBase, cx);
6894 });
6895 }
6896
6897 fn set_max_tabs(cx: &mut TestAppContext, value: Option<usize>) {
6898 cx.update_global(|store: &mut SettingsStore, cx| {
6899 store.update_user_settings(cx, |settings| {
6900 settings.workspace.max_tabs = value.map(|v| NonZero::new(v).unwrap())
6901 });
6902 });
6903 }
6904
6905 fn add_labeled_item(
6906 pane: &Entity<Pane>,
6907 label: &str,
6908 is_dirty: bool,
6909 cx: &mut VisualTestContext,
6910 ) -> Box<Entity<TestItem>> {
6911 pane.update_in(cx, |pane, window, cx| {
6912 let labeled_item =
6913 Box::new(cx.new(|cx| TestItem::new(cx).with_label(label).with_dirty(is_dirty)));
6914 pane.add_item(labeled_item.clone(), false, false, None, window, cx);
6915 labeled_item
6916 })
6917 }
6918
6919 fn set_labeled_items<const COUNT: usize>(
6920 pane: &Entity<Pane>,
6921 labels: [&str; COUNT],
6922 cx: &mut VisualTestContext,
6923 ) -> [Box<Entity<TestItem>>; COUNT] {
6924 pane.update_in(cx, |pane, window, cx| {
6925 pane.items.clear();
6926 let mut active_item_index = 0;
6927
6928 let mut index = 0;
6929 let items = labels.map(|mut label| {
6930 if label.ends_with('*') {
6931 label = label.trim_end_matches('*');
6932 active_item_index = index;
6933 }
6934
6935 let labeled_item = Box::new(cx.new(|cx| TestItem::new(cx).with_label(label)));
6936 pane.add_item(labeled_item.clone(), false, false, None, window, cx);
6937 index += 1;
6938 labeled_item
6939 });
6940
6941 pane.activate_item(active_item_index, false, false, window, cx);
6942
6943 items
6944 })
6945 }
6946
6947 // Assert the item label, with the active item label suffixed with a '*'
6948 #[track_caller]
6949 fn assert_item_labels<const COUNT: usize>(
6950 pane: &Entity<Pane>,
6951 expected_states: [&str; COUNT],
6952 cx: &mut VisualTestContext,
6953 ) {
6954 let actual_states = pane.update(cx, |pane, cx| {
6955 pane.items
6956 .iter()
6957 .enumerate()
6958 .map(|(ix, item)| {
6959 let mut state = item
6960 .to_any()
6961 .downcast::<TestItem>()
6962 .unwrap()
6963 .read(cx)
6964 .label
6965 .clone();
6966 if ix == pane.active_item_index {
6967 state.push('*');
6968 }
6969 if item.is_dirty(cx) {
6970 state.push('^');
6971 }
6972 if pane.is_tab_pinned(ix) {
6973 state.push('!');
6974 }
6975 state
6976 })
6977 .collect::<Vec<_>>()
6978 });
6979 assert_eq!(
6980 actual_states, expected_states,
6981 "pane items do not match expectation"
6982 );
6983 }
6984}