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