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