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