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