1pub mod active_file_name;
2pub mod dock;
3pub mod history_manager;
4pub mod invalid_item_view;
5pub mod item;
6mod modal_layer;
7mod multi_workspace;
8#[cfg(test)]
9mod multi_workspace_tests;
10pub mod notifications;
11pub mod pane;
12pub mod pane_group;
13pub mod path_list {
14 pub use util::path_list::{PathList, SerializedPathList};
15}
16mod persistence;
17pub mod searchable;
18mod security_modal;
19pub mod shared_screen;
20use db::smol::future::yield_now;
21pub use shared_screen::SharedScreen;
22pub mod focus_follows_mouse;
23mod status_bar;
24pub mod tasks;
25mod theme_preview;
26mod toast_layer;
27mod toolbar;
28pub mod welcome;
29mod workspace_settings;
30
31pub use crate::notifications::NotificationFrame;
32pub use dock::Panel;
33pub use multi_workspace::{
34 CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
35 MultiWorkspaceEvent, NewThread, NextProject, NextThread, PreviousProject, PreviousThread,
36 ShowFewerThreads, ShowMoreThreads, Sidebar, SidebarEvent, SidebarHandle, SidebarRenderState,
37 SidebarSide, ToggleWorkspaceSidebar, sidebar_side_context_menu,
38};
39pub use path_list::{PathList, SerializedPathList};
40pub use toast_layer::{ToastAction, ToastLayer, ToastView};
41
42use anyhow::{Context as _, Result, anyhow};
43use client::{
44 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
45 proto::{self, ErrorCode, PanelId, PeerId},
46};
47use collections::{HashMap, HashSet, hash_map};
48use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
49use fs::Fs;
50use futures::{
51 Future, FutureExt, StreamExt,
52 channel::{
53 mpsc::{self, UnboundedReceiver, UnboundedSender},
54 oneshot,
55 },
56 future::{Shared, try_join_all},
57};
58use gpui::{
59 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
60 Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
61 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
62 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
63 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
64 WindowOptions, actions, canvas, point, relative, size, transparent_black,
65};
66pub use history_manager::*;
67pub use item::{
68 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
69 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
70};
71use itertools::Itertools;
72use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
73pub use modal_layer::*;
74use node_runtime::NodeRuntime;
75use notifications::{
76 DetachAndPromptErr, Notifications, dismiss_app_notification,
77 simple_message_notification::MessageNotification,
78};
79pub use pane::*;
80pub use pane_group::{
81 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
82 SplitDirection,
83};
84use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
85pub use persistence::{
86 WorkspaceDb, delete_unloaded_items,
87 model::{
88 DockStructure, ItemId, MultiWorkspaceState, SerializedMultiWorkspace,
89 SerializedWorkspaceLocation, SessionWorkspace,
90 },
91 read_serialized_multi_workspaces, resolve_worktree_workspaces,
92};
93use postage::stream::Stream;
94use project::{
95 DirectoryLister, Project, ProjectEntryId, ProjectGroupKey, ProjectPath, ResolvedPath, Worktree,
96 WorktreeId, WorktreeSettings,
97 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
98 project_settings::ProjectSettings,
99 toolchain_store::ToolchainStoreEvent,
100 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
101};
102use remote::{
103 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
104 remote_client::ConnectionIdentifier,
105};
106use schemars::JsonSchema;
107use serde::Deserialize;
108use session::AppSession;
109use settings::{
110 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
111};
112
113use sqlez::{
114 bindable::{Bind, Column, StaticColumnCount},
115 statement::Statement,
116};
117use status_bar::StatusBar;
118pub use status_bar::StatusItemView;
119use std::{
120 any::TypeId,
121 borrow::Cow,
122 cell::RefCell,
123 cmp,
124 collections::VecDeque,
125 env,
126 hash::Hash,
127 path::{Path, PathBuf},
128 process::ExitStatus,
129 rc::Rc,
130 sync::{
131 Arc, LazyLock,
132 atomic::{AtomicBool, AtomicUsize},
133 },
134 time::Duration,
135};
136use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
137use theme::{ActiveTheme, SystemAppearance};
138use theme_settings::ThemeSettings;
139pub use toolbar::{
140 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
141};
142pub use ui;
143use ui::{Window, prelude::*};
144use util::{
145 ResultExt, TryFutureExt,
146 paths::{PathStyle, SanitizedPath},
147 rel_path::RelPath,
148 serde::default_true,
149};
150use uuid::Uuid;
151pub use workspace_settings::{
152 AutosaveSetting, BottomDockLayout, FocusFollowsMouse, RestoreOnStartupBehavior,
153 StatusBarSettings, TabBarSettings, WorkspaceSettings,
154};
155use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
156
157use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
158use crate::{
159 persistence::{
160 SerializedAxis,
161 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
162 },
163 security_modal::SecurityModal,
164};
165
166pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
167
168static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
169 env::var("ZED_WINDOW_SIZE")
170 .ok()
171 .as_deref()
172 .and_then(parse_pixel_size_env_var)
173});
174
175static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
176 env::var("ZED_WINDOW_POSITION")
177 .ok()
178 .as_deref()
179 .and_then(parse_pixel_position_env_var)
180});
181
182pub trait TerminalProvider {
183 fn spawn(
184 &self,
185 task: SpawnInTerminal,
186 window: &mut Window,
187 cx: &mut App,
188 ) -> Task<Option<Result<ExitStatus>>>;
189}
190
191pub trait DebuggerProvider {
192 // `active_buffer` is used to resolve build task's name against language-specific tasks.
193 fn start_session(
194 &self,
195 definition: DebugScenario,
196 task_context: SharedTaskContext,
197 active_buffer: Option<Entity<Buffer>>,
198 worktree_id: Option<WorktreeId>,
199 window: &mut Window,
200 cx: &mut App,
201 );
202
203 fn spawn_task_or_modal(
204 &self,
205 workspace: &mut Workspace,
206 action: &Spawn,
207 window: &mut Window,
208 cx: &mut Context<Workspace>,
209 );
210
211 fn task_scheduled(&self, cx: &mut App);
212 fn debug_scenario_scheduled(&self, cx: &mut App);
213 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
214
215 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
216}
217
218/// Opens a file or directory.
219#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
220#[action(namespace = workspace)]
221pub struct Open {
222 /// When true, opens in a new window. When false, adds to the current
223 /// window as a new workspace (multi-workspace).
224 #[serde(default = "Open::default_create_new_window")]
225 pub create_new_window: bool,
226}
227
228impl Open {
229 pub const DEFAULT: Self = Self {
230 create_new_window: true,
231 };
232
233 /// Used by `#[serde(default)]` on the `create_new_window` field so that
234 /// the serde default and `Open::DEFAULT` stay in sync.
235 fn default_create_new_window() -> bool {
236 Self::DEFAULT.create_new_window
237 }
238}
239
240impl Default for Open {
241 fn default() -> Self {
242 Self::DEFAULT
243 }
244}
245
246actions!(
247 workspace,
248 [
249 /// Activates the next pane in the workspace.
250 ActivateNextPane,
251 /// Activates the previous pane in the workspace.
252 ActivatePreviousPane,
253 /// Activates the last pane in the workspace.
254 ActivateLastPane,
255 /// Switches to the next window.
256 ActivateNextWindow,
257 /// Switches to the previous window.
258 ActivatePreviousWindow,
259 /// Adds a folder to the current project.
260 AddFolderToProject,
261 /// Clears all notifications.
262 ClearAllNotifications,
263 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
264 ClearNavigationHistory,
265 /// Closes the active dock.
266 CloseActiveDock,
267 /// Closes all docks.
268 CloseAllDocks,
269 /// Toggles all docks.
270 ToggleAllDocks,
271 /// Closes the current window.
272 CloseWindow,
273 /// Closes the current project.
274 CloseProject,
275 /// Opens the feedback dialog.
276 Feedback,
277 /// Follows the next collaborator in the session.
278 FollowNextCollaborator,
279 /// Moves the focused panel to the next position.
280 MoveFocusedPanelToNextPosition,
281 /// Creates a new file.
282 NewFile,
283 /// Creates a new file in a vertical split.
284 NewFileSplitVertical,
285 /// Creates a new file in a horizontal split.
286 NewFileSplitHorizontal,
287 /// Opens a new search.
288 NewSearch,
289 /// Opens a new window.
290 NewWindow,
291 /// Opens multiple files.
292 OpenFiles,
293 /// Opens the current location in terminal.
294 OpenInTerminal,
295 /// Opens the component preview.
296 OpenComponentPreview,
297 /// Reloads the active item.
298 ReloadActiveItem,
299 /// Resets the active dock to its default size.
300 ResetActiveDockSize,
301 /// Resets all open docks to their default sizes.
302 ResetOpenDocksSize,
303 /// Reloads the application
304 Reload,
305 /// Saves the current file with a new name.
306 SaveAs,
307 /// Saves without formatting.
308 SaveWithoutFormat,
309 /// Shuts down all debug adapters.
310 ShutdownDebugAdapters,
311 /// Suppresses the current notification.
312 SuppressNotification,
313 /// Toggles the bottom dock.
314 ToggleBottomDock,
315 /// Toggles centered layout mode.
316 ToggleCenteredLayout,
317 /// Toggles edit prediction feature globally for all files.
318 ToggleEditPrediction,
319 /// Toggles the left dock.
320 ToggleLeftDock,
321 /// Toggles the right dock.
322 ToggleRightDock,
323 /// Toggles zoom on the active pane.
324 ToggleZoom,
325 /// Toggles read-only mode for the active item (if supported by that item).
326 ToggleReadOnlyFile,
327 /// Zooms in on the active pane.
328 ZoomIn,
329 /// Zooms out of the active pane.
330 ZoomOut,
331 /// If any worktrees are in restricted mode, shows a modal with possible actions.
332 /// If the modal is shown already, closes it without trusting any worktree.
333 ToggleWorktreeSecurity,
334 /// Clears all trusted worktrees, placing them in restricted mode on next open.
335 /// Requires restart to take effect on already opened projects.
336 ClearTrustedWorktrees,
337 /// Stops following a collaborator.
338 Unfollow,
339 /// Restores the banner.
340 RestoreBanner,
341 /// Toggles expansion of the selected item.
342 ToggleExpandItem,
343 ]
344);
345
346/// Activates a specific pane by its index.
347#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
348#[action(namespace = workspace)]
349pub struct ActivatePane(pub usize);
350
351/// Moves an item to a specific pane by index.
352#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
353#[action(namespace = workspace)]
354#[serde(deny_unknown_fields)]
355pub struct MoveItemToPane {
356 #[serde(default = "default_1")]
357 pub destination: usize,
358 #[serde(default = "default_true")]
359 pub focus: bool,
360 #[serde(default)]
361 pub clone: bool,
362}
363
364fn default_1() -> usize {
365 1
366}
367
368/// Moves an item to a pane in the specified direction.
369#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
370#[action(namespace = workspace)]
371#[serde(deny_unknown_fields)]
372pub struct MoveItemToPaneInDirection {
373 #[serde(default = "default_right")]
374 pub direction: SplitDirection,
375 #[serde(default = "default_true")]
376 pub focus: bool,
377 #[serde(default)]
378 pub clone: bool,
379}
380
381/// Creates a new file in a split of the desired direction.
382#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
383#[action(namespace = workspace)]
384#[serde(deny_unknown_fields)]
385pub struct NewFileSplit(pub SplitDirection);
386
387fn default_right() -> SplitDirection {
388 SplitDirection::Right
389}
390
391/// Saves all open files in the workspace.
392#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
393#[action(namespace = workspace)]
394#[serde(deny_unknown_fields)]
395pub struct SaveAll {
396 #[serde(default)]
397 pub save_intent: Option<SaveIntent>,
398}
399
400/// Saves the current file with the specified options.
401#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
402#[action(namespace = workspace)]
403#[serde(deny_unknown_fields)]
404pub struct Save {
405 #[serde(default)]
406 pub save_intent: Option<SaveIntent>,
407}
408
409/// Moves Focus to the central panes in the workspace.
410#[derive(Clone, Debug, PartialEq, Eq, Action)]
411#[action(namespace = workspace)]
412pub struct FocusCenterPane;
413
414/// Closes all items and panes in the workspace.
415#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
416#[action(namespace = workspace)]
417#[serde(deny_unknown_fields)]
418pub struct CloseAllItemsAndPanes {
419 #[serde(default)]
420 pub save_intent: Option<SaveIntent>,
421}
422
423/// Closes all inactive tabs and panes in the workspace.
424#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
425#[action(namespace = workspace)]
426#[serde(deny_unknown_fields)]
427pub struct CloseInactiveTabsAndPanes {
428 #[serde(default)]
429 pub save_intent: Option<SaveIntent>,
430}
431
432/// Closes the active item across all panes.
433#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
434#[action(namespace = workspace)]
435#[serde(deny_unknown_fields)]
436pub struct CloseItemInAllPanes {
437 #[serde(default)]
438 pub save_intent: Option<SaveIntent>,
439 #[serde(default)]
440 pub close_pinned: bool,
441}
442
443/// Sends a sequence of keystrokes to the active element.
444#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
445#[action(namespace = workspace)]
446pub struct SendKeystrokes(pub String);
447
448actions!(
449 project_symbols,
450 [
451 /// Toggles the project symbols search.
452 #[action(name = "Toggle")]
453 ToggleProjectSymbols
454 ]
455);
456
457/// Toggles the file finder interface.
458#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
459#[action(namespace = file_finder, name = "Toggle")]
460#[serde(deny_unknown_fields)]
461pub struct ToggleFileFinder {
462 #[serde(default)]
463 pub separate_history: bool,
464}
465
466/// Opens a new terminal in the center.
467#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
468#[action(namespace = workspace)]
469#[serde(deny_unknown_fields)]
470pub struct NewCenterTerminal {
471 /// If true, creates a local terminal even in remote projects.
472 #[serde(default)]
473 pub local: bool,
474}
475
476/// Opens a new terminal.
477#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
478#[action(namespace = workspace)]
479#[serde(deny_unknown_fields)]
480pub struct NewTerminal {
481 /// If true, creates a local terminal even in remote projects.
482 #[serde(default)]
483 pub local: bool,
484}
485
486/// Increases size of a currently focused dock by a given amount of pixels.
487#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
488#[action(namespace = workspace)]
489#[serde(deny_unknown_fields)]
490pub struct IncreaseActiveDockSize {
491 /// For 0px parameter, uses UI font size value.
492 #[serde(default)]
493 pub px: u32,
494}
495
496/// Decreases size of a currently focused dock by a given amount of pixels.
497#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
498#[action(namespace = workspace)]
499#[serde(deny_unknown_fields)]
500pub struct DecreaseActiveDockSize {
501 /// For 0px parameter, uses UI font size value.
502 #[serde(default)]
503 pub px: u32,
504}
505
506/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
507#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
508#[action(namespace = workspace)]
509#[serde(deny_unknown_fields)]
510pub struct IncreaseOpenDocksSize {
511 /// For 0px parameter, uses UI font size value.
512 #[serde(default)]
513 pub px: u32,
514}
515
516/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
517#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
518#[action(namespace = workspace)]
519#[serde(deny_unknown_fields)]
520pub struct DecreaseOpenDocksSize {
521 /// For 0px parameter, uses UI font size value.
522 #[serde(default)]
523 pub px: u32,
524}
525
526actions!(
527 workspace,
528 [
529 /// Activates the pane to the left.
530 ActivatePaneLeft,
531 /// Activates the pane to the right.
532 ActivatePaneRight,
533 /// Activates the pane above.
534 ActivatePaneUp,
535 /// Activates the pane below.
536 ActivatePaneDown,
537 /// Swaps the current pane with the one to the left.
538 SwapPaneLeft,
539 /// Swaps the current pane with the one to the right.
540 SwapPaneRight,
541 /// Swaps the current pane with the one above.
542 SwapPaneUp,
543 /// Swaps the current pane with the one below.
544 SwapPaneDown,
545 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
546 SwapPaneAdjacent,
547 /// Move the current pane to be at the far left.
548 MovePaneLeft,
549 /// Move the current pane to be at the far right.
550 MovePaneRight,
551 /// Move the current pane to be at the very top.
552 MovePaneUp,
553 /// Move the current pane to be at the very bottom.
554 MovePaneDown,
555 ]
556);
557
558#[derive(PartialEq, Eq, Debug)]
559pub enum CloseIntent {
560 /// Quit the program entirely.
561 Quit,
562 /// Close a window.
563 CloseWindow,
564 /// Replace the workspace in an existing window.
565 ReplaceWindow,
566}
567
568#[derive(Clone)]
569pub struct Toast {
570 id: NotificationId,
571 msg: Cow<'static, str>,
572 autohide: bool,
573 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
574}
575
576impl Toast {
577 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
578 Toast {
579 id,
580 msg: msg.into(),
581 on_click: None,
582 autohide: false,
583 }
584 }
585
586 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
587 where
588 M: Into<Cow<'static, str>>,
589 F: Fn(&mut Window, &mut App) + 'static,
590 {
591 self.on_click = Some((message.into(), Arc::new(on_click)));
592 self
593 }
594
595 pub fn autohide(mut self) -> Self {
596 self.autohide = true;
597 self
598 }
599}
600
601impl PartialEq for Toast {
602 fn eq(&self, other: &Self) -> bool {
603 self.id == other.id
604 && self.msg == other.msg
605 && self.on_click.is_some() == other.on_click.is_some()
606 }
607}
608
609/// Opens a new terminal with the specified working directory.
610#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
611#[action(namespace = workspace)]
612#[serde(deny_unknown_fields)]
613pub struct OpenTerminal {
614 pub working_directory: PathBuf,
615 /// If true, creates a local terminal even in remote projects.
616 #[serde(default)]
617 pub local: bool,
618}
619
620#[derive(
621 Clone,
622 Copy,
623 Debug,
624 Default,
625 Hash,
626 PartialEq,
627 Eq,
628 PartialOrd,
629 Ord,
630 serde::Serialize,
631 serde::Deserialize,
632)]
633pub struct WorkspaceId(i64);
634
635impl WorkspaceId {
636 pub fn from_i64(value: i64) -> Self {
637 Self(value)
638 }
639}
640
641impl StaticColumnCount for WorkspaceId {}
642impl Bind for WorkspaceId {
643 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
644 self.0.bind(statement, start_index)
645 }
646}
647impl Column for WorkspaceId {
648 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
649 i64::column(statement, start_index)
650 .map(|(i, next_index)| (Self(i), next_index))
651 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
652 }
653}
654impl From<WorkspaceId> for i64 {
655 fn from(val: WorkspaceId) -> Self {
656 val.0
657 }
658}
659
660fn prompt_and_open_paths(
661 app_state: Arc<AppState>,
662 options: PathPromptOptions,
663 create_new_window: bool,
664 cx: &mut App,
665) {
666 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
667 workspace_window
668 .update(cx, |multi_workspace, window, cx| {
669 let workspace = multi_workspace.workspace().clone();
670 workspace.update(cx, |workspace, cx| {
671 prompt_for_open_path_and_open(
672 workspace,
673 app_state,
674 options,
675 create_new_window,
676 window,
677 cx,
678 );
679 });
680 })
681 .ok();
682 } else {
683 let task = Workspace::new_local(
684 Vec::new(),
685 app_state.clone(),
686 None,
687 None,
688 None,
689 OpenMode::Activate,
690 cx,
691 );
692 cx.spawn(async move |cx| {
693 let OpenResult { window, .. } = task.await?;
694 window.update(cx, |multi_workspace, window, cx| {
695 window.activate_window();
696 let workspace = multi_workspace.workspace().clone();
697 workspace.update(cx, |workspace, cx| {
698 prompt_for_open_path_and_open(
699 workspace,
700 app_state,
701 options,
702 create_new_window,
703 window,
704 cx,
705 );
706 });
707 })?;
708 anyhow::Ok(())
709 })
710 .detach_and_log_err(cx);
711 }
712}
713
714pub fn prompt_for_open_path_and_open(
715 workspace: &mut Workspace,
716 app_state: Arc<AppState>,
717 options: PathPromptOptions,
718 create_new_window: bool,
719 window: &mut Window,
720 cx: &mut Context<Workspace>,
721) {
722 let paths = workspace.prompt_for_open_path(
723 options,
724 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
725 window,
726 cx,
727 );
728 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
729 cx.spawn_in(window, async move |this, cx| {
730 let Some(paths) = paths.await.log_err().flatten() else {
731 return;
732 };
733 if !create_new_window {
734 if let Some(handle) = multi_workspace_handle {
735 if let Some(task) = handle
736 .update(cx, |multi_workspace, window, cx| {
737 multi_workspace.open_project(paths, OpenMode::Activate, window, cx)
738 })
739 .log_err()
740 {
741 task.await.log_err();
742 }
743 return;
744 }
745 }
746 if let Some(task) = this
747 .update_in(cx, |this, window, cx| {
748 this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
749 })
750 .log_err()
751 {
752 task.await.log_err();
753 }
754 })
755 .detach();
756}
757
758pub fn init(app_state: Arc<AppState>, cx: &mut App) {
759 component::init();
760 theme_preview::init(cx);
761 toast_layer::init(cx);
762 history_manager::init(app_state.fs.clone(), cx);
763
764 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
765 .on_action(|_: &Reload, cx| reload(cx))
766 .on_action(|action: &Open, cx: &mut App| {
767 let app_state = AppState::global(cx);
768 prompt_and_open_paths(
769 app_state,
770 PathPromptOptions {
771 files: true,
772 directories: true,
773 multiple: true,
774 prompt: None,
775 },
776 action.create_new_window,
777 cx,
778 );
779 })
780 .on_action(|_: &OpenFiles, cx: &mut App| {
781 let directories = cx.can_select_mixed_files_and_dirs();
782 let app_state = AppState::global(cx);
783 prompt_and_open_paths(
784 app_state,
785 PathPromptOptions {
786 files: true,
787 directories,
788 multiple: true,
789 prompt: None,
790 },
791 true,
792 cx,
793 );
794 });
795}
796
797type BuildProjectItemFn =
798 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
799
800type BuildProjectItemForPathFn =
801 fn(
802 &Entity<Project>,
803 &ProjectPath,
804 &mut Window,
805 &mut App,
806 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
807
808#[derive(Clone, Default)]
809struct ProjectItemRegistry {
810 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
811 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
812}
813
814impl ProjectItemRegistry {
815 fn register<T: ProjectItem>(&mut self) {
816 self.build_project_item_fns_by_type.insert(
817 TypeId::of::<T::Item>(),
818 |item, project, pane, window, cx| {
819 let item = item.downcast().unwrap();
820 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
821 as Box<dyn ItemHandle>
822 },
823 );
824 self.build_project_item_for_path_fns
825 .push(|project, project_path, window, cx| {
826 let project_path = project_path.clone();
827 let is_file = project
828 .read(cx)
829 .entry_for_path(&project_path, cx)
830 .is_some_and(|entry| entry.is_file());
831 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
832 let is_local = project.read(cx).is_local();
833 let project_item =
834 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
835 let project = project.clone();
836 Some(window.spawn(cx, async move |cx| {
837 match project_item.await.with_context(|| {
838 format!(
839 "opening project path {:?}",
840 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
841 )
842 }) {
843 Ok(project_item) => {
844 let project_item = project_item;
845 let project_entry_id: Option<ProjectEntryId> =
846 project_item.read_with(cx, project::ProjectItem::entry_id);
847 let build_workspace_item = Box::new(
848 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
849 Box::new(cx.new(|cx| {
850 T::for_project_item(
851 project,
852 Some(pane),
853 project_item,
854 window,
855 cx,
856 )
857 })) as Box<dyn ItemHandle>
858 },
859 ) as Box<_>;
860 Ok((project_entry_id, build_workspace_item))
861 }
862 Err(e) => {
863 log::warn!("Failed to open a project item: {e:#}");
864 if e.error_code() == ErrorCode::Internal {
865 if let Some(abs_path) =
866 entry_abs_path.as_deref().filter(|_| is_file)
867 {
868 if let Some(broken_project_item_view) =
869 cx.update(|window, cx| {
870 T::for_broken_project_item(
871 abs_path, is_local, &e, window, cx,
872 )
873 })?
874 {
875 let build_workspace_item = Box::new(
876 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
877 cx.new(|_| broken_project_item_view).boxed_clone()
878 },
879 )
880 as Box<_>;
881 return Ok((None, build_workspace_item));
882 }
883 }
884 }
885 Err(e)
886 }
887 }
888 }))
889 });
890 }
891
892 fn open_path(
893 &self,
894 project: &Entity<Project>,
895 path: &ProjectPath,
896 window: &mut Window,
897 cx: &mut App,
898 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
899 let Some(open_project_item) = self
900 .build_project_item_for_path_fns
901 .iter()
902 .rev()
903 .find_map(|open_project_item| open_project_item(project, path, window, cx))
904 else {
905 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
906 };
907 open_project_item
908 }
909
910 fn build_item<T: project::ProjectItem>(
911 &self,
912 item: Entity<T>,
913 project: Entity<Project>,
914 pane: Option<&Pane>,
915 window: &mut Window,
916 cx: &mut App,
917 ) -> Option<Box<dyn ItemHandle>> {
918 let build = self
919 .build_project_item_fns_by_type
920 .get(&TypeId::of::<T>())?;
921 Some(build(item.into_any(), project, pane, window, cx))
922 }
923}
924
925type WorkspaceItemBuilder =
926 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
927
928impl Global for ProjectItemRegistry {}
929
930/// Registers a [ProjectItem] for the app. When opening a file, all the registered
931/// items will get a chance to open the file, starting from the project item that
932/// was added last.
933pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
934 cx.default_global::<ProjectItemRegistry>().register::<I>();
935}
936
937#[derive(Default)]
938pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
939
940struct FollowableViewDescriptor {
941 from_state_proto: fn(
942 Entity<Workspace>,
943 ViewId,
944 &mut Option<proto::view::Variant>,
945 &mut Window,
946 &mut App,
947 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
948 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
949}
950
951impl Global for FollowableViewRegistry {}
952
953impl FollowableViewRegistry {
954 pub fn register<I: FollowableItem>(cx: &mut App) {
955 cx.default_global::<Self>().0.insert(
956 TypeId::of::<I>(),
957 FollowableViewDescriptor {
958 from_state_proto: |workspace, id, state, window, cx| {
959 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
960 cx.foreground_executor()
961 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
962 })
963 },
964 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
965 },
966 );
967 }
968
969 pub fn from_state_proto(
970 workspace: Entity<Workspace>,
971 view_id: ViewId,
972 mut state: Option<proto::view::Variant>,
973 window: &mut Window,
974 cx: &mut App,
975 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
976 cx.update_default_global(|this: &mut Self, cx| {
977 this.0.values().find_map(|descriptor| {
978 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
979 })
980 })
981 }
982
983 pub fn to_followable_view(
984 view: impl Into<AnyView>,
985 cx: &App,
986 ) -> Option<Box<dyn FollowableItemHandle>> {
987 let this = cx.try_global::<Self>()?;
988 let view = view.into();
989 let descriptor = this.0.get(&view.entity_type())?;
990 Some((descriptor.to_followable_view)(&view))
991 }
992}
993
994#[derive(Copy, Clone)]
995struct SerializableItemDescriptor {
996 deserialize: fn(
997 Entity<Project>,
998 WeakEntity<Workspace>,
999 WorkspaceId,
1000 ItemId,
1001 &mut Window,
1002 &mut Context<Pane>,
1003 ) -> Task<Result<Box<dyn ItemHandle>>>,
1004 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
1005 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
1006}
1007
1008#[derive(Default)]
1009struct SerializableItemRegistry {
1010 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
1011 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
1012}
1013
1014impl Global for SerializableItemRegistry {}
1015
1016impl SerializableItemRegistry {
1017 fn deserialize(
1018 item_kind: &str,
1019 project: Entity<Project>,
1020 workspace: WeakEntity<Workspace>,
1021 workspace_id: WorkspaceId,
1022 item_item: ItemId,
1023 window: &mut Window,
1024 cx: &mut Context<Pane>,
1025 ) -> Task<Result<Box<dyn ItemHandle>>> {
1026 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1027 return Task::ready(Err(anyhow!(
1028 "cannot deserialize {}, descriptor not found",
1029 item_kind
1030 )));
1031 };
1032
1033 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1034 }
1035
1036 fn cleanup(
1037 item_kind: &str,
1038 workspace_id: WorkspaceId,
1039 loaded_items: Vec<ItemId>,
1040 window: &mut Window,
1041 cx: &mut App,
1042 ) -> Task<Result<()>> {
1043 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1044 return Task::ready(Err(anyhow!(
1045 "cannot cleanup {}, descriptor not found",
1046 item_kind
1047 )));
1048 };
1049
1050 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1051 }
1052
1053 fn view_to_serializable_item_handle(
1054 view: AnyView,
1055 cx: &App,
1056 ) -> Option<Box<dyn SerializableItemHandle>> {
1057 let this = cx.try_global::<Self>()?;
1058 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1059 Some((descriptor.view_to_serializable_item)(view))
1060 }
1061
1062 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1063 let this = cx.try_global::<Self>()?;
1064 this.descriptors_by_kind.get(item_kind).copied()
1065 }
1066}
1067
1068pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1069 let serialized_item_kind = I::serialized_item_kind();
1070
1071 let registry = cx.default_global::<SerializableItemRegistry>();
1072 let descriptor = SerializableItemDescriptor {
1073 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1074 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1075 cx.foreground_executor()
1076 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1077 },
1078 cleanup: |workspace_id, loaded_items, window, cx| {
1079 I::cleanup(workspace_id, loaded_items, window, cx)
1080 },
1081 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1082 };
1083 registry
1084 .descriptors_by_kind
1085 .insert(Arc::from(serialized_item_kind), descriptor);
1086 registry
1087 .descriptors_by_type
1088 .insert(TypeId::of::<I>(), descriptor);
1089}
1090
1091pub struct AppState {
1092 pub languages: Arc<LanguageRegistry>,
1093 pub client: Arc<Client>,
1094 pub user_store: Entity<UserStore>,
1095 pub workspace_store: Entity<WorkspaceStore>,
1096 pub fs: Arc<dyn fs::Fs>,
1097 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1098 pub node_runtime: NodeRuntime,
1099 pub session: Entity<AppSession>,
1100}
1101
1102struct GlobalAppState(Arc<AppState>);
1103
1104impl Global for GlobalAppState {}
1105
1106pub struct WorkspaceStore {
1107 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1108 client: Arc<Client>,
1109 _subscriptions: Vec<client::Subscription>,
1110}
1111
1112#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1113pub enum CollaboratorId {
1114 PeerId(PeerId),
1115 Agent,
1116}
1117
1118impl From<PeerId> for CollaboratorId {
1119 fn from(peer_id: PeerId) -> Self {
1120 CollaboratorId::PeerId(peer_id)
1121 }
1122}
1123
1124impl From<&PeerId> for CollaboratorId {
1125 fn from(peer_id: &PeerId) -> Self {
1126 CollaboratorId::PeerId(*peer_id)
1127 }
1128}
1129
1130#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1131struct Follower {
1132 project_id: Option<u64>,
1133 peer_id: PeerId,
1134}
1135
1136impl AppState {
1137 #[track_caller]
1138 pub fn global(cx: &App) -> Arc<Self> {
1139 cx.global::<GlobalAppState>().0.clone()
1140 }
1141 pub fn try_global(cx: &App) -> Option<Arc<Self>> {
1142 cx.try_global::<GlobalAppState>()
1143 .map(|state| state.0.clone())
1144 }
1145 pub fn set_global(state: Arc<AppState>, cx: &mut App) {
1146 cx.set_global(GlobalAppState(state));
1147 }
1148
1149 #[cfg(any(test, feature = "test-support"))]
1150 pub fn test(cx: &mut App) -> Arc<Self> {
1151 use fs::Fs;
1152 use node_runtime::NodeRuntime;
1153 use session::Session;
1154 use settings::SettingsStore;
1155
1156 if !cx.has_global::<SettingsStore>() {
1157 let settings_store = SettingsStore::test(cx);
1158 cx.set_global(settings_store);
1159 }
1160
1161 let fs = fs::FakeFs::new(cx.background_executor().clone());
1162 <dyn Fs>::set_global(fs.clone(), cx);
1163 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1164 let clock = Arc::new(clock::FakeSystemClock::new());
1165 let http_client = http_client::FakeHttpClient::with_404_response();
1166 let client = Client::new(clock, http_client, cx);
1167 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1168 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1169 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1170
1171 theme_settings::init(theme::LoadThemes::JustBase, cx);
1172 client::init(&client, cx);
1173
1174 Arc::new(Self {
1175 client,
1176 fs,
1177 languages,
1178 user_store,
1179 workspace_store,
1180 node_runtime: NodeRuntime::unavailable(),
1181 build_window_options: |_, _| Default::default(),
1182 session,
1183 })
1184 }
1185}
1186
1187struct DelayedDebouncedEditAction {
1188 task: Option<Task<()>>,
1189 cancel_channel: Option<oneshot::Sender<()>>,
1190}
1191
1192impl DelayedDebouncedEditAction {
1193 fn new() -> DelayedDebouncedEditAction {
1194 DelayedDebouncedEditAction {
1195 task: None,
1196 cancel_channel: None,
1197 }
1198 }
1199
1200 fn fire_new<F>(
1201 &mut self,
1202 delay: Duration,
1203 window: &mut Window,
1204 cx: &mut Context<Workspace>,
1205 func: F,
1206 ) where
1207 F: 'static
1208 + Send
1209 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1210 {
1211 if let Some(channel) = self.cancel_channel.take() {
1212 _ = channel.send(());
1213 }
1214
1215 let (sender, mut receiver) = oneshot::channel::<()>();
1216 self.cancel_channel = Some(sender);
1217
1218 let previous_task = self.task.take();
1219 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1220 let mut timer = cx.background_executor().timer(delay).fuse();
1221 if let Some(previous_task) = previous_task {
1222 previous_task.await;
1223 }
1224
1225 futures::select_biased! {
1226 _ = receiver => return,
1227 _ = timer => {}
1228 }
1229
1230 if let Some(result) = workspace
1231 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1232 .log_err()
1233 {
1234 result.await.log_err();
1235 }
1236 }));
1237 }
1238}
1239
1240pub enum Event {
1241 PaneAdded(Entity<Pane>),
1242 PaneRemoved,
1243 ItemAdded {
1244 item: Box<dyn ItemHandle>,
1245 },
1246 ActiveItemChanged,
1247 ItemRemoved {
1248 item_id: EntityId,
1249 },
1250 UserSavedItem {
1251 pane: WeakEntity<Pane>,
1252 item: Box<dyn WeakItemHandle>,
1253 save_intent: SaveIntent,
1254 },
1255 ContactRequestedJoin(u64),
1256 WorkspaceCreated(WeakEntity<Workspace>),
1257 OpenBundledFile {
1258 text: Cow<'static, str>,
1259 title: &'static str,
1260 language: &'static str,
1261 },
1262 ZoomChanged,
1263 ModalOpened,
1264 Activate,
1265 PanelAdded(AnyView),
1266}
1267
1268#[derive(Debug, Clone)]
1269pub enum OpenVisible {
1270 All,
1271 None,
1272 OnlyFiles,
1273 OnlyDirectories,
1274}
1275
1276enum WorkspaceLocation {
1277 // Valid local paths or SSH project to serialize
1278 Location(SerializedWorkspaceLocation, PathList),
1279 // No valid location found hence clear session id
1280 DetachFromSession,
1281 // No valid location found to serialize
1282 None,
1283}
1284
1285type PromptForNewPath = Box<
1286 dyn Fn(
1287 &mut Workspace,
1288 DirectoryLister,
1289 Option<String>,
1290 &mut Window,
1291 &mut Context<Workspace>,
1292 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1293>;
1294
1295type PromptForOpenPath = Box<
1296 dyn Fn(
1297 &mut Workspace,
1298 DirectoryLister,
1299 &mut Window,
1300 &mut Context<Workspace>,
1301 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1302>;
1303
1304#[derive(Default)]
1305struct DispatchingKeystrokes {
1306 dispatched: HashSet<Vec<Keystroke>>,
1307 queue: VecDeque<Keystroke>,
1308 task: Option<Shared<Task<()>>>,
1309}
1310
1311/// Collects everything project-related for a certain window opened.
1312/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1313///
1314/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1315/// The `Workspace` owns everybody's state and serves as a default, "global context",
1316/// that can be used to register a global action to be triggered from any place in the window.
1317pub struct Workspace {
1318 weak_self: WeakEntity<Self>,
1319 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1320 zoomed: Option<AnyWeakView>,
1321 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1322 zoomed_position: Option<DockPosition>,
1323 center: PaneGroup,
1324 left_dock: Entity<Dock>,
1325 bottom_dock: Entity<Dock>,
1326 right_dock: Entity<Dock>,
1327 panes: Vec<Entity<Pane>>,
1328 active_worktree_override: Option<WorktreeId>,
1329 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1330 active_pane: Entity<Pane>,
1331 last_active_center_pane: Option<WeakEntity<Pane>>,
1332 last_active_view_id: Option<proto::ViewId>,
1333 status_bar: Entity<StatusBar>,
1334 pub(crate) modal_layer: Entity<ModalLayer>,
1335 toast_layer: Entity<ToastLayer>,
1336 titlebar_item: Option<AnyView>,
1337 notifications: Notifications,
1338 suppressed_notifications: HashSet<NotificationId>,
1339 project: Entity<Project>,
1340 follower_states: HashMap<CollaboratorId, FollowerState>,
1341 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1342 window_edited: bool,
1343 last_window_title: Option<String>,
1344 dirty_items: HashMap<EntityId, Subscription>,
1345 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1346 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1347 database_id: Option<WorkspaceId>,
1348 app_state: Arc<AppState>,
1349 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1350 _subscriptions: Vec<Subscription>,
1351 _apply_leader_updates: Task<Result<()>>,
1352 _observe_current_user: Task<Result<()>>,
1353 _schedule_serialize_workspace: Option<Task<()>>,
1354 _serialize_workspace_task: Option<Task<()>>,
1355 _schedule_serialize_ssh_paths: Option<Task<()>>,
1356 pane_history_timestamp: Arc<AtomicUsize>,
1357 bounds: Bounds<Pixels>,
1358 pub centered_layout: bool,
1359 bounds_save_task_queued: Option<Task<()>>,
1360 on_prompt_for_new_path: Option<PromptForNewPath>,
1361 on_prompt_for_open_path: Option<PromptForOpenPath>,
1362 terminal_provider: Option<Box<dyn TerminalProvider>>,
1363 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1364 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1365 _items_serializer: Task<Result<()>>,
1366 session_id: Option<String>,
1367 scheduled_tasks: Vec<Task<()>>,
1368 last_open_dock_positions: Vec<DockPosition>,
1369 removing: bool,
1370 open_in_dev_container: bool,
1371 _dev_container_task: Option<Task<Result<()>>>,
1372 _panels_task: Option<Task<Result<()>>>,
1373 sidebar_focus_handle: Option<FocusHandle>,
1374 multi_workspace: Option<WeakEntity<MultiWorkspace>>,
1375}
1376
1377impl EventEmitter<Event> for Workspace {}
1378
1379#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1380pub struct ViewId {
1381 pub creator: CollaboratorId,
1382 pub id: u64,
1383}
1384
1385pub struct FollowerState {
1386 center_pane: Entity<Pane>,
1387 dock_pane: Option<Entity<Pane>>,
1388 active_view_id: Option<ViewId>,
1389 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1390}
1391
1392struct FollowerView {
1393 view: Box<dyn FollowableItemHandle>,
1394 location: Option<proto::PanelId>,
1395}
1396
1397#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1398pub enum OpenMode {
1399 /// Open the workspace in a new window.
1400 NewWindow,
1401 /// Add to the window's multi workspace without activating it (used during deserialization).
1402 Add,
1403 /// Add to the window's multi workspace and activate it.
1404 #[default]
1405 Activate,
1406}
1407
1408impl Workspace {
1409 pub fn new(
1410 workspace_id: Option<WorkspaceId>,
1411 project: Entity<Project>,
1412 app_state: Arc<AppState>,
1413 window: &mut Window,
1414 cx: &mut Context<Self>,
1415 ) -> Self {
1416 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1417 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1418 if let TrustedWorktreesEvent::Trusted(..) = e {
1419 // Do not persist auto trusted worktrees
1420 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1421 worktrees_store.update(cx, |worktrees_store, cx| {
1422 worktrees_store.schedule_serialization(
1423 cx,
1424 |new_trusted_worktrees, cx| {
1425 let timeout =
1426 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1427 let db = WorkspaceDb::global(cx);
1428 cx.background_spawn(async move {
1429 timeout.await;
1430 db.save_trusted_worktrees(new_trusted_worktrees)
1431 .await
1432 .log_err();
1433 })
1434 },
1435 )
1436 });
1437 }
1438 }
1439 })
1440 .detach();
1441
1442 cx.observe_global::<SettingsStore>(|_, cx| {
1443 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1444 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1445 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1446 trusted_worktrees.auto_trust_all(cx);
1447 })
1448 }
1449 }
1450 })
1451 .detach();
1452 }
1453
1454 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1455 match event {
1456 project::Event::RemoteIdChanged(_) => {
1457 this.update_window_title(window, cx);
1458 }
1459
1460 project::Event::CollaboratorLeft(peer_id) => {
1461 this.collaborator_left(*peer_id, window, cx);
1462 }
1463
1464 &project::Event::WorktreeRemoved(_) => {
1465 this.update_window_title(window, cx);
1466 this.serialize_workspace(window, cx);
1467 this.update_history(cx);
1468 }
1469
1470 &project::Event::WorktreeAdded(id) => {
1471 this.update_window_title(window, cx);
1472 if this
1473 .project()
1474 .read(cx)
1475 .worktree_for_id(id, cx)
1476 .is_some_and(|wt| wt.read(cx).is_visible())
1477 {
1478 this.serialize_workspace(window, cx);
1479 this.update_history(cx);
1480 }
1481 }
1482 project::Event::WorktreeUpdatedEntries(..) => {
1483 this.update_window_title(window, cx);
1484 this.serialize_workspace(window, cx);
1485 }
1486
1487 project::Event::DisconnectedFromHost => {
1488 this.update_window_edited(window, cx);
1489 let leaders_to_unfollow =
1490 this.follower_states.keys().copied().collect::<Vec<_>>();
1491 for leader_id in leaders_to_unfollow {
1492 this.unfollow(leader_id, window, cx);
1493 }
1494 }
1495
1496 project::Event::DisconnectedFromRemote {
1497 server_not_running: _,
1498 } => {
1499 this.update_window_edited(window, cx);
1500 }
1501
1502 project::Event::Closed => {
1503 window.remove_window();
1504 }
1505
1506 project::Event::DeletedEntry(_, entry_id) => {
1507 for pane in this.panes.iter() {
1508 pane.update(cx, |pane, cx| {
1509 pane.handle_deleted_project_item(*entry_id, window, cx)
1510 });
1511 }
1512 }
1513
1514 project::Event::Toast {
1515 notification_id,
1516 message,
1517 link,
1518 } => this.show_notification(
1519 NotificationId::named(notification_id.clone()),
1520 cx,
1521 |cx| {
1522 let mut notification = MessageNotification::new(message.clone(), cx);
1523 if let Some(link) = link {
1524 notification = notification
1525 .more_info_message(link.label)
1526 .more_info_url(link.url);
1527 }
1528
1529 cx.new(|_| notification)
1530 },
1531 ),
1532
1533 project::Event::HideToast { notification_id } => {
1534 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1535 }
1536
1537 project::Event::LanguageServerPrompt(request) => {
1538 struct LanguageServerPrompt;
1539
1540 this.show_notification(
1541 NotificationId::composite::<LanguageServerPrompt>(request.id),
1542 cx,
1543 |cx| {
1544 cx.new(|cx| {
1545 notifications::LanguageServerPrompt::new(request.clone(), cx)
1546 })
1547 },
1548 );
1549 }
1550
1551 project::Event::AgentLocationChanged => {
1552 this.handle_agent_location_changed(window, cx)
1553 }
1554
1555 _ => {}
1556 }
1557 cx.notify()
1558 })
1559 .detach();
1560
1561 cx.subscribe_in(
1562 &project.read(cx).breakpoint_store(),
1563 window,
1564 |workspace, _, event, window, cx| match event {
1565 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1566 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1567 workspace.serialize_workspace(window, cx);
1568 }
1569 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1570 },
1571 )
1572 .detach();
1573 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1574 cx.subscribe_in(
1575 &toolchain_store,
1576 window,
1577 |workspace, _, event, window, cx| match event {
1578 ToolchainStoreEvent::CustomToolchainsModified => {
1579 workspace.serialize_workspace(window, cx);
1580 }
1581 _ => {}
1582 },
1583 )
1584 .detach();
1585 }
1586
1587 cx.on_focus_lost(window, |this, window, cx| {
1588 let focus_handle = this.focus_handle(cx);
1589 window.focus(&focus_handle, cx);
1590 })
1591 .detach();
1592
1593 let weak_handle = cx.entity().downgrade();
1594 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1595
1596 let center_pane = cx.new(|cx| {
1597 let mut center_pane = Pane::new(
1598 weak_handle.clone(),
1599 project.clone(),
1600 pane_history_timestamp.clone(),
1601 None,
1602 NewFile.boxed_clone(),
1603 true,
1604 window,
1605 cx,
1606 );
1607 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1608 center_pane.set_should_display_welcome_page(true);
1609 center_pane
1610 });
1611 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1612 .detach();
1613
1614 window.focus(¢er_pane.focus_handle(cx), cx);
1615
1616 cx.emit(Event::PaneAdded(center_pane.clone()));
1617
1618 let any_window_handle = window.window_handle();
1619 app_state.workspace_store.update(cx, |store, _| {
1620 store
1621 .workspaces
1622 .insert((any_window_handle, weak_handle.clone()));
1623 });
1624
1625 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1626 let mut connection_status = app_state.client.status();
1627 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1628 current_user.next().await;
1629 connection_status.next().await;
1630 let mut stream =
1631 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1632
1633 while stream.recv().await.is_some() {
1634 this.update(cx, |_, cx| cx.notify())?;
1635 }
1636 anyhow::Ok(())
1637 });
1638
1639 // All leader updates are enqueued and then processed in a single task, so
1640 // that each asynchronous operation can be run in order.
1641 let (leader_updates_tx, mut leader_updates_rx) =
1642 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1643 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1644 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1645 Self::process_leader_update(&this, leader_id, update, cx)
1646 .await
1647 .log_err();
1648 }
1649
1650 Ok(())
1651 });
1652
1653 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1654 let modal_layer = cx.new(|_| ModalLayer::new());
1655 let toast_layer = cx.new(|_| ToastLayer::new());
1656 cx.subscribe(
1657 &modal_layer,
1658 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1659 cx.emit(Event::ModalOpened);
1660 },
1661 )
1662 .detach();
1663
1664 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1665 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1666 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1667 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1668 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1669 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1670 let multi_workspace = window
1671 .root::<MultiWorkspace>()
1672 .flatten()
1673 .map(|mw| mw.downgrade());
1674 let status_bar = cx.new(|cx| {
1675 let mut status_bar =
1676 StatusBar::new(¢er_pane.clone(), multi_workspace.clone(), window, cx);
1677 status_bar.add_left_item(left_dock_buttons, window, cx);
1678 status_bar.add_right_item(right_dock_buttons, window, cx);
1679 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1680 status_bar
1681 });
1682
1683 let session_id = app_state.session.read(cx).id().to_owned();
1684
1685 let mut active_call = None;
1686 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1687 let subscriptions =
1688 vec![
1689 call.0
1690 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1691 ];
1692 active_call = Some((call, subscriptions));
1693 }
1694
1695 let (serializable_items_tx, serializable_items_rx) =
1696 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1697 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1698 Self::serialize_items(&this, serializable_items_rx, cx).await
1699 });
1700
1701 let subscriptions = vec![
1702 cx.observe_window_activation(window, Self::on_window_activation_changed),
1703 cx.observe_window_bounds(window, move |this, window, cx| {
1704 if this.bounds_save_task_queued.is_some() {
1705 return;
1706 }
1707 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1708 cx.background_executor()
1709 .timer(Duration::from_millis(100))
1710 .await;
1711 this.update_in(cx, |this, window, cx| {
1712 this.save_window_bounds(window, cx).detach();
1713 this.bounds_save_task_queued.take();
1714 })
1715 .ok();
1716 }));
1717 cx.notify();
1718 }),
1719 cx.observe_window_appearance(window, |_, window, cx| {
1720 let window_appearance = window.appearance();
1721
1722 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1723
1724 theme_settings::reload_theme(cx);
1725 theme_settings::reload_icon_theme(cx);
1726 }),
1727 cx.on_release({
1728 let weak_handle = weak_handle.clone();
1729 move |this, cx| {
1730 this.app_state.workspace_store.update(cx, move |store, _| {
1731 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1732 })
1733 }
1734 }),
1735 ];
1736
1737 cx.defer_in(window, move |this, window, cx| {
1738 this.update_window_title(window, cx);
1739 this.show_initial_notifications(cx);
1740 });
1741
1742 let mut center = PaneGroup::new(center_pane.clone());
1743 center.set_is_center(true);
1744 center.mark_positions(cx);
1745
1746 Workspace {
1747 weak_self: weak_handle.clone(),
1748 zoomed: None,
1749 zoomed_position: None,
1750 previous_dock_drag_coordinates: None,
1751 center,
1752 panes: vec![center_pane.clone()],
1753 panes_by_item: Default::default(),
1754 active_pane: center_pane.clone(),
1755 last_active_center_pane: Some(center_pane.downgrade()),
1756 last_active_view_id: None,
1757 status_bar,
1758 modal_layer,
1759 toast_layer,
1760 titlebar_item: None,
1761 active_worktree_override: None,
1762 notifications: Notifications::default(),
1763 suppressed_notifications: HashSet::default(),
1764 left_dock,
1765 bottom_dock,
1766 right_dock,
1767 _panels_task: None,
1768 project: project.clone(),
1769 follower_states: Default::default(),
1770 last_leaders_by_pane: Default::default(),
1771 dispatching_keystrokes: Default::default(),
1772 window_edited: false,
1773 last_window_title: None,
1774 dirty_items: Default::default(),
1775 active_call,
1776 database_id: workspace_id,
1777 app_state,
1778 _observe_current_user,
1779 _apply_leader_updates,
1780 _schedule_serialize_workspace: None,
1781 _serialize_workspace_task: None,
1782 _schedule_serialize_ssh_paths: None,
1783 leader_updates_tx,
1784 _subscriptions: subscriptions,
1785 pane_history_timestamp,
1786 workspace_actions: Default::default(),
1787 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1788 bounds: Default::default(),
1789 centered_layout: false,
1790 bounds_save_task_queued: None,
1791 on_prompt_for_new_path: None,
1792 on_prompt_for_open_path: None,
1793 terminal_provider: None,
1794 debugger_provider: None,
1795 serializable_items_tx,
1796 _items_serializer,
1797 session_id: Some(session_id),
1798
1799 scheduled_tasks: Vec::new(),
1800 last_open_dock_positions: Vec::new(),
1801 removing: false,
1802 sidebar_focus_handle: None,
1803 multi_workspace,
1804 open_in_dev_container: false,
1805 _dev_container_task: None,
1806 }
1807 }
1808
1809 pub fn new_local(
1810 abs_paths: Vec<PathBuf>,
1811 app_state: Arc<AppState>,
1812 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1813 env: Option<HashMap<String, String>>,
1814 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1815 open_mode: OpenMode,
1816 cx: &mut App,
1817 ) -> Task<anyhow::Result<OpenResult>> {
1818 let project_handle = Project::local(
1819 app_state.client.clone(),
1820 app_state.node_runtime.clone(),
1821 app_state.user_store.clone(),
1822 app_state.languages.clone(),
1823 app_state.fs.clone(),
1824 env,
1825 Default::default(),
1826 cx,
1827 );
1828
1829 let db = WorkspaceDb::global(cx);
1830 let kvp = db::kvp::KeyValueStore::global(cx);
1831 cx.spawn(async move |cx| {
1832 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1833 for path in abs_paths.into_iter() {
1834 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1835 paths_to_open.push(canonical)
1836 } else {
1837 paths_to_open.push(path)
1838 }
1839 }
1840
1841 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1842
1843 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1844 paths_to_open = paths.ordered_paths().cloned().collect();
1845 if !paths.is_lexicographically_ordered() {
1846 project_handle.update(cx, |project, cx| {
1847 project.set_worktrees_reordered(true, cx);
1848 });
1849 }
1850 }
1851
1852 // Get project paths for all of the abs_paths
1853 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1854 Vec::with_capacity(paths_to_open.len());
1855
1856 for path in paths_to_open.into_iter() {
1857 if let Some((_, project_entry)) = cx
1858 .update(|cx| {
1859 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1860 })
1861 .await
1862 .log_err()
1863 {
1864 project_paths.push((path, Some(project_entry)));
1865 } else {
1866 project_paths.push((path, None));
1867 }
1868 }
1869
1870 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1871 serialized_workspace.id
1872 } else {
1873 db.next_id().await.unwrap_or_else(|_| Default::default())
1874 };
1875
1876 let toolchains = db.toolchains(workspace_id).await?;
1877
1878 for (toolchain, worktree_path, path) in toolchains {
1879 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1880 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1881 this.find_worktree(&worktree_path, cx)
1882 .and_then(|(worktree, rel_path)| {
1883 if rel_path.is_empty() {
1884 Some(worktree.read(cx).id())
1885 } else {
1886 None
1887 }
1888 })
1889 }) else {
1890 // We did not find a worktree with a given path, but that's whatever.
1891 continue;
1892 };
1893 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1894 continue;
1895 }
1896
1897 project_handle
1898 .update(cx, |this, cx| {
1899 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1900 })
1901 .await;
1902 }
1903 if let Some(workspace) = serialized_workspace.as_ref() {
1904 project_handle.update(cx, |this, cx| {
1905 for (scope, toolchains) in &workspace.user_toolchains {
1906 for toolchain in toolchains {
1907 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1908 }
1909 }
1910 });
1911 }
1912
1913 let window_to_replace = match open_mode {
1914 OpenMode::NewWindow => None,
1915 _ => requesting_window,
1916 };
1917
1918 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1919 if let Some(window) = window_to_replace {
1920 let centered_layout = serialized_workspace
1921 .as_ref()
1922 .map(|w| w.centered_layout)
1923 .unwrap_or(false);
1924
1925 let workspace = window.update(cx, |multi_workspace, window, cx| {
1926 let workspace = cx.new(|cx| {
1927 let mut workspace = Workspace::new(
1928 Some(workspace_id),
1929 project_handle.clone(),
1930 app_state.clone(),
1931 window,
1932 cx,
1933 );
1934
1935 workspace.centered_layout = centered_layout;
1936
1937 // Call init callback to add items before window renders
1938 if let Some(init) = init {
1939 init(&mut workspace, window, cx);
1940 }
1941
1942 workspace
1943 });
1944 match open_mode {
1945 OpenMode::Activate => {
1946 multi_workspace.activate(workspace.clone(), window, cx);
1947 }
1948 OpenMode::Add => {
1949 multi_workspace.add(workspace.clone(), &*window, cx);
1950 }
1951 OpenMode::NewWindow => {
1952 unreachable!()
1953 }
1954 }
1955 workspace
1956 })?;
1957 (window, workspace)
1958 } else {
1959 let window_bounds_override = window_bounds_env_override();
1960
1961 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1962 (Some(WindowBounds::Windowed(bounds)), None)
1963 } else if let Some(workspace) = serialized_workspace.as_ref()
1964 && let Some(display) = workspace.display
1965 && let Some(bounds) = workspace.window_bounds.as_ref()
1966 {
1967 // Reopening an existing workspace - restore its saved bounds
1968 (Some(bounds.0), Some(display))
1969 } else if let Some((display, bounds)) =
1970 persistence::read_default_window_bounds(&kvp)
1971 {
1972 // New or empty workspace - use the last known window bounds
1973 (Some(bounds), Some(display))
1974 } else {
1975 // New window - let GPUI's default_bounds() handle cascading
1976 (None, None)
1977 };
1978
1979 // Use the serialized workspace to construct the new window
1980 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1981 options.window_bounds = window_bounds;
1982 let centered_layout = serialized_workspace
1983 .as_ref()
1984 .map(|w| w.centered_layout)
1985 .unwrap_or(false);
1986 let window = cx.open_window(options, {
1987 let app_state = app_state.clone();
1988 let project_handle = project_handle.clone();
1989 move |window, cx| {
1990 let workspace = cx.new(|cx| {
1991 let mut workspace = Workspace::new(
1992 Some(workspace_id),
1993 project_handle,
1994 app_state,
1995 window,
1996 cx,
1997 );
1998 workspace.centered_layout = centered_layout;
1999
2000 // Call init callback to add items before window renders
2001 if let Some(init) = init {
2002 init(&mut workspace, window, cx);
2003 }
2004
2005 workspace
2006 });
2007 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
2008 }
2009 })?;
2010 let workspace =
2011 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
2012 multi_workspace.workspace().clone()
2013 })?;
2014 (window, workspace)
2015 };
2016
2017 notify_if_database_failed(window, cx);
2018 // Check if this is an empty workspace (no paths to open)
2019 // An empty workspace is one where project_paths is empty
2020 let is_empty_workspace = project_paths.is_empty();
2021 // Check if serialized workspace has paths before it's moved
2022 let serialized_workspace_has_paths = serialized_workspace
2023 .as_ref()
2024 .map(|ws| !ws.paths.is_empty())
2025 .unwrap_or(false);
2026
2027 let opened_items = window
2028 .update(cx, |_, window, cx| {
2029 workspace.update(cx, |_workspace: &mut Workspace, cx| {
2030 open_items(serialized_workspace, project_paths, window, cx)
2031 })
2032 })?
2033 .await
2034 .unwrap_or_default();
2035
2036 // Restore default dock state for empty workspaces
2037 // Only restore if:
2038 // 1. This is an empty workspace (no paths), AND
2039 // 2. The serialized workspace either doesn't exist or has no paths
2040 if is_empty_workspace && !serialized_workspace_has_paths {
2041 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
2042 window
2043 .update(cx, |_, window, cx| {
2044 workspace.update(cx, |workspace, cx| {
2045 for (dock, serialized_dock) in [
2046 (&workspace.right_dock, &default_docks.right),
2047 (&workspace.left_dock, &default_docks.left),
2048 (&workspace.bottom_dock, &default_docks.bottom),
2049 ] {
2050 dock.update(cx, |dock, cx| {
2051 dock.serialized_dock = Some(serialized_dock.clone());
2052 dock.restore_state(window, cx);
2053 });
2054 }
2055 cx.notify();
2056 });
2057 })
2058 .log_err();
2059 }
2060 }
2061
2062 window
2063 .update(cx, |_, _window, cx| {
2064 workspace.update(cx, |this: &mut Workspace, cx| {
2065 this.update_history(cx);
2066 });
2067 })
2068 .log_err();
2069 Ok(OpenResult {
2070 window,
2071 workspace,
2072 opened_items,
2073 })
2074 })
2075 }
2076
2077 pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
2078 self.project.read(cx).project_group_key(cx)
2079 }
2080
2081 pub fn weak_handle(&self) -> WeakEntity<Self> {
2082 self.weak_self.clone()
2083 }
2084
2085 pub fn left_dock(&self) -> &Entity<Dock> {
2086 &self.left_dock
2087 }
2088
2089 pub fn bottom_dock(&self) -> &Entity<Dock> {
2090 &self.bottom_dock
2091 }
2092
2093 pub fn set_bottom_dock_layout(
2094 &mut self,
2095 layout: BottomDockLayout,
2096 window: &mut Window,
2097 cx: &mut Context<Self>,
2098 ) {
2099 let fs = self.project().read(cx).fs();
2100 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2101 content.workspace.bottom_dock_layout = Some(layout);
2102 });
2103
2104 cx.notify();
2105 self.serialize_workspace(window, cx);
2106 }
2107
2108 pub fn right_dock(&self) -> &Entity<Dock> {
2109 &self.right_dock
2110 }
2111
2112 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2113 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2114 }
2115
2116 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2117 let left_dock = self.left_dock.read(cx);
2118 let left_visible = left_dock.is_open();
2119 let left_active_panel = left_dock
2120 .active_panel()
2121 .map(|panel| panel.persistent_name().to_string());
2122 // `zoomed_position` is kept in sync with individual panel zoom state
2123 // by the dock code in `Dock::new` and `Dock::add_panel`.
2124 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2125
2126 let right_dock = self.right_dock.read(cx);
2127 let right_visible = right_dock.is_open();
2128 let right_active_panel = right_dock
2129 .active_panel()
2130 .map(|panel| panel.persistent_name().to_string());
2131 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2132
2133 let bottom_dock = self.bottom_dock.read(cx);
2134 let bottom_visible = bottom_dock.is_open();
2135 let bottom_active_panel = bottom_dock
2136 .active_panel()
2137 .map(|panel| panel.persistent_name().to_string());
2138 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2139
2140 DockStructure {
2141 left: DockData {
2142 visible: left_visible,
2143 active_panel: left_active_panel,
2144 zoom: left_dock_zoom,
2145 },
2146 right: DockData {
2147 visible: right_visible,
2148 active_panel: right_active_panel,
2149 zoom: right_dock_zoom,
2150 },
2151 bottom: DockData {
2152 visible: bottom_visible,
2153 active_panel: bottom_active_panel,
2154 zoom: bottom_dock_zoom,
2155 },
2156 }
2157 }
2158
2159 pub fn set_dock_structure(
2160 &self,
2161 docks: DockStructure,
2162 window: &mut Window,
2163 cx: &mut Context<Self>,
2164 ) {
2165 for (dock, data) in [
2166 (&self.left_dock, docks.left),
2167 (&self.bottom_dock, docks.bottom),
2168 (&self.right_dock, docks.right),
2169 ] {
2170 dock.update(cx, |dock, cx| {
2171 dock.serialized_dock = Some(data);
2172 dock.restore_state(window, cx);
2173 });
2174 }
2175 }
2176
2177 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2178 self.items(cx)
2179 .filter_map(|item| {
2180 let project_path = item.project_path(cx)?;
2181 self.project.read(cx).absolute_path(&project_path, cx)
2182 })
2183 .collect()
2184 }
2185
2186 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2187 match position {
2188 DockPosition::Left => &self.left_dock,
2189 DockPosition::Bottom => &self.bottom_dock,
2190 DockPosition::Right => &self.right_dock,
2191 }
2192 }
2193
2194 pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
2195 self.all_docks().into_iter().find_map(|dock| {
2196 let dock = dock.read(cx);
2197 dock.has_agent_panel(cx).then_some(dock.position())
2198 })
2199 }
2200
2201 pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
2202 self.all_docks().into_iter().find_map(|dock| {
2203 let dock = dock.read(cx);
2204 let panel = dock.panel::<T>()?;
2205 dock.stored_panel_size_state(&panel)
2206 })
2207 }
2208
2209 pub fn persisted_panel_size_state(
2210 &self,
2211 panel_key: &'static str,
2212 cx: &App,
2213 ) -> Option<dock::PanelSizeState> {
2214 dock::Dock::load_persisted_size_state(self, panel_key, cx)
2215 }
2216
2217 pub fn persist_panel_size_state(
2218 &self,
2219 panel_key: &str,
2220 size_state: dock::PanelSizeState,
2221 cx: &mut App,
2222 ) {
2223 let Some(workspace_id) = self
2224 .database_id()
2225 .map(|id| i64::from(id).to_string())
2226 .or(self.session_id())
2227 else {
2228 return;
2229 };
2230
2231 let kvp = db::kvp::KeyValueStore::global(cx);
2232 let panel_key = panel_key.to_string();
2233 cx.background_spawn(async move {
2234 let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
2235 scope
2236 .write(
2237 format!("{workspace_id}:{panel_key}"),
2238 serde_json::to_string(&size_state)?,
2239 )
2240 .await
2241 })
2242 .detach_and_log_err(cx);
2243 }
2244
2245 pub fn set_panel_size_state<T: Panel>(
2246 &mut self,
2247 size_state: dock::PanelSizeState,
2248 window: &mut Window,
2249 cx: &mut Context<Self>,
2250 ) -> bool {
2251 let Some(panel) = self.panel::<T>(cx) else {
2252 return false;
2253 };
2254
2255 let dock = self.dock_at_position(panel.position(window, cx));
2256 let did_set = dock.update(cx, |dock, cx| {
2257 dock.set_panel_size_state(&panel, size_state, cx)
2258 });
2259
2260 if did_set {
2261 self.persist_panel_size_state(T::panel_key(), size_state, cx);
2262 }
2263
2264 did_set
2265 }
2266
2267 pub fn toggle_dock_panel_flexible_size(
2268 &self,
2269 dock: &Entity<Dock>,
2270 panel: &dyn PanelHandle,
2271 window: &mut Window,
2272 cx: &mut App,
2273 ) {
2274 let position = dock.read(cx).position();
2275 let current_size = self.dock_size(&dock.read(cx), window, cx);
2276 let current_flex =
2277 current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
2278 dock.update(cx, |dock, cx| {
2279 dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
2280 });
2281 }
2282
2283 fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
2284 let panel = dock.active_panel()?;
2285 let size_state = dock
2286 .stored_panel_size_state(panel.as_ref())
2287 .unwrap_or_default();
2288 let position = dock.position();
2289
2290 let use_flex = panel.has_flexible_size(window, cx);
2291
2292 if position.axis() == Axis::Horizontal
2293 && use_flex
2294 && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
2295 {
2296 let workspace_width = self.bounds.size.width;
2297 if workspace_width <= Pixels::ZERO {
2298 return None;
2299 }
2300 let flex = flex.max(0.001);
2301 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2302 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2303 // Both docks are flex items sharing the full workspace width.
2304 let total_flex = flex + 1.0 + opposite_flex;
2305 return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
2306 } else {
2307 // Opposite dock is fixed-width; flex items share (W - fixed).
2308 let opposite_fixed = opposite
2309 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2310 .unwrap_or_default();
2311 let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
2312 return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
2313 }
2314 }
2315
2316 Some(
2317 size_state
2318 .size
2319 .unwrap_or_else(|| panel.default_size(window, cx)),
2320 )
2321 }
2322
2323 pub fn dock_flex_for_size(
2324 &self,
2325 position: DockPosition,
2326 size: Pixels,
2327 window: &Window,
2328 cx: &App,
2329 ) -> Option<f32> {
2330 if position.axis() != Axis::Horizontal {
2331 return None;
2332 }
2333
2334 let workspace_width = self.bounds.size.width;
2335 if workspace_width <= Pixels::ZERO {
2336 return None;
2337 }
2338
2339 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2340 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2341 let size = size.clamp(px(0.), workspace_width - px(1.));
2342 Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
2343 } else {
2344 let opposite_width = opposite
2345 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2346 .unwrap_or_default();
2347 let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
2348 let remaining = (available - size).max(px(1.));
2349 Some((size / remaining).max(0.0))
2350 }
2351 }
2352
2353 fn opposite_dock_panel_and_size_state(
2354 &self,
2355 position: DockPosition,
2356 window: &Window,
2357 cx: &App,
2358 ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
2359 let opposite_position = match position {
2360 DockPosition::Left => DockPosition::Right,
2361 DockPosition::Right => DockPosition::Left,
2362 DockPosition::Bottom => return None,
2363 };
2364
2365 let opposite_dock = self.dock_at_position(opposite_position).read(cx);
2366 let panel = opposite_dock.visible_panel()?;
2367 let mut size_state = opposite_dock
2368 .stored_panel_size_state(panel.as_ref())
2369 .unwrap_or_default();
2370 if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
2371 size_state.flex = self.default_dock_flex(opposite_position);
2372 }
2373 Some((panel.clone(), size_state))
2374 }
2375
2376 pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
2377 if position.axis() != Axis::Horizontal {
2378 return None;
2379 }
2380
2381 let pane = self.last_active_center_pane.clone()?.upgrade()?;
2382 Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
2383 }
2384
2385 pub fn is_edited(&self) -> bool {
2386 self.window_edited
2387 }
2388
2389 pub fn add_panel<T: Panel>(
2390 &mut self,
2391 panel: Entity<T>,
2392 window: &mut Window,
2393 cx: &mut Context<Self>,
2394 ) {
2395 let focus_handle = panel.panel_focus_handle(cx);
2396 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2397 .detach();
2398
2399 let dock_position = panel.position(window, cx);
2400 let dock = self.dock_at_position(dock_position);
2401 let any_panel = panel.to_any();
2402 let persisted_size_state =
2403 self.persisted_panel_size_state(T::panel_key(), cx)
2404 .or_else(|| {
2405 load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
2406 let state = dock::PanelSizeState {
2407 size: Some(size),
2408 flex: None,
2409 };
2410 self.persist_panel_size_state(T::panel_key(), state, cx);
2411 state
2412 })
2413 });
2414
2415 dock.update(cx, |dock, cx| {
2416 let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
2417 if let Some(size_state) = persisted_size_state {
2418 dock.set_panel_size_state(&panel, size_state, cx);
2419 }
2420 index
2421 });
2422
2423 cx.emit(Event::PanelAdded(any_panel));
2424 }
2425
2426 pub fn remove_panel<T: Panel>(
2427 &mut self,
2428 panel: &Entity<T>,
2429 window: &mut Window,
2430 cx: &mut Context<Self>,
2431 ) {
2432 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2433 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2434 }
2435 }
2436
2437 pub fn status_bar(&self) -> &Entity<StatusBar> {
2438 &self.status_bar
2439 }
2440
2441 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2442 self.sidebar_focus_handle = handle;
2443 }
2444
2445 pub fn status_bar_visible(&self, cx: &App) -> bool {
2446 StatusBarSettings::get_global(cx).show
2447 }
2448
2449 pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
2450 self.multi_workspace.as_ref()
2451 }
2452
2453 pub fn set_multi_workspace(
2454 &mut self,
2455 multi_workspace: WeakEntity<MultiWorkspace>,
2456 cx: &mut App,
2457 ) {
2458 self.status_bar.update(cx, |status_bar, cx| {
2459 status_bar.set_multi_workspace(multi_workspace.clone(), cx);
2460 });
2461 self.multi_workspace = Some(multi_workspace);
2462 }
2463
2464 pub fn app_state(&self) -> &Arc<AppState> {
2465 &self.app_state
2466 }
2467
2468 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2469 self._panels_task = Some(task);
2470 }
2471
2472 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2473 self._panels_task.take()
2474 }
2475
2476 pub fn user_store(&self) -> &Entity<UserStore> {
2477 &self.app_state.user_store
2478 }
2479
2480 pub fn project(&self) -> &Entity<Project> {
2481 &self.project
2482 }
2483
2484 pub fn path_style(&self, cx: &App) -> PathStyle {
2485 self.project.read(cx).path_style(cx)
2486 }
2487
2488 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2489 let mut history: HashMap<EntityId, usize> = HashMap::default();
2490
2491 for pane_handle in &self.panes {
2492 let pane = pane_handle.read(cx);
2493
2494 for entry in pane.activation_history() {
2495 history.insert(
2496 entry.entity_id,
2497 history
2498 .get(&entry.entity_id)
2499 .cloned()
2500 .unwrap_or(0)
2501 .max(entry.timestamp),
2502 );
2503 }
2504 }
2505
2506 history
2507 }
2508
2509 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2510 let mut recent_item: Option<Entity<T>> = None;
2511 let mut recent_timestamp = 0;
2512 for pane_handle in &self.panes {
2513 let pane = pane_handle.read(cx);
2514 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2515 pane.items().map(|item| (item.item_id(), item)).collect();
2516 for entry in pane.activation_history() {
2517 if entry.timestamp > recent_timestamp
2518 && let Some(&item) = item_map.get(&entry.entity_id)
2519 && let Some(typed_item) = item.act_as::<T>(cx)
2520 {
2521 recent_timestamp = entry.timestamp;
2522 recent_item = Some(typed_item);
2523 }
2524 }
2525 }
2526 recent_item
2527 }
2528
2529 pub fn recent_navigation_history_iter(
2530 &self,
2531 cx: &App,
2532 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2533 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2534 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2535
2536 for pane in &self.panes {
2537 let pane = pane.read(cx);
2538
2539 pane.nav_history()
2540 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2541 if let Some(fs_path) = &fs_path {
2542 abs_paths_opened
2543 .entry(fs_path.clone())
2544 .or_default()
2545 .insert(project_path.clone());
2546 }
2547 let timestamp = entry.timestamp;
2548 match history.entry(project_path) {
2549 hash_map::Entry::Occupied(mut entry) => {
2550 let (_, old_timestamp) = entry.get();
2551 if ×tamp > old_timestamp {
2552 entry.insert((fs_path, timestamp));
2553 }
2554 }
2555 hash_map::Entry::Vacant(entry) => {
2556 entry.insert((fs_path, timestamp));
2557 }
2558 }
2559 });
2560
2561 if let Some(item) = pane.active_item()
2562 && let Some(project_path) = item.project_path(cx)
2563 {
2564 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2565
2566 if let Some(fs_path) = &fs_path {
2567 abs_paths_opened
2568 .entry(fs_path.clone())
2569 .or_default()
2570 .insert(project_path.clone());
2571 }
2572
2573 history.insert(project_path, (fs_path, std::usize::MAX));
2574 }
2575 }
2576
2577 history
2578 .into_iter()
2579 .sorted_by_key(|(_, (_, order))| *order)
2580 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2581 .rev()
2582 .filter(move |(history_path, abs_path)| {
2583 let latest_project_path_opened = abs_path
2584 .as_ref()
2585 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2586 .and_then(|project_paths| {
2587 project_paths
2588 .iter()
2589 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2590 });
2591
2592 latest_project_path_opened.is_none_or(|path| path == history_path)
2593 })
2594 }
2595
2596 pub fn recent_navigation_history(
2597 &self,
2598 limit: Option<usize>,
2599 cx: &App,
2600 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2601 self.recent_navigation_history_iter(cx)
2602 .take(limit.unwrap_or(usize::MAX))
2603 .collect()
2604 }
2605
2606 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2607 for pane in &self.panes {
2608 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2609 }
2610 }
2611
2612 fn navigate_history(
2613 &mut self,
2614 pane: WeakEntity<Pane>,
2615 mode: NavigationMode,
2616 window: &mut Window,
2617 cx: &mut Context<Workspace>,
2618 ) -> Task<Result<()>> {
2619 self.navigate_history_impl(
2620 pane,
2621 mode,
2622 window,
2623 &mut |history, cx| history.pop(mode, cx),
2624 cx,
2625 )
2626 }
2627
2628 fn navigate_tag_history(
2629 &mut self,
2630 pane: WeakEntity<Pane>,
2631 mode: TagNavigationMode,
2632 window: &mut Window,
2633 cx: &mut Context<Workspace>,
2634 ) -> Task<Result<()>> {
2635 self.navigate_history_impl(
2636 pane,
2637 NavigationMode::Normal,
2638 window,
2639 &mut |history, _cx| history.pop_tag(mode),
2640 cx,
2641 )
2642 }
2643
2644 fn navigate_history_impl(
2645 &mut self,
2646 pane: WeakEntity<Pane>,
2647 mode: NavigationMode,
2648 window: &mut Window,
2649 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2650 cx: &mut Context<Workspace>,
2651 ) -> Task<Result<()>> {
2652 let to_load = if let Some(pane) = pane.upgrade() {
2653 pane.update(cx, |pane, cx| {
2654 window.focus(&pane.focus_handle(cx), cx);
2655 loop {
2656 // Retrieve the weak item handle from the history.
2657 let entry = cb(pane.nav_history_mut(), cx)?;
2658
2659 // If the item is still present in this pane, then activate it.
2660 if let Some(index) = entry
2661 .item
2662 .upgrade()
2663 .and_then(|v| pane.index_for_item(v.as_ref()))
2664 {
2665 let prev_active_item_index = pane.active_item_index();
2666 pane.nav_history_mut().set_mode(mode);
2667 pane.activate_item(index, true, true, window, cx);
2668 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2669
2670 let mut navigated = prev_active_item_index != pane.active_item_index();
2671 if let Some(data) = entry.data {
2672 navigated |= pane.active_item()?.navigate(data, window, cx);
2673 }
2674
2675 if navigated {
2676 break None;
2677 }
2678 } else {
2679 // If the item is no longer present in this pane, then retrieve its
2680 // path info in order to reopen it.
2681 break pane
2682 .nav_history()
2683 .path_for_item(entry.item.id())
2684 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2685 }
2686 }
2687 })
2688 } else {
2689 None
2690 };
2691
2692 if let Some((project_path, abs_path, entry)) = to_load {
2693 // If the item was no longer present, then load it again from its previous path, first try the local path
2694 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2695
2696 cx.spawn_in(window, async move |workspace, cx| {
2697 let open_by_project_path = open_by_project_path.await;
2698 let mut navigated = false;
2699 match open_by_project_path
2700 .with_context(|| format!("Navigating to {project_path:?}"))
2701 {
2702 Ok((project_entry_id, build_item)) => {
2703 let prev_active_item_id = pane.update(cx, |pane, _| {
2704 pane.nav_history_mut().set_mode(mode);
2705 pane.active_item().map(|p| p.item_id())
2706 })?;
2707
2708 pane.update_in(cx, |pane, window, cx| {
2709 let item = pane.open_item(
2710 project_entry_id,
2711 project_path,
2712 true,
2713 entry.is_preview,
2714 true,
2715 None,
2716 window, cx,
2717 build_item,
2718 );
2719 navigated |= Some(item.item_id()) != prev_active_item_id;
2720 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2721 if let Some(data) = entry.data {
2722 navigated |= item.navigate(data, window, cx);
2723 }
2724 })?;
2725 }
2726 Err(open_by_project_path_e) => {
2727 // Fall back to opening by abs path, in case an external file was opened and closed,
2728 // and its worktree is now dropped
2729 if let Some(abs_path) = abs_path {
2730 let prev_active_item_id = pane.update(cx, |pane, _| {
2731 pane.nav_history_mut().set_mode(mode);
2732 pane.active_item().map(|p| p.item_id())
2733 })?;
2734 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2735 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2736 })?;
2737 match open_by_abs_path
2738 .await
2739 .with_context(|| format!("Navigating to {abs_path:?}"))
2740 {
2741 Ok(item) => {
2742 pane.update_in(cx, |pane, window, cx| {
2743 navigated |= Some(item.item_id()) != prev_active_item_id;
2744 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2745 if let Some(data) = entry.data {
2746 navigated |= item.navigate(data, window, cx);
2747 }
2748 })?;
2749 }
2750 Err(open_by_abs_path_e) => {
2751 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2752 }
2753 }
2754 }
2755 }
2756 }
2757
2758 if !navigated {
2759 workspace
2760 .update_in(cx, |workspace, window, cx| {
2761 Self::navigate_history(workspace, pane, mode, window, cx)
2762 })?
2763 .await?;
2764 }
2765
2766 Ok(())
2767 })
2768 } else {
2769 Task::ready(Ok(()))
2770 }
2771 }
2772
2773 pub fn go_back(
2774 &mut self,
2775 pane: WeakEntity<Pane>,
2776 window: &mut Window,
2777 cx: &mut Context<Workspace>,
2778 ) -> Task<Result<()>> {
2779 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2780 }
2781
2782 pub fn go_forward(
2783 &mut self,
2784 pane: WeakEntity<Pane>,
2785 window: &mut Window,
2786 cx: &mut Context<Workspace>,
2787 ) -> Task<Result<()>> {
2788 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2789 }
2790
2791 pub fn reopen_closed_item(
2792 &mut self,
2793 window: &mut Window,
2794 cx: &mut Context<Workspace>,
2795 ) -> Task<Result<()>> {
2796 self.navigate_history(
2797 self.active_pane().downgrade(),
2798 NavigationMode::ReopeningClosedItem,
2799 window,
2800 cx,
2801 )
2802 }
2803
2804 pub fn client(&self) -> &Arc<Client> {
2805 &self.app_state.client
2806 }
2807
2808 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2809 self.titlebar_item = Some(item);
2810 cx.notify();
2811 }
2812
2813 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2814 self.on_prompt_for_new_path = Some(prompt)
2815 }
2816
2817 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2818 self.on_prompt_for_open_path = Some(prompt)
2819 }
2820
2821 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2822 self.terminal_provider = Some(Box::new(provider));
2823 }
2824
2825 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2826 self.debugger_provider = Some(Arc::new(provider));
2827 }
2828
2829 pub fn set_open_in_dev_container(&mut self, value: bool) {
2830 self.open_in_dev_container = value;
2831 }
2832
2833 pub fn open_in_dev_container(&self) -> bool {
2834 self.open_in_dev_container
2835 }
2836
2837 pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
2838 self._dev_container_task = Some(task);
2839 }
2840
2841 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2842 self.debugger_provider.clone()
2843 }
2844
2845 pub fn prompt_for_open_path(
2846 &mut self,
2847 path_prompt_options: PathPromptOptions,
2848 lister: DirectoryLister,
2849 window: &mut Window,
2850 cx: &mut Context<Self>,
2851 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2852 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2853 let prompt = self.on_prompt_for_open_path.take().unwrap();
2854 let rx = prompt(self, lister, window, cx);
2855 self.on_prompt_for_open_path = Some(prompt);
2856 rx
2857 } else {
2858 let (tx, rx) = oneshot::channel();
2859 let abs_path = cx.prompt_for_paths(path_prompt_options);
2860
2861 cx.spawn_in(window, async move |workspace, cx| {
2862 let Ok(result) = abs_path.await else {
2863 return Ok(());
2864 };
2865
2866 match result {
2867 Ok(result) => {
2868 tx.send(result).ok();
2869 }
2870 Err(err) => {
2871 let rx = workspace.update_in(cx, |workspace, window, cx| {
2872 workspace.show_portal_error(err.to_string(), cx);
2873 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2874 let rx = prompt(workspace, lister, window, cx);
2875 workspace.on_prompt_for_open_path = Some(prompt);
2876 rx
2877 })?;
2878 if let Ok(path) = rx.await {
2879 tx.send(path).ok();
2880 }
2881 }
2882 };
2883 anyhow::Ok(())
2884 })
2885 .detach();
2886
2887 rx
2888 }
2889 }
2890
2891 pub fn prompt_for_new_path(
2892 &mut self,
2893 lister: DirectoryLister,
2894 suggested_name: Option<String>,
2895 window: &mut Window,
2896 cx: &mut Context<Self>,
2897 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2898 if self.project.read(cx).is_via_collab()
2899 || self.project.read(cx).is_via_remote_server()
2900 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2901 {
2902 let prompt = self.on_prompt_for_new_path.take().unwrap();
2903 let rx = prompt(self, lister, suggested_name, window, cx);
2904 self.on_prompt_for_new_path = Some(prompt);
2905 return rx;
2906 }
2907
2908 let (tx, rx) = oneshot::channel();
2909 cx.spawn_in(window, async move |workspace, cx| {
2910 let abs_path = workspace.update(cx, |workspace, cx| {
2911 let relative_to = workspace
2912 .most_recent_active_path(cx)
2913 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2914 .or_else(|| {
2915 let project = workspace.project.read(cx);
2916 project.visible_worktrees(cx).find_map(|worktree| {
2917 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2918 })
2919 })
2920 .or_else(std::env::home_dir)
2921 .unwrap_or_else(|| PathBuf::from(""));
2922 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2923 })?;
2924 let abs_path = match abs_path.await? {
2925 Ok(path) => path,
2926 Err(err) => {
2927 let rx = workspace.update_in(cx, |workspace, window, cx| {
2928 workspace.show_portal_error(err.to_string(), cx);
2929
2930 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2931 let rx = prompt(workspace, lister, suggested_name, window, cx);
2932 workspace.on_prompt_for_new_path = Some(prompt);
2933 rx
2934 })?;
2935 if let Ok(path) = rx.await {
2936 tx.send(path).ok();
2937 }
2938 return anyhow::Ok(());
2939 }
2940 };
2941
2942 tx.send(abs_path.map(|path| vec![path])).ok();
2943 anyhow::Ok(())
2944 })
2945 .detach();
2946
2947 rx
2948 }
2949
2950 pub fn titlebar_item(&self) -> Option<AnyView> {
2951 self.titlebar_item.clone()
2952 }
2953
2954 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2955 /// When set, git-related operations should use this worktree instead of deriving
2956 /// the active worktree from the focused file.
2957 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2958 self.active_worktree_override
2959 }
2960
2961 pub fn set_active_worktree_override(
2962 &mut self,
2963 worktree_id: Option<WorktreeId>,
2964 cx: &mut Context<Self>,
2965 ) {
2966 self.active_worktree_override = worktree_id;
2967 cx.notify();
2968 }
2969
2970 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2971 self.active_worktree_override = None;
2972 cx.notify();
2973 }
2974
2975 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2976 ///
2977 /// If the given workspace has a local project, then it will be passed
2978 /// to the callback. Otherwise, a new empty window will be created.
2979 pub fn with_local_workspace<T, F>(
2980 &mut self,
2981 window: &mut Window,
2982 cx: &mut Context<Self>,
2983 callback: F,
2984 ) -> Task<Result<T>>
2985 where
2986 T: 'static,
2987 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2988 {
2989 if self.project.read(cx).is_local() {
2990 Task::ready(Ok(callback(self, window, cx)))
2991 } else {
2992 let env = self.project.read(cx).cli_environment(cx);
2993 let task = Self::new_local(
2994 Vec::new(),
2995 self.app_state.clone(),
2996 None,
2997 env,
2998 None,
2999 OpenMode::Activate,
3000 cx,
3001 );
3002 cx.spawn_in(window, async move |_vh, cx| {
3003 let OpenResult {
3004 window: multi_workspace_window,
3005 ..
3006 } = task.await?;
3007 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3008 let workspace = multi_workspace.workspace().clone();
3009 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3010 })
3011 })
3012 }
3013 }
3014
3015 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
3016 ///
3017 /// If the given workspace has a local project, then it will be passed
3018 /// to the callback. Otherwise, a new empty window will be created.
3019 pub fn with_local_or_wsl_workspace<T, F>(
3020 &mut self,
3021 window: &mut Window,
3022 cx: &mut Context<Self>,
3023 callback: F,
3024 ) -> Task<Result<T>>
3025 where
3026 T: 'static,
3027 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
3028 {
3029 let project = self.project.read(cx);
3030 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
3031 Task::ready(Ok(callback(self, window, cx)))
3032 } else {
3033 let env = self.project.read(cx).cli_environment(cx);
3034 let task = Self::new_local(
3035 Vec::new(),
3036 self.app_state.clone(),
3037 None,
3038 env,
3039 None,
3040 OpenMode::Activate,
3041 cx,
3042 );
3043 cx.spawn_in(window, async move |_vh, cx| {
3044 let OpenResult {
3045 window: multi_workspace_window,
3046 ..
3047 } = task.await?;
3048 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3049 let workspace = multi_workspace.workspace().clone();
3050 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3051 })
3052 })
3053 }
3054 }
3055
3056 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3057 self.project.read(cx).worktrees(cx)
3058 }
3059
3060 pub fn visible_worktrees<'a>(
3061 &self,
3062 cx: &'a App,
3063 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3064 self.project.read(cx).visible_worktrees(cx)
3065 }
3066
3067 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
3068 let futures = self
3069 .worktrees(cx)
3070 .filter_map(|worktree| worktree.read(cx).as_local())
3071 .map(|worktree| worktree.scan_complete())
3072 .collect::<Vec<_>>();
3073 async move {
3074 for future in futures {
3075 future.await;
3076 }
3077 }
3078 }
3079
3080 pub fn close_global(cx: &mut App) {
3081 cx.defer(|cx| {
3082 cx.windows().iter().find(|window| {
3083 window
3084 .update(cx, |_, window, _| {
3085 if window.is_window_active() {
3086 //This can only get called when the window's project connection has been lost
3087 //so we don't need to prompt the user for anything and instead just close the window
3088 window.remove_window();
3089 true
3090 } else {
3091 false
3092 }
3093 })
3094 .unwrap_or(false)
3095 });
3096 });
3097 }
3098
3099 pub fn move_focused_panel_to_next_position(
3100 &mut self,
3101 _: &MoveFocusedPanelToNextPosition,
3102 window: &mut Window,
3103 cx: &mut Context<Self>,
3104 ) {
3105 let docks = self.all_docks();
3106 let active_dock = docks
3107 .into_iter()
3108 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3109
3110 if let Some(dock) = active_dock {
3111 dock.update(cx, |dock, cx| {
3112 let active_panel = dock
3113 .active_panel()
3114 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
3115
3116 if let Some(panel) = active_panel {
3117 panel.move_to_next_position(window, cx);
3118 }
3119 })
3120 }
3121 }
3122
3123 pub fn prepare_to_close(
3124 &mut self,
3125 close_intent: CloseIntent,
3126 window: &mut Window,
3127 cx: &mut Context<Self>,
3128 ) -> Task<Result<bool>> {
3129 let active_call = self.active_global_call();
3130
3131 cx.spawn_in(window, async move |this, cx| {
3132 this.update(cx, |this, _| {
3133 if close_intent == CloseIntent::CloseWindow {
3134 this.removing = true;
3135 }
3136 })?;
3137
3138 let workspace_count = cx.update(|_window, cx| {
3139 cx.windows()
3140 .iter()
3141 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
3142 .count()
3143 })?;
3144
3145 #[cfg(target_os = "macos")]
3146 let save_last_workspace = false;
3147
3148 // On Linux and Windows, closing the last window should restore the last workspace.
3149 #[cfg(not(target_os = "macos"))]
3150 let save_last_workspace = {
3151 let remaining_workspaces = cx.update(|_window, cx| {
3152 cx.windows()
3153 .iter()
3154 .filter_map(|window| window.downcast::<MultiWorkspace>())
3155 .filter_map(|multi_workspace| {
3156 multi_workspace
3157 .update(cx, |multi_workspace, _, cx| {
3158 multi_workspace.workspace().read(cx).removing
3159 })
3160 .ok()
3161 })
3162 .filter(|removing| !removing)
3163 .count()
3164 })?;
3165
3166 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
3167 };
3168
3169 if let Some(active_call) = active_call
3170 && workspace_count == 1
3171 && cx
3172 .update(|_window, cx| active_call.0.is_in_room(cx))
3173 .unwrap_or(false)
3174 {
3175 if close_intent == CloseIntent::CloseWindow {
3176 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
3177 let answer = cx.update(|window, cx| {
3178 window.prompt(
3179 PromptLevel::Warning,
3180 "Do you want to leave the current call?",
3181 None,
3182 &["Close window and hang up", "Cancel"],
3183 cx,
3184 )
3185 })?;
3186
3187 if answer.await.log_err() == Some(1) {
3188 return anyhow::Ok(false);
3189 } else {
3190 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
3191 task.await.log_err();
3192 }
3193 }
3194 }
3195 if close_intent == CloseIntent::ReplaceWindow {
3196 _ = cx.update(|_window, cx| {
3197 let multi_workspace = cx
3198 .windows()
3199 .iter()
3200 .filter_map(|window| window.downcast::<MultiWorkspace>())
3201 .next()
3202 .unwrap();
3203 let project = multi_workspace
3204 .read(cx)?
3205 .workspace()
3206 .read(cx)
3207 .project
3208 .clone();
3209 if project.read(cx).is_shared() {
3210 active_call.0.unshare_project(project, cx)?;
3211 }
3212 Ok::<_, anyhow::Error>(())
3213 });
3214 }
3215 }
3216
3217 let save_result = this
3218 .update_in(cx, |this, window, cx| {
3219 this.save_all_internal(SaveIntent::Close, window, cx)
3220 })?
3221 .await;
3222
3223 // If we're not quitting, but closing, we remove the workspace from
3224 // the current session.
3225 if close_intent != CloseIntent::Quit
3226 && !save_last_workspace
3227 && save_result.as_ref().is_ok_and(|&res| res)
3228 {
3229 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
3230 .await;
3231 }
3232
3233 save_result
3234 })
3235 }
3236
3237 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
3238 self.save_all_internal(
3239 action.save_intent.unwrap_or(SaveIntent::SaveAll),
3240 window,
3241 cx,
3242 )
3243 .detach_and_log_err(cx);
3244 }
3245
3246 fn send_keystrokes(
3247 &mut self,
3248 action: &SendKeystrokes,
3249 window: &mut Window,
3250 cx: &mut Context<Self>,
3251 ) {
3252 let keystrokes: Vec<Keystroke> = action
3253 .0
3254 .split(' ')
3255 .flat_map(|k| Keystroke::parse(k).log_err())
3256 .map(|k| {
3257 cx.keyboard_mapper()
3258 .map_key_equivalent(k, false)
3259 .inner()
3260 .clone()
3261 })
3262 .collect();
3263 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
3264 }
3265
3266 pub fn send_keystrokes_impl(
3267 &mut self,
3268 keystrokes: Vec<Keystroke>,
3269 window: &mut Window,
3270 cx: &mut Context<Self>,
3271 ) -> Shared<Task<()>> {
3272 let mut state = self.dispatching_keystrokes.borrow_mut();
3273 if !state.dispatched.insert(keystrokes.clone()) {
3274 cx.propagate();
3275 return state.task.clone().unwrap();
3276 }
3277
3278 state.queue.extend(keystrokes);
3279
3280 let keystrokes = self.dispatching_keystrokes.clone();
3281 if state.task.is_none() {
3282 state.task = Some(
3283 window
3284 .spawn(cx, async move |cx| {
3285 // limit to 100 keystrokes to avoid infinite recursion.
3286 for _ in 0..100 {
3287 let keystroke = {
3288 let mut state = keystrokes.borrow_mut();
3289 let Some(keystroke) = state.queue.pop_front() else {
3290 state.dispatched.clear();
3291 state.task.take();
3292 return;
3293 };
3294 keystroke
3295 };
3296 cx.update(|window, cx| {
3297 let focused = window.focused(cx);
3298 window.dispatch_keystroke(keystroke.clone(), cx);
3299 if window.focused(cx) != focused {
3300 // dispatch_keystroke may cause the focus to change.
3301 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3302 // And we need that to happen before the next keystroke to keep vim mode happy...
3303 // (Note that the tests always do this implicitly, so you must manually test with something like:
3304 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3305 // )
3306 window.draw(cx).clear();
3307 }
3308 })
3309 .ok();
3310
3311 // Yield between synthetic keystrokes so deferred focus and
3312 // other effects can settle before dispatching the next key.
3313 yield_now().await;
3314 }
3315
3316 *keystrokes.borrow_mut() = Default::default();
3317 log::error!("over 100 keystrokes passed to send_keystrokes");
3318 })
3319 .shared(),
3320 );
3321 }
3322 state.task.clone().unwrap()
3323 }
3324
3325 fn save_all_internal(
3326 &mut self,
3327 mut save_intent: SaveIntent,
3328 window: &mut Window,
3329 cx: &mut Context<Self>,
3330 ) -> Task<Result<bool>> {
3331 if self.project.read(cx).is_disconnected(cx) {
3332 return Task::ready(Ok(true));
3333 }
3334 let dirty_items = self
3335 .panes
3336 .iter()
3337 .flat_map(|pane| {
3338 pane.read(cx).items().filter_map(|item| {
3339 if item.is_dirty(cx) {
3340 item.tab_content_text(0, cx);
3341 Some((pane.downgrade(), item.boxed_clone()))
3342 } else {
3343 None
3344 }
3345 })
3346 })
3347 .collect::<Vec<_>>();
3348
3349 let project = self.project.clone();
3350 cx.spawn_in(window, async move |workspace, cx| {
3351 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3352 let (serialize_tasks, remaining_dirty_items) =
3353 workspace.update_in(cx, |workspace, window, cx| {
3354 let mut remaining_dirty_items = Vec::new();
3355 let mut serialize_tasks = Vec::new();
3356 for (pane, item) in dirty_items {
3357 if let Some(task) = item
3358 .to_serializable_item_handle(cx)
3359 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3360 {
3361 serialize_tasks.push(task);
3362 } else {
3363 remaining_dirty_items.push((pane, item));
3364 }
3365 }
3366 (serialize_tasks, remaining_dirty_items)
3367 })?;
3368
3369 futures::future::try_join_all(serialize_tasks).await?;
3370
3371 if !remaining_dirty_items.is_empty() {
3372 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3373 }
3374
3375 if remaining_dirty_items.len() > 1 {
3376 let answer = workspace.update_in(cx, |_, window, cx| {
3377 cx.emit(Event::Activate);
3378 let detail = Pane::file_names_for_prompt(
3379 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3380 cx,
3381 );
3382 window.prompt(
3383 PromptLevel::Warning,
3384 "Do you want to save all changes in the following files?",
3385 Some(&detail),
3386 &["Save all", "Discard all", "Cancel"],
3387 cx,
3388 )
3389 })?;
3390 match answer.await.log_err() {
3391 Some(0) => save_intent = SaveIntent::SaveAll,
3392 Some(1) => save_intent = SaveIntent::Skip,
3393 Some(2) => return Ok(false),
3394 _ => {}
3395 }
3396 }
3397
3398 remaining_dirty_items
3399 } else {
3400 dirty_items
3401 };
3402
3403 for (pane, item) in dirty_items {
3404 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3405 (
3406 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3407 item.project_entry_ids(cx),
3408 )
3409 })?;
3410 if (singleton || !project_entry_ids.is_empty())
3411 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3412 {
3413 return Ok(false);
3414 }
3415 }
3416 Ok(true)
3417 })
3418 }
3419
3420 pub fn open_workspace_for_paths(
3421 &mut self,
3422 // replace_current_window: bool,
3423 mut open_mode: OpenMode,
3424 paths: Vec<PathBuf>,
3425 window: &mut Window,
3426 cx: &mut Context<Self>,
3427 ) -> Task<Result<Entity<Workspace>>> {
3428 let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
3429 let is_remote = self.project.read(cx).is_via_collab();
3430 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3431 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3432
3433 let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
3434 if workspace_is_empty {
3435 open_mode = OpenMode::Activate;
3436 }
3437
3438 let app_state = self.app_state.clone();
3439
3440 cx.spawn(async move |_, cx| {
3441 let OpenResult { workspace, .. } = cx
3442 .update(|cx| {
3443 open_paths(
3444 &paths,
3445 app_state,
3446 OpenOptions {
3447 requesting_window,
3448 open_mode,
3449 ..Default::default()
3450 },
3451 cx,
3452 )
3453 })
3454 .await?;
3455 Ok(workspace)
3456 })
3457 }
3458
3459 #[allow(clippy::type_complexity)]
3460 pub fn open_paths(
3461 &mut self,
3462 mut abs_paths: Vec<PathBuf>,
3463 options: OpenOptions,
3464 pane: Option<WeakEntity<Pane>>,
3465 window: &mut Window,
3466 cx: &mut Context<Self>,
3467 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3468 let fs = self.app_state.fs.clone();
3469
3470 let caller_ordered_abs_paths = abs_paths.clone();
3471
3472 // Sort the paths to ensure we add worktrees for parents before their children.
3473 abs_paths.sort_unstable();
3474 cx.spawn_in(window, async move |this, cx| {
3475 let mut tasks = Vec::with_capacity(abs_paths.len());
3476
3477 for abs_path in &abs_paths {
3478 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3479 OpenVisible::All => Some(true),
3480 OpenVisible::None => Some(false),
3481 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3482 Some(Some(metadata)) => Some(!metadata.is_dir),
3483 Some(None) => Some(true),
3484 None => None,
3485 },
3486 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3487 Some(Some(metadata)) => Some(metadata.is_dir),
3488 Some(None) => Some(false),
3489 None => None,
3490 },
3491 };
3492 let project_path = match visible {
3493 Some(visible) => match this
3494 .update(cx, |this, cx| {
3495 Workspace::project_path_for_path(
3496 this.project.clone(),
3497 abs_path,
3498 visible,
3499 cx,
3500 )
3501 })
3502 .log_err()
3503 {
3504 Some(project_path) => project_path.await.log_err(),
3505 None => None,
3506 },
3507 None => None,
3508 };
3509
3510 let this = this.clone();
3511 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3512 let fs = fs.clone();
3513 let pane = pane.clone();
3514 let task = cx.spawn(async move |cx| {
3515 let (_worktree, project_path) = project_path?;
3516 if fs.is_dir(&abs_path).await {
3517 // Opening a directory should not race to update the active entry.
3518 // We'll select/reveal a deterministic final entry after all paths finish opening.
3519 None
3520 } else {
3521 Some(
3522 this.update_in(cx, |this, window, cx| {
3523 this.open_path(
3524 project_path,
3525 pane,
3526 options.focus.unwrap_or(true),
3527 window,
3528 cx,
3529 )
3530 })
3531 .ok()?
3532 .await,
3533 )
3534 }
3535 });
3536 tasks.push(task);
3537 }
3538
3539 let results = futures::future::join_all(tasks).await;
3540
3541 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3542 let mut winner: Option<(PathBuf, bool)> = None;
3543 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3544 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3545 if !metadata.is_dir {
3546 winner = Some((abs_path, false));
3547 break;
3548 }
3549 if winner.is_none() {
3550 winner = Some((abs_path, true));
3551 }
3552 } else if winner.is_none() {
3553 winner = Some((abs_path, false));
3554 }
3555 }
3556
3557 // Compute the winner entry id on the foreground thread and emit once, after all
3558 // paths finish opening. This avoids races between concurrently-opening paths
3559 // (directories in particular) and makes the resulting project panel selection
3560 // deterministic.
3561 if let Some((winner_abs_path, winner_is_dir)) = winner {
3562 'emit_winner: {
3563 let winner_abs_path: Arc<Path> =
3564 SanitizedPath::new(&winner_abs_path).as_path().into();
3565
3566 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3567 OpenVisible::All => true,
3568 OpenVisible::None => false,
3569 OpenVisible::OnlyFiles => !winner_is_dir,
3570 OpenVisible::OnlyDirectories => winner_is_dir,
3571 };
3572
3573 let Some(worktree_task) = this
3574 .update(cx, |workspace, cx| {
3575 workspace.project.update(cx, |project, cx| {
3576 project.find_or_create_worktree(
3577 winner_abs_path.as_ref(),
3578 visible,
3579 cx,
3580 )
3581 })
3582 })
3583 .ok()
3584 else {
3585 break 'emit_winner;
3586 };
3587
3588 let Ok((worktree, _)) = worktree_task.await else {
3589 break 'emit_winner;
3590 };
3591
3592 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3593 let worktree = worktree.read(cx);
3594 let worktree_abs_path = worktree.abs_path();
3595 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3596 worktree.root_entry()
3597 } else {
3598 winner_abs_path
3599 .strip_prefix(worktree_abs_path.as_ref())
3600 .ok()
3601 .and_then(|relative_path| {
3602 let relative_path =
3603 RelPath::new(relative_path, PathStyle::local())
3604 .log_err()?;
3605 worktree.entry_for_path(&relative_path)
3606 })
3607 }?;
3608 Some(entry.id)
3609 }) else {
3610 break 'emit_winner;
3611 };
3612
3613 this.update(cx, |workspace, cx| {
3614 workspace.project.update(cx, |_, cx| {
3615 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3616 });
3617 })
3618 .ok();
3619 }
3620 }
3621
3622 results
3623 })
3624 }
3625
3626 pub fn open_resolved_path(
3627 &mut self,
3628 path: ResolvedPath,
3629 window: &mut Window,
3630 cx: &mut Context<Self>,
3631 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3632 match path {
3633 ResolvedPath::ProjectPath { project_path, .. } => {
3634 self.open_path(project_path, None, true, window, cx)
3635 }
3636 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3637 PathBuf::from(path),
3638 OpenOptions {
3639 visible: Some(OpenVisible::None),
3640 ..Default::default()
3641 },
3642 window,
3643 cx,
3644 ),
3645 }
3646 }
3647
3648 pub fn absolute_path_of_worktree(
3649 &self,
3650 worktree_id: WorktreeId,
3651 cx: &mut Context<Self>,
3652 ) -> Option<PathBuf> {
3653 self.project
3654 .read(cx)
3655 .worktree_for_id(worktree_id, cx)
3656 // TODO: use `abs_path` or `root_dir`
3657 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3658 }
3659
3660 pub fn add_folder_to_project(
3661 &mut self,
3662 _: &AddFolderToProject,
3663 window: &mut Window,
3664 cx: &mut Context<Self>,
3665 ) {
3666 let project = self.project.read(cx);
3667 if project.is_via_collab() {
3668 self.show_error(
3669 &anyhow!("You cannot add folders to someone else's project"),
3670 cx,
3671 );
3672 return;
3673 }
3674 let paths = self.prompt_for_open_path(
3675 PathPromptOptions {
3676 files: false,
3677 directories: true,
3678 multiple: true,
3679 prompt: None,
3680 },
3681 DirectoryLister::Project(self.project.clone()),
3682 window,
3683 cx,
3684 );
3685 cx.spawn_in(window, async move |this, cx| {
3686 if let Some(paths) = paths.await.log_err().flatten() {
3687 let results = this
3688 .update_in(cx, |this, window, cx| {
3689 this.open_paths(
3690 paths,
3691 OpenOptions {
3692 visible: Some(OpenVisible::All),
3693 ..Default::default()
3694 },
3695 None,
3696 window,
3697 cx,
3698 )
3699 })?
3700 .await;
3701 for result in results.into_iter().flatten() {
3702 result.log_err();
3703 }
3704 }
3705 anyhow::Ok(())
3706 })
3707 .detach_and_log_err(cx);
3708 }
3709
3710 pub fn project_path_for_path(
3711 project: Entity<Project>,
3712 abs_path: &Path,
3713 visible: bool,
3714 cx: &mut App,
3715 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3716 let entry = project.update(cx, |project, cx| {
3717 project.find_or_create_worktree(abs_path, visible, cx)
3718 });
3719 cx.spawn(async move |cx| {
3720 let (worktree, path) = entry.await?;
3721 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3722 Ok((worktree, ProjectPath { worktree_id, path }))
3723 })
3724 }
3725
3726 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3727 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3728 }
3729
3730 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3731 self.items_of_type(cx).max_by_key(|item| item.item_id())
3732 }
3733
3734 pub fn items_of_type<'a, T: Item>(
3735 &'a self,
3736 cx: &'a App,
3737 ) -> impl 'a + Iterator<Item = Entity<T>> {
3738 self.panes
3739 .iter()
3740 .flat_map(|pane| pane.read(cx).items_of_type())
3741 }
3742
3743 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3744 self.active_pane().read(cx).active_item()
3745 }
3746
3747 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3748 let item = self.active_item(cx)?;
3749 item.to_any_view().downcast::<I>().ok()
3750 }
3751
3752 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3753 self.active_item(cx).and_then(|item| item.project_path(cx))
3754 }
3755
3756 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3757 self.recent_navigation_history_iter(cx)
3758 .filter_map(|(path, abs_path)| {
3759 let worktree = self
3760 .project
3761 .read(cx)
3762 .worktree_for_id(path.worktree_id, cx)?;
3763 if worktree.read(cx).is_visible() {
3764 abs_path
3765 } else {
3766 None
3767 }
3768 })
3769 .next()
3770 }
3771
3772 pub fn save_active_item(
3773 &mut self,
3774 save_intent: SaveIntent,
3775 window: &mut Window,
3776 cx: &mut App,
3777 ) -> Task<Result<()>> {
3778 let project = self.project.clone();
3779 let pane = self.active_pane();
3780 let item = pane.read(cx).active_item();
3781 let pane = pane.downgrade();
3782
3783 window.spawn(cx, async move |cx| {
3784 if let Some(item) = item {
3785 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3786 .await
3787 .map(|_| ())
3788 } else {
3789 Ok(())
3790 }
3791 })
3792 }
3793
3794 pub fn close_inactive_items_and_panes(
3795 &mut self,
3796 action: &CloseInactiveTabsAndPanes,
3797 window: &mut Window,
3798 cx: &mut Context<Self>,
3799 ) {
3800 if let Some(task) = self.close_all_internal(
3801 true,
3802 action.save_intent.unwrap_or(SaveIntent::Close),
3803 window,
3804 cx,
3805 ) {
3806 task.detach_and_log_err(cx)
3807 }
3808 }
3809
3810 pub fn close_all_items_and_panes(
3811 &mut self,
3812 action: &CloseAllItemsAndPanes,
3813 window: &mut Window,
3814 cx: &mut Context<Self>,
3815 ) {
3816 if let Some(task) = self.close_all_internal(
3817 false,
3818 action.save_intent.unwrap_or(SaveIntent::Close),
3819 window,
3820 cx,
3821 ) {
3822 task.detach_and_log_err(cx)
3823 }
3824 }
3825
3826 /// Closes the active item across all panes.
3827 pub fn close_item_in_all_panes(
3828 &mut self,
3829 action: &CloseItemInAllPanes,
3830 window: &mut Window,
3831 cx: &mut Context<Self>,
3832 ) {
3833 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3834 return;
3835 };
3836
3837 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3838 let close_pinned = action.close_pinned;
3839
3840 if let Some(project_path) = active_item.project_path(cx) {
3841 self.close_items_with_project_path(
3842 &project_path,
3843 save_intent,
3844 close_pinned,
3845 window,
3846 cx,
3847 );
3848 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3849 let item_id = active_item.item_id();
3850 self.active_pane().update(cx, |pane, cx| {
3851 pane.close_item_by_id(item_id, save_intent, window, cx)
3852 .detach_and_log_err(cx);
3853 });
3854 }
3855 }
3856
3857 /// Closes all items with the given project path across all panes.
3858 pub fn close_items_with_project_path(
3859 &mut self,
3860 project_path: &ProjectPath,
3861 save_intent: SaveIntent,
3862 close_pinned: bool,
3863 window: &mut Window,
3864 cx: &mut Context<Self>,
3865 ) {
3866 let panes = self.panes().to_vec();
3867 for pane in panes {
3868 pane.update(cx, |pane, cx| {
3869 pane.close_items_for_project_path(
3870 project_path,
3871 save_intent,
3872 close_pinned,
3873 window,
3874 cx,
3875 )
3876 .detach_and_log_err(cx);
3877 });
3878 }
3879 }
3880
3881 fn close_all_internal(
3882 &mut self,
3883 retain_active_pane: bool,
3884 save_intent: SaveIntent,
3885 window: &mut Window,
3886 cx: &mut Context<Self>,
3887 ) -> Option<Task<Result<()>>> {
3888 let current_pane = self.active_pane();
3889
3890 let mut tasks = Vec::new();
3891
3892 if retain_active_pane {
3893 let current_pane_close = current_pane.update(cx, |pane, cx| {
3894 pane.close_other_items(
3895 &CloseOtherItems {
3896 save_intent: None,
3897 close_pinned: false,
3898 },
3899 None,
3900 window,
3901 cx,
3902 )
3903 });
3904
3905 tasks.push(current_pane_close);
3906 }
3907
3908 for pane in self.panes() {
3909 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3910 continue;
3911 }
3912
3913 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3914 pane.close_all_items(
3915 &CloseAllItems {
3916 save_intent: Some(save_intent),
3917 close_pinned: false,
3918 },
3919 window,
3920 cx,
3921 )
3922 });
3923
3924 tasks.push(close_pane_items)
3925 }
3926
3927 if tasks.is_empty() {
3928 None
3929 } else {
3930 Some(cx.spawn_in(window, async move |_, _| {
3931 for task in tasks {
3932 task.await?
3933 }
3934 Ok(())
3935 }))
3936 }
3937 }
3938
3939 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3940 self.dock_at_position(position).read(cx).is_open()
3941 }
3942
3943 pub fn toggle_dock(
3944 &mut self,
3945 dock_side: DockPosition,
3946 window: &mut Window,
3947 cx: &mut Context<Self>,
3948 ) {
3949 let mut focus_center = false;
3950 let mut reveal_dock = false;
3951
3952 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3953 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3954
3955 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3956 telemetry::event!(
3957 "Panel Button Clicked",
3958 name = panel.persistent_name(),
3959 toggle_state = !was_visible
3960 );
3961 }
3962 if was_visible {
3963 self.save_open_dock_positions(cx);
3964 }
3965
3966 let dock = self.dock_at_position(dock_side);
3967 dock.update(cx, |dock, cx| {
3968 dock.set_open(!was_visible, window, cx);
3969
3970 if dock.active_panel().is_none() {
3971 let Some(panel_ix) = dock
3972 .first_enabled_panel_idx(cx)
3973 .log_with_level(log::Level::Info)
3974 else {
3975 return;
3976 };
3977 dock.activate_panel(panel_ix, window, cx);
3978 }
3979
3980 if let Some(active_panel) = dock.active_panel() {
3981 if was_visible {
3982 if active_panel
3983 .panel_focus_handle(cx)
3984 .contains_focused(window, cx)
3985 {
3986 focus_center = true;
3987 }
3988 } else {
3989 let focus_handle = &active_panel.panel_focus_handle(cx);
3990 window.focus(focus_handle, cx);
3991 reveal_dock = true;
3992 }
3993 }
3994 });
3995
3996 if reveal_dock {
3997 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3998 }
3999
4000 if focus_center {
4001 self.active_pane
4002 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4003 }
4004
4005 cx.notify();
4006 self.serialize_workspace(window, cx);
4007 }
4008
4009 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
4010 self.all_docks().into_iter().find(|&dock| {
4011 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
4012 })
4013 }
4014
4015 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
4016 if let Some(dock) = self.active_dock(window, cx).cloned() {
4017 self.save_open_dock_positions(cx);
4018 dock.update(cx, |dock, cx| {
4019 dock.set_open(false, window, cx);
4020 });
4021 return true;
4022 }
4023 false
4024 }
4025
4026 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4027 self.save_open_dock_positions(cx);
4028 for dock in self.all_docks() {
4029 dock.update(cx, |dock, cx| {
4030 dock.set_open(false, window, cx);
4031 });
4032 }
4033
4034 cx.focus_self(window);
4035 cx.notify();
4036 self.serialize_workspace(window, cx);
4037 }
4038
4039 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
4040 self.all_docks()
4041 .into_iter()
4042 .filter_map(|dock| {
4043 let dock_ref = dock.read(cx);
4044 if dock_ref.is_open() {
4045 Some(dock_ref.position())
4046 } else {
4047 None
4048 }
4049 })
4050 .collect()
4051 }
4052
4053 /// Saves the positions of currently open docks.
4054 ///
4055 /// Updates `last_open_dock_positions` with positions of all currently open
4056 /// docks, to later be restored by the 'Toggle All Docks' action.
4057 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
4058 let open_dock_positions = self.get_open_dock_positions(cx);
4059 if !open_dock_positions.is_empty() {
4060 self.last_open_dock_positions = open_dock_positions;
4061 }
4062 }
4063
4064 /// Toggles all docks between open and closed states.
4065 ///
4066 /// If any docks are open, closes all and remembers their positions. If all
4067 /// docks are closed, restores the last remembered dock configuration.
4068 fn toggle_all_docks(
4069 &mut self,
4070 _: &ToggleAllDocks,
4071 window: &mut Window,
4072 cx: &mut Context<Self>,
4073 ) {
4074 let open_dock_positions = self.get_open_dock_positions(cx);
4075
4076 if !open_dock_positions.is_empty() {
4077 self.close_all_docks(window, cx);
4078 } else if !self.last_open_dock_positions.is_empty() {
4079 self.restore_last_open_docks(window, cx);
4080 }
4081 }
4082
4083 /// Reopens docks from the most recently remembered configuration.
4084 ///
4085 /// Opens all docks whose positions are stored in `last_open_dock_positions`
4086 /// and clears the stored positions.
4087 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4088 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
4089
4090 for position in positions_to_open {
4091 let dock = self.dock_at_position(position);
4092 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
4093 }
4094
4095 cx.focus_self(window);
4096 cx.notify();
4097 self.serialize_workspace(window, cx);
4098 }
4099
4100 /// Transfer focus to the panel of the given type.
4101 pub fn focus_panel<T: Panel>(
4102 &mut self,
4103 window: &mut Window,
4104 cx: &mut Context<Self>,
4105 ) -> Option<Entity<T>> {
4106 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
4107 panel.to_any().downcast().ok()
4108 }
4109
4110 /// Focus the panel of the given type if it isn't already focused. If it is
4111 /// already focused, then transfer focus back to the workspace center.
4112 /// When the `close_panel_on_toggle` setting is enabled, also closes the
4113 /// panel when transferring focus back to the center.
4114 pub fn toggle_panel_focus<T: Panel>(
4115 &mut self,
4116 window: &mut Window,
4117 cx: &mut Context<Self>,
4118 ) -> bool {
4119 let mut did_focus_panel = false;
4120 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
4121 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
4122 did_focus_panel
4123 });
4124
4125 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
4126 self.close_panel::<T>(window, cx);
4127 }
4128
4129 telemetry::event!(
4130 "Panel Button Clicked",
4131 name = T::persistent_name(),
4132 toggle_state = did_focus_panel
4133 );
4134
4135 did_focus_panel
4136 }
4137
4138 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4139 if let Some(item) = self.active_item(cx) {
4140 item.item_focus_handle(cx).focus(window, cx);
4141 } else {
4142 log::error!("Could not find a focus target when switching focus to the center panes",);
4143 }
4144 }
4145
4146 pub fn activate_panel_for_proto_id(
4147 &mut self,
4148 panel_id: PanelId,
4149 window: &mut Window,
4150 cx: &mut Context<Self>,
4151 ) -> Option<Arc<dyn PanelHandle>> {
4152 let mut panel = None;
4153 for dock in self.all_docks() {
4154 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
4155 panel = dock.update(cx, |dock, cx| {
4156 dock.activate_panel(panel_index, window, cx);
4157 dock.set_open(true, window, cx);
4158 dock.active_panel().cloned()
4159 });
4160 break;
4161 }
4162 }
4163
4164 if panel.is_some() {
4165 cx.notify();
4166 self.serialize_workspace(window, cx);
4167 }
4168
4169 panel
4170 }
4171
4172 /// Focus or unfocus the given panel type, depending on the given callback.
4173 fn focus_or_unfocus_panel<T: Panel>(
4174 &mut self,
4175 window: &mut Window,
4176 cx: &mut Context<Self>,
4177 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
4178 ) -> Option<Arc<dyn PanelHandle>> {
4179 let mut result_panel = None;
4180 let mut serialize = false;
4181 for dock in self.all_docks() {
4182 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4183 let mut focus_center = false;
4184 let panel = dock.update(cx, |dock, cx| {
4185 dock.activate_panel(panel_index, window, cx);
4186
4187 let panel = dock.active_panel().cloned();
4188 if let Some(panel) = panel.as_ref() {
4189 if should_focus(&**panel, window, cx) {
4190 dock.set_open(true, window, cx);
4191 panel.panel_focus_handle(cx).focus(window, cx);
4192 } else {
4193 focus_center = true;
4194 }
4195 }
4196 panel
4197 });
4198
4199 if focus_center {
4200 self.active_pane
4201 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4202 }
4203
4204 result_panel = panel;
4205 serialize = true;
4206 break;
4207 }
4208 }
4209
4210 if serialize {
4211 self.serialize_workspace(window, cx);
4212 }
4213
4214 cx.notify();
4215 result_panel
4216 }
4217
4218 /// Open the panel of the given type
4219 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4220 for dock in self.all_docks() {
4221 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4222 dock.update(cx, |dock, cx| {
4223 dock.activate_panel(panel_index, window, cx);
4224 dock.set_open(true, window, cx);
4225 });
4226 }
4227 }
4228 }
4229
4230 /// Open the panel of the given type, dismissing any zoomed items that
4231 /// would obscure it (e.g. a zoomed terminal).
4232 pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4233 let dock_position = self.all_docks().iter().find_map(|dock| {
4234 let dock = dock.read(cx);
4235 dock.panel_index_for_type::<T>().map(|_| dock.position())
4236 });
4237 self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
4238 self.open_panel::<T>(window, cx);
4239 }
4240
4241 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4242 for dock in self.all_docks().iter() {
4243 dock.update(cx, |dock, cx| {
4244 if dock.panel::<T>().is_some() {
4245 dock.set_open(false, window, cx)
4246 }
4247 })
4248 }
4249 }
4250
4251 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4252 self.all_docks()
4253 .iter()
4254 .find_map(|dock| dock.read(cx).panel::<T>())
4255 }
4256
4257 fn dismiss_zoomed_items_to_reveal(
4258 &mut self,
4259 dock_to_reveal: Option<DockPosition>,
4260 window: &mut Window,
4261 cx: &mut Context<Self>,
4262 ) {
4263 // If a center pane is zoomed, unzoom it.
4264 for pane in &self.panes {
4265 if pane != &self.active_pane || dock_to_reveal.is_some() {
4266 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4267 }
4268 }
4269
4270 // If another dock is zoomed, hide it.
4271 let mut focus_center = false;
4272 for dock in self.all_docks() {
4273 dock.update(cx, |dock, cx| {
4274 if Some(dock.position()) != dock_to_reveal
4275 && let Some(panel) = dock.active_panel()
4276 && panel.is_zoomed(window, cx)
4277 {
4278 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4279 dock.set_open(false, window, cx);
4280 }
4281 });
4282 }
4283
4284 if focus_center {
4285 self.active_pane
4286 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4287 }
4288
4289 if self.zoomed_position != dock_to_reveal {
4290 self.zoomed = None;
4291 self.zoomed_position = None;
4292 cx.emit(Event::ZoomChanged);
4293 }
4294
4295 cx.notify();
4296 }
4297
4298 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4299 let pane = cx.new(|cx| {
4300 let mut pane = Pane::new(
4301 self.weak_handle(),
4302 self.project.clone(),
4303 self.pane_history_timestamp.clone(),
4304 None,
4305 NewFile.boxed_clone(),
4306 true,
4307 window,
4308 cx,
4309 );
4310 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4311 pane
4312 });
4313 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4314 .detach();
4315 self.panes.push(pane.clone());
4316
4317 window.focus(&pane.focus_handle(cx), cx);
4318
4319 cx.emit(Event::PaneAdded(pane.clone()));
4320 pane
4321 }
4322
4323 pub fn add_item_to_center(
4324 &mut self,
4325 item: Box<dyn ItemHandle>,
4326 window: &mut Window,
4327 cx: &mut Context<Self>,
4328 ) -> bool {
4329 if let Some(center_pane) = self.last_active_center_pane.clone() {
4330 if let Some(center_pane) = center_pane.upgrade() {
4331 center_pane.update(cx, |pane, cx| {
4332 pane.add_item(item, true, true, None, window, cx)
4333 });
4334 true
4335 } else {
4336 false
4337 }
4338 } else {
4339 false
4340 }
4341 }
4342
4343 pub fn add_item_to_active_pane(
4344 &mut self,
4345 item: Box<dyn ItemHandle>,
4346 destination_index: Option<usize>,
4347 focus_item: bool,
4348 window: &mut Window,
4349 cx: &mut App,
4350 ) {
4351 self.add_item(
4352 self.active_pane.clone(),
4353 item,
4354 destination_index,
4355 false,
4356 focus_item,
4357 window,
4358 cx,
4359 )
4360 }
4361
4362 pub fn add_item(
4363 &mut self,
4364 pane: Entity<Pane>,
4365 item: Box<dyn ItemHandle>,
4366 destination_index: Option<usize>,
4367 activate_pane: bool,
4368 focus_item: bool,
4369 window: &mut Window,
4370 cx: &mut App,
4371 ) {
4372 pane.update(cx, |pane, cx| {
4373 pane.add_item(
4374 item,
4375 activate_pane,
4376 focus_item,
4377 destination_index,
4378 window,
4379 cx,
4380 )
4381 });
4382 }
4383
4384 pub fn split_item(
4385 &mut self,
4386 split_direction: SplitDirection,
4387 item: Box<dyn ItemHandle>,
4388 window: &mut Window,
4389 cx: &mut Context<Self>,
4390 ) {
4391 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4392 self.add_item(new_pane, item, None, true, true, window, cx);
4393 }
4394
4395 pub fn open_abs_path(
4396 &mut self,
4397 abs_path: PathBuf,
4398 options: OpenOptions,
4399 window: &mut Window,
4400 cx: &mut Context<Self>,
4401 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4402 cx.spawn_in(window, async move |workspace, cx| {
4403 let open_paths_task_result = workspace
4404 .update_in(cx, |workspace, window, cx| {
4405 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4406 })
4407 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4408 .await;
4409 anyhow::ensure!(
4410 open_paths_task_result.len() == 1,
4411 "open abs path {abs_path:?} task returned incorrect number of results"
4412 );
4413 match open_paths_task_result
4414 .into_iter()
4415 .next()
4416 .expect("ensured single task result")
4417 {
4418 Some(open_result) => {
4419 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4420 }
4421 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4422 }
4423 })
4424 }
4425
4426 pub fn split_abs_path(
4427 &mut self,
4428 abs_path: PathBuf,
4429 visible: bool,
4430 window: &mut Window,
4431 cx: &mut Context<Self>,
4432 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4433 let project_path_task =
4434 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4435 cx.spawn_in(window, async move |this, cx| {
4436 let (_, path) = project_path_task.await?;
4437 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4438 .await
4439 })
4440 }
4441
4442 pub fn open_path(
4443 &mut self,
4444 path: impl Into<ProjectPath>,
4445 pane: Option<WeakEntity<Pane>>,
4446 focus_item: bool,
4447 window: &mut Window,
4448 cx: &mut App,
4449 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4450 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4451 }
4452
4453 pub fn open_path_preview(
4454 &mut self,
4455 path: impl Into<ProjectPath>,
4456 pane: Option<WeakEntity<Pane>>,
4457 focus_item: bool,
4458 allow_preview: bool,
4459 activate: bool,
4460 window: &mut Window,
4461 cx: &mut App,
4462 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4463 let pane = pane.unwrap_or_else(|| {
4464 self.last_active_center_pane.clone().unwrap_or_else(|| {
4465 self.panes
4466 .first()
4467 .expect("There must be an active pane")
4468 .downgrade()
4469 })
4470 });
4471
4472 let project_path = path.into();
4473 let task = self.load_path(project_path.clone(), window, cx);
4474 window.spawn(cx, async move |cx| {
4475 let (project_entry_id, build_item) = task.await?;
4476
4477 pane.update_in(cx, |pane, window, cx| {
4478 pane.open_item(
4479 project_entry_id,
4480 project_path,
4481 focus_item,
4482 allow_preview,
4483 activate,
4484 None,
4485 window,
4486 cx,
4487 build_item,
4488 )
4489 })
4490 })
4491 }
4492
4493 pub fn split_path(
4494 &mut self,
4495 path: impl Into<ProjectPath>,
4496 window: &mut Window,
4497 cx: &mut Context<Self>,
4498 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4499 self.split_path_preview(path, false, None, window, cx)
4500 }
4501
4502 pub fn split_path_preview(
4503 &mut self,
4504 path: impl Into<ProjectPath>,
4505 allow_preview: bool,
4506 split_direction: Option<SplitDirection>,
4507 window: &mut Window,
4508 cx: &mut Context<Self>,
4509 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4510 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4511 self.panes
4512 .first()
4513 .expect("There must be an active pane")
4514 .downgrade()
4515 });
4516
4517 if let Member::Pane(center_pane) = &self.center.root
4518 && center_pane.read(cx).items_len() == 0
4519 {
4520 return self.open_path(path, Some(pane), true, window, cx);
4521 }
4522
4523 let project_path = path.into();
4524 let task = self.load_path(project_path.clone(), window, cx);
4525 cx.spawn_in(window, async move |this, cx| {
4526 let (project_entry_id, build_item) = task.await?;
4527 this.update_in(cx, move |this, window, cx| -> Option<_> {
4528 let pane = pane.upgrade()?;
4529 let new_pane = this.split_pane(
4530 pane,
4531 split_direction.unwrap_or(SplitDirection::Right),
4532 window,
4533 cx,
4534 );
4535 new_pane.update(cx, |new_pane, cx| {
4536 Some(new_pane.open_item(
4537 project_entry_id,
4538 project_path,
4539 true,
4540 allow_preview,
4541 true,
4542 None,
4543 window,
4544 cx,
4545 build_item,
4546 ))
4547 })
4548 })
4549 .map(|option| option.context("pane was dropped"))?
4550 })
4551 }
4552
4553 fn load_path(
4554 &mut self,
4555 path: ProjectPath,
4556 window: &mut Window,
4557 cx: &mut App,
4558 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4559 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4560 registry.open_path(self.project(), &path, window, cx)
4561 }
4562
4563 pub fn find_project_item<T>(
4564 &self,
4565 pane: &Entity<Pane>,
4566 project_item: &Entity<T::Item>,
4567 cx: &App,
4568 ) -> Option<Entity<T>>
4569 where
4570 T: ProjectItem,
4571 {
4572 use project::ProjectItem as _;
4573 let project_item = project_item.read(cx);
4574 let entry_id = project_item.entry_id(cx);
4575 let project_path = project_item.project_path(cx);
4576
4577 let mut item = None;
4578 if let Some(entry_id) = entry_id {
4579 item = pane.read(cx).item_for_entry(entry_id, cx);
4580 }
4581 if item.is_none()
4582 && let Some(project_path) = project_path
4583 {
4584 item = pane.read(cx).item_for_path(project_path, cx);
4585 }
4586
4587 item.and_then(|item| item.downcast::<T>())
4588 }
4589
4590 pub fn is_project_item_open<T>(
4591 &self,
4592 pane: &Entity<Pane>,
4593 project_item: &Entity<T::Item>,
4594 cx: &App,
4595 ) -> bool
4596 where
4597 T: ProjectItem,
4598 {
4599 self.find_project_item::<T>(pane, project_item, cx)
4600 .is_some()
4601 }
4602
4603 pub fn open_project_item<T>(
4604 &mut self,
4605 pane: Entity<Pane>,
4606 project_item: Entity<T::Item>,
4607 activate_pane: bool,
4608 focus_item: bool,
4609 keep_old_preview: bool,
4610 allow_new_preview: bool,
4611 window: &mut Window,
4612 cx: &mut Context<Self>,
4613 ) -> Entity<T>
4614 where
4615 T: ProjectItem,
4616 {
4617 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4618
4619 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4620 if !keep_old_preview
4621 && let Some(old_id) = old_item_id
4622 && old_id != item.item_id()
4623 {
4624 // switching to a different item, so unpreview old active item
4625 pane.update(cx, |pane, _| {
4626 pane.unpreview_item_if_preview(old_id);
4627 });
4628 }
4629
4630 self.activate_item(&item, activate_pane, focus_item, window, cx);
4631 if !allow_new_preview {
4632 pane.update(cx, |pane, _| {
4633 pane.unpreview_item_if_preview(item.item_id());
4634 });
4635 }
4636 return item;
4637 }
4638
4639 let item = pane.update(cx, |pane, cx| {
4640 cx.new(|cx| {
4641 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4642 })
4643 });
4644 let mut destination_index = None;
4645 pane.update(cx, |pane, cx| {
4646 if !keep_old_preview && let Some(old_id) = old_item_id {
4647 pane.unpreview_item_if_preview(old_id);
4648 }
4649 if allow_new_preview {
4650 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4651 }
4652 });
4653
4654 self.add_item(
4655 pane,
4656 Box::new(item.clone()),
4657 destination_index,
4658 activate_pane,
4659 focus_item,
4660 window,
4661 cx,
4662 );
4663 item
4664 }
4665
4666 pub fn open_shared_screen(
4667 &mut self,
4668 peer_id: PeerId,
4669 window: &mut Window,
4670 cx: &mut Context<Self>,
4671 ) {
4672 if let Some(shared_screen) =
4673 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4674 {
4675 self.active_pane.update(cx, |pane, cx| {
4676 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4677 });
4678 }
4679 }
4680
4681 pub fn activate_item(
4682 &mut self,
4683 item: &dyn ItemHandle,
4684 activate_pane: bool,
4685 focus_item: bool,
4686 window: &mut Window,
4687 cx: &mut App,
4688 ) -> bool {
4689 let result = self.panes.iter().find_map(|pane| {
4690 pane.read(cx)
4691 .index_for_item(item)
4692 .map(|ix| (pane.clone(), ix))
4693 });
4694 if let Some((pane, ix)) = result {
4695 pane.update(cx, |pane, cx| {
4696 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4697 });
4698 true
4699 } else {
4700 false
4701 }
4702 }
4703
4704 fn activate_pane_at_index(
4705 &mut self,
4706 action: &ActivatePane,
4707 window: &mut Window,
4708 cx: &mut Context<Self>,
4709 ) {
4710 let panes = self.center.panes();
4711 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4712 window.focus(&pane.focus_handle(cx), cx);
4713 } else {
4714 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4715 .detach();
4716 }
4717 }
4718
4719 fn move_item_to_pane_at_index(
4720 &mut self,
4721 action: &MoveItemToPane,
4722 window: &mut Window,
4723 cx: &mut Context<Self>,
4724 ) {
4725 let panes = self.center.panes();
4726 let destination = match panes.get(action.destination) {
4727 Some(&destination) => destination.clone(),
4728 None => {
4729 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4730 return;
4731 }
4732 let direction = SplitDirection::Right;
4733 let split_off_pane = self
4734 .find_pane_in_direction(direction, cx)
4735 .unwrap_or_else(|| self.active_pane.clone());
4736 let new_pane = self.add_pane(window, cx);
4737 self.center.split(&split_off_pane, &new_pane, direction, cx);
4738 new_pane
4739 }
4740 };
4741
4742 if action.clone {
4743 if self
4744 .active_pane
4745 .read(cx)
4746 .active_item()
4747 .is_some_and(|item| item.can_split(cx))
4748 {
4749 clone_active_item(
4750 self.database_id(),
4751 &self.active_pane,
4752 &destination,
4753 action.focus,
4754 window,
4755 cx,
4756 );
4757 return;
4758 }
4759 }
4760 move_active_item(
4761 &self.active_pane,
4762 &destination,
4763 action.focus,
4764 true,
4765 window,
4766 cx,
4767 )
4768 }
4769
4770 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4771 let panes = self.center.panes();
4772 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4773 let next_ix = (ix + 1) % panes.len();
4774 let next_pane = panes[next_ix].clone();
4775 window.focus(&next_pane.focus_handle(cx), cx);
4776 }
4777 }
4778
4779 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4780 let panes = self.center.panes();
4781 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4782 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4783 let prev_pane = panes[prev_ix].clone();
4784 window.focus(&prev_pane.focus_handle(cx), cx);
4785 }
4786 }
4787
4788 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4789 let last_pane = self.center.last_pane();
4790 window.focus(&last_pane.focus_handle(cx), cx);
4791 }
4792
4793 pub fn activate_pane_in_direction(
4794 &mut self,
4795 direction: SplitDirection,
4796 window: &mut Window,
4797 cx: &mut App,
4798 ) {
4799 use ActivateInDirectionTarget as Target;
4800 enum Origin {
4801 Sidebar,
4802 LeftDock,
4803 RightDock,
4804 BottomDock,
4805 Center,
4806 }
4807
4808 let origin: Origin = if self
4809 .sidebar_focus_handle
4810 .as_ref()
4811 .is_some_and(|h| h.contains_focused(window, cx))
4812 {
4813 Origin::Sidebar
4814 } else {
4815 [
4816 (&self.left_dock, Origin::LeftDock),
4817 (&self.right_dock, Origin::RightDock),
4818 (&self.bottom_dock, Origin::BottomDock),
4819 ]
4820 .into_iter()
4821 .find_map(|(dock, origin)| {
4822 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4823 Some(origin)
4824 } else {
4825 None
4826 }
4827 })
4828 .unwrap_or(Origin::Center)
4829 };
4830
4831 let get_last_active_pane = || {
4832 let pane = self
4833 .last_active_center_pane
4834 .clone()
4835 .unwrap_or_else(|| {
4836 self.panes
4837 .first()
4838 .expect("There must be an active pane")
4839 .downgrade()
4840 })
4841 .upgrade()?;
4842 (pane.read(cx).items_len() != 0).then_some(pane)
4843 };
4844
4845 let try_dock =
4846 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4847
4848 let sidebar_target = self
4849 .sidebar_focus_handle
4850 .as_ref()
4851 .map(|h| Target::Sidebar(h.clone()));
4852
4853 let sidebar_on_right = self
4854 .multi_workspace
4855 .as_ref()
4856 .and_then(|mw| mw.upgrade())
4857 .map_or(false, |mw| {
4858 mw.read(cx).sidebar_side(cx) == SidebarSide::Right
4859 });
4860
4861 let away_from_sidebar = if sidebar_on_right {
4862 SplitDirection::Left
4863 } else {
4864 SplitDirection::Right
4865 };
4866
4867 let (near_dock, far_dock) = if sidebar_on_right {
4868 (&self.right_dock, &self.left_dock)
4869 } else {
4870 (&self.left_dock, &self.right_dock)
4871 };
4872
4873 let target = match (origin, direction) {
4874 (Origin::Sidebar, dir) if dir == away_from_sidebar => try_dock(near_dock)
4875 .or_else(|| get_last_active_pane().map(Target::Pane))
4876 .or_else(|| try_dock(&self.bottom_dock))
4877 .or_else(|| try_dock(far_dock)),
4878
4879 (Origin::Sidebar, _) => None,
4880
4881 // We're in the center, so we first try to go to a different pane,
4882 // otherwise try to go to a dock.
4883 (Origin::Center, direction) => {
4884 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4885 Some(Target::Pane(pane))
4886 } else {
4887 match direction {
4888 SplitDirection::Up => None,
4889 SplitDirection::Down => try_dock(&self.bottom_dock),
4890 SplitDirection::Left => {
4891 let dock_target = try_dock(&self.left_dock);
4892 if sidebar_on_right {
4893 dock_target
4894 } else {
4895 dock_target.or(sidebar_target)
4896 }
4897 }
4898 SplitDirection::Right => {
4899 let dock_target = try_dock(&self.right_dock);
4900 if sidebar_on_right {
4901 dock_target.or(sidebar_target)
4902 } else {
4903 dock_target
4904 }
4905 }
4906 }
4907 }
4908 }
4909
4910 (Origin::LeftDock, SplitDirection::Right) => {
4911 if let Some(last_active_pane) = get_last_active_pane() {
4912 Some(Target::Pane(last_active_pane))
4913 } else {
4914 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4915 }
4916 }
4917
4918 (Origin::LeftDock, SplitDirection::Left) => {
4919 if sidebar_on_right {
4920 None
4921 } else {
4922 sidebar_target
4923 }
4924 }
4925
4926 (Origin::LeftDock, SplitDirection::Down)
4927 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4928
4929 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4930 (Origin::BottomDock, SplitDirection::Left) => {
4931 let dock_target = try_dock(&self.left_dock);
4932 if sidebar_on_right {
4933 dock_target
4934 } else {
4935 dock_target.or(sidebar_target)
4936 }
4937 }
4938 (Origin::BottomDock, SplitDirection::Right) => {
4939 let dock_target = try_dock(&self.right_dock);
4940 if sidebar_on_right {
4941 dock_target.or(sidebar_target)
4942 } else {
4943 dock_target
4944 }
4945 }
4946
4947 (Origin::RightDock, SplitDirection::Left) => {
4948 if let Some(last_active_pane) = get_last_active_pane() {
4949 Some(Target::Pane(last_active_pane))
4950 } else {
4951 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
4952 }
4953 }
4954
4955 (Origin::RightDock, SplitDirection::Right) => {
4956 if sidebar_on_right {
4957 sidebar_target
4958 } else {
4959 None
4960 }
4961 }
4962
4963 _ => None,
4964 };
4965
4966 match target {
4967 Some(ActivateInDirectionTarget::Pane(pane)) => {
4968 let pane = pane.read(cx);
4969 if let Some(item) = pane.active_item() {
4970 item.item_focus_handle(cx).focus(window, cx);
4971 } else {
4972 log::error!(
4973 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4974 );
4975 }
4976 }
4977 Some(ActivateInDirectionTarget::Dock(dock)) => {
4978 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4979 window.defer(cx, move |window, cx| {
4980 let dock = dock.read(cx);
4981 if let Some(panel) = dock.active_panel() {
4982 panel.panel_focus_handle(cx).focus(window, cx);
4983 } else {
4984 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4985 }
4986 })
4987 }
4988 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4989 focus_handle.focus(window, cx);
4990 }
4991 None => {}
4992 }
4993 }
4994
4995 pub fn move_item_to_pane_in_direction(
4996 &mut self,
4997 action: &MoveItemToPaneInDirection,
4998 window: &mut Window,
4999 cx: &mut Context<Self>,
5000 ) {
5001 let destination = match self.find_pane_in_direction(action.direction, cx) {
5002 Some(destination) => destination,
5003 None => {
5004 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
5005 return;
5006 }
5007 let new_pane = self.add_pane(window, cx);
5008 self.center
5009 .split(&self.active_pane, &new_pane, action.direction, cx);
5010 new_pane
5011 }
5012 };
5013
5014 if action.clone {
5015 if self
5016 .active_pane
5017 .read(cx)
5018 .active_item()
5019 .is_some_and(|item| item.can_split(cx))
5020 {
5021 clone_active_item(
5022 self.database_id(),
5023 &self.active_pane,
5024 &destination,
5025 action.focus,
5026 window,
5027 cx,
5028 );
5029 return;
5030 }
5031 }
5032 move_active_item(
5033 &self.active_pane,
5034 &destination,
5035 action.focus,
5036 true,
5037 window,
5038 cx,
5039 );
5040 }
5041
5042 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
5043 self.center.bounding_box_for_pane(pane)
5044 }
5045
5046 pub fn find_pane_in_direction(
5047 &mut self,
5048 direction: SplitDirection,
5049 cx: &App,
5050 ) -> Option<Entity<Pane>> {
5051 self.center
5052 .find_pane_in_direction(&self.active_pane, direction, cx)
5053 .cloned()
5054 }
5055
5056 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
5057 if let Some(to) = self.find_pane_in_direction(direction, cx) {
5058 self.center.swap(&self.active_pane, &to, cx);
5059 cx.notify();
5060 }
5061 }
5062
5063 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
5064 if self
5065 .center
5066 .move_to_border(&self.active_pane, direction, cx)
5067 .unwrap()
5068 {
5069 cx.notify();
5070 }
5071 }
5072
5073 pub fn resize_pane(
5074 &mut self,
5075 axis: gpui::Axis,
5076 amount: Pixels,
5077 window: &mut Window,
5078 cx: &mut Context<Self>,
5079 ) {
5080 let docks = self.all_docks();
5081 let active_dock = docks
5082 .into_iter()
5083 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
5084
5085 if let Some(dock_entity) = active_dock {
5086 let dock = dock_entity.read(cx);
5087 let Some(panel_size) = self.dock_size(&dock, window, cx) else {
5088 return;
5089 };
5090 match dock.position() {
5091 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
5092 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
5093 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
5094 }
5095 } else {
5096 self.center
5097 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
5098 }
5099 cx.notify();
5100 }
5101
5102 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
5103 self.center.reset_pane_sizes(cx);
5104 cx.notify();
5105 }
5106
5107 fn handle_pane_focused(
5108 &mut self,
5109 pane: Entity<Pane>,
5110 window: &mut Window,
5111 cx: &mut Context<Self>,
5112 ) {
5113 // This is explicitly hoisted out of the following check for pane identity as
5114 // terminal panel panes are not registered as a center panes.
5115 self.status_bar.update(cx, |status_bar, cx| {
5116 status_bar.set_active_pane(&pane, window, cx);
5117 });
5118 if self.active_pane != pane {
5119 self.set_active_pane(&pane, window, cx);
5120 }
5121
5122 if self.last_active_center_pane.is_none() {
5123 self.last_active_center_pane = Some(pane.downgrade());
5124 }
5125
5126 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
5127 // This prevents the dock from closing when focus events fire during window activation.
5128 // We also preserve any dock whose active panel itself has focus — this covers
5129 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
5130 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
5131 let dock_read = dock.read(cx);
5132 if let Some(panel) = dock_read.active_panel() {
5133 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
5134 || panel.panel_focus_handle(cx).contains_focused(window, cx)
5135 {
5136 return Some(dock_read.position());
5137 }
5138 }
5139 None
5140 });
5141
5142 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
5143 if pane.read(cx).is_zoomed() {
5144 self.zoomed = Some(pane.downgrade().into());
5145 } else {
5146 self.zoomed = None;
5147 }
5148 self.zoomed_position = None;
5149 cx.emit(Event::ZoomChanged);
5150 self.update_active_view_for_followers(window, cx);
5151 pane.update(cx, |pane, _| {
5152 pane.track_alternate_file_items();
5153 });
5154
5155 cx.notify();
5156 }
5157
5158 fn set_active_pane(
5159 &mut self,
5160 pane: &Entity<Pane>,
5161 window: &mut Window,
5162 cx: &mut Context<Self>,
5163 ) {
5164 self.active_pane = pane.clone();
5165 self.active_item_path_changed(true, window, cx);
5166 self.last_active_center_pane = Some(pane.downgrade());
5167 }
5168
5169 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5170 self.update_active_view_for_followers(window, cx);
5171 }
5172
5173 fn handle_pane_event(
5174 &mut self,
5175 pane: &Entity<Pane>,
5176 event: &pane::Event,
5177 window: &mut Window,
5178 cx: &mut Context<Self>,
5179 ) {
5180 let mut serialize_workspace = true;
5181 match event {
5182 pane::Event::AddItem { item } => {
5183 item.added_to_pane(self, pane.clone(), window, cx);
5184 cx.emit(Event::ItemAdded {
5185 item: item.boxed_clone(),
5186 });
5187 }
5188 pane::Event::Split { direction, mode } => {
5189 match mode {
5190 SplitMode::ClonePane => {
5191 self.split_and_clone(pane.clone(), *direction, window, cx)
5192 .detach();
5193 }
5194 SplitMode::EmptyPane => {
5195 self.split_pane(pane.clone(), *direction, window, cx);
5196 }
5197 SplitMode::MovePane => {
5198 self.split_and_move(pane.clone(), *direction, window, cx);
5199 }
5200 };
5201 }
5202 pane::Event::JoinIntoNext => {
5203 self.join_pane_into_next(pane.clone(), window, cx);
5204 }
5205 pane::Event::JoinAll => {
5206 self.join_all_panes(window, cx);
5207 }
5208 pane::Event::Remove { focus_on_pane } => {
5209 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5210 }
5211 pane::Event::ActivateItem {
5212 local,
5213 focus_changed,
5214 } => {
5215 window.invalidate_character_coordinates();
5216
5217 pane.update(cx, |pane, _| {
5218 pane.track_alternate_file_items();
5219 });
5220 if *local {
5221 self.unfollow_in_pane(pane, window, cx);
5222 }
5223 serialize_workspace = *focus_changed || pane != self.active_pane();
5224 if pane == self.active_pane() {
5225 self.active_item_path_changed(*focus_changed, window, cx);
5226 self.update_active_view_for_followers(window, cx);
5227 } else if *local {
5228 self.set_active_pane(pane, window, cx);
5229 }
5230 }
5231 pane::Event::UserSavedItem { item, save_intent } => {
5232 cx.emit(Event::UserSavedItem {
5233 pane: pane.downgrade(),
5234 item: item.boxed_clone(),
5235 save_intent: *save_intent,
5236 });
5237 serialize_workspace = false;
5238 }
5239 pane::Event::ChangeItemTitle => {
5240 if *pane == self.active_pane {
5241 self.active_item_path_changed(false, window, cx);
5242 }
5243 serialize_workspace = false;
5244 }
5245 pane::Event::RemovedItem { item } => {
5246 cx.emit(Event::ActiveItemChanged);
5247 self.update_window_edited(window, cx);
5248 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5249 && entry.get().entity_id() == pane.entity_id()
5250 {
5251 entry.remove();
5252 }
5253 cx.emit(Event::ItemRemoved {
5254 item_id: item.item_id(),
5255 });
5256 }
5257 pane::Event::Focus => {
5258 window.invalidate_character_coordinates();
5259 self.handle_pane_focused(pane.clone(), window, cx);
5260 }
5261 pane::Event::ZoomIn => {
5262 if *pane == self.active_pane {
5263 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5264 if pane.read(cx).has_focus(window, cx) {
5265 self.zoomed = Some(pane.downgrade().into());
5266 self.zoomed_position = None;
5267 cx.emit(Event::ZoomChanged);
5268 }
5269 cx.notify();
5270 }
5271 }
5272 pane::Event::ZoomOut => {
5273 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5274 if self.zoomed_position.is_none() {
5275 self.zoomed = None;
5276 cx.emit(Event::ZoomChanged);
5277 }
5278 cx.notify();
5279 }
5280 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5281 }
5282
5283 if serialize_workspace {
5284 self.serialize_workspace(window, cx);
5285 }
5286 }
5287
5288 pub fn unfollow_in_pane(
5289 &mut self,
5290 pane: &Entity<Pane>,
5291 window: &mut Window,
5292 cx: &mut Context<Workspace>,
5293 ) -> Option<CollaboratorId> {
5294 let leader_id = self.leader_for_pane(pane)?;
5295 self.unfollow(leader_id, window, cx);
5296 Some(leader_id)
5297 }
5298
5299 pub fn split_pane(
5300 &mut self,
5301 pane_to_split: Entity<Pane>,
5302 split_direction: SplitDirection,
5303 window: &mut Window,
5304 cx: &mut Context<Self>,
5305 ) -> Entity<Pane> {
5306 let new_pane = self.add_pane(window, cx);
5307 self.center
5308 .split(&pane_to_split, &new_pane, split_direction, cx);
5309 cx.notify();
5310 new_pane
5311 }
5312
5313 pub fn split_and_move(
5314 &mut self,
5315 pane: Entity<Pane>,
5316 direction: SplitDirection,
5317 window: &mut Window,
5318 cx: &mut Context<Self>,
5319 ) {
5320 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5321 return;
5322 };
5323 let new_pane = self.add_pane(window, cx);
5324 new_pane.update(cx, |pane, cx| {
5325 pane.add_item(item, true, true, None, window, cx)
5326 });
5327 self.center.split(&pane, &new_pane, direction, cx);
5328 cx.notify();
5329 }
5330
5331 pub fn split_and_clone(
5332 &mut self,
5333 pane: Entity<Pane>,
5334 direction: SplitDirection,
5335 window: &mut Window,
5336 cx: &mut Context<Self>,
5337 ) -> Task<Option<Entity<Pane>>> {
5338 let Some(item) = pane.read(cx).active_item() else {
5339 return Task::ready(None);
5340 };
5341 if !item.can_split(cx) {
5342 return Task::ready(None);
5343 }
5344 let task = item.clone_on_split(self.database_id(), window, cx);
5345 cx.spawn_in(window, async move |this, cx| {
5346 if let Some(clone) = task.await {
5347 this.update_in(cx, |this, window, cx| {
5348 let new_pane = this.add_pane(window, cx);
5349 let nav_history = pane.read(cx).fork_nav_history();
5350 new_pane.update(cx, |pane, cx| {
5351 pane.set_nav_history(nav_history, cx);
5352 pane.add_item(clone, true, true, None, window, cx)
5353 });
5354 this.center.split(&pane, &new_pane, direction, cx);
5355 cx.notify();
5356 new_pane
5357 })
5358 .ok()
5359 } else {
5360 None
5361 }
5362 })
5363 }
5364
5365 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5366 let active_item = self.active_pane.read(cx).active_item();
5367 for pane in &self.panes {
5368 join_pane_into_active(&self.active_pane, pane, window, cx);
5369 }
5370 if let Some(active_item) = active_item {
5371 self.activate_item(active_item.as_ref(), true, true, window, cx);
5372 }
5373 cx.notify();
5374 }
5375
5376 pub fn join_pane_into_next(
5377 &mut self,
5378 pane: Entity<Pane>,
5379 window: &mut Window,
5380 cx: &mut Context<Self>,
5381 ) {
5382 let next_pane = self
5383 .find_pane_in_direction(SplitDirection::Right, cx)
5384 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5385 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5386 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5387 let Some(next_pane) = next_pane else {
5388 return;
5389 };
5390 move_all_items(&pane, &next_pane, window, cx);
5391 cx.notify();
5392 }
5393
5394 fn remove_pane(
5395 &mut self,
5396 pane: Entity<Pane>,
5397 focus_on: Option<Entity<Pane>>,
5398 window: &mut Window,
5399 cx: &mut Context<Self>,
5400 ) {
5401 if self.center.remove(&pane, cx).unwrap() {
5402 self.force_remove_pane(&pane, &focus_on, window, cx);
5403 self.unfollow_in_pane(&pane, window, cx);
5404 self.last_leaders_by_pane.remove(&pane.downgrade());
5405 for removed_item in pane.read(cx).items() {
5406 self.panes_by_item.remove(&removed_item.item_id());
5407 }
5408
5409 cx.notify();
5410 } else {
5411 self.active_item_path_changed(true, window, cx);
5412 }
5413 cx.emit(Event::PaneRemoved);
5414 }
5415
5416 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5417 &mut self.panes
5418 }
5419
5420 pub fn panes(&self) -> &[Entity<Pane>] {
5421 &self.panes
5422 }
5423
5424 pub fn active_pane(&self) -> &Entity<Pane> {
5425 &self.active_pane
5426 }
5427
5428 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5429 for dock in self.all_docks() {
5430 if dock.focus_handle(cx).contains_focused(window, cx)
5431 && let Some(pane) = dock
5432 .read(cx)
5433 .active_panel()
5434 .and_then(|panel| panel.pane(cx))
5435 {
5436 return pane;
5437 }
5438 }
5439 self.active_pane().clone()
5440 }
5441
5442 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5443 self.find_pane_in_direction(SplitDirection::Right, cx)
5444 .unwrap_or_else(|| {
5445 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5446 })
5447 }
5448
5449 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5450 self.pane_for_item_id(handle.item_id())
5451 }
5452
5453 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5454 let weak_pane = self.panes_by_item.get(&item_id)?;
5455 weak_pane.upgrade()
5456 }
5457
5458 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5459 self.panes
5460 .iter()
5461 .find(|pane| pane.entity_id() == entity_id)
5462 .cloned()
5463 }
5464
5465 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5466 self.follower_states.retain(|leader_id, state| {
5467 if *leader_id == CollaboratorId::PeerId(peer_id) {
5468 for item in state.items_by_leader_view_id.values() {
5469 item.view.set_leader_id(None, window, cx);
5470 }
5471 false
5472 } else {
5473 true
5474 }
5475 });
5476 cx.notify();
5477 }
5478
5479 pub fn start_following(
5480 &mut self,
5481 leader_id: impl Into<CollaboratorId>,
5482 window: &mut Window,
5483 cx: &mut Context<Self>,
5484 ) -> Option<Task<Result<()>>> {
5485 let leader_id = leader_id.into();
5486 let pane = self.active_pane().clone();
5487
5488 self.last_leaders_by_pane
5489 .insert(pane.downgrade(), leader_id);
5490 self.unfollow(leader_id, window, cx);
5491 self.unfollow_in_pane(&pane, window, cx);
5492 self.follower_states.insert(
5493 leader_id,
5494 FollowerState {
5495 center_pane: pane.clone(),
5496 dock_pane: None,
5497 active_view_id: None,
5498 items_by_leader_view_id: Default::default(),
5499 },
5500 );
5501 cx.notify();
5502
5503 match leader_id {
5504 CollaboratorId::PeerId(leader_peer_id) => {
5505 let room_id = self.active_call()?.room_id(cx)?;
5506 let project_id = self.project.read(cx).remote_id();
5507 let request = self.app_state.client.request(proto::Follow {
5508 room_id,
5509 project_id,
5510 leader_id: Some(leader_peer_id),
5511 });
5512
5513 Some(cx.spawn_in(window, async move |this, cx| {
5514 let response = request.await?;
5515 this.update(cx, |this, _| {
5516 let state = this
5517 .follower_states
5518 .get_mut(&leader_id)
5519 .context("following interrupted")?;
5520 state.active_view_id = response
5521 .active_view
5522 .as_ref()
5523 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5524 anyhow::Ok(())
5525 })??;
5526 if let Some(view) = response.active_view {
5527 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5528 }
5529 this.update_in(cx, |this, window, cx| {
5530 this.leader_updated(leader_id, window, cx)
5531 })?;
5532 Ok(())
5533 }))
5534 }
5535 CollaboratorId::Agent => {
5536 self.leader_updated(leader_id, window, cx)?;
5537 Some(Task::ready(Ok(())))
5538 }
5539 }
5540 }
5541
5542 pub fn follow_next_collaborator(
5543 &mut self,
5544 _: &FollowNextCollaborator,
5545 window: &mut Window,
5546 cx: &mut Context<Self>,
5547 ) {
5548 let collaborators = self.project.read(cx).collaborators();
5549 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5550 let mut collaborators = collaborators.keys().copied();
5551 for peer_id in collaborators.by_ref() {
5552 if CollaboratorId::PeerId(peer_id) == leader_id {
5553 break;
5554 }
5555 }
5556 collaborators.next().map(CollaboratorId::PeerId)
5557 } else if let Some(last_leader_id) =
5558 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5559 {
5560 match last_leader_id {
5561 CollaboratorId::PeerId(peer_id) => {
5562 if collaborators.contains_key(peer_id) {
5563 Some(*last_leader_id)
5564 } else {
5565 None
5566 }
5567 }
5568 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5569 }
5570 } else {
5571 None
5572 };
5573
5574 let pane = self.active_pane.clone();
5575 let Some(leader_id) = next_leader_id.or_else(|| {
5576 Some(CollaboratorId::PeerId(
5577 collaborators.keys().copied().next()?,
5578 ))
5579 }) else {
5580 return;
5581 };
5582 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5583 return;
5584 }
5585 if let Some(task) = self.start_following(leader_id, window, cx) {
5586 task.detach_and_log_err(cx)
5587 }
5588 }
5589
5590 pub fn follow(
5591 &mut self,
5592 leader_id: impl Into<CollaboratorId>,
5593 window: &mut Window,
5594 cx: &mut Context<Self>,
5595 ) {
5596 let leader_id = leader_id.into();
5597
5598 if let CollaboratorId::PeerId(peer_id) = leader_id {
5599 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5600 return;
5601 };
5602 let Some(remote_participant) =
5603 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5604 else {
5605 return;
5606 };
5607
5608 let project = self.project.read(cx);
5609
5610 let other_project_id = match remote_participant.location {
5611 ParticipantLocation::External => None,
5612 ParticipantLocation::UnsharedProject => None,
5613 ParticipantLocation::SharedProject { project_id } => {
5614 if Some(project_id) == project.remote_id() {
5615 None
5616 } else {
5617 Some(project_id)
5618 }
5619 }
5620 };
5621
5622 // if they are active in another project, follow there.
5623 if let Some(project_id) = other_project_id {
5624 let app_state = self.app_state.clone();
5625 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5626 .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
5627 Some(format!("{error:#}"))
5628 });
5629 }
5630 }
5631
5632 // if you're already following, find the right pane and focus it.
5633 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5634 window.focus(&follower_state.pane().focus_handle(cx), cx);
5635
5636 return;
5637 }
5638
5639 // Otherwise, follow.
5640 if let Some(task) = self.start_following(leader_id, window, cx) {
5641 task.detach_and_log_err(cx)
5642 }
5643 }
5644
5645 pub fn unfollow(
5646 &mut self,
5647 leader_id: impl Into<CollaboratorId>,
5648 window: &mut Window,
5649 cx: &mut Context<Self>,
5650 ) -> Option<()> {
5651 cx.notify();
5652
5653 let leader_id = leader_id.into();
5654 let state = self.follower_states.remove(&leader_id)?;
5655 for (_, item) in state.items_by_leader_view_id {
5656 item.view.set_leader_id(None, window, cx);
5657 }
5658
5659 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5660 let project_id = self.project.read(cx).remote_id();
5661 let room_id = self.active_call()?.room_id(cx)?;
5662 self.app_state
5663 .client
5664 .send(proto::Unfollow {
5665 room_id,
5666 project_id,
5667 leader_id: Some(leader_peer_id),
5668 })
5669 .log_err();
5670 }
5671
5672 Some(())
5673 }
5674
5675 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5676 self.follower_states.contains_key(&id.into())
5677 }
5678
5679 fn active_item_path_changed(
5680 &mut self,
5681 focus_changed: bool,
5682 window: &mut Window,
5683 cx: &mut Context<Self>,
5684 ) {
5685 cx.emit(Event::ActiveItemChanged);
5686 let active_entry = self.active_project_path(cx);
5687 self.project.update(cx, |project, cx| {
5688 project.set_active_path(active_entry.clone(), cx)
5689 });
5690
5691 if focus_changed && let Some(project_path) = &active_entry {
5692 let git_store_entity = self.project.read(cx).git_store().clone();
5693 git_store_entity.update(cx, |git_store, cx| {
5694 git_store.set_active_repo_for_path(project_path, cx);
5695 });
5696 }
5697
5698 self.update_window_title(window, cx);
5699 }
5700
5701 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5702 let project = self.project().read(cx);
5703 let mut title = String::new();
5704
5705 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5706 let name = {
5707 let settings_location = SettingsLocation {
5708 worktree_id: worktree.read(cx).id(),
5709 path: RelPath::empty(),
5710 };
5711
5712 let settings = WorktreeSettings::get(Some(settings_location), cx);
5713 match &settings.project_name {
5714 Some(name) => name.as_str(),
5715 None => worktree.read(cx).root_name_str(),
5716 }
5717 };
5718 if i > 0 {
5719 title.push_str(", ");
5720 }
5721 title.push_str(name);
5722 }
5723
5724 if title.is_empty() {
5725 title = "empty project".to_string();
5726 }
5727
5728 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5729 let filename = path.path.file_name().or_else(|| {
5730 Some(
5731 project
5732 .worktree_for_id(path.worktree_id, cx)?
5733 .read(cx)
5734 .root_name_str(),
5735 )
5736 });
5737
5738 if let Some(filename) = filename {
5739 title.push_str(" — ");
5740 title.push_str(filename.as_ref());
5741 }
5742 }
5743
5744 if project.is_via_collab() {
5745 title.push_str(" ↙");
5746 } else if project.is_shared() {
5747 title.push_str(" ↗");
5748 }
5749
5750 if let Some(last_title) = self.last_window_title.as_ref()
5751 && &title == last_title
5752 {
5753 return;
5754 }
5755 window.set_window_title(&title);
5756 SystemWindowTabController::update_tab_title(
5757 cx,
5758 window.window_handle().window_id(),
5759 SharedString::from(&title),
5760 );
5761 self.last_window_title = Some(title);
5762 }
5763
5764 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5765 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5766 if is_edited != self.window_edited {
5767 self.window_edited = is_edited;
5768 window.set_window_edited(self.window_edited)
5769 }
5770 }
5771
5772 fn update_item_dirty_state(
5773 &mut self,
5774 item: &dyn ItemHandle,
5775 window: &mut Window,
5776 cx: &mut App,
5777 ) {
5778 let is_dirty = item.is_dirty(cx);
5779 let item_id = item.item_id();
5780 let was_dirty = self.dirty_items.contains_key(&item_id);
5781 if is_dirty == was_dirty {
5782 return;
5783 }
5784 if was_dirty {
5785 self.dirty_items.remove(&item_id);
5786 self.update_window_edited(window, cx);
5787 return;
5788 }
5789
5790 let workspace = self.weak_handle();
5791 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5792 return;
5793 };
5794 let on_release_callback = Box::new(move |cx: &mut App| {
5795 window_handle
5796 .update(cx, |_, window, cx| {
5797 workspace
5798 .update(cx, |workspace, cx| {
5799 workspace.dirty_items.remove(&item_id);
5800 workspace.update_window_edited(window, cx)
5801 })
5802 .ok();
5803 })
5804 .ok();
5805 });
5806
5807 let s = item.on_release(cx, on_release_callback);
5808 self.dirty_items.insert(item_id, s);
5809 self.update_window_edited(window, cx);
5810 }
5811
5812 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5813 if self.notifications.is_empty() {
5814 None
5815 } else {
5816 Some(
5817 div()
5818 .absolute()
5819 .right_3()
5820 .bottom_3()
5821 .w_112()
5822 .h_full()
5823 .flex()
5824 .flex_col()
5825 .justify_end()
5826 .gap_2()
5827 .children(
5828 self.notifications
5829 .iter()
5830 .map(|(_, notification)| notification.clone().into_any()),
5831 ),
5832 )
5833 }
5834 }
5835
5836 // RPC handlers
5837
5838 fn active_view_for_follower(
5839 &self,
5840 follower_project_id: Option<u64>,
5841 window: &mut Window,
5842 cx: &mut Context<Self>,
5843 ) -> Option<proto::View> {
5844 let (item, panel_id) = self.active_item_for_followers(window, cx);
5845 let item = item?;
5846 let leader_id = self
5847 .pane_for(&*item)
5848 .and_then(|pane| self.leader_for_pane(&pane));
5849 let leader_peer_id = match leader_id {
5850 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5851 Some(CollaboratorId::Agent) | None => None,
5852 };
5853
5854 let item_handle = item.to_followable_item_handle(cx)?;
5855 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5856 let variant = item_handle.to_state_proto(window, cx)?;
5857
5858 if item_handle.is_project_item(window, cx)
5859 && (follower_project_id.is_none()
5860 || follower_project_id != self.project.read(cx).remote_id())
5861 {
5862 return None;
5863 }
5864
5865 Some(proto::View {
5866 id: id.to_proto(),
5867 leader_id: leader_peer_id,
5868 variant: Some(variant),
5869 panel_id: panel_id.map(|id| id as i32),
5870 })
5871 }
5872
5873 fn handle_follow(
5874 &mut self,
5875 follower_project_id: Option<u64>,
5876 window: &mut Window,
5877 cx: &mut Context<Self>,
5878 ) -> proto::FollowResponse {
5879 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5880
5881 cx.notify();
5882 proto::FollowResponse {
5883 views: active_view.iter().cloned().collect(),
5884 active_view,
5885 }
5886 }
5887
5888 fn handle_update_followers(
5889 &mut self,
5890 leader_id: PeerId,
5891 message: proto::UpdateFollowers,
5892 _window: &mut Window,
5893 _cx: &mut Context<Self>,
5894 ) {
5895 self.leader_updates_tx
5896 .unbounded_send((leader_id, message))
5897 .ok();
5898 }
5899
5900 async fn process_leader_update(
5901 this: &WeakEntity<Self>,
5902 leader_id: PeerId,
5903 update: proto::UpdateFollowers,
5904 cx: &mut AsyncWindowContext,
5905 ) -> Result<()> {
5906 match update.variant.context("invalid update")? {
5907 proto::update_followers::Variant::CreateView(view) => {
5908 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5909 let should_add_view = this.update(cx, |this, _| {
5910 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5911 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5912 } else {
5913 anyhow::Ok(false)
5914 }
5915 })??;
5916
5917 if should_add_view {
5918 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5919 }
5920 }
5921 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5922 let should_add_view = this.update(cx, |this, _| {
5923 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5924 state.active_view_id = update_active_view
5925 .view
5926 .as_ref()
5927 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5928
5929 if state.active_view_id.is_some_and(|view_id| {
5930 !state.items_by_leader_view_id.contains_key(&view_id)
5931 }) {
5932 anyhow::Ok(true)
5933 } else {
5934 anyhow::Ok(false)
5935 }
5936 } else {
5937 anyhow::Ok(false)
5938 }
5939 })??;
5940
5941 if should_add_view && let Some(view) = update_active_view.view {
5942 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5943 }
5944 }
5945 proto::update_followers::Variant::UpdateView(update_view) => {
5946 let variant = update_view.variant.context("missing update view variant")?;
5947 let id = update_view.id.context("missing update view id")?;
5948 let mut tasks = Vec::new();
5949 this.update_in(cx, |this, window, cx| {
5950 let project = this.project.clone();
5951 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5952 let view_id = ViewId::from_proto(id.clone())?;
5953 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5954 tasks.push(item.view.apply_update_proto(
5955 &project,
5956 variant.clone(),
5957 window,
5958 cx,
5959 ));
5960 }
5961 }
5962 anyhow::Ok(())
5963 })??;
5964 try_join_all(tasks).await.log_err();
5965 }
5966 }
5967 this.update_in(cx, |this, window, cx| {
5968 this.leader_updated(leader_id, window, cx)
5969 })?;
5970 Ok(())
5971 }
5972
5973 async fn add_view_from_leader(
5974 this: WeakEntity<Self>,
5975 leader_id: PeerId,
5976 view: &proto::View,
5977 cx: &mut AsyncWindowContext,
5978 ) -> Result<()> {
5979 let this = this.upgrade().context("workspace dropped")?;
5980
5981 let Some(id) = view.id.clone() else {
5982 anyhow::bail!("no id for view");
5983 };
5984 let id = ViewId::from_proto(id)?;
5985 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5986
5987 let pane = this.update(cx, |this, _cx| {
5988 let state = this
5989 .follower_states
5990 .get(&leader_id.into())
5991 .context("stopped following")?;
5992 anyhow::Ok(state.pane().clone())
5993 })?;
5994 let existing_item = pane.update_in(cx, |pane, window, cx| {
5995 let client = this.read(cx).client().clone();
5996 pane.items().find_map(|item| {
5997 let item = item.to_followable_item_handle(cx)?;
5998 if item.remote_id(&client, window, cx) == Some(id) {
5999 Some(item)
6000 } else {
6001 None
6002 }
6003 })
6004 })?;
6005 let item = if let Some(existing_item) = existing_item {
6006 existing_item
6007 } else {
6008 let variant = view.variant.clone();
6009 anyhow::ensure!(variant.is_some(), "missing view variant");
6010
6011 let task = cx.update(|window, cx| {
6012 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
6013 })?;
6014
6015 let Some(task) = task else {
6016 anyhow::bail!(
6017 "failed to construct view from leader (maybe from a different version of zed?)"
6018 );
6019 };
6020
6021 let mut new_item = task.await?;
6022 pane.update_in(cx, |pane, window, cx| {
6023 let mut item_to_remove = None;
6024 for (ix, item) in pane.items().enumerate() {
6025 if let Some(item) = item.to_followable_item_handle(cx) {
6026 match new_item.dedup(item.as_ref(), window, cx) {
6027 Some(item::Dedup::KeepExisting) => {
6028 new_item =
6029 item.boxed_clone().to_followable_item_handle(cx).unwrap();
6030 break;
6031 }
6032 Some(item::Dedup::ReplaceExisting) => {
6033 item_to_remove = Some((ix, item.item_id()));
6034 break;
6035 }
6036 None => {}
6037 }
6038 }
6039 }
6040
6041 if let Some((ix, id)) = item_to_remove {
6042 pane.remove_item(id, false, false, window, cx);
6043 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
6044 }
6045 })?;
6046
6047 new_item
6048 };
6049
6050 this.update_in(cx, |this, window, cx| {
6051 let state = this.follower_states.get_mut(&leader_id.into())?;
6052 item.set_leader_id(Some(leader_id.into()), window, cx);
6053 state.items_by_leader_view_id.insert(
6054 id,
6055 FollowerView {
6056 view: item,
6057 location: panel_id,
6058 },
6059 );
6060
6061 Some(())
6062 })
6063 .context("no follower state")?;
6064
6065 Ok(())
6066 }
6067
6068 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6069 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
6070 return;
6071 };
6072
6073 if let Some(agent_location) = self.project.read(cx).agent_location() {
6074 let buffer_entity_id = agent_location.buffer.entity_id();
6075 let view_id = ViewId {
6076 creator: CollaboratorId::Agent,
6077 id: buffer_entity_id.as_u64(),
6078 };
6079 follower_state.active_view_id = Some(view_id);
6080
6081 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
6082 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
6083 hash_map::Entry::Vacant(entry) => {
6084 let existing_view =
6085 follower_state
6086 .center_pane
6087 .read(cx)
6088 .items()
6089 .find_map(|item| {
6090 let item = item.to_followable_item_handle(cx)?;
6091 if item.buffer_kind(cx) == ItemBufferKind::Singleton
6092 && item.project_item_model_ids(cx).as_slice()
6093 == [buffer_entity_id]
6094 {
6095 Some(item)
6096 } else {
6097 None
6098 }
6099 });
6100 let view = existing_view.or_else(|| {
6101 agent_location.buffer.upgrade().and_then(|buffer| {
6102 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
6103 registry.build_item(buffer, self.project.clone(), None, window, cx)
6104 })?
6105 .to_followable_item_handle(cx)
6106 })
6107 });
6108
6109 view.map(|view| {
6110 entry.insert(FollowerView {
6111 view,
6112 location: None,
6113 })
6114 })
6115 }
6116 };
6117
6118 if let Some(item) = item {
6119 item.view
6120 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
6121 item.view
6122 .update_agent_location(agent_location.position, window, cx);
6123 }
6124 } else {
6125 follower_state.active_view_id = None;
6126 }
6127
6128 self.leader_updated(CollaboratorId::Agent, window, cx);
6129 }
6130
6131 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
6132 let mut is_project_item = true;
6133 let mut update = proto::UpdateActiveView::default();
6134 if window.is_window_active() {
6135 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
6136
6137 if let Some(item) = active_item
6138 && item.item_focus_handle(cx).contains_focused(window, cx)
6139 {
6140 let leader_id = self
6141 .pane_for(&*item)
6142 .and_then(|pane| self.leader_for_pane(&pane));
6143 let leader_peer_id = match leader_id {
6144 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
6145 Some(CollaboratorId::Agent) | None => None,
6146 };
6147
6148 if let Some(item) = item.to_followable_item_handle(cx) {
6149 let id = item
6150 .remote_id(&self.app_state.client, window, cx)
6151 .map(|id| id.to_proto());
6152
6153 if let Some(id) = id
6154 && let Some(variant) = item.to_state_proto(window, cx)
6155 {
6156 let view = Some(proto::View {
6157 id,
6158 leader_id: leader_peer_id,
6159 variant: Some(variant),
6160 panel_id: panel_id.map(|id| id as i32),
6161 });
6162
6163 is_project_item = item.is_project_item(window, cx);
6164 update = proto::UpdateActiveView { view };
6165 };
6166 }
6167 }
6168 }
6169
6170 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
6171 if active_view_id != self.last_active_view_id.as_ref() {
6172 self.last_active_view_id = active_view_id.cloned();
6173 self.update_followers(
6174 is_project_item,
6175 proto::update_followers::Variant::UpdateActiveView(update),
6176 window,
6177 cx,
6178 );
6179 }
6180 }
6181
6182 fn active_item_for_followers(
6183 &self,
6184 window: &mut Window,
6185 cx: &mut App,
6186 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
6187 let mut active_item = None;
6188 let mut panel_id = None;
6189 for dock in self.all_docks() {
6190 if dock.focus_handle(cx).contains_focused(window, cx)
6191 && let Some(panel) = dock.read(cx).active_panel()
6192 && let Some(pane) = panel.pane(cx)
6193 && let Some(item) = pane.read(cx).active_item()
6194 {
6195 active_item = Some(item);
6196 panel_id = panel.remote_id();
6197 break;
6198 }
6199 }
6200
6201 if active_item.is_none() {
6202 active_item = self.active_pane().read(cx).active_item();
6203 }
6204 (active_item, panel_id)
6205 }
6206
6207 fn update_followers(
6208 &self,
6209 project_only: bool,
6210 update: proto::update_followers::Variant,
6211 _: &mut Window,
6212 cx: &mut App,
6213 ) -> Option<()> {
6214 // If this update only applies to for followers in the current project,
6215 // then skip it unless this project is shared. If it applies to all
6216 // followers, regardless of project, then set `project_id` to none,
6217 // indicating that it goes to all followers.
6218 let project_id = if project_only {
6219 Some(self.project.read(cx).remote_id()?)
6220 } else {
6221 None
6222 };
6223 self.app_state().workspace_store.update(cx, |store, cx| {
6224 store.update_followers(project_id, update, cx)
6225 })
6226 }
6227
6228 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6229 self.follower_states.iter().find_map(|(leader_id, state)| {
6230 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6231 Some(*leader_id)
6232 } else {
6233 None
6234 }
6235 })
6236 }
6237
6238 fn leader_updated(
6239 &mut self,
6240 leader_id: impl Into<CollaboratorId>,
6241 window: &mut Window,
6242 cx: &mut Context<Self>,
6243 ) -> Option<Box<dyn ItemHandle>> {
6244 cx.notify();
6245
6246 let leader_id = leader_id.into();
6247 let (panel_id, item) = match leader_id {
6248 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6249 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6250 };
6251
6252 let state = self.follower_states.get(&leader_id)?;
6253 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6254 let pane;
6255 if let Some(panel_id) = panel_id {
6256 pane = self
6257 .activate_panel_for_proto_id(panel_id, window, cx)?
6258 .pane(cx)?;
6259 let state = self.follower_states.get_mut(&leader_id)?;
6260 state.dock_pane = Some(pane.clone());
6261 } else {
6262 pane = state.center_pane.clone();
6263 let state = self.follower_states.get_mut(&leader_id)?;
6264 if let Some(dock_pane) = state.dock_pane.take() {
6265 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6266 }
6267 }
6268
6269 pane.update(cx, |pane, cx| {
6270 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6271 if let Some(index) = pane.index_for_item(item.as_ref()) {
6272 pane.activate_item(index, false, false, window, cx);
6273 } else {
6274 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6275 }
6276
6277 if focus_active_item {
6278 pane.focus_active_item(window, cx)
6279 }
6280 });
6281
6282 Some(item)
6283 }
6284
6285 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6286 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6287 let active_view_id = state.active_view_id?;
6288 Some(
6289 state
6290 .items_by_leader_view_id
6291 .get(&active_view_id)?
6292 .view
6293 .boxed_clone(),
6294 )
6295 }
6296
6297 fn active_item_for_peer(
6298 &self,
6299 peer_id: PeerId,
6300 window: &mut Window,
6301 cx: &mut Context<Self>,
6302 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6303 let call = self.active_call()?;
6304 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6305 let leader_in_this_app;
6306 let leader_in_this_project;
6307 match participant.location {
6308 ParticipantLocation::SharedProject { project_id } => {
6309 leader_in_this_app = true;
6310 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6311 }
6312 ParticipantLocation::UnsharedProject => {
6313 leader_in_this_app = true;
6314 leader_in_this_project = false;
6315 }
6316 ParticipantLocation::External => {
6317 leader_in_this_app = false;
6318 leader_in_this_project = false;
6319 }
6320 };
6321 let state = self.follower_states.get(&peer_id.into())?;
6322 let mut item_to_activate = None;
6323 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6324 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6325 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6326 {
6327 item_to_activate = Some((item.location, item.view.boxed_clone()));
6328 }
6329 } else if let Some(shared_screen) =
6330 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6331 {
6332 item_to_activate = Some((None, Box::new(shared_screen)));
6333 }
6334 item_to_activate
6335 }
6336
6337 fn shared_screen_for_peer(
6338 &self,
6339 peer_id: PeerId,
6340 pane: &Entity<Pane>,
6341 window: &mut Window,
6342 cx: &mut App,
6343 ) -> Option<Entity<SharedScreen>> {
6344 self.active_call()?
6345 .create_shared_screen(peer_id, pane, window, cx)
6346 }
6347
6348 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6349 if window.is_window_active() {
6350 self.update_active_view_for_followers(window, cx);
6351
6352 if let Some(database_id) = self.database_id {
6353 let db = WorkspaceDb::global(cx);
6354 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6355 .detach();
6356 }
6357 } else {
6358 for pane in &self.panes {
6359 pane.update(cx, |pane, cx| {
6360 if let Some(item) = pane.active_item() {
6361 item.workspace_deactivated(window, cx);
6362 }
6363 for item in pane.items() {
6364 if matches!(
6365 item.workspace_settings(cx).autosave,
6366 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6367 ) {
6368 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6369 .detach_and_log_err(cx);
6370 }
6371 }
6372 });
6373 }
6374 }
6375 }
6376
6377 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6378 self.active_call.as_ref().map(|(call, _)| &*call.0)
6379 }
6380
6381 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6382 self.active_call.as_ref().map(|(call, _)| call.clone())
6383 }
6384
6385 fn on_active_call_event(
6386 &mut self,
6387 event: &ActiveCallEvent,
6388 window: &mut Window,
6389 cx: &mut Context<Self>,
6390 ) {
6391 match event {
6392 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6393 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6394 self.leader_updated(participant_id, window, cx);
6395 }
6396 }
6397 }
6398
6399 pub fn database_id(&self) -> Option<WorkspaceId> {
6400 self.database_id
6401 }
6402
6403 #[cfg(any(test, feature = "test-support"))]
6404 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6405 self.database_id = Some(id);
6406 }
6407
6408 pub fn session_id(&self) -> Option<String> {
6409 self.session_id.clone()
6410 }
6411
6412 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6413 let Some(display) = window.display(cx) else {
6414 return Task::ready(());
6415 };
6416 let Ok(display_uuid) = display.uuid() else {
6417 return Task::ready(());
6418 };
6419
6420 let window_bounds = window.inner_window_bounds();
6421 let database_id = self.database_id;
6422 let has_paths = !self.root_paths(cx).is_empty();
6423 let db = WorkspaceDb::global(cx);
6424 let kvp = db::kvp::KeyValueStore::global(cx);
6425
6426 cx.background_executor().spawn(async move {
6427 if !has_paths {
6428 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6429 .await
6430 .log_err();
6431 }
6432 if let Some(database_id) = database_id {
6433 db.set_window_open_status(
6434 database_id,
6435 SerializedWindowBounds(window_bounds),
6436 display_uuid,
6437 )
6438 .await
6439 .log_err();
6440 } else {
6441 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6442 .await
6443 .log_err();
6444 }
6445 })
6446 }
6447
6448 /// Bypass the 200ms serialization throttle and write workspace state to
6449 /// the DB immediately. Returns a task the caller can await to ensure the
6450 /// write completes. Used by the quit handler so the most recent state
6451 /// isn't lost to a pending throttle timer when the process exits.
6452 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6453 self._schedule_serialize_workspace.take();
6454 self._serialize_workspace_task.take();
6455 self.bounds_save_task_queued.take();
6456
6457 let bounds_task = self.save_window_bounds(window, cx);
6458 let serialize_task = self.serialize_workspace_internal(window, cx);
6459 cx.spawn(async move |_| {
6460 bounds_task.await;
6461 serialize_task.await;
6462 })
6463 }
6464
6465 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6466 let project = self.project().read(cx);
6467 project
6468 .visible_worktrees(cx)
6469 .map(|worktree| worktree.read(cx).abs_path())
6470 .collect::<Vec<_>>()
6471 }
6472
6473 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6474 match member {
6475 Member::Axis(PaneAxis { members, .. }) => {
6476 for child in members.iter() {
6477 self.remove_panes(child.clone(), window, cx)
6478 }
6479 }
6480 Member::Pane(pane) => {
6481 self.force_remove_pane(&pane, &None, window, cx);
6482 }
6483 }
6484 }
6485
6486 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6487 self.session_id.take();
6488 self.serialize_workspace_internal(window, cx)
6489 }
6490
6491 fn force_remove_pane(
6492 &mut self,
6493 pane: &Entity<Pane>,
6494 focus_on: &Option<Entity<Pane>>,
6495 window: &mut Window,
6496 cx: &mut Context<Workspace>,
6497 ) {
6498 self.panes.retain(|p| p != pane);
6499 if let Some(focus_on) = focus_on {
6500 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6501 } else if self.active_pane() == pane {
6502 self.panes
6503 .last()
6504 .unwrap()
6505 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6506 }
6507 if self.last_active_center_pane == Some(pane.downgrade()) {
6508 self.last_active_center_pane = None;
6509 }
6510 cx.notify();
6511 }
6512
6513 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6514 if self._schedule_serialize_workspace.is_none() {
6515 self._schedule_serialize_workspace =
6516 Some(cx.spawn_in(window, async move |this, cx| {
6517 cx.background_executor()
6518 .timer(SERIALIZATION_THROTTLE_TIME)
6519 .await;
6520 this.update_in(cx, |this, window, cx| {
6521 this._serialize_workspace_task =
6522 Some(this.serialize_workspace_internal(window, cx));
6523 this._schedule_serialize_workspace.take();
6524 })
6525 .log_err();
6526 }));
6527 }
6528 }
6529
6530 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6531 let Some(database_id) = self.database_id() else {
6532 return Task::ready(());
6533 };
6534
6535 fn serialize_pane_handle(
6536 pane_handle: &Entity<Pane>,
6537 window: &mut Window,
6538 cx: &mut App,
6539 ) -> SerializedPane {
6540 let (items, active, pinned_count) = {
6541 let pane = pane_handle.read(cx);
6542 let active_item_id = pane.active_item().map(|item| item.item_id());
6543 (
6544 pane.items()
6545 .filter_map(|handle| {
6546 let handle = handle.to_serializable_item_handle(cx)?;
6547
6548 Some(SerializedItem {
6549 kind: Arc::from(handle.serialized_item_kind()),
6550 item_id: handle.item_id().as_u64(),
6551 active: Some(handle.item_id()) == active_item_id,
6552 preview: pane.is_active_preview_item(handle.item_id()),
6553 })
6554 })
6555 .collect::<Vec<_>>(),
6556 pane.has_focus(window, cx),
6557 pane.pinned_count(),
6558 )
6559 };
6560
6561 SerializedPane::new(items, active, pinned_count)
6562 }
6563
6564 fn build_serialized_pane_group(
6565 pane_group: &Member,
6566 window: &mut Window,
6567 cx: &mut App,
6568 ) -> SerializedPaneGroup {
6569 match pane_group {
6570 Member::Axis(PaneAxis {
6571 axis,
6572 members,
6573 flexes,
6574 bounding_boxes: _,
6575 }) => SerializedPaneGroup::Group {
6576 axis: SerializedAxis(*axis),
6577 children: members
6578 .iter()
6579 .map(|member| build_serialized_pane_group(member, window, cx))
6580 .collect::<Vec<_>>(),
6581 flexes: Some(flexes.lock().clone()),
6582 },
6583 Member::Pane(pane_handle) => {
6584 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6585 }
6586 }
6587 }
6588
6589 fn build_serialized_docks(
6590 this: &Workspace,
6591 window: &mut Window,
6592 cx: &mut App,
6593 ) -> DockStructure {
6594 this.capture_dock_state(window, cx)
6595 }
6596
6597 match self.workspace_location(cx) {
6598 WorkspaceLocation::Location(location, paths) => {
6599 let breakpoints = self.project.update(cx, |project, cx| {
6600 project
6601 .breakpoint_store()
6602 .read(cx)
6603 .all_source_breakpoints(cx)
6604 });
6605 let user_toolchains = self
6606 .project
6607 .read(cx)
6608 .user_toolchains(cx)
6609 .unwrap_or_default();
6610
6611 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6612 let docks = build_serialized_docks(self, window, cx);
6613 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6614
6615 let serialized_workspace = SerializedWorkspace {
6616 id: database_id,
6617 location,
6618 paths,
6619 center_group,
6620 window_bounds,
6621 display: Default::default(),
6622 docks,
6623 centered_layout: self.centered_layout,
6624 session_id: self.session_id.clone(),
6625 breakpoints,
6626 window_id: Some(window.window_handle().window_id().as_u64()),
6627 user_toolchains,
6628 };
6629
6630 let db = WorkspaceDb::global(cx);
6631 window.spawn(cx, async move |_| {
6632 db.save_workspace(serialized_workspace).await;
6633 })
6634 }
6635 WorkspaceLocation::DetachFromSession => {
6636 let window_bounds = SerializedWindowBounds(window.window_bounds());
6637 let display = window.display(cx).and_then(|d| d.uuid().ok());
6638 // Save dock state for empty local workspaces
6639 let docks = build_serialized_docks(self, window, cx);
6640 let db = WorkspaceDb::global(cx);
6641 let kvp = db::kvp::KeyValueStore::global(cx);
6642 window.spawn(cx, async move |_| {
6643 db.set_window_open_status(
6644 database_id,
6645 window_bounds,
6646 display.unwrap_or_default(),
6647 )
6648 .await
6649 .log_err();
6650 db.set_session_id(database_id, None).await.log_err();
6651 persistence::write_default_dock_state(&kvp, docks)
6652 .await
6653 .log_err();
6654 })
6655 }
6656 WorkspaceLocation::None => {
6657 // Save dock state for empty non-local workspaces
6658 let docks = build_serialized_docks(self, window, cx);
6659 let kvp = db::kvp::KeyValueStore::global(cx);
6660 window.spawn(cx, async move |_| {
6661 persistence::write_default_dock_state(&kvp, docks)
6662 .await
6663 .log_err();
6664 })
6665 }
6666 }
6667 }
6668
6669 fn has_any_items_open(&self, cx: &App) -> bool {
6670 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6671 }
6672
6673 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6674 let paths = PathList::new(&self.root_paths(cx));
6675 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6676 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6677 } else if self.project.read(cx).is_local() {
6678 if !paths.is_empty() || self.has_any_items_open(cx) {
6679 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6680 } else {
6681 WorkspaceLocation::DetachFromSession
6682 }
6683 } else {
6684 WorkspaceLocation::None
6685 }
6686 }
6687
6688 fn update_history(&self, cx: &mut App) {
6689 let Some(id) = self.database_id() else {
6690 return;
6691 };
6692 if !self.project.read(cx).is_local() {
6693 return;
6694 }
6695 if let Some(manager) = HistoryManager::global(cx) {
6696 let paths = PathList::new(&self.root_paths(cx));
6697 manager.update(cx, |this, cx| {
6698 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6699 });
6700 }
6701 }
6702
6703 async fn serialize_items(
6704 this: &WeakEntity<Self>,
6705 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6706 cx: &mut AsyncWindowContext,
6707 ) -> Result<()> {
6708 const CHUNK_SIZE: usize = 200;
6709
6710 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6711
6712 while let Some(items_received) = serializable_items.next().await {
6713 let unique_items =
6714 items_received
6715 .into_iter()
6716 .fold(HashMap::default(), |mut acc, item| {
6717 acc.entry(item.item_id()).or_insert(item);
6718 acc
6719 });
6720
6721 // We use into_iter() here so that the references to the items are moved into
6722 // the tasks and not kept alive while we're sleeping.
6723 for (_, item) in unique_items.into_iter() {
6724 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6725 item.serialize(workspace, false, window, cx)
6726 }) {
6727 cx.background_spawn(async move { task.await.log_err() })
6728 .detach();
6729 }
6730 }
6731
6732 cx.background_executor()
6733 .timer(SERIALIZATION_THROTTLE_TIME)
6734 .await;
6735 }
6736
6737 Ok(())
6738 }
6739
6740 pub(crate) fn enqueue_item_serialization(
6741 &mut self,
6742 item: Box<dyn SerializableItemHandle>,
6743 ) -> Result<()> {
6744 self.serializable_items_tx
6745 .unbounded_send(item)
6746 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6747 }
6748
6749 pub(crate) fn load_workspace(
6750 serialized_workspace: SerializedWorkspace,
6751 paths_to_open: Vec<Option<ProjectPath>>,
6752 window: &mut Window,
6753 cx: &mut Context<Workspace>,
6754 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6755 cx.spawn_in(window, async move |workspace, cx| {
6756 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6757
6758 let mut center_group = None;
6759 let mut center_items = None;
6760
6761 // Traverse the splits tree and add to things
6762 if let Some((group, active_pane, items)) = serialized_workspace
6763 .center_group
6764 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6765 .await
6766 {
6767 center_items = Some(items);
6768 center_group = Some((group, active_pane))
6769 }
6770
6771 let mut items_by_project_path = HashMap::default();
6772 let mut item_ids_by_kind = HashMap::default();
6773 let mut all_deserialized_items = Vec::default();
6774 cx.update(|_, cx| {
6775 for item in center_items.unwrap_or_default().into_iter().flatten() {
6776 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6777 item_ids_by_kind
6778 .entry(serializable_item_handle.serialized_item_kind())
6779 .or_insert(Vec::new())
6780 .push(item.item_id().as_u64() as ItemId);
6781 }
6782
6783 if let Some(project_path) = item.project_path(cx) {
6784 items_by_project_path.insert(project_path, item.clone());
6785 }
6786 all_deserialized_items.push(item);
6787 }
6788 })?;
6789
6790 let opened_items = paths_to_open
6791 .into_iter()
6792 .map(|path_to_open| {
6793 path_to_open
6794 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6795 })
6796 .collect::<Vec<_>>();
6797
6798 // Remove old panes from workspace panes list
6799 workspace.update_in(cx, |workspace, window, cx| {
6800 if let Some((center_group, active_pane)) = center_group {
6801 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6802
6803 // Swap workspace center group
6804 workspace.center = PaneGroup::with_root(center_group);
6805 workspace.center.set_is_center(true);
6806 workspace.center.mark_positions(cx);
6807
6808 if let Some(active_pane) = active_pane {
6809 workspace.set_active_pane(&active_pane, window, cx);
6810 cx.focus_self(window);
6811 } else {
6812 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6813 }
6814 }
6815
6816 let docks = serialized_workspace.docks;
6817
6818 for (dock, serialized_dock) in [
6819 (&mut workspace.right_dock, docks.right),
6820 (&mut workspace.left_dock, docks.left),
6821 (&mut workspace.bottom_dock, docks.bottom),
6822 ]
6823 .iter_mut()
6824 {
6825 dock.update(cx, |dock, cx| {
6826 dock.serialized_dock = Some(serialized_dock.clone());
6827 dock.restore_state(window, cx);
6828 });
6829 }
6830
6831 cx.notify();
6832 })?;
6833
6834 let _ = project
6835 .update(cx, |project, cx| {
6836 project
6837 .breakpoint_store()
6838 .update(cx, |breakpoint_store, cx| {
6839 breakpoint_store
6840 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6841 })
6842 })
6843 .await;
6844
6845 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6846 // after loading the items, we might have different items and in order to avoid
6847 // the database filling up, we delete items that haven't been loaded now.
6848 //
6849 // The items that have been loaded, have been saved after they've been added to the workspace.
6850 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6851 item_ids_by_kind
6852 .into_iter()
6853 .map(|(item_kind, loaded_items)| {
6854 SerializableItemRegistry::cleanup(
6855 item_kind,
6856 serialized_workspace.id,
6857 loaded_items,
6858 window,
6859 cx,
6860 )
6861 .log_err()
6862 })
6863 .collect::<Vec<_>>()
6864 })?;
6865
6866 futures::future::join_all(clean_up_tasks).await;
6867
6868 workspace
6869 .update_in(cx, |workspace, window, cx| {
6870 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6871 workspace.serialize_workspace_internal(window, cx).detach();
6872
6873 // Ensure that we mark the window as edited if we did load dirty items
6874 workspace.update_window_edited(window, cx);
6875 })
6876 .ok();
6877
6878 Ok(opened_items)
6879 })
6880 }
6881
6882 pub fn key_context(&self, cx: &App) -> KeyContext {
6883 let mut context = KeyContext::new_with_defaults();
6884 context.add("Workspace");
6885 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6886 if let Some(status) = self
6887 .debugger_provider
6888 .as_ref()
6889 .and_then(|provider| provider.active_thread_state(cx))
6890 {
6891 match status {
6892 ThreadStatus::Running | ThreadStatus::Stepping => {
6893 context.add("debugger_running");
6894 }
6895 ThreadStatus::Stopped => context.add("debugger_stopped"),
6896 ThreadStatus::Exited | ThreadStatus::Ended => {}
6897 }
6898 }
6899
6900 if self.left_dock.read(cx).is_open() {
6901 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6902 context.set("left_dock", active_panel.panel_key());
6903 }
6904 }
6905
6906 if self.right_dock.read(cx).is_open() {
6907 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6908 context.set("right_dock", active_panel.panel_key());
6909 }
6910 }
6911
6912 if self.bottom_dock.read(cx).is_open() {
6913 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6914 context.set("bottom_dock", active_panel.panel_key());
6915 }
6916 }
6917
6918 context
6919 }
6920
6921 /// Multiworkspace uses this to add workspace action handling to itself
6922 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6923 self.add_workspace_actions_listeners(div, window, cx)
6924 .on_action(cx.listener(
6925 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6926 for action in &action_sequence.0 {
6927 window.dispatch_action(action.boxed_clone(), cx);
6928 }
6929 },
6930 ))
6931 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6932 .on_action(cx.listener(Self::close_all_items_and_panes))
6933 .on_action(cx.listener(Self::close_item_in_all_panes))
6934 .on_action(cx.listener(Self::save_all))
6935 .on_action(cx.listener(Self::send_keystrokes))
6936 .on_action(cx.listener(Self::add_folder_to_project))
6937 .on_action(cx.listener(Self::follow_next_collaborator))
6938 .on_action(cx.listener(Self::activate_pane_at_index))
6939 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6940 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6941 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6942 .on_action(cx.listener(Self::toggle_theme_mode))
6943 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6944 let pane = workspace.active_pane().clone();
6945 workspace.unfollow_in_pane(&pane, window, cx);
6946 }))
6947 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6948 workspace
6949 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6950 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6951 }))
6952 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6953 workspace
6954 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6955 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6956 }))
6957 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6958 workspace
6959 .save_active_item(SaveIntent::SaveAs, window, cx)
6960 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6961 }))
6962 .on_action(
6963 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6964 workspace.activate_previous_pane(window, cx)
6965 }),
6966 )
6967 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6968 workspace.activate_next_pane(window, cx)
6969 }))
6970 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6971 workspace.activate_last_pane(window, cx)
6972 }))
6973 .on_action(
6974 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6975 workspace.activate_next_window(cx)
6976 }),
6977 )
6978 .on_action(
6979 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6980 workspace.activate_previous_window(cx)
6981 }),
6982 )
6983 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6984 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6985 }))
6986 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6987 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6988 }))
6989 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6990 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6991 }))
6992 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6993 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6994 }))
6995 .on_action(cx.listener(
6996 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6997 workspace.move_item_to_pane_in_direction(action, window, cx)
6998 },
6999 ))
7000 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
7001 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
7002 }))
7003 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
7004 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
7005 }))
7006 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
7007 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
7008 }))
7009 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
7010 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
7011 }))
7012 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
7013 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
7014 SplitDirection::Down,
7015 SplitDirection::Up,
7016 SplitDirection::Right,
7017 SplitDirection::Left,
7018 ];
7019 for dir in DIRECTION_PRIORITY {
7020 if workspace.find_pane_in_direction(dir, cx).is_some() {
7021 workspace.swap_pane_in_direction(dir, cx);
7022 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
7023 break;
7024 }
7025 }
7026 }))
7027 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
7028 workspace.move_pane_to_border(SplitDirection::Left, cx)
7029 }))
7030 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
7031 workspace.move_pane_to_border(SplitDirection::Right, cx)
7032 }))
7033 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
7034 workspace.move_pane_to_border(SplitDirection::Up, cx)
7035 }))
7036 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
7037 workspace.move_pane_to_border(SplitDirection::Down, cx)
7038 }))
7039 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
7040 this.toggle_dock(DockPosition::Left, window, cx);
7041 }))
7042 .on_action(cx.listener(
7043 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
7044 workspace.toggle_dock(DockPosition::Right, window, cx);
7045 },
7046 ))
7047 .on_action(cx.listener(
7048 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
7049 workspace.toggle_dock(DockPosition::Bottom, window, cx);
7050 },
7051 ))
7052 .on_action(cx.listener(
7053 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
7054 if !workspace.close_active_dock(window, cx) {
7055 cx.propagate();
7056 }
7057 },
7058 ))
7059 .on_action(
7060 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
7061 workspace.close_all_docks(window, cx);
7062 }),
7063 )
7064 .on_action(cx.listener(Self::toggle_all_docks))
7065 .on_action(cx.listener(
7066 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
7067 workspace.clear_all_notifications(cx);
7068 },
7069 ))
7070 .on_action(cx.listener(
7071 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
7072 workspace.clear_navigation_history(window, cx);
7073 },
7074 ))
7075 .on_action(cx.listener(
7076 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
7077 if let Some((notification_id, _)) = workspace.notifications.pop() {
7078 workspace.suppress_notification(¬ification_id, cx);
7079 }
7080 },
7081 ))
7082 .on_action(cx.listener(
7083 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
7084 workspace.show_worktree_trust_security_modal(true, window, cx);
7085 },
7086 ))
7087 .on_action(
7088 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
7089 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
7090 trusted_worktrees.update(cx, |trusted_worktrees, _| {
7091 trusted_worktrees.clear_trusted_paths()
7092 });
7093 let db = WorkspaceDb::global(cx);
7094 cx.spawn(async move |_, cx| {
7095 if db.clear_trusted_worktrees().await.log_err().is_some() {
7096 cx.update(|cx| reload(cx));
7097 }
7098 })
7099 .detach();
7100 }
7101 }),
7102 )
7103 .on_action(cx.listener(
7104 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
7105 workspace.reopen_closed_item(window, cx).detach();
7106 },
7107 ))
7108 .on_action(cx.listener(
7109 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
7110 for dock in workspace.all_docks() {
7111 if dock.focus_handle(cx).contains_focused(window, cx) {
7112 let panel = dock.read(cx).active_panel().cloned();
7113 if let Some(panel) = panel {
7114 dock.update(cx, |dock, cx| {
7115 dock.set_panel_size_state(
7116 panel.as_ref(),
7117 dock::PanelSizeState::default(),
7118 cx,
7119 );
7120 });
7121 }
7122 return;
7123 }
7124 }
7125 },
7126 ))
7127 .on_action(cx.listener(
7128 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
7129 for dock in workspace.all_docks() {
7130 let panel = dock.read(cx).visible_panel().cloned();
7131 if let Some(panel) = panel {
7132 dock.update(cx, |dock, cx| {
7133 dock.set_panel_size_state(
7134 panel.as_ref(),
7135 dock::PanelSizeState::default(),
7136 cx,
7137 );
7138 });
7139 }
7140 }
7141 },
7142 ))
7143 .on_action(cx.listener(
7144 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
7145 adjust_active_dock_size_by_px(
7146 px_with_ui_font_fallback(act.px, cx),
7147 workspace,
7148 window,
7149 cx,
7150 );
7151 },
7152 ))
7153 .on_action(cx.listener(
7154 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
7155 adjust_active_dock_size_by_px(
7156 px_with_ui_font_fallback(act.px, cx) * -1.,
7157 workspace,
7158 window,
7159 cx,
7160 );
7161 },
7162 ))
7163 .on_action(cx.listener(
7164 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
7165 adjust_open_docks_size_by_px(
7166 px_with_ui_font_fallback(act.px, cx),
7167 workspace,
7168 window,
7169 cx,
7170 );
7171 },
7172 ))
7173 .on_action(cx.listener(
7174 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
7175 adjust_open_docks_size_by_px(
7176 px_with_ui_font_fallback(act.px, cx) * -1.,
7177 workspace,
7178 window,
7179 cx,
7180 );
7181 },
7182 ))
7183 .on_action(cx.listener(Workspace::toggle_centered_layout))
7184 .on_action(cx.listener(
7185 |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
7186 if let Some(active_dock) = workspace.active_dock(window, cx) {
7187 let dock = active_dock.read(cx);
7188 if let Some(active_panel) = dock.active_panel() {
7189 if active_panel.pane(cx).is_none() {
7190 let mut recent_pane: Option<Entity<Pane>> = None;
7191 let mut recent_timestamp = 0;
7192 for pane_handle in workspace.panes() {
7193 let pane = pane_handle.read(cx);
7194 for entry in pane.activation_history() {
7195 if entry.timestamp > recent_timestamp {
7196 recent_timestamp = entry.timestamp;
7197 recent_pane = Some(pane_handle.clone());
7198 }
7199 }
7200 }
7201
7202 if let Some(pane) = recent_pane {
7203 let wrap_around = action.wrap_around;
7204 pane.update(cx, |pane, cx| {
7205 let current_index = pane.active_item_index();
7206 let items_len = pane.items_len();
7207 if items_len > 0 {
7208 let next_index = if current_index + 1 < items_len {
7209 current_index + 1
7210 } else if wrap_around {
7211 0
7212 } else {
7213 return;
7214 };
7215 pane.activate_item(
7216 next_index, false, false, window, cx,
7217 );
7218 }
7219 });
7220 return;
7221 }
7222 }
7223 }
7224 }
7225 cx.propagate();
7226 },
7227 ))
7228 .on_action(cx.listener(
7229 |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
7230 if let Some(active_dock) = workspace.active_dock(window, cx) {
7231 let dock = active_dock.read(cx);
7232 if let Some(active_panel) = dock.active_panel() {
7233 if active_panel.pane(cx).is_none() {
7234 let mut recent_pane: Option<Entity<Pane>> = None;
7235 let mut recent_timestamp = 0;
7236 for pane_handle in workspace.panes() {
7237 let pane = pane_handle.read(cx);
7238 for entry in pane.activation_history() {
7239 if entry.timestamp > recent_timestamp {
7240 recent_timestamp = entry.timestamp;
7241 recent_pane = Some(pane_handle.clone());
7242 }
7243 }
7244 }
7245
7246 if let Some(pane) = recent_pane {
7247 let wrap_around = action.wrap_around;
7248 pane.update(cx, |pane, cx| {
7249 let current_index = pane.active_item_index();
7250 let items_len = pane.items_len();
7251 if items_len > 0 {
7252 let prev_index = if current_index > 0 {
7253 current_index - 1
7254 } else if wrap_around {
7255 items_len.saturating_sub(1)
7256 } else {
7257 return;
7258 };
7259 pane.activate_item(
7260 prev_index, false, false, window, cx,
7261 );
7262 }
7263 });
7264 return;
7265 }
7266 }
7267 }
7268 }
7269 cx.propagate();
7270 },
7271 ))
7272 .on_action(cx.listener(
7273 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7274 if let Some(active_dock) = workspace.active_dock(window, cx) {
7275 let dock = active_dock.read(cx);
7276 if let Some(active_panel) = dock.active_panel() {
7277 if active_panel.pane(cx).is_none() {
7278 let active_pane = workspace.active_pane().clone();
7279 active_pane.update(cx, |pane, cx| {
7280 pane.close_active_item(action, window, cx)
7281 .detach_and_log_err(cx);
7282 });
7283 return;
7284 }
7285 }
7286 }
7287 cx.propagate();
7288 },
7289 ))
7290 .on_action(
7291 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7292 let pane = workspace.active_pane().clone();
7293 if let Some(item) = pane.read(cx).active_item() {
7294 item.toggle_read_only(window, cx);
7295 }
7296 }),
7297 )
7298 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7299 workspace.focus_center_pane(window, cx);
7300 }))
7301 .on_action(cx.listener(Workspace::cancel))
7302 }
7303
7304 #[cfg(any(test, feature = "test-support"))]
7305 pub fn set_random_database_id(&mut self) {
7306 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7307 }
7308
7309 #[cfg(any(test, feature = "test-support"))]
7310 pub(crate) fn test_new(
7311 project: Entity<Project>,
7312 window: &mut Window,
7313 cx: &mut Context<Self>,
7314 ) -> Self {
7315 use node_runtime::NodeRuntime;
7316 use session::Session;
7317
7318 let client = project.read(cx).client();
7319 let user_store = project.read(cx).user_store();
7320 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7321 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7322 window.activate_window();
7323 let app_state = Arc::new(AppState {
7324 languages: project.read(cx).languages().clone(),
7325 workspace_store,
7326 client,
7327 user_store,
7328 fs: project.read(cx).fs().clone(),
7329 build_window_options: |_, _| Default::default(),
7330 node_runtime: NodeRuntime::unavailable(),
7331 session,
7332 });
7333 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7334 workspace
7335 .active_pane
7336 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7337 workspace
7338 }
7339
7340 pub fn register_action<A: Action>(
7341 &mut self,
7342 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7343 ) -> &mut Self {
7344 let callback = Arc::new(callback);
7345
7346 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7347 let callback = callback.clone();
7348 div.on_action(cx.listener(move |workspace, event, window, cx| {
7349 (callback)(workspace, event, window, cx)
7350 }))
7351 }));
7352 self
7353 }
7354 pub fn register_action_renderer(
7355 &mut self,
7356 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7357 ) -> &mut Self {
7358 self.workspace_actions.push(Box::new(callback));
7359 self
7360 }
7361
7362 fn add_workspace_actions_listeners(
7363 &self,
7364 mut div: Div,
7365 window: &mut Window,
7366 cx: &mut Context<Self>,
7367 ) -> Div {
7368 for action in self.workspace_actions.iter() {
7369 div = (action)(div, self, window, cx)
7370 }
7371 div
7372 }
7373
7374 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7375 self.modal_layer.read(cx).has_active_modal()
7376 }
7377
7378 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7379 self.modal_layer
7380 .read(cx)
7381 .is_active_modal_command_palette(cx)
7382 }
7383
7384 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7385 self.modal_layer.read(cx).active_modal()
7386 }
7387
7388 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7389 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7390 /// If no modal is active, the new modal will be shown.
7391 ///
7392 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7393 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7394 /// will not be shown.
7395 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7396 where
7397 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7398 {
7399 self.modal_layer.update(cx, |modal_layer, cx| {
7400 modal_layer.toggle_modal(window, cx, build)
7401 })
7402 }
7403
7404 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7405 self.modal_layer
7406 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7407 }
7408
7409 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7410 self.toast_layer
7411 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7412 }
7413
7414 pub fn toggle_centered_layout(
7415 &mut self,
7416 _: &ToggleCenteredLayout,
7417 _: &mut Window,
7418 cx: &mut Context<Self>,
7419 ) {
7420 self.centered_layout = !self.centered_layout;
7421 if let Some(database_id) = self.database_id() {
7422 let db = WorkspaceDb::global(cx);
7423 let centered_layout = self.centered_layout;
7424 cx.background_spawn(async move {
7425 db.set_centered_layout(database_id, centered_layout).await
7426 })
7427 .detach_and_log_err(cx);
7428 }
7429 cx.notify();
7430 }
7431
7432 fn adjust_padding(padding: Option<f32>) -> f32 {
7433 padding
7434 .unwrap_or(CenteredPaddingSettings::default().0)
7435 .clamp(
7436 CenteredPaddingSettings::MIN_PADDING,
7437 CenteredPaddingSettings::MAX_PADDING,
7438 )
7439 }
7440
7441 fn render_dock(
7442 &self,
7443 position: DockPosition,
7444 dock: &Entity<Dock>,
7445 window: &mut Window,
7446 cx: &mut App,
7447 ) -> Option<Div> {
7448 if self.zoomed_position == Some(position) {
7449 return None;
7450 }
7451
7452 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7453 let pane = panel.pane(cx)?;
7454 let follower_states = &self.follower_states;
7455 leader_border_for_pane(follower_states, &pane, window, cx)
7456 });
7457
7458 let mut container = div()
7459 .flex()
7460 .overflow_hidden()
7461 .flex_none()
7462 .child(dock.clone())
7463 .children(leader_border);
7464
7465 // Apply sizing only when the dock is open. When closed the dock is still
7466 // included in the element tree so its focus handle remains mounted — without
7467 // this, toggle_panel_focus cannot focus the panel when the dock is closed.
7468 let dock = dock.read(cx);
7469 if let Some(panel) = dock.visible_panel() {
7470 let size_state = dock.stored_panel_size_state(panel.as_ref());
7471 if position.axis() == Axis::Horizontal {
7472 let use_flexible = panel.has_flexible_size(window, cx);
7473 let flex_grow = if use_flexible {
7474 size_state
7475 .and_then(|state| state.flex)
7476 .or_else(|| self.default_dock_flex(position))
7477 } else {
7478 None
7479 };
7480 if let Some(grow) = flex_grow {
7481 let grow = grow.max(0.001);
7482 let style = container.style();
7483 style.flex_grow = Some(grow);
7484 style.flex_shrink = Some(1.0);
7485 style.flex_basis = Some(relative(0.).into());
7486 } else {
7487 let size = size_state
7488 .and_then(|state| state.size)
7489 .unwrap_or_else(|| panel.default_size(window, cx));
7490 container = container.w(size);
7491 }
7492 } else {
7493 let size = size_state
7494 .and_then(|state| state.size)
7495 .unwrap_or_else(|| panel.default_size(window, cx));
7496 container = container.h(size);
7497 }
7498 }
7499
7500 Some(container)
7501 }
7502
7503 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7504 window
7505 .root::<MultiWorkspace>()
7506 .flatten()
7507 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7508 }
7509
7510 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7511 self.zoomed.as_ref()
7512 }
7513
7514 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7515 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7516 return;
7517 };
7518 let windows = cx.windows();
7519 let next_window =
7520 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7521 || {
7522 windows
7523 .iter()
7524 .cycle()
7525 .skip_while(|window| window.window_id() != current_window_id)
7526 .nth(1)
7527 },
7528 );
7529
7530 if let Some(window) = next_window {
7531 window
7532 .update(cx, |_, window, _| window.activate_window())
7533 .ok();
7534 }
7535 }
7536
7537 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7538 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7539 return;
7540 };
7541 let windows = cx.windows();
7542 let prev_window =
7543 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7544 || {
7545 windows
7546 .iter()
7547 .rev()
7548 .cycle()
7549 .skip_while(|window| window.window_id() != current_window_id)
7550 .nth(1)
7551 },
7552 );
7553
7554 if let Some(window) = prev_window {
7555 window
7556 .update(cx, |_, window, _| window.activate_window())
7557 .ok();
7558 }
7559 }
7560
7561 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7562 if cx.stop_active_drag(window) {
7563 } else if let Some((notification_id, _)) = self.notifications.pop() {
7564 dismiss_app_notification(¬ification_id, cx);
7565 } else {
7566 cx.propagate();
7567 }
7568 }
7569
7570 fn resize_dock(
7571 &mut self,
7572 dock_pos: DockPosition,
7573 new_size: Pixels,
7574 window: &mut Window,
7575 cx: &mut Context<Self>,
7576 ) {
7577 match dock_pos {
7578 DockPosition::Left => self.resize_left_dock(new_size, window, cx),
7579 DockPosition::Right => self.resize_right_dock(new_size, window, cx),
7580 DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
7581 }
7582 }
7583
7584 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7585 let workspace_width = self.bounds.size.width;
7586 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7587
7588 self.right_dock.read_with(cx, |right_dock, cx| {
7589 let right_dock_size = right_dock
7590 .stored_active_panel_size(window, cx)
7591 .unwrap_or(Pixels::ZERO);
7592 if right_dock_size + size > workspace_width {
7593 size = workspace_width - right_dock_size
7594 }
7595 });
7596
7597 let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
7598 self.left_dock.update(cx, |left_dock, cx| {
7599 if WorkspaceSettings::get_global(cx)
7600 .resize_all_panels_in_dock
7601 .contains(&DockPosition::Left)
7602 {
7603 left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7604 } else {
7605 left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7606 }
7607 });
7608 }
7609
7610 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7611 let workspace_width = self.bounds.size.width;
7612 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7613 self.left_dock.read_with(cx, |left_dock, cx| {
7614 let left_dock_size = left_dock
7615 .stored_active_panel_size(window, cx)
7616 .unwrap_or(Pixels::ZERO);
7617 if left_dock_size + size > workspace_width {
7618 size = workspace_width - left_dock_size
7619 }
7620 });
7621 let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
7622 self.right_dock.update(cx, |right_dock, cx| {
7623 if WorkspaceSettings::get_global(cx)
7624 .resize_all_panels_in_dock
7625 .contains(&DockPosition::Right)
7626 {
7627 right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7628 } else {
7629 right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7630 }
7631 });
7632 }
7633
7634 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7635 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7636 self.bottom_dock.update(cx, |bottom_dock, cx| {
7637 if WorkspaceSettings::get_global(cx)
7638 .resize_all_panels_in_dock
7639 .contains(&DockPosition::Bottom)
7640 {
7641 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7642 } else {
7643 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7644 }
7645 });
7646 }
7647
7648 fn toggle_edit_predictions_all_files(
7649 &mut self,
7650 _: &ToggleEditPrediction,
7651 _window: &mut Window,
7652 cx: &mut Context<Self>,
7653 ) {
7654 let fs = self.project().read(cx).fs().clone();
7655 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7656 update_settings_file(fs, cx, move |file, _| {
7657 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7658 });
7659 }
7660
7661 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7662 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7663 let next_mode = match current_mode {
7664 Some(theme_settings::ThemeAppearanceMode::Light) => {
7665 theme_settings::ThemeAppearanceMode::Dark
7666 }
7667 Some(theme_settings::ThemeAppearanceMode::Dark) => {
7668 theme_settings::ThemeAppearanceMode::Light
7669 }
7670 Some(theme_settings::ThemeAppearanceMode::System) | None => {
7671 match cx.theme().appearance() {
7672 theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
7673 theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
7674 }
7675 }
7676 };
7677
7678 let fs = self.project().read(cx).fs().clone();
7679 settings::update_settings_file(fs, cx, move |settings, _cx| {
7680 theme_settings::set_mode(settings, next_mode);
7681 });
7682 }
7683
7684 pub fn show_worktree_trust_security_modal(
7685 &mut self,
7686 toggle: bool,
7687 window: &mut Window,
7688 cx: &mut Context<Self>,
7689 ) {
7690 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7691 if toggle {
7692 security_modal.update(cx, |security_modal, cx| {
7693 security_modal.dismiss(cx);
7694 })
7695 } else {
7696 security_modal.update(cx, |security_modal, cx| {
7697 security_modal.refresh_restricted_paths(cx);
7698 });
7699 }
7700 } else {
7701 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7702 .map(|trusted_worktrees| {
7703 trusted_worktrees
7704 .read(cx)
7705 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7706 })
7707 .unwrap_or(false);
7708 if has_restricted_worktrees {
7709 let project = self.project().read(cx);
7710 let remote_host = project
7711 .remote_connection_options(cx)
7712 .map(RemoteHostLocation::from);
7713 let worktree_store = project.worktree_store().downgrade();
7714 self.toggle_modal(window, cx, |_, cx| {
7715 SecurityModal::new(worktree_store, remote_host, cx)
7716 });
7717 }
7718 }
7719 }
7720}
7721
7722pub trait AnyActiveCall {
7723 fn entity(&self) -> AnyEntity;
7724 fn is_in_room(&self, _: &App) -> bool;
7725 fn room_id(&self, _: &App) -> Option<u64>;
7726 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7727 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7728 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7729 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7730 fn is_sharing_project(&self, _: &App) -> bool;
7731 fn has_remote_participants(&self, _: &App) -> bool;
7732 fn local_participant_is_guest(&self, _: &App) -> bool;
7733 fn client(&self, _: &App) -> Arc<Client>;
7734 fn share_on_join(&self, _: &App) -> bool;
7735 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7736 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7737 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7738 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7739 fn join_project(
7740 &self,
7741 _: u64,
7742 _: Arc<LanguageRegistry>,
7743 _: Arc<dyn Fs>,
7744 _: &mut App,
7745 ) -> Task<Result<Entity<Project>>>;
7746 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7747 fn subscribe(
7748 &self,
7749 _: &mut Window,
7750 _: &mut Context<Workspace>,
7751 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7752 ) -> Subscription;
7753 fn create_shared_screen(
7754 &self,
7755 _: PeerId,
7756 _: &Entity<Pane>,
7757 _: &mut Window,
7758 _: &mut App,
7759 ) -> Option<Entity<SharedScreen>>;
7760}
7761
7762#[derive(Clone)]
7763pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7764impl Global for GlobalAnyActiveCall {}
7765
7766impl GlobalAnyActiveCall {
7767 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7768 cx.try_global()
7769 }
7770
7771 pub(crate) fn global(cx: &App) -> &Self {
7772 cx.global()
7773 }
7774}
7775
7776/// Workspace-local view of a remote participant's location.
7777#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7778pub enum ParticipantLocation {
7779 SharedProject { project_id: u64 },
7780 UnsharedProject,
7781 External,
7782}
7783
7784impl ParticipantLocation {
7785 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7786 match location
7787 .and_then(|l| l.variant)
7788 .context("participant location was not provided")?
7789 {
7790 proto::participant_location::Variant::SharedProject(project) => {
7791 Ok(Self::SharedProject {
7792 project_id: project.id,
7793 })
7794 }
7795 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7796 proto::participant_location::Variant::External(_) => Ok(Self::External),
7797 }
7798 }
7799}
7800/// Workspace-local view of a remote collaborator's state.
7801/// This is the subset of `call::RemoteParticipant` that workspace needs.
7802#[derive(Clone)]
7803pub struct RemoteCollaborator {
7804 pub user: Arc<User>,
7805 pub peer_id: PeerId,
7806 pub location: ParticipantLocation,
7807 pub participant_index: ParticipantIndex,
7808}
7809
7810pub enum ActiveCallEvent {
7811 ParticipantLocationChanged { participant_id: PeerId },
7812 RemoteVideoTracksChanged { participant_id: PeerId },
7813}
7814
7815fn leader_border_for_pane(
7816 follower_states: &HashMap<CollaboratorId, FollowerState>,
7817 pane: &Entity<Pane>,
7818 _: &Window,
7819 cx: &App,
7820) -> Option<Div> {
7821 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7822 if state.pane() == pane {
7823 Some((*leader_id, state))
7824 } else {
7825 None
7826 }
7827 })?;
7828
7829 let mut leader_color = match leader_id {
7830 CollaboratorId::PeerId(leader_peer_id) => {
7831 let leader = GlobalAnyActiveCall::try_global(cx)?
7832 .0
7833 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7834
7835 cx.theme()
7836 .players()
7837 .color_for_participant(leader.participant_index.0)
7838 .cursor
7839 }
7840 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7841 };
7842 leader_color.fade_out(0.3);
7843 Some(
7844 div()
7845 .absolute()
7846 .size_full()
7847 .left_0()
7848 .top_0()
7849 .border_2()
7850 .border_color(leader_color),
7851 )
7852}
7853
7854fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7855 ZED_WINDOW_POSITION
7856 .zip(*ZED_WINDOW_SIZE)
7857 .map(|(position, size)| Bounds {
7858 origin: position,
7859 size,
7860 })
7861}
7862
7863fn open_items(
7864 serialized_workspace: Option<SerializedWorkspace>,
7865 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7866 window: &mut Window,
7867 cx: &mut Context<Workspace>,
7868) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7869 let restored_items = serialized_workspace.map(|serialized_workspace| {
7870 Workspace::load_workspace(
7871 serialized_workspace,
7872 project_paths_to_open
7873 .iter()
7874 .map(|(_, project_path)| project_path)
7875 .cloned()
7876 .collect(),
7877 window,
7878 cx,
7879 )
7880 });
7881
7882 cx.spawn_in(window, async move |workspace, cx| {
7883 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7884
7885 if let Some(restored_items) = restored_items {
7886 let restored_items = restored_items.await?;
7887
7888 let restored_project_paths = restored_items
7889 .iter()
7890 .filter_map(|item| {
7891 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7892 .ok()
7893 .flatten()
7894 })
7895 .collect::<HashSet<_>>();
7896
7897 for restored_item in restored_items {
7898 opened_items.push(restored_item.map(Ok));
7899 }
7900
7901 project_paths_to_open
7902 .iter_mut()
7903 .for_each(|(_, project_path)| {
7904 if let Some(project_path_to_open) = project_path
7905 && restored_project_paths.contains(project_path_to_open)
7906 {
7907 *project_path = None;
7908 }
7909 });
7910 } else {
7911 for _ in 0..project_paths_to_open.len() {
7912 opened_items.push(None);
7913 }
7914 }
7915 assert!(opened_items.len() == project_paths_to_open.len());
7916
7917 let tasks =
7918 project_paths_to_open
7919 .into_iter()
7920 .enumerate()
7921 .map(|(ix, (abs_path, project_path))| {
7922 let workspace = workspace.clone();
7923 cx.spawn(async move |cx| {
7924 let file_project_path = project_path?;
7925 let abs_path_task = workspace.update(cx, |workspace, cx| {
7926 workspace.project().update(cx, |project, cx| {
7927 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7928 })
7929 });
7930
7931 // We only want to open file paths here. If one of the items
7932 // here is a directory, it was already opened further above
7933 // with a `find_or_create_worktree`.
7934 if let Ok(task) = abs_path_task
7935 && task.await.is_none_or(|p| p.is_file())
7936 {
7937 return Some((
7938 ix,
7939 workspace
7940 .update_in(cx, |workspace, window, cx| {
7941 workspace.open_path(
7942 file_project_path,
7943 None,
7944 true,
7945 window,
7946 cx,
7947 )
7948 })
7949 .log_err()?
7950 .await,
7951 ));
7952 }
7953 None
7954 })
7955 });
7956
7957 let tasks = tasks.collect::<Vec<_>>();
7958
7959 let tasks = futures::future::join_all(tasks);
7960 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7961 opened_items[ix] = Some(path_open_result);
7962 }
7963
7964 Ok(opened_items)
7965 })
7966}
7967
7968#[derive(Clone)]
7969enum ActivateInDirectionTarget {
7970 Pane(Entity<Pane>),
7971 Dock(Entity<Dock>),
7972 Sidebar(FocusHandle),
7973}
7974
7975fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7976 window
7977 .update(cx, |multi_workspace, _, cx| {
7978 let workspace = multi_workspace.workspace().clone();
7979 workspace.update(cx, |workspace, cx| {
7980 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7981 struct DatabaseFailedNotification;
7982
7983 workspace.show_notification(
7984 NotificationId::unique::<DatabaseFailedNotification>(),
7985 cx,
7986 |cx| {
7987 cx.new(|cx| {
7988 MessageNotification::new("Failed to load the database file.", cx)
7989 .primary_message("File an Issue")
7990 .primary_icon(IconName::Plus)
7991 .primary_on_click(|window, cx| {
7992 window.dispatch_action(Box::new(FileBugReport), cx)
7993 })
7994 })
7995 },
7996 );
7997 }
7998 });
7999 })
8000 .log_err();
8001}
8002
8003fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
8004 if val == 0 {
8005 ThemeSettings::get_global(cx).ui_font_size(cx)
8006 } else {
8007 px(val as f32)
8008 }
8009}
8010
8011fn adjust_active_dock_size_by_px(
8012 px: Pixels,
8013 workspace: &mut Workspace,
8014 window: &mut Window,
8015 cx: &mut Context<Workspace>,
8016) {
8017 let Some(active_dock) = workspace
8018 .all_docks()
8019 .into_iter()
8020 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
8021 else {
8022 return;
8023 };
8024 let dock = active_dock.read(cx);
8025 let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
8026 return;
8027 };
8028 workspace.resize_dock(dock.position(), panel_size + px, window, cx);
8029}
8030
8031fn adjust_open_docks_size_by_px(
8032 px: Pixels,
8033 workspace: &mut Workspace,
8034 window: &mut Window,
8035 cx: &mut Context<Workspace>,
8036) {
8037 let docks = workspace
8038 .all_docks()
8039 .into_iter()
8040 .filter_map(|dock_entity| {
8041 let dock = dock_entity.read(cx);
8042 if dock.is_open() {
8043 let dock_pos = dock.position();
8044 let panel_size = workspace.dock_size(&dock, window, cx)?;
8045 Some((dock_pos, panel_size + px))
8046 } else {
8047 None
8048 }
8049 })
8050 .collect::<Vec<_>>();
8051
8052 for (position, new_size) in docks {
8053 workspace.resize_dock(position, new_size, window, cx);
8054 }
8055}
8056
8057impl Focusable for Workspace {
8058 fn focus_handle(&self, cx: &App) -> FocusHandle {
8059 self.active_pane.focus_handle(cx)
8060 }
8061}
8062
8063#[derive(Clone)]
8064struct DraggedDock(DockPosition);
8065
8066impl Render for DraggedDock {
8067 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8068 gpui::Empty
8069 }
8070}
8071
8072impl Render for Workspace {
8073 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8074 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
8075 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
8076 log::info!("Rendered first frame");
8077 }
8078
8079 let centered_layout = self.centered_layout
8080 && self.center.panes().len() == 1
8081 && self.active_item(cx).is_some();
8082 let render_padding = |size| {
8083 (size > 0.0).then(|| {
8084 div()
8085 .h_full()
8086 .w(relative(size))
8087 .bg(cx.theme().colors().editor_background)
8088 .border_color(cx.theme().colors().pane_group_border)
8089 })
8090 };
8091 let paddings = if centered_layout {
8092 let settings = WorkspaceSettings::get_global(cx).centered_layout;
8093 (
8094 render_padding(Self::adjust_padding(
8095 settings.left_padding.map(|padding| padding.0),
8096 )),
8097 render_padding(Self::adjust_padding(
8098 settings.right_padding.map(|padding| padding.0),
8099 )),
8100 )
8101 } else {
8102 (None, None)
8103 };
8104 let ui_font = theme_settings::setup_ui_font(window, cx);
8105
8106 let theme = cx.theme().clone();
8107 let colors = theme.colors();
8108 let notification_entities = self
8109 .notifications
8110 .iter()
8111 .map(|(_, notification)| notification.entity_id())
8112 .collect::<Vec<_>>();
8113 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
8114
8115 div()
8116 .relative()
8117 .size_full()
8118 .flex()
8119 .flex_col()
8120 .font(ui_font)
8121 .gap_0()
8122 .justify_start()
8123 .items_start()
8124 .text_color(colors.text)
8125 .overflow_hidden()
8126 .children(self.titlebar_item.clone())
8127 .on_modifiers_changed(move |_, _, cx| {
8128 for &id in ¬ification_entities {
8129 cx.notify(id);
8130 }
8131 })
8132 .child(
8133 div()
8134 .size_full()
8135 .relative()
8136 .flex_1()
8137 .flex()
8138 .flex_col()
8139 .child(
8140 div()
8141 .id("workspace")
8142 .bg(colors.background)
8143 .relative()
8144 .flex_1()
8145 .w_full()
8146 .flex()
8147 .flex_col()
8148 .overflow_hidden()
8149 .border_t_1()
8150 .border_b_1()
8151 .border_color(colors.border)
8152 .child({
8153 let this = cx.entity();
8154 canvas(
8155 move |bounds, window, cx| {
8156 this.update(cx, |this, cx| {
8157 let bounds_changed = this.bounds != bounds;
8158 this.bounds = bounds;
8159
8160 if bounds_changed {
8161 this.left_dock.update(cx, |dock, cx| {
8162 dock.clamp_panel_size(
8163 bounds.size.width,
8164 window,
8165 cx,
8166 )
8167 });
8168
8169 this.right_dock.update(cx, |dock, cx| {
8170 dock.clamp_panel_size(
8171 bounds.size.width,
8172 window,
8173 cx,
8174 )
8175 });
8176
8177 this.bottom_dock.update(cx, |dock, cx| {
8178 dock.clamp_panel_size(
8179 bounds.size.height,
8180 window,
8181 cx,
8182 )
8183 });
8184 }
8185 })
8186 },
8187 |_, _, _, _| {},
8188 )
8189 .absolute()
8190 .size_full()
8191 })
8192 .when(self.zoomed.is_none(), |this| {
8193 this.on_drag_move(cx.listener(
8194 move |workspace,
8195 e: &DragMoveEvent<DraggedDock>,
8196 window,
8197 cx| {
8198 if workspace.previous_dock_drag_coordinates
8199 != Some(e.event.position)
8200 {
8201 workspace.previous_dock_drag_coordinates =
8202 Some(e.event.position);
8203
8204 match e.drag(cx).0 {
8205 DockPosition::Left => {
8206 workspace.resize_left_dock(
8207 e.event.position.x
8208 - workspace.bounds.left(),
8209 window,
8210 cx,
8211 );
8212 }
8213 DockPosition::Right => {
8214 workspace.resize_right_dock(
8215 workspace.bounds.right()
8216 - e.event.position.x,
8217 window,
8218 cx,
8219 );
8220 }
8221 DockPosition::Bottom => {
8222 workspace.resize_bottom_dock(
8223 workspace.bounds.bottom()
8224 - e.event.position.y,
8225 window,
8226 cx,
8227 );
8228 }
8229 };
8230 workspace.serialize_workspace(window, cx);
8231 }
8232 },
8233 ))
8234
8235 })
8236 .child({
8237 match bottom_dock_layout {
8238 BottomDockLayout::Full => div()
8239 .flex()
8240 .flex_col()
8241 .h_full()
8242 .child(
8243 div()
8244 .flex()
8245 .flex_row()
8246 .flex_1()
8247 .overflow_hidden()
8248 .children(self.render_dock(
8249 DockPosition::Left,
8250 &self.left_dock,
8251 window,
8252 cx,
8253 ))
8254
8255 .child(
8256 div()
8257 .flex()
8258 .flex_col()
8259 .flex_1()
8260 .overflow_hidden()
8261 .child(
8262 h_flex()
8263 .flex_1()
8264 .when_some(
8265 paddings.0,
8266 |this, p| {
8267 this.child(
8268 p.border_r_1(),
8269 )
8270 },
8271 )
8272 .child(self.center.render(
8273 self.zoomed.as_ref(),
8274 &PaneRenderContext {
8275 follower_states:
8276 &self.follower_states,
8277 active_call: self.active_call(),
8278 active_pane: &self.active_pane,
8279 app_state: &self.app_state,
8280 project: &self.project,
8281 workspace: &self.weak_self,
8282 },
8283 window,
8284 cx,
8285 ))
8286 .when_some(
8287 paddings.1,
8288 |this, p| {
8289 this.child(
8290 p.border_l_1(),
8291 )
8292 },
8293 ),
8294 ),
8295 )
8296
8297 .children(self.render_dock(
8298 DockPosition::Right,
8299 &self.right_dock,
8300 window,
8301 cx,
8302 )),
8303 )
8304 .child(div().w_full().children(self.render_dock(
8305 DockPosition::Bottom,
8306 &self.bottom_dock,
8307 window,
8308 cx
8309 ))),
8310
8311 BottomDockLayout::LeftAligned => div()
8312 .flex()
8313 .flex_row()
8314 .h_full()
8315 .child(
8316 div()
8317 .flex()
8318 .flex_col()
8319 .flex_1()
8320 .h_full()
8321 .child(
8322 div()
8323 .flex()
8324 .flex_row()
8325 .flex_1()
8326 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8327
8328 .child(
8329 div()
8330 .flex()
8331 .flex_col()
8332 .flex_1()
8333 .overflow_hidden()
8334 .child(
8335 h_flex()
8336 .flex_1()
8337 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8338 .child(self.center.render(
8339 self.zoomed.as_ref(),
8340 &PaneRenderContext {
8341 follower_states:
8342 &self.follower_states,
8343 active_call: self.active_call(),
8344 active_pane: &self.active_pane,
8345 app_state: &self.app_state,
8346 project: &self.project,
8347 workspace: &self.weak_self,
8348 },
8349 window,
8350 cx,
8351 ))
8352 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8353 )
8354 )
8355
8356 )
8357 .child(
8358 div()
8359 .w_full()
8360 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8361 ),
8362 )
8363 .children(self.render_dock(
8364 DockPosition::Right,
8365 &self.right_dock,
8366 window,
8367 cx,
8368 )),
8369 BottomDockLayout::RightAligned => div()
8370 .flex()
8371 .flex_row()
8372 .h_full()
8373 .children(self.render_dock(
8374 DockPosition::Left,
8375 &self.left_dock,
8376 window,
8377 cx,
8378 ))
8379
8380 .child(
8381 div()
8382 .flex()
8383 .flex_col()
8384 .flex_1()
8385 .h_full()
8386 .child(
8387 div()
8388 .flex()
8389 .flex_row()
8390 .flex_1()
8391 .child(
8392 div()
8393 .flex()
8394 .flex_col()
8395 .flex_1()
8396 .overflow_hidden()
8397 .child(
8398 h_flex()
8399 .flex_1()
8400 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8401 .child(self.center.render(
8402 self.zoomed.as_ref(),
8403 &PaneRenderContext {
8404 follower_states:
8405 &self.follower_states,
8406 active_call: self.active_call(),
8407 active_pane: &self.active_pane,
8408 app_state: &self.app_state,
8409 project: &self.project,
8410 workspace: &self.weak_self,
8411 },
8412 window,
8413 cx,
8414 ))
8415 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8416 )
8417 )
8418
8419 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8420 )
8421 .child(
8422 div()
8423 .w_full()
8424 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8425 ),
8426 ),
8427 BottomDockLayout::Contained => div()
8428 .flex()
8429 .flex_row()
8430 .h_full()
8431 .children(self.render_dock(
8432 DockPosition::Left,
8433 &self.left_dock,
8434 window,
8435 cx,
8436 ))
8437
8438 .child(
8439 div()
8440 .flex()
8441 .flex_col()
8442 .flex_1()
8443 .overflow_hidden()
8444 .child(
8445 h_flex()
8446 .flex_1()
8447 .when_some(paddings.0, |this, p| {
8448 this.child(p.border_r_1())
8449 })
8450 .child(self.center.render(
8451 self.zoomed.as_ref(),
8452 &PaneRenderContext {
8453 follower_states:
8454 &self.follower_states,
8455 active_call: self.active_call(),
8456 active_pane: &self.active_pane,
8457 app_state: &self.app_state,
8458 project: &self.project,
8459 workspace: &self.weak_self,
8460 },
8461 window,
8462 cx,
8463 ))
8464 .when_some(paddings.1, |this, p| {
8465 this.child(p.border_l_1())
8466 }),
8467 )
8468 .children(self.render_dock(
8469 DockPosition::Bottom,
8470 &self.bottom_dock,
8471 window,
8472 cx,
8473 )),
8474 )
8475
8476 .children(self.render_dock(
8477 DockPosition::Right,
8478 &self.right_dock,
8479 window,
8480 cx,
8481 )),
8482 }
8483 })
8484 .children(self.zoomed.as_ref().and_then(|view| {
8485 let zoomed_view = view.upgrade()?;
8486 let div = div()
8487 .occlude()
8488 .absolute()
8489 .overflow_hidden()
8490 .border_color(colors.border)
8491 .bg(colors.background)
8492 .child(zoomed_view)
8493 .inset_0()
8494 .shadow_lg();
8495
8496 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8497 return Some(div);
8498 }
8499
8500 Some(match self.zoomed_position {
8501 Some(DockPosition::Left) => div.right_2().border_r_1(),
8502 Some(DockPosition::Right) => div.left_2().border_l_1(),
8503 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8504 None => {
8505 div.top_2().bottom_2().left_2().right_2().border_1()
8506 }
8507 })
8508 }))
8509 .children(self.render_notifications(window, cx)),
8510 )
8511 .when(self.status_bar_visible(cx), |parent| {
8512 parent.child(self.status_bar.clone())
8513 })
8514 .child(self.toast_layer.clone()),
8515 )
8516 }
8517}
8518
8519impl WorkspaceStore {
8520 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8521 Self {
8522 workspaces: Default::default(),
8523 _subscriptions: vec![
8524 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8525 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8526 ],
8527 client,
8528 }
8529 }
8530
8531 pub fn update_followers(
8532 &self,
8533 project_id: Option<u64>,
8534 update: proto::update_followers::Variant,
8535 cx: &App,
8536 ) -> Option<()> {
8537 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8538 let room_id = active_call.0.room_id(cx)?;
8539 self.client
8540 .send(proto::UpdateFollowers {
8541 room_id,
8542 project_id,
8543 variant: Some(update),
8544 })
8545 .log_err()
8546 }
8547
8548 pub async fn handle_follow(
8549 this: Entity<Self>,
8550 envelope: TypedEnvelope<proto::Follow>,
8551 mut cx: AsyncApp,
8552 ) -> Result<proto::FollowResponse> {
8553 this.update(&mut cx, |this, cx| {
8554 let follower = Follower {
8555 project_id: envelope.payload.project_id,
8556 peer_id: envelope.original_sender_id()?,
8557 };
8558
8559 let mut response = proto::FollowResponse::default();
8560
8561 this.workspaces.retain(|(window_handle, weak_workspace)| {
8562 let Some(workspace) = weak_workspace.upgrade() else {
8563 return false;
8564 };
8565 window_handle
8566 .update(cx, |_, window, cx| {
8567 workspace.update(cx, |workspace, cx| {
8568 let handler_response =
8569 workspace.handle_follow(follower.project_id, window, cx);
8570 if let Some(active_view) = handler_response.active_view
8571 && workspace.project.read(cx).remote_id() == follower.project_id
8572 {
8573 response.active_view = Some(active_view)
8574 }
8575 });
8576 })
8577 .is_ok()
8578 });
8579
8580 Ok(response)
8581 })
8582 }
8583
8584 async fn handle_update_followers(
8585 this: Entity<Self>,
8586 envelope: TypedEnvelope<proto::UpdateFollowers>,
8587 mut cx: AsyncApp,
8588 ) -> Result<()> {
8589 let leader_id = envelope.original_sender_id()?;
8590 let update = envelope.payload;
8591
8592 this.update(&mut cx, |this, cx| {
8593 this.workspaces.retain(|(window_handle, weak_workspace)| {
8594 let Some(workspace) = weak_workspace.upgrade() else {
8595 return false;
8596 };
8597 window_handle
8598 .update(cx, |_, window, cx| {
8599 workspace.update(cx, |workspace, cx| {
8600 let project_id = workspace.project.read(cx).remote_id();
8601 if update.project_id != project_id && update.project_id.is_some() {
8602 return;
8603 }
8604 workspace.handle_update_followers(
8605 leader_id,
8606 update.clone(),
8607 window,
8608 cx,
8609 );
8610 });
8611 })
8612 .is_ok()
8613 });
8614 Ok(())
8615 })
8616 }
8617
8618 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8619 self.workspaces.iter().map(|(_, weak)| weak)
8620 }
8621
8622 pub fn workspaces_with_windows(
8623 &self,
8624 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8625 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8626 }
8627}
8628
8629impl ViewId {
8630 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8631 Ok(Self {
8632 creator: message
8633 .creator
8634 .map(CollaboratorId::PeerId)
8635 .context("creator is missing")?,
8636 id: message.id,
8637 })
8638 }
8639
8640 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8641 if let CollaboratorId::PeerId(peer_id) = self.creator {
8642 Some(proto::ViewId {
8643 creator: Some(peer_id),
8644 id: self.id,
8645 })
8646 } else {
8647 None
8648 }
8649 }
8650}
8651
8652impl FollowerState {
8653 fn pane(&self) -> &Entity<Pane> {
8654 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8655 }
8656}
8657
8658pub trait WorkspaceHandle {
8659 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8660}
8661
8662impl WorkspaceHandle for Entity<Workspace> {
8663 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8664 self.read(cx)
8665 .worktrees(cx)
8666 .flat_map(|worktree| {
8667 let worktree_id = worktree.read(cx).id();
8668 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8669 worktree_id,
8670 path: f.path.clone(),
8671 })
8672 })
8673 .collect::<Vec<_>>()
8674 }
8675}
8676
8677pub async fn last_opened_workspace_location(
8678 db: &WorkspaceDb,
8679 fs: &dyn fs::Fs,
8680) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8681 db.last_workspace(fs)
8682 .await
8683 .log_err()
8684 .flatten()
8685 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8686}
8687
8688pub async fn last_session_workspace_locations(
8689 db: &WorkspaceDb,
8690 last_session_id: &str,
8691 last_session_window_stack: Option<Vec<WindowId>>,
8692 fs: &dyn fs::Fs,
8693) -> Option<Vec<SessionWorkspace>> {
8694 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8695 .await
8696 .log_err()
8697}
8698
8699pub async fn restore_multiworkspace(
8700 multi_workspace: SerializedMultiWorkspace,
8701 app_state: Arc<AppState>,
8702 cx: &mut AsyncApp,
8703) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8704 let SerializedMultiWorkspace {
8705 active_workspace,
8706 state,
8707 } = multi_workspace;
8708 let MultiWorkspaceState {
8709 sidebar_open,
8710 project_group_keys,
8711 sidebar_state,
8712 ..
8713 } = state;
8714
8715 let workspace_result = if active_workspace.paths.is_empty() {
8716 cx.update(|cx| {
8717 open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx)
8718 })
8719 .await
8720 } else {
8721 cx.update(|cx| {
8722 Workspace::new_local(
8723 active_workspace.paths.paths().to_vec(),
8724 app_state.clone(),
8725 None,
8726 None,
8727 None,
8728 OpenMode::Activate,
8729 cx,
8730 )
8731 })
8732 .await
8733 .map(|result| result.window)
8734 };
8735
8736 let window_handle = match workspace_result {
8737 Ok(handle) => handle,
8738 Err(err) => {
8739 log::error!("Failed to restore active workspace: {err:#}");
8740
8741 // Try each project group's paths as a fallback.
8742 let mut fallback_handle = None;
8743 for key in &project_group_keys {
8744 let key: ProjectGroupKey = key.clone().into();
8745 let paths = key.path_list().paths().to_vec();
8746 match cx
8747 .update(|cx| {
8748 Workspace::new_local(
8749 paths,
8750 app_state.clone(),
8751 None,
8752 None,
8753 None,
8754 OpenMode::Activate,
8755 cx,
8756 )
8757 })
8758 .await
8759 {
8760 Ok(OpenResult { window, .. }) => {
8761 fallback_handle = Some(window);
8762 break;
8763 }
8764 Err(fallback_err) => {
8765 log::error!("Fallback project group also failed: {fallback_err:#}");
8766 }
8767 }
8768 }
8769
8770 fallback_handle.ok_or(err)?
8771 }
8772 };
8773
8774 if !project_group_keys.is_empty() {
8775 let fs = app_state.fs.clone();
8776
8777 // Resolve linked worktree paths to their main repo paths so
8778 // stale keys from previous sessions get normalized and deduped.
8779 let mut resolved_keys: Vec<ProjectGroupKey> = Vec::new();
8780 for key in project_group_keys.into_iter().map(ProjectGroupKey::from) {
8781 let mut resolved_paths = Vec::new();
8782 for path in key.path_list().paths() {
8783 if let Some(common_dir) =
8784 project::discover_root_repo_common_dir(path, fs.as_ref()).await
8785 {
8786 let main_path = common_dir.parent().unwrap_or(&common_dir);
8787 resolved_paths.push(main_path.to_path_buf());
8788 } else {
8789 resolved_paths.push(path.to_path_buf());
8790 }
8791 }
8792 let resolved = ProjectGroupKey::new(key.host(), PathList::new(&resolved_paths));
8793 if !resolved_keys.contains(&resolved) {
8794 resolved_keys.push(resolved);
8795 }
8796 }
8797
8798 window_handle
8799 .update(cx, |multi_workspace, _window, _cx| {
8800 multi_workspace.restore_project_group_keys(resolved_keys);
8801 })
8802 .ok();
8803 }
8804
8805 if sidebar_open {
8806 window_handle
8807 .update(cx, |multi_workspace, _, cx| {
8808 multi_workspace.open_sidebar(cx);
8809 })
8810 .ok();
8811 }
8812
8813 if let Some(sidebar_state) = sidebar_state {
8814 window_handle
8815 .update(cx, |multi_workspace, window, cx| {
8816 if let Some(sidebar) = multi_workspace.sidebar() {
8817 sidebar.restore_serialized_state(&sidebar_state, window, cx);
8818 }
8819 multi_workspace.serialize(cx);
8820 })
8821 .ok();
8822 }
8823
8824 window_handle
8825 .update(cx, |_, window, _cx| {
8826 window.activate_window();
8827 })
8828 .ok();
8829
8830 Ok(window_handle)
8831}
8832
8833actions!(
8834 collab,
8835 [
8836 /// Opens the channel notes for the current call.
8837 ///
8838 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8839 /// channel in the collab panel.
8840 ///
8841 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8842 /// can be copied via "Copy link to section" in the context menu of the channel notes
8843 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8844 OpenChannelNotes,
8845 /// Mutes your microphone.
8846 Mute,
8847 /// Deafens yourself (mute both microphone and speakers).
8848 Deafen,
8849 /// Leaves the current call.
8850 LeaveCall,
8851 /// Shares the current project with collaborators.
8852 ShareProject,
8853 /// Shares your screen with collaborators.
8854 ScreenShare,
8855 /// Copies the current room name and session id for debugging purposes.
8856 CopyRoomId,
8857 ]
8858);
8859
8860/// Opens the channel notes for a specific channel by its ID.
8861#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8862#[action(namespace = collab)]
8863#[serde(deny_unknown_fields)]
8864pub struct OpenChannelNotesById {
8865 pub channel_id: u64,
8866}
8867
8868actions!(
8869 zed,
8870 [
8871 /// Opens the Zed log file.
8872 OpenLog,
8873 /// Reveals the Zed log file in the system file manager.
8874 RevealLogInFileManager
8875 ]
8876);
8877
8878async fn join_channel_internal(
8879 channel_id: ChannelId,
8880 app_state: &Arc<AppState>,
8881 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8882 requesting_workspace: Option<WeakEntity<Workspace>>,
8883 active_call: &dyn AnyActiveCall,
8884 cx: &mut AsyncApp,
8885) -> Result<bool> {
8886 let (should_prompt, already_in_channel) = cx.update(|cx| {
8887 if !active_call.is_in_room(cx) {
8888 return (false, false);
8889 }
8890
8891 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8892 let should_prompt = active_call.is_sharing_project(cx)
8893 && active_call.has_remote_participants(cx)
8894 && !already_in_channel;
8895 (should_prompt, already_in_channel)
8896 });
8897
8898 if already_in_channel {
8899 let task = cx.update(|cx| {
8900 if let Some((project, host)) = active_call.most_active_project(cx) {
8901 Some(join_in_room_project(project, host, app_state.clone(), cx))
8902 } else {
8903 None
8904 }
8905 });
8906 if let Some(task) = task {
8907 task.await?;
8908 }
8909 return anyhow::Ok(true);
8910 }
8911
8912 if should_prompt {
8913 if let Some(multi_workspace) = requesting_window {
8914 let answer = multi_workspace
8915 .update(cx, |_, window, cx| {
8916 window.prompt(
8917 PromptLevel::Warning,
8918 "Do you want to switch channels?",
8919 Some("Leaving this call will unshare your current project."),
8920 &["Yes, Join Channel", "Cancel"],
8921 cx,
8922 )
8923 })?
8924 .await;
8925
8926 if answer == Ok(1) {
8927 return Ok(false);
8928 }
8929 } else {
8930 return Ok(false);
8931 }
8932 }
8933
8934 let client = cx.update(|cx| active_call.client(cx));
8935
8936 let mut client_status = client.status();
8937
8938 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8939 'outer: loop {
8940 let Some(status) = client_status.recv().await else {
8941 anyhow::bail!("error connecting");
8942 };
8943
8944 match status {
8945 Status::Connecting
8946 | Status::Authenticating
8947 | Status::Authenticated
8948 | Status::Reconnecting
8949 | Status::Reauthenticating
8950 | Status::Reauthenticated => continue,
8951 Status::Connected { .. } => break 'outer,
8952 Status::SignedOut | Status::AuthenticationError => {
8953 return Err(ErrorCode::SignedOut.into());
8954 }
8955 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8956 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8957 return Err(ErrorCode::Disconnected.into());
8958 }
8959 }
8960 }
8961
8962 let joined = cx
8963 .update(|cx| active_call.join_channel(channel_id, cx))
8964 .await?;
8965
8966 if !joined {
8967 return anyhow::Ok(true);
8968 }
8969
8970 cx.update(|cx| active_call.room_update_completed(cx)).await;
8971
8972 let task = cx.update(|cx| {
8973 if let Some((project, host)) = active_call.most_active_project(cx) {
8974 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8975 }
8976
8977 // If you are the first to join a channel, see if you should share your project.
8978 if !active_call.has_remote_participants(cx)
8979 && !active_call.local_participant_is_guest(cx)
8980 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8981 {
8982 let project = workspace.update(cx, |workspace, cx| {
8983 let project = workspace.project.read(cx);
8984
8985 if !active_call.share_on_join(cx) {
8986 return None;
8987 }
8988
8989 if (project.is_local() || project.is_via_remote_server())
8990 && project.visible_worktrees(cx).any(|tree| {
8991 tree.read(cx)
8992 .root_entry()
8993 .is_some_and(|entry| entry.is_dir())
8994 })
8995 {
8996 Some(workspace.project.clone())
8997 } else {
8998 None
8999 }
9000 });
9001 if let Some(project) = project {
9002 let share_task = active_call.share_project(project, cx);
9003 return Some(cx.spawn(async move |_cx| -> Result<()> {
9004 share_task.await?;
9005 Ok(())
9006 }));
9007 }
9008 }
9009
9010 None
9011 });
9012 if let Some(task) = task {
9013 task.await?;
9014 return anyhow::Ok(true);
9015 }
9016 anyhow::Ok(false)
9017}
9018
9019pub fn join_channel(
9020 channel_id: ChannelId,
9021 app_state: Arc<AppState>,
9022 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9023 requesting_workspace: Option<WeakEntity<Workspace>>,
9024 cx: &mut App,
9025) -> Task<Result<()>> {
9026 let active_call = GlobalAnyActiveCall::global(cx).clone();
9027 cx.spawn(async move |cx| {
9028 let result = join_channel_internal(
9029 channel_id,
9030 &app_state,
9031 requesting_window,
9032 requesting_workspace,
9033 &*active_call.0,
9034 cx,
9035 )
9036 .await;
9037
9038 // join channel succeeded, and opened a window
9039 if matches!(result, Ok(true)) {
9040 return anyhow::Ok(());
9041 }
9042
9043 // find an existing workspace to focus and show call controls
9044 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
9045 if active_window.is_none() {
9046 // no open workspaces, make one to show the error in (blergh)
9047 let OpenResult {
9048 window: window_handle,
9049 ..
9050 } = cx
9051 .update(|cx| {
9052 Workspace::new_local(
9053 vec![],
9054 app_state.clone(),
9055 requesting_window,
9056 None,
9057 None,
9058 OpenMode::Activate,
9059 cx,
9060 )
9061 })
9062 .await?;
9063
9064 window_handle
9065 .update(cx, |_, window, _cx| {
9066 window.activate_window();
9067 })
9068 .ok();
9069
9070 if result.is_ok() {
9071 cx.update(|cx| {
9072 cx.dispatch_action(&OpenChannelNotes);
9073 });
9074 }
9075
9076 active_window = Some(window_handle);
9077 }
9078
9079 if let Err(err) = result {
9080 log::error!("failed to join channel: {}", err);
9081 if let Some(active_window) = active_window {
9082 active_window
9083 .update(cx, |_, window, cx| {
9084 let detail: SharedString = match err.error_code() {
9085 ErrorCode::SignedOut => "Please sign in to continue.".into(),
9086 ErrorCode::UpgradeRequired => concat!(
9087 "Your are running an unsupported version of Zed. ",
9088 "Please update to continue."
9089 )
9090 .into(),
9091 ErrorCode::NoSuchChannel => concat!(
9092 "No matching channel was found. ",
9093 "Please check the link and try again."
9094 )
9095 .into(),
9096 ErrorCode::Forbidden => concat!(
9097 "This channel is private, and you do not have access. ",
9098 "Please ask someone to add you and try again."
9099 )
9100 .into(),
9101 ErrorCode::Disconnected => {
9102 "Please check your internet connection and try again.".into()
9103 }
9104 _ => format!("{}\n\nPlease try again.", err).into(),
9105 };
9106 window.prompt(
9107 PromptLevel::Critical,
9108 "Failed to join channel",
9109 Some(&detail),
9110 &["Ok"],
9111 cx,
9112 )
9113 })?
9114 .await
9115 .ok();
9116 }
9117 }
9118
9119 // return ok, we showed the error to the user.
9120 anyhow::Ok(())
9121 })
9122}
9123
9124pub async fn get_any_active_multi_workspace(
9125 app_state: Arc<AppState>,
9126 mut cx: AsyncApp,
9127) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
9128 // find an existing workspace to focus and show call controls
9129 let active_window = activate_any_workspace_window(&mut cx);
9130 if active_window.is_none() {
9131 cx.update(|cx| {
9132 Workspace::new_local(
9133 vec![],
9134 app_state.clone(),
9135 None,
9136 None,
9137 None,
9138 OpenMode::Activate,
9139 cx,
9140 )
9141 })
9142 .await?;
9143 }
9144 activate_any_workspace_window(&mut cx).context("could not open zed")
9145}
9146
9147fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
9148 cx.update(|cx| {
9149 if let Some(workspace_window) = cx
9150 .active_window()
9151 .and_then(|window| window.downcast::<MultiWorkspace>())
9152 {
9153 return Some(workspace_window);
9154 }
9155
9156 for window in cx.windows() {
9157 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
9158 workspace_window
9159 .update(cx, |_, window, _| window.activate_window())
9160 .ok();
9161 return Some(workspace_window);
9162 }
9163 }
9164 None
9165 })
9166}
9167
9168pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
9169 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
9170}
9171
9172pub fn workspace_windows_for_location(
9173 serialized_location: &SerializedWorkspaceLocation,
9174 cx: &App,
9175) -> Vec<WindowHandle<MultiWorkspace>> {
9176 cx.windows()
9177 .into_iter()
9178 .filter_map(|window| window.downcast::<MultiWorkspace>())
9179 .filter(|multi_workspace| {
9180 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
9181 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
9182 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
9183 }
9184 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
9185 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
9186 a.distro_name == b.distro_name
9187 }
9188 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
9189 a.container_id == b.container_id
9190 }
9191 #[cfg(any(test, feature = "test-support"))]
9192 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
9193 a.id == b.id
9194 }
9195 _ => false,
9196 };
9197
9198 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
9199 multi_workspace.workspaces().any(|workspace| {
9200 match workspace.read(cx).workspace_location(cx) {
9201 WorkspaceLocation::Location(location, _) => {
9202 match (&location, serialized_location) {
9203 (
9204 SerializedWorkspaceLocation::Local,
9205 SerializedWorkspaceLocation::Local,
9206 ) => true,
9207 (
9208 SerializedWorkspaceLocation::Remote(a),
9209 SerializedWorkspaceLocation::Remote(b),
9210 ) => same_host(a, b),
9211 _ => false,
9212 }
9213 }
9214 _ => false,
9215 }
9216 })
9217 })
9218 })
9219 .collect()
9220}
9221
9222pub async fn find_existing_workspace(
9223 abs_paths: &[PathBuf],
9224 open_options: &OpenOptions,
9225 location: &SerializedWorkspaceLocation,
9226 cx: &mut AsyncApp,
9227) -> (
9228 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
9229 OpenVisible,
9230) {
9231 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9232 let mut open_visible = OpenVisible::All;
9233 let mut best_match = None;
9234
9235 cx.update(|cx| {
9236 for window in workspace_windows_for_location(location, cx) {
9237 if let Ok(multi_workspace) = window.read(cx) {
9238 for workspace in multi_workspace.workspaces() {
9239 let project = workspace.read(cx).project.read(cx);
9240 let m = project.visibility_for_paths(
9241 abs_paths,
9242 open_options.open_new_workspace == None,
9243 cx,
9244 );
9245 if m > best_match {
9246 existing = Some((window, workspace.clone()));
9247 best_match = m;
9248 } else if best_match.is_none() && open_options.open_new_workspace == Some(false)
9249 {
9250 existing = Some((window, workspace.clone()))
9251 }
9252 }
9253 }
9254 }
9255 });
9256
9257 // With -n, only reuse a window if the path is genuinely contained
9258 // within an existing worktree (don't fall back to any arbitrary window).
9259 if open_options.open_new_workspace == Some(true) && best_match.is_none() {
9260 existing = None;
9261 }
9262
9263 if open_options.open_new_workspace != Some(true) {
9264 let all_paths_are_files = existing
9265 .as_ref()
9266 .and_then(|(_, target_workspace)| {
9267 cx.update(|cx| {
9268 let workspace = target_workspace.read(cx);
9269 let project = workspace.project.read(cx);
9270 let path_style = workspace.path_style(cx);
9271 Some(!abs_paths.iter().any(|path| {
9272 let path = util::paths::SanitizedPath::new(path);
9273 project.worktrees(cx).any(|worktree| {
9274 let worktree = worktree.read(cx);
9275 let abs_path = worktree.abs_path();
9276 path_style
9277 .strip_prefix(path.as_ref(), abs_path.as_ref())
9278 .and_then(|rel| worktree.entry_for_path(&rel))
9279 .is_some_and(|e| e.is_dir())
9280 })
9281 }))
9282 })
9283 })
9284 .unwrap_or(false);
9285
9286 if open_options.open_new_workspace.is_none()
9287 && existing.is_some()
9288 && open_options.wait
9289 && all_paths_are_files
9290 {
9291 cx.update(|cx| {
9292 let windows = workspace_windows_for_location(location, cx);
9293 let window = cx
9294 .active_window()
9295 .and_then(|window| window.downcast::<MultiWorkspace>())
9296 .filter(|window| windows.contains(window))
9297 .or_else(|| windows.into_iter().next());
9298 if let Some(window) = window {
9299 if let Ok(multi_workspace) = window.read(cx) {
9300 let active_workspace = multi_workspace.workspace().clone();
9301 existing = Some((window, active_workspace));
9302 open_visible = OpenVisible::None;
9303 }
9304 }
9305 });
9306 }
9307 }
9308 (existing, open_visible)
9309}
9310
9311#[derive(Default, Clone)]
9312pub struct OpenOptions {
9313 pub visible: Option<OpenVisible>,
9314 pub focus: Option<bool>,
9315 pub open_new_workspace: Option<bool>,
9316 pub wait: bool,
9317 pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
9318 pub open_mode: OpenMode,
9319 pub env: Option<HashMap<String, String>>,
9320 pub open_in_dev_container: bool,
9321}
9322
9323/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9324/// or [`Workspace::open_workspace_for_paths`].
9325pub struct OpenResult {
9326 pub window: WindowHandle<MultiWorkspace>,
9327 pub workspace: Entity<Workspace>,
9328 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9329}
9330
9331/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9332pub fn open_workspace_by_id(
9333 workspace_id: WorkspaceId,
9334 app_state: Arc<AppState>,
9335 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9336 cx: &mut App,
9337) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9338 let project_handle = Project::local(
9339 app_state.client.clone(),
9340 app_state.node_runtime.clone(),
9341 app_state.user_store.clone(),
9342 app_state.languages.clone(),
9343 app_state.fs.clone(),
9344 None,
9345 project::LocalProjectFlags {
9346 init_worktree_trust: true,
9347 ..project::LocalProjectFlags::default()
9348 },
9349 cx,
9350 );
9351
9352 let db = WorkspaceDb::global(cx);
9353 let kvp = db::kvp::KeyValueStore::global(cx);
9354 cx.spawn(async move |cx| {
9355 let serialized_workspace = db
9356 .workspace_for_id(workspace_id)
9357 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9358
9359 let centered_layout = serialized_workspace.centered_layout;
9360
9361 let (window, workspace) = if let Some(window) = requesting_window {
9362 let workspace = window.update(cx, |multi_workspace, window, cx| {
9363 let workspace = cx.new(|cx| {
9364 let mut workspace = Workspace::new(
9365 Some(workspace_id),
9366 project_handle.clone(),
9367 app_state.clone(),
9368 window,
9369 cx,
9370 );
9371 workspace.centered_layout = centered_layout;
9372 workspace
9373 });
9374 multi_workspace.add(workspace.clone(), &*window, cx);
9375 workspace
9376 })?;
9377 (window, workspace)
9378 } else {
9379 let window_bounds_override = window_bounds_env_override();
9380
9381 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9382 (Some(WindowBounds::Windowed(bounds)), None)
9383 } else if let Some(display) = serialized_workspace.display
9384 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9385 {
9386 (Some(bounds.0), Some(display))
9387 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9388 (Some(bounds), Some(display))
9389 } else {
9390 (None, None)
9391 };
9392
9393 let options = cx.update(|cx| {
9394 let mut options = (app_state.build_window_options)(display, cx);
9395 options.window_bounds = window_bounds;
9396 options
9397 });
9398
9399 let window = cx.open_window(options, {
9400 let app_state = app_state.clone();
9401 let project_handle = project_handle.clone();
9402 move |window, cx| {
9403 let workspace = cx.new(|cx| {
9404 let mut workspace = Workspace::new(
9405 Some(workspace_id),
9406 project_handle,
9407 app_state,
9408 window,
9409 cx,
9410 );
9411 workspace.centered_layout = centered_layout;
9412 workspace
9413 });
9414 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9415 }
9416 })?;
9417
9418 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9419 multi_workspace.workspace().clone()
9420 })?;
9421
9422 (window, workspace)
9423 };
9424
9425 notify_if_database_failed(window, cx);
9426
9427 // Restore items from the serialized workspace
9428 window
9429 .update(cx, |_, window, cx| {
9430 workspace.update(cx, |_workspace, cx| {
9431 open_items(Some(serialized_workspace), vec![], window, cx)
9432 })
9433 })?
9434 .await?;
9435
9436 window.update(cx, |_, window, cx| {
9437 workspace.update(cx, |workspace, cx| {
9438 workspace.serialize_workspace(window, cx);
9439 });
9440 })?;
9441
9442 Ok(window)
9443 })
9444}
9445
9446#[allow(clippy::type_complexity)]
9447pub fn open_paths(
9448 abs_paths: &[PathBuf],
9449 app_state: Arc<AppState>,
9450 mut open_options: OpenOptions,
9451 cx: &mut App,
9452) -> Task<anyhow::Result<OpenResult>> {
9453 let abs_paths = abs_paths.to_vec();
9454 #[cfg(target_os = "windows")]
9455 let wsl_path = abs_paths
9456 .iter()
9457 .find_map(|p| util::paths::WslPath::from_path(p));
9458
9459 cx.spawn(async move |cx| {
9460 let (mut existing, mut open_visible) = find_existing_workspace(
9461 &abs_paths,
9462 &open_options,
9463 &SerializedWorkspaceLocation::Local,
9464 cx,
9465 )
9466 .await;
9467
9468 // Fallback: if no workspace contains the paths and all paths are files,
9469 // prefer an existing local workspace window (active window first).
9470 if open_options.open_new_workspace.is_none() && existing.is_none() {
9471 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9472 let all_metadatas = futures::future::join_all(all_paths)
9473 .await
9474 .into_iter()
9475 .filter_map(|result| result.ok().flatten());
9476
9477 if all_metadatas.into_iter().all(|file| !file.is_dir) {
9478 cx.update(|cx| {
9479 let windows = workspace_windows_for_location(
9480 &SerializedWorkspaceLocation::Local,
9481 cx,
9482 );
9483 let window = cx
9484 .active_window()
9485 .and_then(|window| window.downcast::<MultiWorkspace>())
9486 .filter(|window| windows.contains(window))
9487 .or_else(|| windows.into_iter().next());
9488 if let Some(window) = window {
9489 if let Ok(multi_workspace) = window.read(cx) {
9490 let active_workspace = multi_workspace.workspace().clone();
9491 existing = Some((window, active_workspace));
9492 open_visible = OpenVisible::None;
9493 }
9494 }
9495 });
9496 }
9497 }
9498
9499 // Fallback for directories: when no flag is specified and no existing
9500 // workspace matched, add the directory as a new workspace in the
9501 // active window's MultiWorkspace (instead of opening a new window).
9502 if open_options.open_new_workspace.is_none() && existing.is_none() {
9503 let target_window = cx.update(|cx| {
9504 let windows = workspace_windows_for_location(
9505 &SerializedWorkspaceLocation::Local,
9506 cx,
9507 );
9508 let window = cx
9509 .active_window()
9510 .and_then(|window| window.downcast::<MultiWorkspace>())
9511 .filter(|window| windows.contains(window))
9512 .or_else(|| windows.into_iter().next());
9513 window.filter(|window| {
9514 window.read(cx).is_ok_and(|mw| mw.multi_workspace_enabled(cx))
9515 })
9516 });
9517
9518 if let Some(window) = target_window {
9519 open_options.requesting_window = Some(window);
9520 window
9521 .update(cx, |multi_workspace, _, cx| {
9522 multi_workspace.open_sidebar(cx);
9523 })
9524 .log_err();
9525 }
9526 }
9527
9528 let open_in_dev_container = open_options.open_in_dev_container;
9529
9530 let result = if let Some((existing, target_workspace)) = existing {
9531 let open_task = existing
9532 .update(cx, |multi_workspace, window, cx| {
9533 window.activate_window();
9534 multi_workspace.activate(target_workspace.clone(), window, cx);
9535 target_workspace.update(cx, |workspace, cx| {
9536 if open_in_dev_container {
9537 workspace.set_open_in_dev_container(true);
9538 }
9539 workspace.open_paths(
9540 abs_paths,
9541 OpenOptions {
9542 visible: Some(open_visible),
9543 ..Default::default()
9544 },
9545 None,
9546 window,
9547 cx,
9548 )
9549 })
9550 })?
9551 .await;
9552
9553 _ = existing.update(cx, |multi_workspace, _, cx| {
9554 let workspace = multi_workspace.workspace().clone();
9555 workspace.update(cx, |workspace, cx| {
9556 for item in open_task.iter().flatten() {
9557 if let Err(e) = item {
9558 workspace.show_error(&e, cx);
9559 }
9560 }
9561 });
9562 });
9563
9564 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9565 } else {
9566 let init = if open_in_dev_container {
9567 Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
9568 workspace.set_open_in_dev_container(true);
9569 }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
9570 } else {
9571 None
9572 };
9573 let result = cx
9574 .update(move |cx| {
9575 Workspace::new_local(
9576 abs_paths,
9577 app_state.clone(),
9578 open_options.requesting_window,
9579 open_options.env,
9580 init,
9581 open_options.open_mode,
9582 cx,
9583 )
9584 })
9585 .await;
9586
9587 if let Ok(ref result) = result {
9588 result.window
9589 .update(cx, |_, window, _cx| {
9590 window.activate_window();
9591 })
9592 .log_err();
9593 }
9594
9595 result
9596 };
9597
9598 #[cfg(target_os = "windows")]
9599 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9600 && let Ok(ref result) = result
9601 {
9602 result.window
9603 .update(cx, move |multi_workspace, _window, cx| {
9604 struct OpenInWsl;
9605 let workspace = multi_workspace.workspace().clone();
9606 workspace.update(cx, |workspace, cx| {
9607 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9608 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9609 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9610 cx.new(move |cx| {
9611 MessageNotification::new(msg, cx)
9612 .primary_message("Open in WSL")
9613 .primary_icon(IconName::FolderOpen)
9614 .primary_on_click(move |window, cx| {
9615 window.dispatch_action(Box::new(remote::OpenWslPath {
9616 distro: remote::WslConnectionOptions {
9617 distro_name: distro.clone(),
9618 user: None,
9619 },
9620 paths: vec![path.clone().into()],
9621 }), cx)
9622 })
9623 })
9624 });
9625 });
9626 })
9627 .unwrap();
9628 };
9629 result
9630 })
9631}
9632
9633pub fn open_new(
9634 open_options: OpenOptions,
9635 app_state: Arc<AppState>,
9636 cx: &mut App,
9637 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9638) -> Task<anyhow::Result<()>> {
9639 let addition = open_options.open_mode;
9640 let task = Workspace::new_local(
9641 Vec::new(),
9642 app_state,
9643 open_options.requesting_window,
9644 open_options.env,
9645 Some(Box::new(init)),
9646 addition,
9647 cx,
9648 );
9649 cx.spawn(async move |cx| {
9650 let OpenResult { window, .. } = task.await?;
9651 window
9652 .update(cx, |_, window, _cx| {
9653 window.activate_window();
9654 })
9655 .ok();
9656 Ok(())
9657 })
9658}
9659
9660pub fn create_and_open_local_file(
9661 path: &'static Path,
9662 window: &mut Window,
9663 cx: &mut Context<Workspace>,
9664 default_content: impl 'static + Send + FnOnce() -> Rope,
9665) -> Task<Result<Box<dyn ItemHandle>>> {
9666 cx.spawn_in(window, async move |workspace, cx| {
9667 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9668 if !fs.is_file(path).await {
9669 fs.create_file(path, Default::default()).await?;
9670 fs.save(path, &default_content(), Default::default())
9671 .await?;
9672 }
9673
9674 workspace
9675 .update_in(cx, |workspace, window, cx| {
9676 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9677 let path = workspace
9678 .project
9679 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9680 cx.spawn_in(window, async move |workspace, cx| {
9681 let path = path.await?;
9682
9683 let path = fs.canonicalize(&path).await.unwrap_or(path);
9684
9685 let mut items = workspace
9686 .update_in(cx, |workspace, window, cx| {
9687 workspace.open_paths(
9688 vec![path.to_path_buf()],
9689 OpenOptions {
9690 visible: Some(OpenVisible::None),
9691 ..Default::default()
9692 },
9693 None,
9694 window,
9695 cx,
9696 )
9697 })?
9698 .await;
9699 let item = items.pop().flatten();
9700 item.with_context(|| format!("path {path:?} is not a file"))?
9701 })
9702 })
9703 })?
9704 .await?
9705 .await
9706 })
9707}
9708
9709pub fn open_remote_project_with_new_connection(
9710 window: WindowHandle<MultiWorkspace>,
9711 remote_connection: Arc<dyn RemoteConnection>,
9712 cancel_rx: oneshot::Receiver<()>,
9713 delegate: Arc<dyn RemoteClientDelegate>,
9714 app_state: Arc<AppState>,
9715 paths: Vec<PathBuf>,
9716 cx: &mut App,
9717) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9718 cx.spawn(async move |cx| {
9719 let (workspace_id, serialized_workspace) =
9720 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9721 .await?;
9722
9723 let session = match cx
9724 .update(|cx| {
9725 remote::RemoteClient::new(
9726 ConnectionIdentifier::Workspace(workspace_id.0),
9727 remote_connection,
9728 cancel_rx,
9729 delegate,
9730 cx,
9731 )
9732 })
9733 .await?
9734 {
9735 Some(result) => result,
9736 None => return Ok(Vec::new()),
9737 };
9738
9739 let project = cx.update(|cx| {
9740 project::Project::remote(
9741 session,
9742 app_state.client.clone(),
9743 app_state.node_runtime.clone(),
9744 app_state.user_store.clone(),
9745 app_state.languages.clone(),
9746 app_state.fs.clone(),
9747 true,
9748 cx,
9749 )
9750 });
9751
9752 open_remote_project_inner(
9753 project,
9754 paths,
9755 workspace_id,
9756 serialized_workspace,
9757 app_state,
9758 window,
9759 cx,
9760 )
9761 .await
9762 })
9763}
9764
9765pub fn open_remote_project_with_existing_connection(
9766 connection_options: RemoteConnectionOptions,
9767 project: Entity<Project>,
9768 paths: Vec<PathBuf>,
9769 app_state: Arc<AppState>,
9770 window: WindowHandle<MultiWorkspace>,
9771 cx: &mut AsyncApp,
9772) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9773 cx.spawn(async move |cx| {
9774 let (workspace_id, serialized_workspace) =
9775 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9776
9777 open_remote_project_inner(
9778 project,
9779 paths,
9780 workspace_id,
9781 serialized_workspace,
9782 app_state,
9783 window,
9784 cx,
9785 )
9786 .await
9787 })
9788}
9789
9790async fn open_remote_project_inner(
9791 project: Entity<Project>,
9792 paths: Vec<PathBuf>,
9793 workspace_id: WorkspaceId,
9794 serialized_workspace: Option<SerializedWorkspace>,
9795 app_state: Arc<AppState>,
9796 window: WindowHandle<MultiWorkspace>,
9797 cx: &mut AsyncApp,
9798) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9799 let db = cx.update(|cx| WorkspaceDb::global(cx));
9800 let toolchains = db.toolchains(workspace_id).await?;
9801 for (toolchain, worktree_path, path) in toolchains {
9802 project
9803 .update(cx, |this, cx| {
9804 let Some(worktree_id) =
9805 this.find_worktree(&worktree_path, cx)
9806 .and_then(|(worktree, rel_path)| {
9807 if rel_path.is_empty() {
9808 Some(worktree.read(cx).id())
9809 } else {
9810 None
9811 }
9812 })
9813 else {
9814 return Task::ready(None);
9815 };
9816
9817 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9818 })
9819 .await;
9820 }
9821 let mut project_paths_to_open = vec![];
9822 let mut project_path_errors = vec![];
9823
9824 for path in paths {
9825 let result = cx
9826 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9827 .await;
9828 match result {
9829 Ok((_, project_path)) => {
9830 project_paths_to_open.push((path.clone(), Some(project_path)));
9831 }
9832 Err(error) => {
9833 project_path_errors.push(error);
9834 }
9835 };
9836 }
9837
9838 if project_paths_to_open.is_empty() {
9839 return Err(project_path_errors.pop().context("no paths given")?);
9840 }
9841
9842 let workspace = window.update(cx, |multi_workspace, window, cx| {
9843 telemetry::event!("SSH Project Opened");
9844
9845 let new_workspace = cx.new(|cx| {
9846 let mut workspace =
9847 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9848 workspace.update_history(cx);
9849
9850 if let Some(ref serialized) = serialized_workspace {
9851 workspace.centered_layout = serialized.centered_layout;
9852 }
9853
9854 workspace
9855 });
9856
9857 multi_workspace.activate(new_workspace.clone(), window, cx);
9858 new_workspace
9859 })?;
9860
9861 let items = window
9862 .update(cx, |_, window, cx| {
9863 window.activate_window();
9864 workspace.update(cx, |_workspace, cx| {
9865 open_items(serialized_workspace, project_paths_to_open, window, cx)
9866 })
9867 })?
9868 .await?;
9869
9870 workspace.update(cx, |workspace, cx| {
9871 for error in project_path_errors {
9872 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9873 if let Some(path) = error.error_tag("path") {
9874 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9875 }
9876 } else {
9877 workspace.show_error(&error, cx)
9878 }
9879 }
9880 });
9881
9882 Ok(items.into_iter().map(|item| item?.ok()).collect())
9883}
9884
9885fn deserialize_remote_project(
9886 connection_options: RemoteConnectionOptions,
9887 paths: Vec<PathBuf>,
9888 cx: &AsyncApp,
9889) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9890 let db = cx.update(|cx| WorkspaceDb::global(cx));
9891 cx.background_spawn(async move {
9892 let remote_connection_id = db
9893 .get_or_create_remote_connection(connection_options)
9894 .await?;
9895
9896 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9897
9898 let workspace_id = if let Some(workspace_id) =
9899 serialized_workspace.as_ref().map(|workspace| workspace.id)
9900 {
9901 workspace_id
9902 } else {
9903 db.next_id().await?
9904 };
9905
9906 Ok((workspace_id, serialized_workspace))
9907 })
9908}
9909
9910pub fn join_in_room_project(
9911 project_id: u64,
9912 follow_user_id: u64,
9913 app_state: Arc<AppState>,
9914 cx: &mut App,
9915) -> Task<Result<()>> {
9916 let windows = cx.windows();
9917 cx.spawn(async move |cx| {
9918 let existing_window_and_workspace: Option<(
9919 WindowHandle<MultiWorkspace>,
9920 Entity<Workspace>,
9921 )> = windows.into_iter().find_map(|window_handle| {
9922 window_handle
9923 .downcast::<MultiWorkspace>()
9924 .and_then(|window_handle| {
9925 window_handle
9926 .update(cx, |multi_workspace, _window, cx| {
9927 for workspace in multi_workspace.workspaces() {
9928 if workspace.read(cx).project().read(cx).remote_id()
9929 == Some(project_id)
9930 {
9931 return Some((window_handle, workspace.clone()));
9932 }
9933 }
9934 None
9935 })
9936 .unwrap_or(None)
9937 })
9938 });
9939
9940 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9941 existing_window_and_workspace
9942 {
9943 existing_window
9944 .update(cx, |multi_workspace, window, cx| {
9945 multi_workspace.activate(target_workspace, window, cx);
9946 })
9947 .ok();
9948 existing_window
9949 } else {
9950 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9951 let project = cx
9952 .update(|cx| {
9953 active_call.0.join_project(
9954 project_id,
9955 app_state.languages.clone(),
9956 app_state.fs.clone(),
9957 cx,
9958 )
9959 })
9960 .await?;
9961
9962 let window_bounds_override = window_bounds_env_override();
9963 cx.update(|cx| {
9964 let mut options = (app_state.build_window_options)(None, cx);
9965 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9966 cx.open_window(options, |window, cx| {
9967 let workspace = cx.new(|cx| {
9968 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9969 });
9970 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9971 })
9972 })?
9973 };
9974
9975 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9976 cx.activate(true);
9977 window.activate_window();
9978
9979 // We set the active workspace above, so this is the correct workspace.
9980 let workspace = multi_workspace.workspace().clone();
9981 workspace.update(cx, |workspace, cx| {
9982 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9983 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9984 .or_else(|| {
9985 // If we couldn't follow the given user, follow the host instead.
9986 let collaborator = workspace
9987 .project()
9988 .read(cx)
9989 .collaborators()
9990 .values()
9991 .find(|collaborator| collaborator.is_host)?;
9992 Some(collaborator.peer_id)
9993 });
9994
9995 if let Some(follow_peer_id) = follow_peer_id {
9996 workspace.follow(follow_peer_id, window, cx);
9997 }
9998 });
9999 })?;
10000
10001 anyhow::Ok(())
10002 })
10003}
10004
10005pub fn reload(cx: &mut App) {
10006 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
10007 let mut workspace_windows = cx
10008 .windows()
10009 .into_iter()
10010 .filter_map(|window| window.downcast::<MultiWorkspace>())
10011 .collect::<Vec<_>>();
10012
10013 // If multiple windows have unsaved changes, and need a save prompt,
10014 // prompt in the active window before switching to a different window.
10015 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
10016
10017 let mut prompt = None;
10018 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
10019 prompt = window
10020 .update(cx, |_, window, cx| {
10021 window.prompt(
10022 PromptLevel::Info,
10023 "Are you sure you want to restart?",
10024 None,
10025 &["Restart", "Cancel"],
10026 cx,
10027 )
10028 })
10029 .ok();
10030 }
10031
10032 cx.spawn(async move |cx| {
10033 if let Some(prompt) = prompt {
10034 let answer = prompt.await?;
10035 if answer != 0 {
10036 return anyhow::Ok(());
10037 }
10038 }
10039
10040 // If the user cancels any save prompt, then keep the app open.
10041 for window in workspace_windows {
10042 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
10043 let workspace = multi_workspace.workspace().clone();
10044 workspace.update(cx, |workspace, cx| {
10045 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
10046 })
10047 }) && !should_close.await?
10048 {
10049 return anyhow::Ok(());
10050 }
10051 }
10052 cx.update(|cx| cx.restart());
10053 anyhow::Ok(())
10054 })
10055 .detach_and_log_err(cx);
10056}
10057
10058fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
10059 let mut parts = value.split(',');
10060 let x: usize = parts.next()?.parse().ok()?;
10061 let y: usize = parts.next()?.parse().ok()?;
10062 Some(point(px(x as f32), px(y as f32)))
10063}
10064
10065fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
10066 let mut parts = value.split(',');
10067 let width: usize = parts.next()?.parse().ok()?;
10068 let height: usize = parts.next()?.parse().ok()?;
10069 Some(size(px(width as f32), px(height as f32)))
10070}
10071
10072/// Add client-side decorations (rounded corners, shadows, resize handling) when
10073/// appropriate.
10074///
10075/// The `border_radius_tiling` parameter allows overriding which corners get
10076/// rounded, independently of the actual window tiling state. This is used
10077/// specifically for the workspace switcher sidebar: when the sidebar is open,
10078/// we want square corners on the left (so the sidebar appears flush with the
10079/// window edge) but we still need the shadow padding for proper visual
10080/// appearance. Unlike actual window tiling, this only affects border radius -
10081/// not padding or shadows.
10082pub fn client_side_decorations(
10083 element: impl IntoElement,
10084 window: &mut Window,
10085 cx: &mut App,
10086 border_radius_tiling: Tiling,
10087) -> Stateful<Div> {
10088 const BORDER_SIZE: Pixels = px(1.0);
10089 let decorations = window.window_decorations();
10090 let tiling = match decorations {
10091 Decorations::Server => Tiling::default(),
10092 Decorations::Client { tiling } => tiling,
10093 };
10094
10095 match decorations {
10096 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
10097 Decorations::Server => window.set_client_inset(px(0.0)),
10098 }
10099
10100 struct GlobalResizeEdge(ResizeEdge);
10101 impl Global for GlobalResizeEdge {}
10102
10103 div()
10104 .id("window-backdrop")
10105 .bg(transparent_black())
10106 .map(|div| match decorations {
10107 Decorations::Server => div,
10108 Decorations::Client { .. } => div
10109 .when(
10110 !(tiling.top
10111 || tiling.right
10112 || border_radius_tiling.top
10113 || border_radius_tiling.right),
10114 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10115 )
10116 .when(
10117 !(tiling.top
10118 || tiling.left
10119 || border_radius_tiling.top
10120 || border_radius_tiling.left),
10121 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10122 )
10123 .when(
10124 !(tiling.bottom
10125 || tiling.right
10126 || border_radius_tiling.bottom
10127 || border_radius_tiling.right),
10128 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10129 )
10130 .when(
10131 !(tiling.bottom
10132 || tiling.left
10133 || border_radius_tiling.bottom
10134 || border_radius_tiling.left),
10135 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10136 )
10137 .when(!tiling.top, |div| {
10138 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10139 })
10140 .when(!tiling.bottom, |div| {
10141 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10142 })
10143 .when(!tiling.left, |div| {
10144 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10145 })
10146 .when(!tiling.right, |div| {
10147 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10148 })
10149 .on_mouse_move(move |e, window, cx| {
10150 let size = window.window_bounds().get_bounds().size;
10151 let pos = e.position;
10152
10153 let new_edge =
10154 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10155
10156 let edge = cx.try_global::<GlobalResizeEdge>();
10157 if new_edge != edge.map(|edge| edge.0) {
10158 window
10159 .window_handle()
10160 .update(cx, |workspace, _, cx| {
10161 cx.notify(workspace.entity_id());
10162 })
10163 .ok();
10164 }
10165 })
10166 .on_mouse_down(MouseButton::Left, move |e, window, _| {
10167 let size = window.window_bounds().get_bounds().size;
10168 let pos = e.position;
10169
10170 let edge = match resize_edge(
10171 pos,
10172 theme::CLIENT_SIDE_DECORATION_SHADOW,
10173 size,
10174 tiling,
10175 ) {
10176 Some(value) => value,
10177 None => return,
10178 };
10179
10180 window.start_window_resize(edge);
10181 }),
10182 })
10183 .size_full()
10184 .child(
10185 div()
10186 .cursor(CursorStyle::Arrow)
10187 .map(|div| match decorations {
10188 Decorations::Server => div,
10189 Decorations::Client { .. } => div
10190 .border_color(cx.theme().colors().border)
10191 .when(
10192 !(tiling.top
10193 || tiling.right
10194 || border_radius_tiling.top
10195 || border_radius_tiling.right),
10196 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10197 )
10198 .when(
10199 !(tiling.top
10200 || tiling.left
10201 || border_radius_tiling.top
10202 || border_radius_tiling.left),
10203 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10204 )
10205 .when(
10206 !(tiling.bottom
10207 || tiling.right
10208 || border_radius_tiling.bottom
10209 || border_radius_tiling.right),
10210 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10211 )
10212 .when(
10213 !(tiling.bottom
10214 || tiling.left
10215 || border_radius_tiling.bottom
10216 || border_radius_tiling.left),
10217 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10218 )
10219 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10220 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10221 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10222 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10223 .when(!tiling.is_tiled(), |div| {
10224 div.shadow(vec![gpui::BoxShadow {
10225 color: Hsla {
10226 h: 0.,
10227 s: 0.,
10228 l: 0.,
10229 a: 0.4,
10230 },
10231 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10232 spread_radius: px(0.),
10233 offset: point(px(0.0), px(0.0)),
10234 }])
10235 }),
10236 })
10237 .on_mouse_move(|_e, _, cx| {
10238 cx.stop_propagation();
10239 })
10240 .size_full()
10241 .child(element),
10242 )
10243 .map(|div| match decorations {
10244 Decorations::Server => div,
10245 Decorations::Client { tiling, .. } => div.child(
10246 canvas(
10247 |_bounds, window, _| {
10248 window.insert_hitbox(
10249 Bounds::new(
10250 point(px(0.0), px(0.0)),
10251 window.window_bounds().get_bounds().size,
10252 ),
10253 HitboxBehavior::Normal,
10254 )
10255 },
10256 move |_bounds, hitbox, window, cx| {
10257 let mouse = window.mouse_position();
10258 let size = window.window_bounds().get_bounds().size;
10259 let Some(edge) =
10260 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10261 else {
10262 return;
10263 };
10264 cx.set_global(GlobalResizeEdge(edge));
10265 window.set_cursor_style(
10266 match edge {
10267 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10268 ResizeEdge::Left | ResizeEdge::Right => {
10269 CursorStyle::ResizeLeftRight
10270 }
10271 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10272 CursorStyle::ResizeUpLeftDownRight
10273 }
10274 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10275 CursorStyle::ResizeUpRightDownLeft
10276 }
10277 },
10278 &hitbox,
10279 );
10280 },
10281 )
10282 .size_full()
10283 .absolute(),
10284 ),
10285 })
10286}
10287
10288fn resize_edge(
10289 pos: Point<Pixels>,
10290 shadow_size: Pixels,
10291 window_size: Size<Pixels>,
10292 tiling: Tiling,
10293) -> Option<ResizeEdge> {
10294 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10295 if bounds.contains(&pos) {
10296 return None;
10297 }
10298
10299 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10300 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10301 if !tiling.top && top_left_bounds.contains(&pos) {
10302 return Some(ResizeEdge::TopLeft);
10303 }
10304
10305 let top_right_bounds = Bounds::new(
10306 Point::new(window_size.width - corner_size.width, px(0.)),
10307 corner_size,
10308 );
10309 if !tiling.top && top_right_bounds.contains(&pos) {
10310 return Some(ResizeEdge::TopRight);
10311 }
10312
10313 let bottom_left_bounds = Bounds::new(
10314 Point::new(px(0.), window_size.height - corner_size.height),
10315 corner_size,
10316 );
10317 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10318 return Some(ResizeEdge::BottomLeft);
10319 }
10320
10321 let bottom_right_bounds = Bounds::new(
10322 Point::new(
10323 window_size.width - corner_size.width,
10324 window_size.height - corner_size.height,
10325 ),
10326 corner_size,
10327 );
10328 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10329 return Some(ResizeEdge::BottomRight);
10330 }
10331
10332 if !tiling.top && pos.y < shadow_size {
10333 Some(ResizeEdge::Top)
10334 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10335 Some(ResizeEdge::Bottom)
10336 } else if !tiling.left && pos.x < shadow_size {
10337 Some(ResizeEdge::Left)
10338 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10339 Some(ResizeEdge::Right)
10340 } else {
10341 None
10342 }
10343}
10344
10345fn join_pane_into_active(
10346 active_pane: &Entity<Pane>,
10347 pane: &Entity<Pane>,
10348 window: &mut Window,
10349 cx: &mut App,
10350) {
10351 if pane == active_pane {
10352 } else if pane.read(cx).items_len() == 0 {
10353 pane.update(cx, |_, cx| {
10354 cx.emit(pane::Event::Remove {
10355 focus_on_pane: None,
10356 });
10357 })
10358 } else {
10359 move_all_items(pane, active_pane, window, cx);
10360 }
10361}
10362
10363fn move_all_items(
10364 from_pane: &Entity<Pane>,
10365 to_pane: &Entity<Pane>,
10366 window: &mut Window,
10367 cx: &mut App,
10368) {
10369 let destination_is_different = from_pane != to_pane;
10370 let mut moved_items = 0;
10371 for (item_ix, item_handle) in from_pane
10372 .read(cx)
10373 .items()
10374 .enumerate()
10375 .map(|(ix, item)| (ix, item.clone()))
10376 .collect::<Vec<_>>()
10377 {
10378 let ix = item_ix - moved_items;
10379 if destination_is_different {
10380 // Close item from previous pane
10381 from_pane.update(cx, |source, cx| {
10382 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10383 });
10384 moved_items += 1;
10385 }
10386
10387 // This automatically removes duplicate items in the pane
10388 to_pane.update(cx, |destination, cx| {
10389 destination.add_item(item_handle, true, true, None, window, cx);
10390 window.focus(&destination.focus_handle(cx), cx)
10391 });
10392 }
10393}
10394
10395pub fn move_item(
10396 source: &Entity<Pane>,
10397 destination: &Entity<Pane>,
10398 item_id_to_move: EntityId,
10399 destination_index: usize,
10400 activate: bool,
10401 window: &mut Window,
10402 cx: &mut App,
10403) {
10404 let Some((item_ix, item_handle)) = source
10405 .read(cx)
10406 .items()
10407 .enumerate()
10408 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10409 .map(|(ix, item)| (ix, item.clone()))
10410 else {
10411 // Tab was closed during drag
10412 return;
10413 };
10414
10415 if source != destination {
10416 // Close item from previous pane
10417 source.update(cx, |source, cx| {
10418 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10419 });
10420 }
10421
10422 // This automatically removes duplicate items in the pane
10423 destination.update(cx, |destination, cx| {
10424 destination.add_item_inner(
10425 item_handle,
10426 activate,
10427 activate,
10428 activate,
10429 Some(destination_index),
10430 window,
10431 cx,
10432 );
10433 if activate {
10434 window.focus(&destination.focus_handle(cx), cx)
10435 }
10436 });
10437}
10438
10439pub fn move_active_item(
10440 source: &Entity<Pane>,
10441 destination: &Entity<Pane>,
10442 focus_destination: bool,
10443 close_if_empty: bool,
10444 window: &mut Window,
10445 cx: &mut App,
10446) {
10447 if source == destination {
10448 return;
10449 }
10450 let Some(active_item) = source.read(cx).active_item() else {
10451 return;
10452 };
10453 source.update(cx, |source_pane, cx| {
10454 let item_id = active_item.item_id();
10455 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10456 destination.update(cx, |target_pane, cx| {
10457 target_pane.add_item(
10458 active_item,
10459 focus_destination,
10460 focus_destination,
10461 Some(target_pane.items_len()),
10462 window,
10463 cx,
10464 );
10465 });
10466 });
10467}
10468
10469pub fn clone_active_item(
10470 workspace_id: Option<WorkspaceId>,
10471 source: &Entity<Pane>,
10472 destination: &Entity<Pane>,
10473 focus_destination: bool,
10474 window: &mut Window,
10475 cx: &mut App,
10476) {
10477 if source == destination {
10478 return;
10479 }
10480 let Some(active_item) = source.read(cx).active_item() else {
10481 return;
10482 };
10483 if !active_item.can_split(cx) {
10484 return;
10485 }
10486 let destination = destination.downgrade();
10487 let task = active_item.clone_on_split(workspace_id, window, cx);
10488 window
10489 .spawn(cx, async move |cx| {
10490 let Some(clone) = task.await else {
10491 return;
10492 };
10493 destination
10494 .update_in(cx, |target_pane, window, cx| {
10495 target_pane.add_item(
10496 clone,
10497 focus_destination,
10498 focus_destination,
10499 Some(target_pane.items_len()),
10500 window,
10501 cx,
10502 );
10503 })
10504 .log_err();
10505 })
10506 .detach();
10507}
10508
10509#[derive(Debug)]
10510pub struct WorkspacePosition {
10511 pub window_bounds: Option<WindowBounds>,
10512 pub display: Option<Uuid>,
10513 pub centered_layout: bool,
10514}
10515
10516pub fn remote_workspace_position_from_db(
10517 connection_options: RemoteConnectionOptions,
10518 paths_to_open: &[PathBuf],
10519 cx: &App,
10520) -> Task<Result<WorkspacePosition>> {
10521 let paths = paths_to_open.to_vec();
10522 let db = WorkspaceDb::global(cx);
10523 let kvp = db::kvp::KeyValueStore::global(cx);
10524
10525 cx.background_spawn(async move {
10526 let remote_connection_id = db
10527 .get_or_create_remote_connection(connection_options)
10528 .await
10529 .context("fetching serialized ssh project")?;
10530 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10531
10532 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10533 (Some(WindowBounds::Windowed(bounds)), None)
10534 } else {
10535 let restorable_bounds = serialized_workspace
10536 .as_ref()
10537 .and_then(|workspace| {
10538 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10539 })
10540 .or_else(|| persistence::read_default_window_bounds(&kvp));
10541
10542 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10543 (Some(serialized_bounds), Some(serialized_display))
10544 } else {
10545 (None, None)
10546 }
10547 };
10548
10549 let centered_layout = serialized_workspace
10550 .as_ref()
10551 .map(|w| w.centered_layout)
10552 .unwrap_or(false);
10553
10554 Ok(WorkspacePosition {
10555 window_bounds,
10556 display,
10557 centered_layout,
10558 })
10559 })
10560}
10561
10562pub fn with_active_or_new_workspace(
10563 cx: &mut App,
10564 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10565) {
10566 match cx
10567 .active_window()
10568 .and_then(|w| w.downcast::<MultiWorkspace>())
10569 {
10570 Some(multi_workspace) => {
10571 cx.defer(move |cx| {
10572 multi_workspace
10573 .update(cx, |multi_workspace, window, cx| {
10574 let workspace = multi_workspace.workspace().clone();
10575 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10576 })
10577 .log_err();
10578 });
10579 }
10580 None => {
10581 let app_state = AppState::global(cx);
10582 open_new(
10583 OpenOptions::default(),
10584 app_state,
10585 cx,
10586 move |workspace, window, cx| f(workspace, window, cx),
10587 )
10588 .detach_and_log_err(cx);
10589 }
10590 }
10591}
10592
10593/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10594/// key. This migration path only runs once per panel per workspace.
10595fn load_legacy_panel_size(
10596 panel_key: &str,
10597 dock_position: DockPosition,
10598 workspace: &Workspace,
10599 cx: &mut App,
10600) -> Option<Pixels> {
10601 #[derive(Deserialize)]
10602 struct LegacyPanelState {
10603 #[serde(default)]
10604 width: Option<Pixels>,
10605 #[serde(default)]
10606 height: Option<Pixels>,
10607 }
10608
10609 let workspace_id = workspace
10610 .database_id()
10611 .map(|id| i64::from(id).to_string())
10612 .or_else(|| workspace.session_id())?;
10613
10614 let legacy_key = match panel_key {
10615 "ProjectPanel" => {
10616 format!("{}-{:?}", "ProjectPanel", workspace_id)
10617 }
10618 "OutlinePanel" => {
10619 format!("{}-{:?}", "OutlinePanel", workspace_id)
10620 }
10621 "GitPanel" => {
10622 format!("{}-{:?}", "GitPanel", workspace_id)
10623 }
10624 "TerminalPanel" => {
10625 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10626 }
10627 _ => return None,
10628 };
10629
10630 let kvp = db::kvp::KeyValueStore::global(cx);
10631 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10632 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10633 let size = match dock_position {
10634 DockPosition::Bottom => state.height,
10635 DockPosition::Left | DockPosition::Right => state.width,
10636 }?;
10637
10638 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10639 .detach_and_log_err(cx);
10640
10641 Some(size)
10642}
10643
10644#[cfg(test)]
10645mod tests {
10646 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10647
10648 use super::*;
10649 use crate::{
10650 dock::{PanelEvent, test::TestPanel},
10651 item::{
10652 ItemBufferKind, ItemEvent,
10653 test::{TestItem, TestProjectItem},
10654 },
10655 };
10656 use fs::FakeFs;
10657 use gpui::{
10658 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10659 UpdateGlobal, VisualTestContext, px,
10660 };
10661 use project::{Project, ProjectEntryId};
10662 use serde_json::json;
10663 use settings::SettingsStore;
10664 use util::path;
10665 use util::rel_path::rel_path;
10666
10667 #[gpui::test]
10668 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10669 init_test(cx);
10670
10671 let fs = FakeFs::new(cx.executor());
10672 let project = Project::test(fs, [], cx).await;
10673 let (workspace, cx) =
10674 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10675
10676 // Adding an item with no ambiguity renders the tab without detail.
10677 let item1 = cx.new(|cx| {
10678 let mut item = TestItem::new(cx);
10679 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10680 item
10681 });
10682 workspace.update_in(cx, |workspace, window, cx| {
10683 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10684 });
10685 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10686
10687 // Adding an item that creates ambiguity increases the level of detail on
10688 // both tabs.
10689 let item2 = cx.new_window_entity(|_window, cx| {
10690 let mut item = TestItem::new(cx);
10691 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10692 item
10693 });
10694 workspace.update_in(cx, |workspace, window, cx| {
10695 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10696 });
10697 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10698 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10699
10700 // Adding an item that creates ambiguity increases the level of detail only
10701 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10702 // we stop at the highest detail available.
10703 let item3 = cx.new(|cx| {
10704 let mut item = TestItem::new(cx);
10705 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10706 item
10707 });
10708 workspace.update_in(cx, |workspace, window, cx| {
10709 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10710 });
10711 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10712 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10713 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10714 }
10715
10716 #[gpui::test]
10717 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10718 init_test(cx);
10719
10720 let fs = FakeFs::new(cx.executor());
10721 fs.insert_tree(
10722 "/root1",
10723 json!({
10724 "one.txt": "",
10725 "two.txt": "",
10726 }),
10727 )
10728 .await;
10729 fs.insert_tree(
10730 "/root2",
10731 json!({
10732 "three.txt": "",
10733 }),
10734 )
10735 .await;
10736
10737 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10738 let (workspace, cx) =
10739 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10740 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10741 let worktree_id = project.update(cx, |project, cx| {
10742 project.worktrees(cx).next().unwrap().read(cx).id()
10743 });
10744
10745 let item1 = cx.new(|cx| {
10746 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10747 });
10748 let item2 = cx.new(|cx| {
10749 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10750 });
10751
10752 // Add an item to an empty pane
10753 workspace.update_in(cx, |workspace, window, cx| {
10754 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10755 });
10756 project.update(cx, |project, cx| {
10757 assert_eq!(
10758 project.active_entry(),
10759 project
10760 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10761 .map(|e| e.id)
10762 );
10763 });
10764 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10765
10766 // Add a second item to a non-empty pane
10767 workspace.update_in(cx, |workspace, window, cx| {
10768 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10769 });
10770 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10771 project.update(cx, |project, cx| {
10772 assert_eq!(
10773 project.active_entry(),
10774 project
10775 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10776 .map(|e| e.id)
10777 );
10778 });
10779
10780 // Close the active item
10781 pane.update_in(cx, |pane, window, cx| {
10782 pane.close_active_item(&Default::default(), window, cx)
10783 })
10784 .await
10785 .unwrap();
10786 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10787 project.update(cx, |project, cx| {
10788 assert_eq!(
10789 project.active_entry(),
10790 project
10791 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10792 .map(|e| e.id)
10793 );
10794 });
10795
10796 // Add a project folder
10797 project
10798 .update(cx, |project, cx| {
10799 project.find_or_create_worktree("root2", true, cx)
10800 })
10801 .await
10802 .unwrap();
10803 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10804
10805 // Remove a project folder
10806 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10807 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10808 }
10809
10810 #[gpui::test]
10811 async fn test_close_window(cx: &mut TestAppContext) {
10812 init_test(cx);
10813
10814 let fs = FakeFs::new(cx.executor());
10815 fs.insert_tree("/root", json!({ "one": "" })).await;
10816
10817 let project = Project::test(fs, ["root".as_ref()], cx).await;
10818 let (workspace, cx) =
10819 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10820
10821 // When there are no dirty items, there's nothing to do.
10822 let item1 = cx.new(TestItem::new);
10823 workspace.update_in(cx, |w, window, cx| {
10824 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10825 });
10826 let task = workspace.update_in(cx, |w, window, cx| {
10827 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10828 });
10829 assert!(task.await.unwrap());
10830
10831 // When there are dirty untitled items, prompt to save each one. If the user
10832 // cancels any prompt, then abort.
10833 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10834 let item3 = cx.new(|cx| {
10835 TestItem::new(cx)
10836 .with_dirty(true)
10837 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10838 });
10839 workspace.update_in(cx, |w, window, cx| {
10840 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10841 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10842 });
10843 let task = workspace.update_in(cx, |w, window, cx| {
10844 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10845 });
10846 cx.executor().run_until_parked();
10847 cx.simulate_prompt_answer("Cancel"); // cancel save all
10848 cx.executor().run_until_parked();
10849 assert!(!cx.has_pending_prompt());
10850 assert!(!task.await.unwrap());
10851 }
10852
10853 #[gpui::test]
10854 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10855 init_test(cx);
10856
10857 let fs = FakeFs::new(cx.executor());
10858 fs.insert_tree("/root", json!({ "one": "" })).await;
10859
10860 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10861 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10862 let multi_workspace_handle =
10863 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10864 cx.run_until_parked();
10865
10866 multi_workspace_handle
10867 .update(cx, |mw, _window, cx| {
10868 mw.open_sidebar(cx);
10869 })
10870 .unwrap();
10871
10872 let workspace_a = multi_workspace_handle
10873 .read_with(cx, |mw, _| mw.workspace().clone())
10874 .unwrap();
10875
10876 let workspace_b = multi_workspace_handle
10877 .update(cx, |mw, window, cx| {
10878 mw.test_add_workspace(project_b, window, cx)
10879 })
10880 .unwrap();
10881
10882 // Activate workspace A
10883 multi_workspace_handle
10884 .update(cx, |mw, window, cx| {
10885 let workspace = mw.workspaces().next().unwrap().clone();
10886 mw.activate(workspace, window, cx);
10887 })
10888 .unwrap();
10889
10890 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10891
10892 // Workspace A has a clean item
10893 let item_a = cx.new(TestItem::new);
10894 workspace_a.update_in(cx, |w, window, cx| {
10895 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10896 });
10897
10898 // Workspace B has a dirty item
10899 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10900 workspace_b.update_in(cx, |w, window, cx| {
10901 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10902 });
10903
10904 // Verify workspace A is active
10905 multi_workspace_handle
10906 .read_with(cx, |mw, _| {
10907 assert_eq!(mw.workspace(), &workspace_a);
10908 })
10909 .unwrap();
10910
10911 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10912 multi_workspace_handle
10913 .update(cx, |mw, window, cx| {
10914 mw.close_window(&CloseWindow, window, cx);
10915 })
10916 .unwrap();
10917 cx.run_until_parked();
10918
10919 // Workspace B should now be active since it has dirty items that need attention
10920 multi_workspace_handle
10921 .read_with(cx, |mw, _| {
10922 assert_eq!(
10923 mw.workspace(),
10924 &workspace_b,
10925 "workspace B should be activated when it prompts"
10926 );
10927 })
10928 .unwrap();
10929
10930 // User cancels the save prompt from workspace B
10931 cx.simulate_prompt_answer("Cancel");
10932 cx.run_until_parked();
10933
10934 // Window should still exist because workspace B's close was cancelled
10935 assert!(
10936 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10937 "window should still exist after cancelling one workspace's close"
10938 );
10939 }
10940
10941 #[gpui::test]
10942 async fn test_remove_workspace_prompts_for_unsaved_changes(cx: &mut TestAppContext) {
10943 init_test(cx);
10944
10945 let fs = FakeFs::new(cx.executor());
10946 fs.insert_tree("/root", json!({ "one": "" })).await;
10947
10948 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10949 let project_b = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10950 let multi_workspace_handle =
10951 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10952 cx.run_until_parked();
10953
10954 multi_workspace_handle
10955 .update(cx, |mw, _window, cx| mw.open_sidebar(cx))
10956 .unwrap();
10957
10958 let workspace_a = multi_workspace_handle
10959 .read_with(cx, |mw, _| mw.workspace().clone())
10960 .unwrap();
10961
10962 let workspace_b = multi_workspace_handle
10963 .update(cx, |mw, window, cx| {
10964 mw.test_add_workspace(project_b, window, cx)
10965 })
10966 .unwrap();
10967
10968 // Activate workspace A.
10969 multi_workspace_handle
10970 .update(cx, |mw, window, cx| {
10971 mw.activate(workspace_a.clone(), window, cx);
10972 })
10973 .unwrap();
10974
10975 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10976
10977 // Workspace B has a dirty item.
10978 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10979 workspace_b.update_in(cx, |w, window, cx| {
10980 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10981 });
10982
10983 // Try to remove workspace B. It should prompt because of the dirty item.
10984 let remove_task = multi_workspace_handle
10985 .update(cx, |mw, window, cx| {
10986 mw.remove([workspace_b.clone()], |_, _, _| unreachable!(), window, cx)
10987 })
10988 .unwrap();
10989 cx.run_until_parked();
10990
10991 // The prompt should have activated workspace B.
10992 multi_workspace_handle
10993 .read_with(cx, |mw, _| {
10994 assert_eq!(
10995 mw.workspace(),
10996 &workspace_b,
10997 "workspace B should be active while prompting"
10998 );
10999 })
11000 .unwrap();
11001
11002 // Cancel the prompt — user stays on workspace B.
11003 cx.simulate_prompt_answer("Cancel");
11004 cx.run_until_parked();
11005 let removed = remove_task.await.unwrap();
11006 assert!(!removed, "removal should have been cancelled");
11007
11008 multi_workspace_handle
11009 .read_with(cx, |mw, _| {
11010 assert_eq!(
11011 mw.workspace(),
11012 &workspace_b,
11013 "user should stay on workspace B after cancelling"
11014 );
11015 assert_eq!(mw.workspaces().count(), 2, "both workspaces should remain");
11016 })
11017 .unwrap();
11018
11019 // Try again. This time accept the prompt.
11020 let remove_task = multi_workspace_handle
11021 .update(cx, |mw, window, cx| {
11022 // First switch back to A.
11023 mw.activate(workspace_a.clone(), window, cx);
11024 mw.remove([workspace_b.clone()], |_, _, _| unreachable!(), window, cx)
11025 })
11026 .unwrap();
11027 cx.run_until_parked();
11028
11029 // Accept the save prompt.
11030 cx.simulate_prompt_answer("Don't Save");
11031 cx.run_until_parked();
11032 let removed = remove_task.await.unwrap();
11033 assert!(removed, "removal should have succeeded");
11034
11035 // Should be back on workspace A, and B should be gone.
11036 multi_workspace_handle
11037 .read_with(cx, |mw, _| {
11038 assert_eq!(
11039 mw.workspace(),
11040 &workspace_a,
11041 "should be back on workspace A after removing B"
11042 );
11043 assert_eq!(mw.workspaces().count(), 1, "only workspace A should remain");
11044 })
11045 .unwrap();
11046 }
11047
11048 #[gpui::test]
11049 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
11050 init_test(cx);
11051
11052 // Register TestItem as a serializable item
11053 cx.update(|cx| {
11054 register_serializable_item::<TestItem>(cx);
11055 });
11056
11057 let fs = FakeFs::new(cx.executor());
11058 fs.insert_tree("/root", json!({ "one": "" })).await;
11059
11060 let project = Project::test(fs, ["root".as_ref()], cx).await;
11061 let (workspace, cx) =
11062 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11063
11064 // When there are dirty untitled items, but they can serialize, then there is no prompt.
11065 let item1 = cx.new(|cx| {
11066 TestItem::new(cx)
11067 .with_dirty(true)
11068 .with_serialize(|| Some(Task::ready(Ok(()))))
11069 });
11070 let item2 = cx.new(|cx| {
11071 TestItem::new(cx)
11072 .with_dirty(true)
11073 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11074 .with_serialize(|| Some(Task::ready(Ok(()))))
11075 });
11076 workspace.update_in(cx, |w, window, cx| {
11077 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
11078 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
11079 });
11080 let task = workspace.update_in(cx, |w, window, cx| {
11081 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
11082 });
11083 assert!(task.await.unwrap());
11084 }
11085
11086 #[gpui::test]
11087 async fn test_close_pane_items(cx: &mut TestAppContext) {
11088 init_test(cx);
11089
11090 let fs = FakeFs::new(cx.executor());
11091
11092 let project = Project::test(fs, None, cx).await;
11093 let (workspace, cx) =
11094 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11095
11096 let item1 = cx.new(|cx| {
11097 TestItem::new(cx)
11098 .with_dirty(true)
11099 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11100 });
11101 let item2 = cx.new(|cx| {
11102 TestItem::new(cx)
11103 .with_dirty(true)
11104 .with_conflict(true)
11105 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11106 });
11107 let item3 = cx.new(|cx| {
11108 TestItem::new(cx)
11109 .with_dirty(true)
11110 .with_conflict(true)
11111 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
11112 });
11113 let item4 = cx.new(|cx| {
11114 TestItem::new(cx).with_dirty(true).with_project_items(&[{
11115 let project_item = TestProjectItem::new_untitled(cx);
11116 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11117 project_item
11118 }])
11119 });
11120 let pane = workspace.update_in(cx, |workspace, window, cx| {
11121 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
11122 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
11123 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
11124 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
11125 workspace.active_pane().clone()
11126 });
11127
11128 let close_items = pane.update_in(cx, |pane, window, cx| {
11129 pane.activate_item(1, true, true, window, cx);
11130 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11131 let item1_id = item1.item_id();
11132 let item3_id = item3.item_id();
11133 let item4_id = item4.item_id();
11134 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
11135 [item1_id, item3_id, item4_id].contains(&id)
11136 })
11137 });
11138 cx.executor().run_until_parked();
11139
11140 assert!(cx.has_pending_prompt());
11141 cx.simulate_prompt_answer("Save all");
11142
11143 cx.executor().run_until_parked();
11144
11145 // Item 1 is saved. There's a prompt to save item 3.
11146 pane.update(cx, |pane, cx| {
11147 assert_eq!(item1.read(cx).save_count, 1);
11148 assert_eq!(item1.read(cx).save_as_count, 0);
11149 assert_eq!(item1.read(cx).reload_count, 0);
11150 assert_eq!(pane.items_len(), 3);
11151 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
11152 });
11153 assert!(cx.has_pending_prompt());
11154
11155 // Cancel saving item 3.
11156 cx.simulate_prompt_answer("Discard");
11157 cx.executor().run_until_parked();
11158
11159 // Item 3 is reloaded. There's a prompt to save item 4.
11160 pane.update(cx, |pane, cx| {
11161 assert_eq!(item3.read(cx).save_count, 0);
11162 assert_eq!(item3.read(cx).save_as_count, 0);
11163 assert_eq!(item3.read(cx).reload_count, 1);
11164 assert_eq!(pane.items_len(), 2);
11165 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
11166 });
11167
11168 // There's a prompt for a path for item 4.
11169 cx.simulate_new_path_selection(|_| Some(Default::default()));
11170 close_items.await.unwrap();
11171
11172 // The requested items are closed.
11173 pane.update(cx, |pane, cx| {
11174 assert_eq!(item4.read(cx).save_count, 0);
11175 assert_eq!(item4.read(cx).save_as_count, 1);
11176 assert_eq!(item4.read(cx).reload_count, 0);
11177 assert_eq!(pane.items_len(), 1);
11178 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11179 });
11180 }
11181
11182 #[gpui::test]
11183 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
11184 init_test(cx);
11185
11186 let fs = FakeFs::new(cx.executor());
11187 let project = Project::test(fs, [], cx).await;
11188 let (workspace, cx) =
11189 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11190
11191 // Create several workspace items with single project entries, and two
11192 // workspace items with multiple project entries.
11193 let single_entry_items = (0..=4)
11194 .map(|project_entry_id| {
11195 cx.new(|cx| {
11196 TestItem::new(cx)
11197 .with_dirty(true)
11198 .with_project_items(&[dirty_project_item(
11199 project_entry_id,
11200 &format!("{project_entry_id}.txt"),
11201 cx,
11202 )])
11203 })
11204 })
11205 .collect::<Vec<_>>();
11206 let item_2_3 = cx.new(|cx| {
11207 TestItem::new(cx)
11208 .with_dirty(true)
11209 .with_buffer_kind(ItemBufferKind::Multibuffer)
11210 .with_project_items(&[
11211 single_entry_items[2].read(cx).project_items[0].clone(),
11212 single_entry_items[3].read(cx).project_items[0].clone(),
11213 ])
11214 });
11215 let item_3_4 = cx.new(|cx| {
11216 TestItem::new(cx)
11217 .with_dirty(true)
11218 .with_buffer_kind(ItemBufferKind::Multibuffer)
11219 .with_project_items(&[
11220 single_entry_items[3].read(cx).project_items[0].clone(),
11221 single_entry_items[4].read(cx).project_items[0].clone(),
11222 ])
11223 });
11224
11225 // Create two panes that contain the following project entries:
11226 // left pane:
11227 // multi-entry items: (2, 3)
11228 // single-entry items: 0, 2, 3, 4
11229 // right pane:
11230 // single-entry items: 4, 1
11231 // multi-entry items: (3, 4)
11232 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11233 let left_pane = workspace.active_pane().clone();
11234 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11235 workspace.add_item_to_active_pane(
11236 single_entry_items[0].boxed_clone(),
11237 None,
11238 true,
11239 window,
11240 cx,
11241 );
11242 workspace.add_item_to_active_pane(
11243 single_entry_items[2].boxed_clone(),
11244 None,
11245 true,
11246 window,
11247 cx,
11248 );
11249 workspace.add_item_to_active_pane(
11250 single_entry_items[3].boxed_clone(),
11251 None,
11252 true,
11253 window,
11254 cx,
11255 );
11256 workspace.add_item_to_active_pane(
11257 single_entry_items[4].boxed_clone(),
11258 None,
11259 true,
11260 window,
11261 cx,
11262 );
11263
11264 let right_pane =
11265 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11266
11267 let boxed_clone = single_entry_items[1].boxed_clone();
11268 let right_pane = window.spawn(cx, async move |cx| {
11269 right_pane.await.inspect(|right_pane| {
11270 right_pane
11271 .update_in(cx, |pane, window, cx| {
11272 pane.add_item(boxed_clone, true, true, None, window, cx);
11273 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11274 })
11275 .unwrap();
11276 })
11277 });
11278
11279 (left_pane, right_pane)
11280 });
11281 let right_pane = right_pane.await.unwrap();
11282 cx.focus(&right_pane);
11283
11284 let close = right_pane.update_in(cx, |pane, window, cx| {
11285 pane.close_all_items(&CloseAllItems::default(), window, cx)
11286 .unwrap()
11287 });
11288 cx.executor().run_until_parked();
11289
11290 let msg = cx.pending_prompt().unwrap().0;
11291 assert!(msg.contains("1.txt"));
11292 assert!(!msg.contains("2.txt"));
11293 assert!(!msg.contains("3.txt"));
11294 assert!(!msg.contains("4.txt"));
11295
11296 // With best-effort close, cancelling item 1 keeps it open but items 4
11297 // and (3,4) still close since their entries exist in left pane.
11298 cx.simulate_prompt_answer("Cancel");
11299 close.await;
11300
11301 right_pane.read_with(cx, |pane, _| {
11302 assert_eq!(pane.items_len(), 1);
11303 });
11304
11305 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11306 left_pane
11307 .update_in(cx, |left_pane, window, cx| {
11308 left_pane.close_item_by_id(
11309 single_entry_items[3].entity_id(),
11310 SaveIntent::Skip,
11311 window,
11312 cx,
11313 )
11314 })
11315 .await
11316 .unwrap();
11317
11318 let close = left_pane.update_in(cx, |pane, window, cx| {
11319 pane.close_all_items(&CloseAllItems::default(), window, cx)
11320 .unwrap()
11321 });
11322 cx.executor().run_until_parked();
11323
11324 let details = cx.pending_prompt().unwrap().1;
11325 assert!(details.contains("0.txt"));
11326 assert!(details.contains("3.txt"));
11327 assert!(details.contains("4.txt"));
11328 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11329 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11330 // assert!(!details.contains("2.txt"));
11331
11332 cx.simulate_prompt_answer("Save all");
11333 cx.executor().run_until_parked();
11334 close.await;
11335
11336 left_pane.read_with(cx, |pane, _| {
11337 assert_eq!(pane.items_len(), 0);
11338 });
11339 }
11340
11341 #[gpui::test]
11342 async fn test_autosave(cx: &mut gpui::TestAppContext) {
11343 init_test(cx);
11344
11345 let fs = FakeFs::new(cx.executor());
11346 let project = Project::test(fs, [], cx).await;
11347 let (workspace, cx) =
11348 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11349 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11350
11351 let item = cx.new(|cx| {
11352 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11353 });
11354 let item_id = item.entity_id();
11355 workspace.update_in(cx, |workspace, window, cx| {
11356 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11357 });
11358
11359 // Autosave on window change.
11360 item.update(cx, |item, cx| {
11361 SettingsStore::update_global(cx, |settings, cx| {
11362 settings.update_user_settings(cx, |settings| {
11363 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11364 })
11365 });
11366 item.is_dirty = true;
11367 });
11368
11369 // Deactivating the window saves the file.
11370 cx.deactivate_window();
11371 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11372
11373 // Re-activating the window doesn't save the file.
11374 cx.update(|window, _| window.activate_window());
11375 cx.executor().run_until_parked();
11376 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11377
11378 // Autosave on focus change.
11379 item.update_in(cx, |item, window, cx| {
11380 cx.focus_self(window);
11381 SettingsStore::update_global(cx, |settings, cx| {
11382 settings.update_user_settings(cx, |settings| {
11383 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11384 })
11385 });
11386 item.is_dirty = true;
11387 });
11388 // Blurring the item saves the file.
11389 item.update_in(cx, |_, window, _| window.blur());
11390 cx.executor().run_until_parked();
11391 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11392
11393 // Deactivating the window still saves the file.
11394 item.update_in(cx, |item, window, cx| {
11395 cx.focus_self(window);
11396 item.is_dirty = true;
11397 });
11398 cx.deactivate_window();
11399 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11400
11401 // Autosave after delay.
11402 item.update(cx, |item, cx| {
11403 SettingsStore::update_global(cx, |settings, cx| {
11404 settings.update_user_settings(cx, |settings| {
11405 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11406 milliseconds: 500.into(),
11407 });
11408 })
11409 });
11410 item.is_dirty = true;
11411 cx.emit(ItemEvent::Edit);
11412 });
11413
11414 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11415 cx.executor().advance_clock(Duration::from_millis(250));
11416 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11417
11418 // After delay expires, the file is saved.
11419 cx.executor().advance_clock(Duration::from_millis(250));
11420 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11421
11422 // Autosave after delay, should save earlier than delay if tab is closed
11423 item.update(cx, |item, cx| {
11424 item.is_dirty = true;
11425 cx.emit(ItemEvent::Edit);
11426 });
11427 cx.executor().advance_clock(Duration::from_millis(250));
11428 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11429
11430 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11431 pane.update_in(cx, |pane, window, cx| {
11432 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11433 })
11434 .await
11435 .unwrap();
11436 assert!(!cx.has_pending_prompt());
11437 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11438
11439 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11440 workspace.update_in(cx, |workspace, window, cx| {
11441 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11442 });
11443 item.update_in(cx, |item, _window, cx| {
11444 item.is_dirty = true;
11445 for project_item in &mut item.project_items {
11446 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11447 }
11448 });
11449 cx.run_until_parked();
11450 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11451
11452 // Autosave on focus change, ensuring closing the tab counts as such.
11453 item.update(cx, |item, cx| {
11454 SettingsStore::update_global(cx, |settings, cx| {
11455 settings.update_user_settings(cx, |settings| {
11456 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11457 })
11458 });
11459 item.is_dirty = true;
11460 for project_item in &mut item.project_items {
11461 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11462 }
11463 });
11464
11465 pane.update_in(cx, |pane, window, cx| {
11466 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11467 })
11468 .await
11469 .unwrap();
11470 assert!(!cx.has_pending_prompt());
11471 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11472
11473 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11474 workspace.update_in(cx, |workspace, window, cx| {
11475 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11476 });
11477 item.update_in(cx, |item, window, cx| {
11478 item.project_items[0].update(cx, |item, _| {
11479 item.entry_id = None;
11480 });
11481 item.is_dirty = true;
11482 window.blur();
11483 });
11484 cx.run_until_parked();
11485 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11486
11487 // Ensure autosave is prevented for deleted files also when closing the buffer.
11488 let _close_items = pane.update_in(cx, |pane, window, cx| {
11489 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11490 });
11491 cx.run_until_parked();
11492 assert!(cx.has_pending_prompt());
11493 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11494 }
11495
11496 #[gpui::test]
11497 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11498 init_test(cx);
11499
11500 let fs = FakeFs::new(cx.executor());
11501 let project = Project::test(fs, [], cx).await;
11502 let (workspace, cx) =
11503 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11504
11505 // Create a multibuffer-like item with two child focus handles,
11506 // simulating individual buffer editors within a multibuffer.
11507 let item = cx.new(|cx| {
11508 TestItem::new(cx)
11509 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11510 .with_child_focus_handles(2, cx)
11511 });
11512 workspace.update_in(cx, |workspace, window, cx| {
11513 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11514 });
11515
11516 // Set autosave to OnFocusChange and focus the first child handle,
11517 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11518 item.update_in(cx, |item, window, cx| {
11519 SettingsStore::update_global(cx, |settings, cx| {
11520 settings.update_user_settings(cx, |settings| {
11521 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11522 })
11523 });
11524 item.is_dirty = true;
11525 window.focus(&item.child_focus_handles[0], cx);
11526 });
11527 cx.executor().run_until_parked();
11528 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11529
11530 // Moving focus from one child to another within the same item should
11531 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11532 item.update_in(cx, |item, window, cx| {
11533 window.focus(&item.child_focus_handles[1], cx);
11534 });
11535 cx.executor().run_until_parked();
11536 item.read_with(cx, |item, _| {
11537 assert_eq!(
11538 item.save_count, 0,
11539 "Switching focus between children within the same item should not autosave"
11540 );
11541 });
11542
11543 // Blurring the item saves the file. This is the core regression scenario:
11544 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11545 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11546 // the leaf is always a child focus handle, so `on_blur` never detected
11547 // focus leaving the item.
11548 item.update_in(cx, |_, window, _| window.blur());
11549 cx.executor().run_until_parked();
11550 item.read_with(cx, |item, _| {
11551 assert_eq!(
11552 item.save_count, 1,
11553 "Blurring should trigger autosave when focus was on a child of the item"
11554 );
11555 });
11556
11557 // Deactivating the window should also trigger autosave when a child of
11558 // the multibuffer item currently owns focus.
11559 item.update_in(cx, |item, window, cx| {
11560 item.is_dirty = true;
11561 window.focus(&item.child_focus_handles[0], cx);
11562 });
11563 cx.executor().run_until_parked();
11564 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11565
11566 cx.deactivate_window();
11567 item.read_with(cx, |item, _| {
11568 assert_eq!(
11569 item.save_count, 2,
11570 "Deactivating window should trigger autosave when focus was on a child"
11571 );
11572 });
11573 }
11574
11575 #[gpui::test]
11576 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11577 init_test(cx);
11578
11579 let fs = FakeFs::new(cx.executor());
11580
11581 let project = Project::test(fs, [], cx).await;
11582 let (workspace, cx) =
11583 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11584
11585 let item = cx.new(|cx| {
11586 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11587 });
11588 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11589 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11590 let toolbar_notify_count = Rc::new(RefCell::new(0));
11591
11592 workspace.update_in(cx, |workspace, window, cx| {
11593 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11594 let toolbar_notification_count = toolbar_notify_count.clone();
11595 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11596 *toolbar_notification_count.borrow_mut() += 1
11597 })
11598 .detach();
11599 });
11600
11601 pane.read_with(cx, |pane, _| {
11602 assert!(!pane.can_navigate_backward());
11603 assert!(!pane.can_navigate_forward());
11604 });
11605
11606 item.update_in(cx, |item, _, cx| {
11607 item.set_state("one".to_string(), cx);
11608 });
11609
11610 // Toolbar must be notified to re-render the navigation buttons
11611 assert_eq!(*toolbar_notify_count.borrow(), 1);
11612
11613 pane.read_with(cx, |pane, _| {
11614 assert!(pane.can_navigate_backward());
11615 assert!(!pane.can_navigate_forward());
11616 });
11617
11618 workspace
11619 .update_in(cx, |workspace, window, cx| {
11620 workspace.go_back(pane.downgrade(), window, cx)
11621 })
11622 .await
11623 .unwrap();
11624
11625 assert_eq!(*toolbar_notify_count.borrow(), 2);
11626 pane.read_with(cx, |pane, _| {
11627 assert!(!pane.can_navigate_backward());
11628 assert!(pane.can_navigate_forward());
11629 });
11630 }
11631
11632 /// Tests that the navigation history deduplicates entries for the same item.
11633 ///
11634 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11635 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11636 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11637 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11638 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11639 ///
11640 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11641 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11642 #[gpui::test]
11643 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11644 init_test(cx);
11645
11646 let fs = FakeFs::new(cx.executor());
11647 let project = Project::test(fs, [], cx).await;
11648 let (workspace, cx) =
11649 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11650
11651 let item_a = cx.new(|cx| {
11652 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11653 });
11654 let item_b = cx.new(|cx| {
11655 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11656 });
11657 let item_c = cx.new(|cx| {
11658 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11659 });
11660
11661 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11662
11663 workspace.update_in(cx, |workspace, window, cx| {
11664 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11665 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11666 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11667 });
11668
11669 workspace.update_in(cx, |workspace, window, cx| {
11670 workspace.activate_item(&item_a, false, false, window, cx);
11671 });
11672 cx.run_until_parked();
11673
11674 workspace.update_in(cx, |workspace, window, cx| {
11675 workspace.activate_item(&item_b, false, false, window, cx);
11676 });
11677 cx.run_until_parked();
11678
11679 workspace.update_in(cx, |workspace, window, cx| {
11680 workspace.activate_item(&item_a, false, false, window, cx);
11681 });
11682 cx.run_until_parked();
11683
11684 workspace.update_in(cx, |workspace, window, cx| {
11685 workspace.activate_item(&item_b, false, false, window, cx);
11686 });
11687 cx.run_until_parked();
11688
11689 workspace.update_in(cx, |workspace, window, cx| {
11690 workspace.activate_item(&item_a, false, false, window, cx);
11691 });
11692 cx.run_until_parked();
11693
11694 workspace.update_in(cx, |workspace, window, cx| {
11695 workspace.activate_item(&item_b, false, false, window, cx);
11696 });
11697 cx.run_until_parked();
11698
11699 workspace.update_in(cx, |workspace, window, cx| {
11700 workspace.activate_item(&item_c, false, false, window, cx);
11701 });
11702 cx.run_until_parked();
11703
11704 let backward_count = pane.read_with(cx, |pane, cx| {
11705 let mut count = 0;
11706 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11707 count += 1;
11708 });
11709 count
11710 });
11711 assert!(
11712 backward_count <= 4,
11713 "Should have at most 4 entries, got {}",
11714 backward_count
11715 );
11716
11717 workspace
11718 .update_in(cx, |workspace, window, cx| {
11719 workspace.go_back(pane.downgrade(), window, cx)
11720 })
11721 .await
11722 .unwrap();
11723
11724 let active_item = workspace.read_with(cx, |workspace, cx| {
11725 workspace.active_item(cx).unwrap().item_id()
11726 });
11727 assert_eq!(
11728 active_item,
11729 item_b.entity_id(),
11730 "After first go_back, should be at item B"
11731 );
11732
11733 workspace
11734 .update_in(cx, |workspace, window, cx| {
11735 workspace.go_back(pane.downgrade(), window, cx)
11736 })
11737 .await
11738 .unwrap();
11739
11740 let active_item = workspace.read_with(cx, |workspace, cx| {
11741 workspace.active_item(cx).unwrap().item_id()
11742 });
11743 assert_eq!(
11744 active_item,
11745 item_a.entity_id(),
11746 "After second go_back, should be at item A"
11747 );
11748
11749 pane.read_with(cx, |pane, _| {
11750 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11751 });
11752 }
11753
11754 #[gpui::test]
11755 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11756 init_test(cx);
11757 let fs = FakeFs::new(cx.executor());
11758 let project = Project::test(fs, [], cx).await;
11759 let (multi_workspace, cx) =
11760 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11761 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11762
11763 workspace.update_in(cx, |workspace, window, cx| {
11764 let first_item = cx.new(|cx| {
11765 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11766 });
11767 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11768 workspace.split_pane(
11769 workspace.active_pane().clone(),
11770 SplitDirection::Right,
11771 window,
11772 cx,
11773 );
11774 workspace.split_pane(
11775 workspace.active_pane().clone(),
11776 SplitDirection::Right,
11777 window,
11778 cx,
11779 );
11780 });
11781
11782 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11783 let panes = workspace.center.panes();
11784 assert!(panes.len() >= 2);
11785 (
11786 panes.first().expect("at least one pane").entity_id(),
11787 panes.last().expect("at least one pane").entity_id(),
11788 )
11789 });
11790
11791 workspace.update_in(cx, |workspace, window, cx| {
11792 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11793 });
11794 workspace.update(cx, |workspace, _| {
11795 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11796 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11797 });
11798
11799 cx.dispatch_action(ActivateLastPane);
11800
11801 workspace.update(cx, |workspace, _| {
11802 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11803 });
11804 }
11805
11806 #[gpui::test]
11807 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11808 init_test(cx);
11809 let fs = FakeFs::new(cx.executor());
11810
11811 let project = Project::test(fs, [], cx).await;
11812 let (workspace, cx) =
11813 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11814
11815 let panel = workspace.update_in(cx, |workspace, window, cx| {
11816 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11817 workspace.add_panel(panel.clone(), window, cx);
11818
11819 workspace
11820 .right_dock()
11821 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11822
11823 panel
11824 });
11825
11826 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11827 pane.update_in(cx, |pane, window, cx| {
11828 let item = cx.new(TestItem::new);
11829 pane.add_item(Box::new(item), true, true, None, window, cx);
11830 });
11831
11832 // Transfer focus from center to panel
11833 workspace.update_in(cx, |workspace, window, cx| {
11834 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11835 });
11836
11837 workspace.update_in(cx, |workspace, window, cx| {
11838 assert!(workspace.right_dock().read(cx).is_open());
11839 assert!(!panel.is_zoomed(window, cx));
11840 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11841 });
11842
11843 // Transfer focus from panel to center
11844 workspace.update_in(cx, |workspace, window, cx| {
11845 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11846 });
11847
11848 workspace.update_in(cx, |workspace, window, cx| {
11849 assert!(workspace.right_dock().read(cx).is_open());
11850 assert!(!panel.is_zoomed(window, cx));
11851 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11852 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11853 });
11854
11855 // Close the dock
11856 workspace.update_in(cx, |workspace, window, cx| {
11857 workspace.toggle_dock(DockPosition::Right, window, cx);
11858 });
11859
11860 workspace.update_in(cx, |workspace, window, cx| {
11861 assert!(!workspace.right_dock().read(cx).is_open());
11862 assert!(!panel.is_zoomed(window, cx));
11863 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11864 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11865 });
11866
11867 // Open the dock
11868 workspace.update_in(cx, |workspace, window, cx| {
11869 workspace.toggle_dock(DockPosition::Right, window, cx);
11870 });
11871
11872 workspace.update_in(cx, |workspace, window, cx| {
11873 assert!(workspace.right_dock().read(cx).is_open());
11874 assert!(!panel.is_zoomed(window, cx));
11875 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11876 });
11877
11878 // Focus and zoom panel
11879 panel.update_in(cx, |panel, window, cx| {
11880 cx.focus_self(window);
11881 panel.set_zoomed(true, window, cx)
11882 });
11883
11884 workspace.update_in(cx, |workspace, window, cx| {
11885 assert!(workspace.right_dock().read(cx).is_open());
11886 assert!(panel.is_zoomed(window, cx));
11887 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11888 });
11889
11890 // Transfer focus to the center closes the dock
11891 workspace.update_in(cx, |workspace, window, cx| {
11892 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11893 });
11894
11895 workspace.update_in(cx, |workspace, window, cx| {
11896 assert!(!workspace.right_dock().read(cx).is_open());
11897 assert!(panel.is_zoomed(window, cx));
11898 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11899 });
11900
11901 // Transferring focus back to the panel keeps it zoomed
11902 workspace.update_in(cx, |workspace, window, cx| {
11903 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11904 });
11905
11906 workspace.update_in(cx, |workspace, window, cx| {
11907 assert!(workspace.right_dock().read(cx).is_open());
11908 assert!(panel.is_zoomed(window, cx));
11909 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11910 });
11911
11912 // Close the dock while it is zoomed
11913 workspace.update_in(cx, |workspace, window, cx| {
11914 workspace.toggle_dock(DockPosition::Right, window, cx)
11915 });
11916
11917 workspace.update_in(cx, |workspace, window, cx| {
11918 assert!(!workspace.right_dock().read(cx).is_open());
11919 assert!(panel.is_zoomed(window, cx));
11920 assert!(workspace.zoomed.is_none());
11921 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11922 });
11923
11924 // Opening the dock, when it's zoomed, retains focus
11925 workspace.update_in(cx, |workspace, window, cx| {
11926 workspace.toggle_dock(DockPosition::Right, window, cx)
11927 });
11928
11929 workspace.update_in(cx, |workspace, window, cx| {
11930 assert!(workspace.right_dock().read(cx).is_open());
11931 assert!(panel.is_zoomed(window, cx));
11932 assert!(workspace.zoomed.is_some());
11933 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11934 });
11935
11936 // Unzoom and close the panel, zoom the active pane.
11937 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11938 workspace.update_in(cx, |workspace, window, cx| {
11939 workspace.toggle_dock(DockPosition::Right, window, cx)
11940 });
11941 pane.update_in(cx, |pane, window, cx| {
11942 pane.toggle_zoom(&Default::default(), window, cx)
11943 });
11944
11945 // Opening a dock unzooms the pane.
11946 workspace.update_in(cx, |workspace, window, cx| {
11947 workspace.toggle_dock(DockPosition::Right, window, cx)
11948 });
11949 workspace.update_in(cx, |workspace, window, cx| {
11950 let pane = pane.read(cx);
11951 assert!(!pane.is_zoomed());
11952 assert!(!pane.focus_handle(cx).is_focused(window));
11953 assert!(workspace.right_dock().read(cx).is_open());
11954 assert!(workspace.zoomed.is_none());
11955 });
11956 }
11957
11958 #[gpui::test]
11959 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11960 init_test(cx);
11961 let fs = FakeFs::new(cx.executor());
11962
11963 let project = Project::test(fs, [], cx).await;
11964 let (workspace, cx) =
11965 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11966
11967 let panel = workspace.update_in(cx, |workspace, window, cx| {
11968 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11969 workspace.add_panel(panel.clone(), window, cx);
11970 panel
11971 });
11972
11973 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11974 pane.update_in(cx, |pane, window, cx| {
11975 let item = cx.new(TestItem::new);
11976 pane.add_item(Box::new(item), true, true, None, window, cx);
11977 });
11978
11979 // Enable close_panel_on_toggle
11980 cx.update_global(|store: &mut SettingsStore, cx| {
11981 store.update_user_settings(cx, |settings| {
11982 settings.workspace.close_panel_on_toggle = Some(true);
11983 });
11984 });
11985
11986 // Panel starts closed. Toggling should open and focus it.
11987 workspace.update_in(cx, |workspace, window, cx| {
11988 assert!(!workspace.right_dock().read(cx).is_open());
11989 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11990 });
11991
11992 workspace.update_in(cx, |workspace, window, cx| {
11993 assert!(
11994 workspace.right_dock().read(cx).is_open(),
11995 "Dock should be open after toggling from center"
11996 );
11997 assert!(
11998 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11999 "Panel should be focused after toggling from center"
12000 );
12001 });
12002
12003 // Panel is open and focused. Toggling should close the panel and
12004 // return focus to the center.
12005 workspace.update_in(cx, |workspace, window, cx| {
12006 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12007 });
12008
12009 workspace.update_in(cx, |workspace, window, cx| {
12010 assert!(
12011 !workspace.right_dock().read(cx).is_open(),
12012 "Dock should be closed after toggling from focused panel"
12013 );
12014 assert!(
12015 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12016 "Panel should not be focused after toggling from focused panel"
12017 );
12018 });
12019
12020 // Open the dock and focus something else so the panel is open but not
12021 // focused. Toggling should focus the panel (not close it).
12022 workspace.update_in(cx, |workspace, window, cx| {
12023 workspace
12024 .right_dock()
12025 .update(cx, |dock, cx| dock.set_open(true, window, cx));
12026 window.focus(&pane.read(cx).focus_handle(cx), cx);
12027 });
12028
12029 workspace.update_in(cx, |workspace, window, cx| {
12030 assert!(workspace.right_dock().read(cx).is_open());
12031 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12032 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12033 });
12034
12035 workspace.update_in(cx, |workspace, window, cx| {
12036 assert!(
12037 workspace.right_dock().read(cx).is_open(),
12038 "Dock should remain open when toggling focuses an open-but-unfocused panel"
12039 );
12040 assert!(
12041 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12042 "Panel should be focused after toggling an open-but-unfocused panel"
12043 );
12044 });
12045
12046 // Now disable the setting and verify the original behavior: toggling
12047 // from a focused panel moves focus to center but leaves the dock open.
12048 cx.update_global(|store: &mut SettingsStore, cx| {
12049 store.update_user_settings(cx, |settings| {
12050 settings.workspace.close_panel_on_toggle = Some(false);
12051 });
12052 });
12053
12054 workspace.update_in(cx, |workspace, window, cx| {
12055 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12056 });
12057
12058 workspace.update_in(cx, |workspace, window, cx| {
12059 assert!(
12060 workspace.right_dock().read(cx).is_open(),
12061 "Dock should remain open when setting is disabled"
12062 );
12063 assert!(
12064 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12065 "Panel should not be focused after toggling with setting disabled"
12066 );
12067 });
12068 }
12069
12070 #[gpui::test]
12071 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
12072 init_test(cx);
12073 let fs = FakeFs::new(cx.executor());
12074
12075 let project = Project::test(fs, [], cx).await;
12076 let (workspace, cx) =
12077 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12078
12079 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
12080 workspace.active_pane().clone()
12081 });
12082
12083 // Add an item to the pane so it can be zoomed
12084 workspace.update_in(cx, |workspace, window, cx| {
12085 let item = cx.new(TestItem::new);
12086 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
12087 });
12088
12089 // Initially not zoomed
12090 workspace.update_in(cx, |workspace, _window, cx| {
12091 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
12092 assert!(
12093 workspace.zoomed.is_none(),
12094 "Workspace should track no zoomed pane"
12095 );
12096 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
12097 });
12098
12099 // Zoom In
12100 pane.update_in(cx, |pane, window, cx| {
12101 pane.zoom_in(&crate::ZoomIn, window, cx);
12102 });
12103
12104 workspace.update_in(cx, |workspace, window, cx| {
12105 assert!(
12106 pane.read(cx).is_zoomed(),
12107 "Pane should be zoomed after ZoomIn"
12108 );
12109 assert!(
12110 workspace.zoomed.is_some(),
12111 "Workspace should track the zoomed pane"
12112 );
12113 assert!(
12114 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
12115 "ZoomIn should focus the pane"
12116 );
12117 });
12118
12119 // Zoom In again is a no-op
12120 pane.update_in(cx, |pane, window, cx| {
12121 pane.zoom_in(&crate::ZoomIn, window, cx);
12122 });
12123
12124 workspace.update_in(cx, |workspace, window, cx| {
12125 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
12126 assert!(
12127 workspace.zoomed.is_some(),
12128 "Workspace still tracks zoomed pane"
12129 );
12130 assert!(
12131 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
12132 "Pane remains focused after repeated ZoomIn"
12133 );
12134 });
12135
12136 // Zoom Out
12137 pane.update_in(cx, |pane, window, cx| {
12138 pane.zoom_out(&crate::ZoomOut, window, cx);
12139 });
12140
12141 workspace.update_in(cx, |workspace, _window, cx| {
12142 assert!(
12143 !pane.read(cx).is_zoomed(),
12144 "Pane should unzoom after ZoomOut"
12145 );
12146 assert!(
12147 workspace.zoomed.is_none(),
12148 "Workspace clears zoom tracking after ZoomOut"
12149 );
12150 });
12151
12152 // Zoom Out again is a no-op
12153 pane.update_in(cx, |pane, window, cx| {
12154 pane.zoom_out(&crate::ZoomOut, window, cx);
12155 });
12156
12157 workspace.update_in(cx, |workspace, _window, cx| {
12158 assert!(
12159 !pane.read(cx).is_zoomed(),
12160 "Second ZoomOut keeps pane unzoomed"
12161 );
12162 assert!(
12163 workspace.zoomed.is_none(),
12164 "Workspace remains without zoomed pane"
12165 );
12166 });
12167 }
12168
12169 #[gpui::test]
12170 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
12171 init_test(cx);
12172 let fs = FakeFs::new(cx.executor());
12173
12174 let project = Project::test(fs, [], cx).await;
12175 let (workspace, cx) =
12176 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12177 workspace.update_in(cx, |workspace, window, cx| {
12178 // Open two docks
12179 let left_dock = workspace.dock_at_position(DockPosition::Left);
12180 let right_dock = workspace.dock_at_position(DockPosition::Right);
12181
12182 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12183 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12184
12185 assert!(left_dock.read(cx).is_open());
12186 assert!(right_dock.read(cx).is_open());
12187 });
12188
12189 workspace.update_in(cx, |workspace, window, cx| {
12190 // Toggle all docks - should close both
12191 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12192
12193 let left_dock = workspace.dock_at_position(DockPosition::Left);
12194 let right_dock = workspace.dock_at_position(DockPosition::Right);
12195 assert!(!left_dock.read(cx).is_open());
12196 assert!(!right_dock.read(cx).is_open());
12197 });
12198
12199 workspace.update_in(cx, |workspace, window, cx| {
12200 // Toggle again - should reopen both
12201 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12202
12203 let left_dock = workspace.dock_at_position(DockPosition::Left);
12204 let right_dock = workspace.dock_at_position(DockPosition::Right);
12205 assert!(left_dock.read(cx).is_open());
12206 assert!(right_dock.read(cx).is_open());
12207 });
12208 }
12209
12210 #[gpui::test]
12211 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
12212 init_test(cx);
12213 let fs = FakeFs::new(cx.executor());
12214
12215 let project = Project::test(fs, [], cx).await;
12216 let (workspace, cx) =
12217 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12218 workspace.update_in(cx, |workspace, window, cx| {
12219 // Open two docks
12220 let left_dock = workspace.dock_at_position(DockPosition::Left);
12221 let right_dock = workspace.dock_at_position(DockPosition::Right);
12222
12223 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12224 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12225
12226 assert!(left_dock.read(cx).is_open());
12227 assert!(right_dock.read(cx).is_open());
12228 });
12229
12230 workspace.update_in(cx, |workspace, window, cx| {
12231 // Close them manually
12232 workspace.toggle_dock(DockPosition::Left, window, cx);
12233 workspace.toggle_dock(DockPosition::Right, window, cx);
12234
12235 let left_dock = workspace.dock_at_position(DockPosition::Left);
12236 let right_dock = workspace.dock_at_position(DockPosition::Right);
12237 assert!(!left_dock.read(cx).is_open());
12238 assert!(!right_dock.read(cx).is_open());
12239 });
12240
12241 workspace.update_in(cx, |workspace, window, cx| {
12242 // Toggle all docks - only last closed (right dock) should reopen
12243 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12244
12245 let left_dock = workspace.dock_at_position(DockPosition::Left);
12246 let right_dock = workspace.dock_at_position(DockPosition::Right);
12247 assert!(!left_dock.read(cx).is_open());
12248 assert!(right_dock.read(cx).is_open());
12249 });
12250 }
12251
12252 #[gpui::test]
12253 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12254 init_test(cx);
12255 let fs = FakeFs::new(cx.executor());
12256 let project = Project::test(fs, [], cx).await;
12257 let (multi_workspace, cx) =
12258 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12259 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12260
12261 // Open two docks (left and right) with one panel each
12262 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12263 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12264 workspace.add_panel(left_panel.clone(), window, cx);
12265
12266 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12267 workspace.add_panel(right_panel.clone(), window, cx);
12268
12269 workspace.toggle_dock(DockPosition::Left, window, cx);
12270 workspace.toggle_dock(DockPosition::Right, window, cx);
12271
12272 // Verify initial state
12273 assert!(
12274 workspace.left_dock().read(cx).is_open(),
12275 "Left dock should be open"
12276 );
12277 assert_eq!(
12278 workspace
12279 .left_dock()
12280 .read(cx)
12281 .visible_panel()
12282 .unwrap()
12283 .panel_id(),
12284 left_panel.panel_id(),
12285 "Left panel should be visible in left dock"
12286 );
12287 assert!(
12288 workspace.right_dock().read(cx).is_open(),
12289 "Right dock should be open"
12290 );
12291 assert_eq!(
12292 workspace
12293 .right_dock()
12294 .read(cx)
12295 .visible_panel()
12296 .unwrap()
12297 .panel_id(),
12298 right_panel.panel_id(),
12299 "Right panel should be visible in right dock"
12300 );
12301 assert!(
12302 !workspace.bottom_dock().read(cx).is_open(),
12303 "Bottom dock should be closed"
12304 );
12305
12306 (left_panel, right_panel)
12307 });
12308
12309 // Focus the left panel and move it to the next position (bottom dock)
12310 workspace.update_in(cx, |workspace, window, cx| {
12311 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12312 assert!(
12313 left_panel.read(cx).focus_handle(cx).is_focused(window),
12314 "Left panel should be focused"
12315 );
12316 });
12317
12318 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12319
12320 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12321 workspace.update(cx, |workspace, cx| {
12322 assert!(
12323 !workspace.left_dock().read(cx).is_open(),
12324 "Left dock should be closed"
12325 );
12326 assert!(
12327 workspace.bottom_dock().read(cx).is_open(),
12328 "Bottom dock should now be open"
12329 );
12330 assert_eq!(
12331 left_panel.read(cx).position,
12332 DockPosition::Bottom,
12333 "Left panel should now be in the bottom dock"
12334 );
12335 assert_eq!(
12336 workspace
12337 .bottom_dock()
12338 .read(cx)
12339 .visible_panel()
12340 .unwrap()
12341 .panel_id(),
12342 left_panel.panel_id(),
12343 "Left panel should be the visible panel in the bottom dock"
12344 );
12345 });
12346
12347 // Toggle all docks off
12348 workspace.update_in(cx, |workspace, window, cx| {
12349 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12350 assert!(
12351 !workspace.left_dock().read(cx).is_open(),
12352 "Left dock should be closed"
12353 );
12354 assert!(
12355 !workspace.right_dock().read(cx).is_open(),
12356 "Right dock should be closed"
12357 );
12358 assert!(
12359 !workspace.bottom_dock().read(cx).is_open(),
12360 "Bottom dock should be closed"
12361 );
12362 });
12363
12364 // Toggle all docks back on and verify positions are restored
12365 workspace.update_in(cx, |workspace, window, cx| {
12366 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12367 assert!(
12368 !workspace.left_dock().read(cx).is_open(),
12369 "Left dock should remain closed"
12370 );
12371 assert!(
12372 workspace.right_dock().read(cx).is_open(),
12373 "Right dock should remain open"
12374 );
12375 assert!(
12376 workspace.bottom_dock().read(cx).is_open(),
12377 "Bottom dock should remain open"
12378 );
12379 assert_eq!(
12380 left_panel.read(cx).position,
12381 DockPosition::Bottom,
12382 "Left panel should remain in the bottom dock"
12383 );
12384 assert_eq!(
12385 right_panel.read(cx).position,
12386 DockPosition::Right,
12387 "Right panel should remain in the right dock"
12388 );
12389 assert_eq!(
12390 workspace
12391 .bottom_dock()
12392 .read(cx)
12393 .visible_panel()
12394 .unwrap()
12395 .panel_id(),
12396 left_panel.panel_id(),
12397 "Left panel should be the visible panel in the right dock"
12398 );
12399 });
12400 }
12401
12402 #[gpui::test]
12403 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12404 init_test(cx);
12405
12406 let fs = FakeFs::new(cx.executor());
12407
12408 let project = Project::test(fs, None, cx).await;
12409 let (workspace, cx) =
12410 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12411
12412 // Let's arrange the panes like this:
12413 //
12414 // +-----------------------+
12415 // | top |
12416 // +------+--------+-------+
12417 // | left | center | right |
12418 // +------+--------+-------+
12419 // | bottom |
12420 // +-----------------------+
12421
12422 let top_item = cx.new(|cx| {
12423 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12424 });
12425 let bottom_item = cx.new(|cx| {
12426 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12427 });
12428 let left_item = cx.new(|cx| {
12429 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12430 });
12431 let right_item = cx.new(|cx| {
12432 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12433 });
12434 let center_item = cx.new(|cx| {
12435 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12436 });
12437
12438 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12439 let top_pane_id = workspace.active_pane().entity_id();
12440 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12441 workspace.split_pane(
12442 workspace.active_pane().clone(),
12443 SplitDirection::Down,
12444 window,
12445 cx,
12446 );
12447 top_pane_id
12448 });
12449 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12450 let bottom_pane_id = workspace.active_pane().entity_id();
12451 workspace.add_item_to_active_pane(
12452 Box::new(bottom_item.clone()),
12453 None,
12454 false,
12455 window,
12456 cx,
12457 );
12458 workspace.split_pane(
12459 workspace.active_pane().clone(),
12460 SplitDirection::Up,
12461 window,
12462 cx,
12463 );
12464 bottom_pane_id
12465 });
12466 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12467 let left_pane_id = workspace.active_pane().entity_id();
12468 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12469 workspace.split_pane(
12470 workspace.active_pane().clone(),
12471 SplitDirection::Right,
12472 window,
12473 cx,
12474 );
12475 left_pane_id
12476 });
12477 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12478 let right_pane_id = workspace.active_pane().entity_id();
12479 workspace.add_item_to_active_pane(
12480 Box::new(right_item.clone()),
12481 None,
12482 false,
12483 window,
12484 cx,
12485 );
12486 workspace.split_pane(
12487 workspace.active_pane().clone(),
12488 SplitDirection::Left,
12489 window,
12490 cx,
12491 );
12492 right_pane_id
12493 });
12494 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12495 let center_pane_id = workspace.active_pane().entity_id();
12496 workspace.add_item_to_active_pane(
12497 Box::new(center_item.clone()),
12498 None,
12499 false,
12500 window,
12501 cx,
12502 );
12503 center_pane_id
12504 });
12505 cx.executor().run_until_parked();
12506
12507 workspace.update_in(cx, |workspace, window, cx| {
12508 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12509
12510 // Join into next from center pane into right
12511 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12512 });
12513
12514 workspace.update_in(cx, |workspace, window, cx| {
12515 let active_pane = workspace.active_pane();
12516 assert_eq!(right_pane_id, active_pane.entity_id());
12517 assert_eq!(2, active_pane.read(cx).items_len());
12518 let item_ids_in_pane =
12519 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12520 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12521 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12522
12523 // Join into next from right pane into bottom
12524 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12525 });
12526
12527 workspace.update_in(cx, |workspace, window, cx| {
12528 let active_pane = workspace.active_pane();
12529 assert_eq!(bottom_pane_id, active_pane.entity_id());
12530 assert_eq!(3, active_pane.read(cx).items_len());
12531 let item_ids_in_pane =
12532 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12533 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12534 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12535 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12536
12537 // Join into next from bottom pane into left
12538 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12539 });
12540
12541 workspace.update_in(cx, |workspace, window, cx| {
12542 let active_pane = workspace.active_pane();
12543 assert_eq!(left_pane_id, active_pane.entity_id());
12544 assert_eq!(4, active_pane.read(cx).items_len());
12545 let item_ids_in_pane =
12546 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12547 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12548 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12549 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12550 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12551
12552 // Join into next from left pane into top
12553 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12554 });
12555
12556 workspace.update_in(cx, |workspace, window, cx| {
12557 let active_pane = workspace.active_pane();
12558 assert_eq!(top_pane_id, active_pane.entity_id());
12559 assert_eq!(5, active_pane.read(cx).items_len());
12560 let item_ids_in_pane =
12561 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12562 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12563 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12564 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12565 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12566 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12567
12568 // Single pane left: no-op
12569 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12570 });
12571
12572 workspace.update(cx, |workspace, _cx| {
12573 let active_pane = workspace.active_pane();
12574 assert_eq!(top_pane_id, active_pane.entity_id());
12575 });
12576 }
12577
12578 fn add_an_item_to_active_pane(
12579 cx: &mut VisualTestContext,
12580 workspace: &Entity<Workspace>,
12581 item_id: u64,
12582 ) -> Entity<TestItem> {
12583 let item = cx.new(|cx| {
12584 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12585 item_id,
12586 "item{item_id}.txt",
12587 cx,
12588 )])
12589 });
12590 workspace.update_in(cx, |workspace, window, cx| {
12591 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12592 });
12593 item
12594 }
12595
12596 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12597 workspace.update_in(cx, |workspace, window, cx| {
12598 workspace.split_pane(
12599 workspace.active_pane().clone(),
12600 SplitDirection::Right,
12601 window,
12602 cx,
12603 )
12604 })
12605 }
12606
12607 #[gpui::test]
12608 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12609 init_test(cx);
12610 let fs = FakeFs::new(cx.executor());
12611 let project = Project::test(fs, None, cx).await;
12612 let (workspace, cx) =
12613 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12614
12615 add_an_item_to_active_pane(cx, &workspace, 1);
12616 split_pane(cx, &workspace);
12617 add_an_item_to_active_pane(cx, &workspace, 2);
12618 split_pane(cx, &workspace); // empty pane
12619 split_pane(cx, &workspace);
12620 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12621
12622 cx.executor().run_until_parked();
12623
12624 workspace.update(cx, |workspace, cx| {
12625 let num_panes = workspace.panes().len();
12626 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12627 let active_item = workspace
12628 .active_pane()
12629 .read(cx)
12630 .active_item()
12631 .expect("item is in focus");
12632
12633 assert_eq!(num_panes, 4);
12634 assert_eq!(num_items_in_current_pane, 1);
12635 assert_eq!(active_item.item_id(), last_item.item_id());
12636 });
12637
12638 workspace.update_in(cx, |workspace, window, cx| {
12639 workspace.join_all_panes(window, cx);
12640 });
12641
12642 workspace.update(cx, |workspace, cx| {
12643 let num_panes = workspace.panes().len();
12644 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12645 let active_item = workspace
12646 .active_pane()
12647 .read(cx)
12648 .active_item()
12649 .expect("item is in focus");
12650
12651 assert_eq!(num_panes, 1);
12652 assert_eq!(num_items_in_current_pane, 3);
12653 assert_eq!(active_item.item_id(), last_item.item_id());
12654 });
12655 }
12656
12657 #[gpui::test]
12658 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12659 init_test(cx);
12660 let fs = FakeFs::new(cx.executor());
12661
12662 let project = Project::test(fs, [], cx).await;
12663 let (multi_workspace, cx) =
12664 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12665 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12666
12667 workspace.update(cx, |workspace, _cx| {
12668 workspace.bounds.size.width = px(800.);
12669 });
12670
12671 workspace.update_in(cx, |workspace, window, cx| {
12672 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12673 workspace.add_panel(panel, window, cx);
12674 workspace.toggle_dock(DockPosition::Right, window, cx);
12675 });
12676
12677 let (panel, resized_width, ratio_basis_width) =
12678 workspace.update_in(cx, |workspace, window, cx| {
12679 let item = cx.new(|cx| {
12680 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12681 });
12682 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12683
12684 let dock = workspace.right_dock().read(cx);
12685 let workspace_width = workspace.bounds.size.width;
12686 let initial_width = workspace
12687 .dock_size(&dock, window, cx)
12688 .expect("flexible dock should have an initial width");
12689
12690 assert_eq!(initial_width, workspace_width / 2.);
12691
12692 workspace.resize_right_dock(px(300.), window, cx);
12693
12694 let dock = workspace.right_dock().read(cx);
12695 let resized_width = workspace
12696 .dock_size(&dock, window, cx)
12697 .expect("flexible dock should keep its resized width");
12698
12699 assert_eq!(resized_width, px(300.));
12700
12701 let panel = workspace
12702 .right_dock()
12703 .read(cx)
12704 .visible_panel()
12705 .expect("flexible dock should have a visible panel")
12706 .panel_id();
12707
12708 (panel, resized_width, workspace_width)
12709 });
12710
12711 workspace.update_in(cx, |workspace, window, cx| {
12712 workspace.toggle_dock(DockPosition::Right, window, cx);
12713 workspace.toggle_dock(DockPosition::Right, window, cx);
12714
12715 let dock = workspace.right_dock().read(cx);
12716 let reopened_width = workspace
12717 .dock_size(&dock, window, cx)
12718 .expect("flexible dock should restore when reopened");
12719
12720 assert_eq!(reopened_width, resized_width);
12721
12722 let right_dock = workspace.right_dock().read(cx);
12723 let flexible_panel = right_dock
12724 .visible_panel()
12725 .expect("flexible dock should still have a visible panel");
12726 assert_eq!(flexible_panel.panel_id(), panel);
12727 assert_eq!(
12728 right_dock
12729 .stored_panel_size_state(flexible_panel.as_ref())
12730 .and_then(|size_state| size_state.flex),
12731 Some(
12732 resized_width.to_f64() as f32
12733 / (workspace.bounds.size.width - resized_width).to_f64() as f32
12734 )
12735 );
12736 });
12737
12738 workspace.update_in(cx, |workspace, window, cx| {
12739 workspace.split_pane(
12740 workspace.active_pane().clone(),
12741 SplitDirection::Right,
12742 window,
12743 cx,
12744 );
12745
12746 let dock = workspace.right_dock().read(cx);
12747 let split_width = workspace
12748 .dock_size(&dock, window, cx)
12749 .expect("flexible dock should keep its user-resized proportion");
12750
12751 assert_eq!(split_width, px(300.));
12752
12753 workspace.bounds.size.width = px(1600.);
12754
12755 let dock = workspace.right_dock().read(cx);
12756 let resized_window_width = workspace
12757 .dock_size(&dock, window, cx)
12758 .expect("flexible dock should preserve proportional size on window resize");
12759
12760 assert_eq!(
12761 resized_window_width,
12762 workspace.bounds.size.width
12763 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12764 );
12765 });
12766 }
12767
12768 #[gpui::test]
12769 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12770 init_test(cx);
12771 let fs = FakeFs::new(cx.executor());
12772
12773 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12774 {
12775 let project = Project::test(fs.clone(), [], cx).await;
12776 let (multi_workspace, cx) =
12777 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12778 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12779
12780 workspace.update(cx, |workspace, _cx| {
12781 workspace.set_random_database_id();
12782 workspace.bounds.size.width = px(800.);
12783 });
12784
12785 let panel = workspace.update_in(cx, |workspace, window, cx| {
12786 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12787 workspace.add_panel(panel.clone(), window, cx);
12788 workspace.toggle_dock(DockPosition::Left, window, cx);
12789 panel
12790 });
12791
12792 workspace.update_in(cx, |workspace, window, cx| {
12793 workspace.resize_left_dock(px(350.), window, cx);
12794 });
12795
12796 cx.run_until_parked();
12797
12798 let persisted = workspace.read_with(cx, |workspace, cx| {
12799 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12800 });
12801 assert_eq!(
12802 persisted.and_then(|s| s.size),
12803 Some(px(350.)),
12804 "fixed-width panel size should be persisted to KVP"
12805 );
12806
12807 // Remove the panel and re-add a fresh instance with the same key.
12808 // The new instance should have its size state restored from KVP.
12809 workspace.update_in(cx, |workspace, window, cx| {
12810 workspace.remove_panel(&panel, window, cx);
12811 });
12812
12813 workspace.update_in(cx, |workspace, window, cx| {
12814 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12815 workspace.add_panel(new_panel, window, cx);
12816
12817 let left_dock = workspace.left_dock().read(cx);
12818 let size_state = left_dock
12819 .panel::<TestPanel>()
12820 .and_then(|p| left_dock.stored_panel_size_state(&p));
12821 assert_eq!(
12822 size_state.and_then(|s| s.size),
12823 Some(px(350.)),
12824 "re-added fixed-width panel should restore persisted size from KVP"
12825 );
12826 });
12827 }
12828
12829 // Flexible panel: both pixel size and ratio are persisted and restored.
12830 {
12831 let project = Project::test(fs.clone(), [], cx).await;
12832 let (multi_workspace, cx) =
12833 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12834 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12835
12836 workspace.update(cx, |workspace, _cx| {
12837 workspace.set_random_database_id();
12838 workspace.bounds.size.width = px(800.);
12839 });
12840
12841 let panel = workspace.update_in(cx, |workspace, window, cx| {
12842 let item = cx.new(|cx| {
12843 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12844 });
12845 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12846
12847 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12848 workspace.add_panel(panel.clone(), window, cx);
12849 workspace.toggle_dock(DockPosition::Right, window, cx);
12850 panel
12851 });
12852
12853 workspace.update_in(cx, |workspace, window, cx| {
12854 workspace.resize_right_dock(px(300.), window, cx);
12855 });
12856
12857 cx.run_until_parked();
12858
12859 let persisted = workspace
12860 .read_with(cx, |workspace, cx| {
12861 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12862 })
12863 .expect("flexible panel state should be persisted to KVP");
12864 assert_eq!(
12865 persisted.size, None,
12866 "flexible panel should not persist a redundant pixel size"
12867 );
12868 let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12869
12870 // Remove the panel and re-add: both size and ratio should be restored.
12871 workspace.update_in(cx, |workspace, window, cx| {
12872 workspace.remove_panel(&panel, window, cx);
12873 });
12874
12875 workspace.update_in(cx, |workspace, window, cx| {
12876 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12877 workspace.add_panel(new_panel, window, cx);
12878
12879 let right_dock = workspace.right_dock().read(cx);
12880 let size_state = right_dock
12881 .panel::<TestPanel>()
12882 .and_then(|p| right_dock.stored_panel_size_state(&p))
12883 .expect("re-added flexible panel should have restored size state from KVP");
12884 assert_eq!(
12885 size_state.size, None,
12886 "re-added flexible panel should not have a persisted pixel size"
12887 );
12888 assert_eq!(
12889 size_state.flex,
12890 Some(original_ratio),
12891 "re-added flexible panel should restore persisted flex"
12892 );
12893 });
12894 }
12895 }
12896
12897 #[gpui::test]
12898 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12899 init_test(cx);
12900 let fs = FakeFs::new(cx.executor());
12901
12902 let project = Project::test(fs, [], cx).await;
12903 let (multi_workspace, cx) =
12904 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12905 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12906
12907 workspace.update(cx, |workspace, _cx| {
12908 workspace.bounds.size.width = px(900.);
12909 });
12910
12911 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12912 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12913 // and the center pane each take half the workspace width.
12914 workspace.update_in(cx, |workspace, window, cx| {
12915 let item = cx.new(|cx| {
12916 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12917 });
12918 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12919
12920 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12921 workspace.add_panel(panel, window, cx);
12922 workspace.toggle_dock(DockPosition::Left, window, cx);
12923
12924 let left_dock = workspace.left_dock().read(cx);
12925 let left_width = workspace
12926 .dock_size(&left_dock, window, cx)
12927 .expect("left dock should have an active panel");
12928
12929 assert_eq!(
12930 left_width,
12931 workspace.bounds.size.width / 2.,
12932 "flexible left panel should split evenly with the center pane"
12933 );
12934 });
12935
12936 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12937 // change horizontal width fractions, so the flexible panel stays at the same
12938 // width as each half of the split.
12939 workspace.update_in(cx, |workspace, window, cx| {
12940 workspace.split_pane(
12941 workspace.active_pane().clone(),
12942 SplitDirection::Down,
12943 window,
12944 cx,
12945 );
12946
12947 let left_dock = workspace.left_dock().read(cx);
12948 let left_width = workspace
12949 .dock_size(&left_dock, window, cx)
12950 .expect("left dock should still have an active panel after vertical split");
12951
12952 assert_eq!(
12953 left_width,
12954 workspace.bounds.size.width / 2.,
12955 "flexible left panel width should match each vertically-split pane"
12956 );
12957 });
12958
12959 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12960 // size reduces the available width, so the flexible left panel and the center
12961 // panes all shrink proportionally to accommodate it.
12962 workspace.update_in(cx, |workspace, window, cx| {
12963 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12964 workspace.add_panel(panel, window, cx);
12965 workspace.toggle_dock(DockPosition::Right, window, cx);
12966
12967 let right_dock = workspace.right_dock().read(cx);
12968 let right_width = workspace
12969 .dock_size(&right_dock, window, cx)
12970 .expect("right dock should have an active panel");
12971
12972 let left_dock = workspace.left_dock().read(cx);
12973 let left_width = workspace
12974 .dock_size(&left_dock, window, cx)
12975 .expect("left dock should still have an active panel");
12976
12977 let available_width = workspace.bounds.size.width - right_width;
12978 assert_eq!(
12979 left_width,
12980 available_width / 2.,
12981 "flexible left panel should shrink proportionally as the right dock takes space"
12982 );
12983 });
12984
12985 // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12986 // flex sizing and the workspace width is divided among left-flex, center
12987 // (implicit flex 1.0), and right-flex.
12988 workspace.update_in(cx, |workspace, window, cx| {
12989 let right_dock = workspace.right_dock().clone();
12990 let right_panel = right_dock
12991 .read(cx)
12992 .visible_panel()
12993 .expect("right dock should have a visible panel")
12994 .clone();
12995 workspace.toggle_dock_panel_flexible_size(
12996 &right_dock,
12997 right_panel.as_ref(),
12998 window,
12999 cx,
13000 );
13001
13002 let right_dock = right_dock.read(cx);
13003 let right_panel = right_dock
13004 .visible_panel()
13005 .expect("right dock should still have a visible panel");
13006 assert!(
13007 right_panel.has_flexible_size(window, cx),
13008 "right panel should now be flexible"
13009 );
13010
13011 let right_size_state = right_dock
13012 .stored_panel_size_state(right_panel.as_ref())
13013 .expect("right panel should have a stored size state after toggling");
13014 let right_flex = right_size_state
13015 .flex
13016 .expect("right panel should have a flex value after toggling");
13017
13018 let left_dock = workspace.left_dock().read(cx);
13019 let left_width = workspace
13020 .dock_size(&left_dock, window, cx)
13021 .expect("left dock should still have an active panel");
13022 let right_width = workspace
13023 .dock_size(&right_dock, window, cx)
13024 .expect("right dock should still have an active panel");
13025
13026 let left_flex = workspace
13027 .default_dock_flex(DockPosition::Left)
13028 .expect("left dock should have a default flex");
13029
13030 let total_flex = left_flex + 1.0 + right_flex;
13031 let expected_left = left_flex / total_flex * workspace.bounds.size.width;
13032 let expected_right = right_flex / total_flex * workspace.bounds.size.width;
13033 assert_eq!(
13034 left_width, expected_left,
13035 "flexible left panel should share workspace width via flex ratios"
13036 );
13037 assert_eq!(
13038 right_width, expected_right,
13039 "flexible right panel should share workspace width via flex ratios"
13040 );
13041 });
13042 }
13043
13044 struct TestModal(FocusHandle);
13045
13046 impl TestModal {
13047 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
13048 Self(cx.focus_handle())
13049 }
13050 }
13051
13052 impl EventEmitter<DismissEvent> for TestModal {}
13053
13054 impl Focusable for TestModal {
13055 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13056 self.0.clone()
13057 }
13058 }
13059
13060 impl ModalView for TestModal {}
13061
13062 impl Render for TestModal {
13063 fn render(
13064 &mut self,
13065 _window: &mut Window,
13066 _cx: &mut Context<TestModal>,
13067 ) -> impl IntoElement {
13068 div().track_focus(&self.0)
13069 }
13070 }
13071
13072 #[gpui::test]
13073 async fn test_panels(cx: &mut gpui::TestAppContext) {
13074 init_test(cx);
13075 let fs = FakeFs::new(cx.executor());
13076
13077 let project = Project::test(fs, [], cx).await;
13078 let (multi_workspace, cx) =
13079 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13080 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13081
13082 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
13083 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
13084 workspace.add_panel(panel_1.clone(), window, cx);
13085 workspace.toggle_dock(DockPosition::Left, window, cx);
13086 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
13087 workspace.add_panel(panel_2.clone(), window, cx);
13088 workspace.toggle_dock(DockPosition::Right, window, cx);
13089
13090 let left_dock = workspace.left_dock();
13091 assert_eq!(
13092 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13093 panel_1.panel_id()
13094 );
13095 assert_eq!(
13096 workspace.dock_size(&left_dock.read(cx), window, cx),
13097 Some(px(300.))
13098 );
13099
13100 workspace.resize_left_dock(px(1337.), window, cx);
13101 assert_eq!(
13102 workspace
13103 .right_dock()
13104 .read(cx)
13105 .visible_panel()
13106 .unwrap()
13107 .panel_id(),
13108 panel_2.panel_id(),
13109 );
13110
13111 (panel_1, panel_2)
13112 });
13113
13114 // Move panel_1 to the right
13115 panel_1.update_in(cx, |panel_1, window, cx| {
13116 panel_1.set_position(DockPosition::Right, window, cx)
13117 });
13118
13119 workspace.update_in(cx, |workspace, window, cx| {
13120 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
13121 // Since it was the only panel on the left, the left dock should now be closed.
13122 assert!(!workspace.left_dock().read(cx).is_open());
13123 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
13124 let right_dock = workspace.right_dock();
13125 assert_eq!(
13126 right_dock.read(cx).visible_panel().unwrap().panel_id(),
13127 panel_1.panel_id()
13128 );
13129 assert_eq!(
13130 right_dock
13131 .read(cx)
13132 .active_panel_size()
13133 .unwrap()
13134 .size
13135 .unwrap(),
13136 px(1337.)
13137 );
13138
13139 // Now we move panel_2 to the left
13140 panel_2.set_position(DockPosition::Left, window, cx);
13141 });
13142
13143 workspace.update(cx, |workspace, cx| {
13144 // Since panel_2 was not visible on the right, we don't open the left dock.
13145 assert!(!workspace.left_dock().read(cx).is_open());
13146 // And the right dock is unaffected in its displaying of panel_1
13147 assert!(workspace.right_dock().read(cx).is_open());
13148 assert_eq!(
13149 workspace
13150 .right_dock()
13151 .read(cx)
13152 .visible_panel()
13153 .unwrap()
13154 .panel_id(),
13155 panel_1.panel_id(),
13156 );
13157 });
13158
13159 // Move panel_1 back to the left
13160 panel_1.update_in(cx, |panel_1, window, cx| {
13161 panel_1.set_position(DockPosition::Left, window, cx)
13162 });
13163
13164 workspace.update_in(cx, |workspace, window, cx| {
13165 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
13166 let left_dock = workspace.left_dock();
13167 assert!(left_dock.read(cx).is_open());
13168 assert_eq!(
13169 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13170 panel_1.panel_id()
13171 );
13172 assert_eq!(
13173 workspace.dock_size(&left_dock.read(cx), window, cx),
13174 Some(px(1337.))
13175 );
13176 // And the right dock should be closed as it no longer has any panels.
13177 assert!(!workspace.right_dock().read(cx).is_open());
13178
13179 // Now we move panel_1 to the bottom
13180 panel_1.set_position(DockPosition::Bottom, window, cx);
13181 });
13182
13183 workspace.update_in(cx, |workspace, window, cx| {
13184 // Since panel_1 was visible on the left, we close the left dock.
13185 assert!(!workspace.left_dock().read(cx).is_open());
13186 // The bottom dock is sized based on the panel's default size,
13187 // since the panel orientation changed from vertical to horizontal.
13188 let bottom_dock = workspace.bottom_dock();
13189 assert_eq!(
13190 workspace.dock_size(&bottom_dock.read(cx), window, cx),
13191 Some(px(300.))
13192 );
13193 // Close bottom dock and move panel_1 back to the left.
13194 bottom_dock.update(cx, |bottom_dock, cx| {
13195 bottom_dock.set_open(false, window, cx)
13196 });
13197 panel_1.set_position(DockPosition::Left, window, cx);
13198 });
13199
13200 // Emit activated event on panel 1
13201 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
13202
13203 // Now the left dock is open and panel_1 is active and focused.
13204 workspace.update_in(cx, |workspace, window, cx| {
13205 let left_dock = workspace.left_dock();
13206 assert!(left_dock.read(cx).is_open());
13207 assert_eq!(
13208 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13209 panel_1.panel_id(),
13210 );
13211 assert!(panel_1.focus_handle(cx).is_focused(window));
13212 });
13213
13214 // Emit closed event on panel 2, which is not active
13215 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13216
13217 // Wo don't close the left dock, because panel_2 wasn't the active panel
13218 workspace.update(cx, |workspace, cx| {
13219 let left_dock = workspace.left_dock();
13220 assert!(left_dock.read(cx).is_open());
13221 assert_eq!(
13222 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13223 panel_1.panel_id(),
13224 );
13225 });
13226
13227 // Emitting a ZoomIn event shows the panel as zoomed.
13228 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13229 workspace.read_with(cx, |workspace, _| {
13230 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13231 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13232 });
13233
13234 // Move panel to another dock while it is zoomed
13235 panel_1.update_in(cx, |panel, window, cx| {
13236 panel.set_position(DockPosition::Right, window, cx)
13237 });
13238 workspace.read_with(cx, |workspace, _| {
13239 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13240
13241 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13242 });
13243
13244 // This is a helper for getting a:
13245 // - valid focus on an element,
13246 // - that isn't a part of the panes and panels system of the Workspace,
13247 // - and doesn't trigger the 'on_focus_lost' API.
13248 let focus_other_view = {
13249 let workspace = workspace.clone();
13250 move |cx: &mut VisualTestContext| {
13251 workspace.update_in(cx, |workspace, window, cx| {
13252 if workspace.active_modal::<TestModal>(cx).is_some() {
13253 workspace.toggle_modal(window, cx, TestModal::new);
13254 workspace.toggle_modal(window, cx, TestModal::new);
13255 } else {
13256 workspace.toggle_modal(window, cx, TestModal::new);
13257 }
13258 })
13259 }
13260 };
13261
13262 // If focus is transferred to another view that's not a panel or another pane, we still show
13263 // the panel as zoomed.
13264 focus_other_view(cx);
13265 workspace.read_with(cx, |workspace, _| {
13266 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13267 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13268 });
13269
13270 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13271 workspace.update_in(cx, |_workspace, window, cx| {
13272 cx.focus_self(window);
13273 });
13274 workspace.read_with(cx, |workspace, _| {
13275 assert_eq!(workspace.zoomed, None);
13276 assert_eq!(workspace.zoomed_position, None);
13277 });
13278
13279 // If focus is transferred again to another view that's not a panel or a pane, we won't
13280 // show the panel as zoomed because it wasn't zoomed before.
13281 focus_other_view(cx);
13282 workspace.read_with(cx, |workspace, _| {
13283 assert_eq!(workspace.zoomed, None);
13284 assert_eq!(workspace.zoomed_position, None);
13285 });
13286
13287 // When the panel is activated, it is zoomed again.
13288 cx.dispatch_action(ToggleRightDock);
13289 workspace.read_with(cx, |workspace, _| {
13290 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13291 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13292 });
13293
13294 // Emitting a ZoomOut event unzooms the panel.
13295 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13296 workspace.read_with(cx, |workspace, _| {
13297 assert_eq!(workspace.zoomed, None);
13298 assert_eq!(workspace.zoomed_position, None);
13299 });
13300
13301 // Emit closed event on panel 1, which is active
13302 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13303
13304 // Now the left dock is closed, because panel_1 was the active panel
13305 workspace.update(cx, |workspace, cx| {
13306 let right_dock = workspace.right_dock();
13307 assert!(!right_dock.read(cx).is_open());
13308 });
13309 }
13310
13311 #[gpui::test]
13312 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13313 init_test(cx);
13314
13315 let fs = FakeFs::new(cx.background_executor.clone());
13316 let project = Project::test(fs, [], cx).await;
13317 let (workspace, cx) =
13318 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13319 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13320
13321 let dirty_regular_buffer = cx.new(|cx| {
13322 TestItem::new(cx)
13323 .with_dirty(true)
13324 .with_label("1.txt")
13325 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13326 });
13327 let dirty_regular_buffer_2 = cx.new(|cx| {
13328 TestItem::new(cx)
13329 .with_dirty(true)
13330 .with_label("2.txt")
13331 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13332 });
13333 let dirty_multi_buffer_with_both = cx.new(|cx| {
13334 TestItem::new(cx)
13335 .with_dirty(true)
13336 .with_buffer_kind(ItemBufferKind::Multibuffer)
13337 .with_label("Fake Project Search")
13338 .with_project_items(&[
13339 dirty_regular_buffer.read(cx).project_items[0].clone(),
13340 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13341 ])
13342 });
13343 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13344 workspace.update_in(cx, |workspace, window, cx| {
13345 workspace.add_item(
13346 pane.clone(),
13347 Box::new(dirty_regular_buffer.clone()),
13348 None,
13349 false,
13350 false,
13351 window,
13352 cx,
13353 );
13354 workspace.add_item(
13355 pane.clone(),
13356 Box::new(dirty_regular_buffer_2.clone()),
13357 None,
13358 false,
13359 false,
13360 window,
13361 cx,
13362 );
13363 workspace.add_item(
13364 pane.clone(),
13365 Box::new(dirty_multi_buffer_with_both.clone()),
13366 None,
13367 false,
13368 false,
13369 window,
13370 cx,
13371 );
13372 });
13373
13374 pane.update_in(cx, |pane, window, cx| {
13375 pane.activate_item(2, true, true, window, cx);
13376 assert_eq!(
13377 pane.active_item().unwrap().item_id(),
13378 multi_buffer_with_both_files_id,
13379 "Should select the multi buffer in the pane"
13380 );
13381 });
13382 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13383 pane.close_other_items(
13384 &CloseOtherItems {
13385 save_intent: Some(SaveIntent::Save),
13386 close_pinned: true,
13387 },
13388 None,
13389 window,
13390 cx,
13391 )
13392 });
13393 cx.background_executor.run_until_parked();
13394 assert!(!cx.has_pending_prompt());
13395 close_all_but_multi_buffer_task
13396 .await
13397 .expect("Closing all buffers but the multi buffer failed");
13398 pane.update(cx, |pane, cx| {
13399 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13400 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13401 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13402 assert_eq!(pane.items_len(), 1);
13403 assert_eq!(
13404 pane.active_item().unwrap().item_id(),
13405 multi_buffer_with_both_files_id,
13406 "Should have only the multi buffer left in the pane"
13407 );
13408 assert!(
13409 dirty_multi_buffer_with_both.read(cx).is_dirty,
13410 "The multi buffer containing the unsaved buffer should still be dirty"
13411 );
13412 });
13413
13414 dirty_regular_buffer.update(cx, |buffer, cx| {
13415 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13416 });
13417
13418 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13419 pane.close_active_item(
13420 &CloseActiveItem {
13421 save_intent: Some(SaveIntent::Close),
13422 close_pinned: false,
13423 },
13424 window,
13425 cx,
13426 )
13427 });
13428 cx.background_executor.run_until_parked();
13429 assert!(
13430 cx.has_pending_prompt(),
13431 "Dirty multi buffer should prompt a save dialog"
13432 );
13433 cx.simulate_prompt_answer("Save");
13434 cx.background_executor.run_until_parked();
13435 close_multi_buffer_task
13436 .await
13437 .expect("Closing the multi buffer failed");
13438 pane.update(cx, |pane, cx| {
13439 assert_eq!(
13440 dirty_multi_buffer_with_both.read(cx).save_count,
13441 1,
13442 "Multi buffer item should get be saved"
13443 );
13444 // Test impl does not save inner items, so we do not assert them
13445 assert_eq!(
13446 pane.items_len(),
13447 0,
13448 "No more items should be left in the pane"
13449 );
13450 assert!(pane.active_item().is_none());
13451 });
13452 }
13453
13454 #[gpui::test]
13455 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13456 cx: &mut TestAppContext,
13457 ) {
13458 init_test(cx);
13459
13460 let fs = FakeFs::new(cx.background_executor.clone());
13461 let project = Project::test(fs, [], cx).await;
13462 let (workspace, cx) =
13463 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13464 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13465
13466 let dirty_regular_buffer = cx.new(|cx| {
13467 TestItem::new(cx)
13468 .with_dirty(true)
13469 .with_label("1.txt")
13470 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13471 });
13472 let dirty_regular_buffer_2 = cx.new(|cx| {
13473 TestItem::new(cx)
13474 .with_dirty(true)
13475 .with_label("2.txt")
13476 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13477 });
13478 let clear_regular_buffer = cx.new(|cx| {
13479 TestItem::new(cx)
13480 .with_label("3.txt")
13481 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13482 });
13483
13484 let dirty_multi_buffer_with_both = cx.new(|cx| {
13485 TestItem::new(cx)
13486 .with_dirty(true)
13487 .with_buffer_kind(ItemBufferKind::Multibuffer)
13488 .with_label("Fake Project Search")
13489 .with_project_items(&[
13490 dirty_regular_buffer.read(cx).project_items[0].clone(),
13491 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13492 clear_regular_buffer.read(cx).project_items[0].clone(),
13493 ])
13494 });
13495 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13496 workspace.update_in(cx, |workspace, window, cx| {
13497 workspace.add_item(
13498 pane.clone(),
13499 Box::new(dirty_regular_buffer.clone()),
13500 None,
13501 false,
13502 false,
13503 window,
13504 cx,
13505 );
13506 workspace.add_item(
13507 pane.clone(),
13508 Box::new(dirty_multi_buffer_with_both.clone()),
13509 None,
13510 false,
13511 false,
13512 window,
13513 cx,
13514 );
13515 });
13516
13517 pane.update_in(cx, |pane, window, cx| {
13518 pane.activate_item(1, true, true, window, cx);
13519 assert_eq!(
13520 pane.active_item().unwrap().item_id(),
13521 multi_buffer_with_both_files_id,
13522 "Should select the multi buffer in the pane"
13523 );
13524 });
13525 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13526 pane.close_active_item(
13527 &CloseActiveItem {
13528 save_intent: None,
13529 close_pinned: false,
13530 },
13531 window,
13532 cx,
13533 )
13534 });
13535 cx.background_executor.run_until_parked();
13536 assert!(
13537 cx.has_pending_prompt(),
13538 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13539 );
13540 }
13541
13542 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13543 /// closed when they are deleted from disk.
13544 #[gpui::test]
13545 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13546 init_test(cx);
13547
13548 // Enable the close_on_disk_deletion setting
13549 cx.update_global(|store: &mut SettingsStore, cx| {
13550 store.update_user_settings(cx, |settings| {
13551 settings.workspace.close_on_file_delete = Some(true);
13552 });
13553 });
13554
13555 let fs = FakeFs::new(cx.background_executor.clone());
13556 let project = Project::test(fs, [], cx).await;
13557 let (workspace, cx) =
13558 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13559 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13560
13561 // Create a test item that simulates a file
13562 let item = cx.new(|cx| {
13563 TestItem::new(cx)
13564 .with_label("test.txt")
13565 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13566 });
13567
13568 // Add item to workspace
13569 workspace.update_in(cx, |workspace, window, cx| {
13570 workspace.add_item(
13571 pane.clone(),
13572 Box::new(item.clone()),
13573 None,
13574 false,
13575 false,
13576 window,
13577 cx,
13578 );
13579 });
13580
13581 // Verify the item is in the pane
13582 pane.read_with(cx, |pane, _| {
13583 assert_eq!(pane.items().count(), 1);
13584 });
13585
13586 // Simulate file deletion by setting the item's deleted state
13587 item.update(cx, |item, _| {
13588 item.set_has_deleted_file(true);
13589 });
13590
13591 // Emit UpdateTab event to trigger the close behavior
13592 cx.run_until_parked();
13593 item.update(cx, |_, cx| {
13594 cx.emit(ItemEvent::UpdateTab);
13595 });
13596
13597 // Allow the close operation to complete
13598 cx.run_until_parked();
13599
13600 // Verify the item was automatically closed
13601 pane.read_with(cx, |pane, _| {
13602 assert_eq!(
13603 pane.items().count(),
13604 0,
13605 "Item should be automatically closed when file is deleted"
13606 );
13607 });
13608 }
13609
13610 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13611 /// open with a strikethrough when they are deleted from disk.
13612 #[gpui::test]
13613 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13614 init_test(cx);
13615
13616 // Ensure close_on_disk_deletion is disabled (default)
13617 cx.update_global(|store: &mut SettingsStore, cx| {
13618 store.update_user_settings(cx, |settings| {
13619 settings.workspace.close_on_file_delete = Some(false);
13620 });
13621 });
13622
13623 let fs = FakeFs::new(cx.background_executor.clone());
13624 let project = Project::test(fs, [], cx).await;
13625 let (workspace, cx) =
13626 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13627 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13628
13629 // Create a test item that simulates a file
13630 let item = cx.new(|cx| {
13631 TestItem::new(cx)
13632 .with_label("test.txt")
13633 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13634 });
13635
13636 // Add item to workspace
13637 workspace.update_in(cx, |workspace, window, cx| {
13638 workspace.add_item(
13639 pane.clone(),
13640 Box::new(item.clone()),
13641 None,
13642 false,
13643 false,
13644 window,
13645 cx,
13646 );
13647 });
13648
13649 // Verify the item is in the pane
13650 pane.read_with(cx, |pane, _| {
13651 assert_eq!(pane.items().count(), 1);
13652 });
13653
13654 // Simulate file deletion
13655 item.update(cx, |item, _| {
13656 item.set_has_deleted_file(true);
13657 });
13658
13659 // Emit UpdateTab event
13660 cx.run_until_parked();
13661 item.update(cx, |_, cx| {
13662 cx.emit(ItemEvent::UpdateTab);
13663 });
13664
13665 // Allow any potential close operation to complete
13666 cx.run_until_parked();
13667
13668 // Verify the item remains open (with strikethrough)
13669 pane.read_with(cx, |pane, _| {
13670 assert_eq!(
13671 pane.items().count(),
13672 1,
13673 "Item should remain open when close_on_disk_deletion is disabled"
13674 );
13675 });
13676
13677 // Verify the item shows as deleted
13678 item.read_with(cx, |item, _| {
13679 assert!(
13680 item.has_deleted_file,
13681 "Item should be marked as having deleted file"
13682 );
13683 });
13684 }
13685
13686 /// Tests that dirty files are not automatically closed when deleted from disk,
13687 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13688 /// unsaved changes without being prompted.
13689 #[gpui::test]
13690 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13691 init_test(cx);
13692
13693 // Enable the close_on_file_delete setting
13694 cx.update_global(|store: &mut SettingsStore, cx| {
13695 store.update_user_settings(cx, |settings| {
13696 settings.workspace.close_on_file_delete = Some(true);
13697 });
13698 });
13699
13700 let fs = FakeFs::new(cx.background_executor.clone());
13701 let project = Project::test(fs, [], cx).await;
13702 let (workspace, cx) =
13703 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13704 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13705
13706 // Create a dirty test item
13707 let item = cx.new(|cx| {
13708 TestItem::new(cx)
13709 .with_dirty(true)
13710 .with_label("test.txt")
13711 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13712 });
13713
13714 // Add item to workspace
13715 workspace.update_in(cx, |workspace, window, cx| {
13716 workspace.add_item(
13717 pane.clone(),
13718 Box::new(item.clone()),
13719 None,
13720 false,
13721 false,
13722 window,
13723 cx,
13724 );
13725 });
13726
13727 // Simulate file deletion
13728 item.update(cx, |item, _| {
13729 item.set_has_deleted_file(true);
13730 });
13731
13732 // Emit UpdateTab event to trigger the close behavior
13733 cx.run_until_parked();
13734 item.update(cx, |_, cx| {
13735 cx.emit(ItemEvent::UpdateTab);
13736 });
13737
13738 // Allow any potential close operation to complete
13739 cx.run_until_parked();
13740
13741 // Verify the item remains open (dirty files are not auto-closed)
13742 pane.read_with(cx, |pane, _| {
13743 assert_eq!(
13744 pane.items().count(),
13745 1,
13746 "Dirty items should not be automatically closed even when file is deleted"
13747 );
13748 });
13749
13750 // Verify the item is marked as deleted and still dirty
13751 item.read_with(cx, |item, _| {
13752 assert!(
13753 item.has_deleted_file,
13754 "Item should be marked as having deleted file"
13755 );
13756 assert!(item.is_dirty, "Item should still be dirty");
13757 });
13758 }
13759
13760 /// Tests that navigation history is cleaned up when files are auto-closed
13761 /// due to deletion from disk.
13762 #[gpui::test]
13763 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13764 init_test(cx);
13765
13766 // Enable the close_on_file_delete setting
13767 cx.update_global(|store: &mut SettingsStore, cx| {
13768 store.update_user_settings(cx, |settings| {
13769 settings.workspace.close_on_file_delete = Some(true);
13770 });
13771 });
13772
13773 let fs = FakeFs::new(cx.background_executor.clone());
13774 let project = Project::test(fs, [], cx).await;
13775 let (workspace, cx) =
13776 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13777 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13778
13779 // Create test items
13780 let item1 = cx.new(|cx| {
13781 TestItem::new(cx)
13782 .with_label("test1.txt")
13783 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13784 });
13785 let item1_id = item1.item_id();
13786
13787 let item2 = cx.new(|cx| {
13788 TestItem::new(cx)
13789 .with_label("test2.txt")
13790 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13791 });
13792
13793 // Add items to workspace
13794 workspace.update_in(cx, |workspace, window, cx| {
13795 workspace.add_item(
13796 pane.clone(),
13797 Box::new(item1.clone()),
13798 None,
13799 false,
13800 false,
13801 window,
13802 cx,
13803 );
13804 workspace.add_item(
13805 pane.clone(),
13806 Box::new(item2.clone()),
13807 None,
13808 false,
13809 false,
13810 window,
13811 cx,
13812 );
13813 });
13814
13815 // Activate item1 to ensure it gets navigation entries
13816 pane.update_in(cx, |pane, window, cx| {
13817 pane.activate_item(0, true, true, window, cx);
13818 });
13819
13820 // Switch to item2 and back to create navigation history
13821 pane.update_in(cx, |pane, window, cx| {
13822 pane.activate_item(1, true, true, window, cx);
13823 });
13824 cx.run_until_parked();
13825
13826 pane.update_in(cx, |pane, window, cx| {
13827 pane.activate_item(0, true, true, window, cx);
13828 });
13829 cx.run_until_parked();
13830
13831 // Simulate file deletion for item1
13832 item1.update(cx, |item, _| {
13833 item.set_has_deleted_file(true);
13834 });
13835
13836 // Emit UpdateTab event to trigger the close behavior
13837 item1.update(cx, |_, cx| {
13838 cx.emit(ItemEvent::UpdateTab);
13839 });
13840 cx.run_until_parked();
13841
13842 // Verify item1 was closed
13843 pane.read_with(cx, |pane, _| {
13844 assert_eq!(
13845 pane.items().count(),
13846 1,
13847 "Should have 1 item remaining after auto-close"
13848 );
13849 });
13850
13851 // Check navigation history after close
13852 let has_item = pane.read_with(cx, |pane, cx| {
13853 let mut has_item = false;
13854 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13855 if entry.item.id() == item1_id {
13856 has_item = true;
13857 }
13858 });
13859 has_item
13860 });
13861
13862 assert!(
13863 !has_item,
13864 "Navigation history should not contain closed item entries"
13865 );
13866 }
13867
13868 #[gpui::test]
13869 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13870 cx: &mut TestAppContext,
13871 ) {
13872 init_test(cx);
13873
13874 let fs = FakeFs::new(cx.background_executor.clone());
13875 let project = Project::test(fs, [], cx).await;
13876 let (workspace, cx) =
13877 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13878 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13879
13880 let dirty_regular_buffer = cx.new(|cx| {
13881 TestItem::new(cx)
13882 .with_dirty(true)
13883 .with_label("1.txt")
13884 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13885 });
13886 let dirty_regular_buffer_2 = cx.new(|cx| {
13887 TestItem::new(cx)
13888 .with_dirty(true)
13889 .with_label("2.txt")
13890 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13891 });
13892 let clear_regular_buffer = cx.new(|cx| {
13893 TestItem::new(cx)
13894 .with_label("3.txt")
13895 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13896 });
13897
13898 let dirty_multi_buffer = cx.new(|cx| {
13899 TestItem::new(cx)
13900 .with_dirty(true)
13901 .with_buffer_kind(ItemBufferKind::Multibuffer)
13902 .with_label("Fake Project Search")
13903 .with_project_items(&[
13904 dirty_regular_buffer.read(cx).project_items[0].clone(),
13905 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13906 clear_regular_buffer.read(cx).project_items[0].clone(),
13907 ])
13908 });
13909 workspace.update_in(cx, |workspace, window, cx| {
13910 workspace.add_item(
13911 pane.clone(),
13912 Box::new(dirty_regular_buffer.clone()),
13913 None,
13914 false,
13915 false,
13916 window,
13917 cx,
13918 );
13919 workspace.add_item(
13920 pane.clone(),
13921 Box::new(dirty_regular_buffer_2.clone()),
13922 None,
13923 false,
13924 false,
13925 window,
13926 cx,
13927 );
13928 workspace.add_item(
13929 pane.clone(),
13930 Box::new(dirty_multi_buffer.clone()),
13931 None,
13932 false,
13933 false,
13934 window,
13935 cx,
13936 );
13937 });
13938
13939 pane.update_in(cx, |pane, window, cx| {
13940 pane.activate_item(2, true, true, window, cx);
13941 assert_eq!(
13942 pane.active_item().unwrap().item_id(),
13943 dirty_multi_buffer.item_id(),
13944 "Should select the multi buffer in the pane"
13945 );
13946 });
13947 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13948 pane.close_active_item(
13949 &CloseActiveItem {
13950 save_intent: None,
13951 close_pinned: false,
13952 },
13953 window,
13954 cx,
13955 )
13956 });
13957 cx.background_executor.run_until_parked();
13958 assert!(
13959 !cx.has_pending_prompt(),
13960 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13961 );
13962 close_multi_buffer_task
13963 .await
13964 .expect("Closing multi buffer failed");
13965 pane.update(cx, |pane, cx| {
13966 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13967 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13968 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13969 assert_eq!(
13970 pane.items()
13971 .map(|item| item.item_id())
13972 .sorted()
13973 .collect::<Vec<_>>(),
13974 vec![
13975 dirty_regular_buffer.item_id(),
13976 dirty_regular_buffer_2.item_id(),
13977 ],
13978 "Should have no multi buffer left in the pane"
13979 );
13980 assert!(dirty_regular_buffer.read(cx).is_dirty);
13981 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13982 });
13983 }
13984
13985 #[gpui::test]
13986 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13987 init_test(cx);
13988 let fs = FakeFs::new(cx.executor());
13989 let project = Project::test(fs, [], cx).await;
13990 let (multi_workspace, cx) =
13991 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13992 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13993
13994 // Add a new panel to the right dock, opening the dock and setting the
13995 // focus to the new panel.
13996 let panel = workspace.update_in(cx, |workspace, window, cx| {
13997 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13998 workspace.add_panel(panel.clone(), window, cx);
13999
14000 workspace
14001 .right_dock()
14002 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14003
14004 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14005
14006 panel
14007 });
14008
14009 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14010 // panel to the next valid position which, in this case, is the left
14011 // dock.
14012 cx.dispatch_action(MoveFocusedPanelToNextPosition);
14013 workspace.update(cx, |workspace, cx| {
14014 assert!(workspace.left_dock().read(cx).is_open());
14015 assert_eq!(panel.read(cx).position, DockPosition::Left);
14016 });
14017
14018 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14019 // panel to the next valid position which, in this case, is the bottom
14020 // dock.
14021 cx.dispatch_action(MoveFocusedPanelToNextPosition);
14022 workspace.update(cx, |workspace, cx| {
14023 assert!(workspace.bottom_dock().read(cx).is_open());
14024 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
14025 });
14026
14027 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
14028 // around moving the panel to its initial position, the right dock.
14029 cx.dispatch_action(MoveFocusedPanelToNextPosition);
14030 workspace.update(cx, |workspace, cx| {
14031 assert!(workspace.right_dock().read(cx).is_open());
14032 assert_eq!(panel.read(cx).position, DockPosition::Right);
14033 });
14034
14035 // Remove focus from the panel, ensuring that, if the panel is not
14036 // focused, the `MoveFocusedPanelToNextPosition` action does not update
14037 // the panel's position, so the panel is still in the right dock.
14038 workspace.update_in(cx, |workspace, window, cx| {
14039 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14040 });
14041
14042 cx.dispatch_action(MoveFocusedPanelToNextPosition);
14043 workspace.update(cx, |workspace, cx| {
14044 assert!(workspace.right_dock().read(cx).is_open());
14045 assert_eq!(panel.read(cx).position, DockPosition::Right);
14046 });
14047 }
14048
14049 #[gpui::test]
14050 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
14051 init_test(cx);
14052
14053 let fs = FakeFs::new(cx.executor());
14054 let project = Project::test(fs, [], cx).await;
14055 let (workspace, cx) =
14056 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14057
14058 let item_1 = cx.new(|cx| {
14059 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14060 });
14061 workspace.update_in(cx, |workspace, window, cx| {
14062 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14063 workspace.move_item_to_pane_in_direction(
14064 &MoveItemToPaneInDirection {
14065 direction: SplitDirection::Right,
14066 focus: true,
14067 clone: false,
14068 },
14069 window,
14070 cx,
14071 );
14072 workspace.move_item_to_pane_at_index(
14073 &MoveItemToPane {
14074 destination: 3,
14075 focus: true,
14076 clone: false,
14077 },
14078 window,
14079 cx,
14080 );
14081
14082 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
14083 assert_eq!(
14084 pane_items_paths(&workspace.active_pane, cx),
14085 vec!["first.txt".to_string()],
14086 "Single item was not moved anywhere"
14087 );
14088 });
14089
14090 let item_2 = cx.new(|cx| {
14091 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
14092 });
14093 workspace.update_in(cx, |workspace, window, cx| {
14094 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
14095 assert_eq!(
14096 pane_items_paths(&workspace.panes[0], cx),
14097 vec!["first.txt".to_string(), "second.txt".to_string()],
14098 );
14099 workspace.move_item_to_pane_in_direction(
14100 &MoveItemToPaneInDirection {
14101 direction: SplitDirection::Right,
14102 focus: true,
14103 clone: false,
14104 },
14105 window,
14106 cx,
14107 );
14108
14109 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
14110 assert_eq!(
14111 pane_items_paths(&workspace.panes[0], cx),
14112 vec!["first.txt".to_string()],
14113 "After moving, one item should be left in the original pane"
14114 );
14115 assert_eq!(
14116 pane_items_paths(&workspace.panes[1], cx),
14117 vec!["second.txt".to_string()],
14118 "New item should have been moved to the new pane"
14119 );
14120 });
14121
14122 let item_3 = cx.new(|cx| {
14123 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
14124 });
14125 workspace.update_in(cx, |workspace, window, cx| {
14126 let original_pane = workspace.panes[0].clone();
14127 workspace.set_active_pane(&original_pane, window, cx);
14128 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
14129 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
14130 assert_eq!(
14131 pane_items_paths(&workspace.active_pane, cx),
14132 vec!["first.txt".to_string(), "third.txt".to_string()],
14133 "New pane should be ready to move one item out"
14134 );
14135
14136 workspace.move_item_to_pane_at_index(
14137 &MoveItemToPane {
14138 destination: 3,
14139 focus: true,
14140 clone: false,
14141 },
14142 window,
14143 cx,
14144 );
14145 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
14146 assert_eq!(
14147 pane_items_paths(&workspace.active_pane, cx),
14148 vec!["first.txt".to_string()],
14149 "After moving, one item should be left in the original pane"
14150 );
14151 assert_eq!(
14152 pane_items_paths(&workspace.panes[1], cx),
14153 vec!["second.txt".to_string()],
14154 "Previously created pane should be unchanged"
14155 );
14156 assert_eq!(
14157 pane_items_paths(&workspace.panes[2], cx),
14158 vec!["third.txt".to_string()],
14159 "New item should have been moved to the new pane"
14160 );
14161 });
14162 }
14163
14164 #[gpui::test]
14165 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
14166 init_test(cx);
14167
14168 let fs = FakeFs::new(cx.executor());
14169 let project = Project::test(fs, [], cx).await;
14170 let (workspace, cx) =
14171 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14172
14173 let item_1 = cx.new(|cx| {
14174 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14175 });
14176 workspace.update_in(cx, |workspace, window, cx| {
14177 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14178 workspace.move_item_to_pane_in_direction(
14179 &MoveItemToPaneInDirection {
14180 direction: SplitDirection::Right,
14181 focus: true,
14182 clone: true,
14183 },
14184 window,
14185 cx,
14186 );
14187 });
14188 cx.run_until_parked();
14189 workspace.update_in(cx, |workspace, window, cx| {
14190 workspace.move_item_to_pane_at_index(
14191 &MoveItemToPane {
14192 destination: 3,
14193 focus: true,
14194 clone: true,
14195 },
14196 window,
14197 cx,
14198 );
14199 });
14200 cx.run_until_parked();
14201
14202 workspace.update(cx, |workspace, cx| {
14203 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
14204 for pane in workspace.panes() {
14205 assert_eq!(
14206 pane_items_paths(pane, cx),
14207 vec!["first.txt".to_string()],
14208 "Single item exists in all panes"
14209 );
14210 }
14211 });
14212
14213 // verify that the active pane has been updated after waiting for the
14214 // pane focus event to fire and resolve
14215 workspace.read_with(cx, |workspace, _app| {
14216 assert_eq!(
14217 workspace.active_pane(),
14218 &workspace.panes[2],
14219 "The third pane should be the active one: {:?}",
14220 workspace.panes
14221 );
14222 })
14223 }
14224
14225 #[gpui::test]
14226 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
14227 init_test(cx);
14228
14229 let fs = FakeFs::new(cx.executor());
14230 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14231
14232 let project = Project::test(fs, ["root".as_ref()], cx).await;
14233 let (workspace, cx) =
14234 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14235
14236 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14237 // Add item to pane A with project path
14238 let item_a = cx.new(|cx| {
14239 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14240 });
14241 workspace.update_in(cx, |workspace, window, cx| {
14242 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14243 });
14244
14245 // Split to create pane B
14246 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14247 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14248 });
14249
14250 // Add item with SAME project path to pane B, and pin it
14251 let item_b = cx.new(|cx| {
14252 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14253 });
14254 pane_b.update_in(cx, |pane, window, cx| {
14255 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14256 pane.set_pinned_count(1);
14257 });
14258
14259 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14260 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14261
14262 // close_pinned: false should only close the unpinned copy
14263 workspace.update_in(cx, |workspace, window, cx| {
14264 workspace.close_item_in_all_panes(
14265 &CloseItemInAllPanes {
14266 save_intent: Some(SaveIntent::Close),
14267 close_pinned: false,
14268 },
14269 window,
14270 cx,
14271 )
14272 });
14273 cx.executor().run_until_parked();
14274
14275 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14276 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14277 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14278 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14279
14280 // Split again, seeing as closing the previous item also closed its
14281 // pane, so only pane remains, which does not allow us to properly test
14282 // that both items close when `close_pinned: true`.
14283 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14284 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14285 });
14286
14287 // Add an item with the same project path to pane C so that
14288 // close_item_in_all_panes can determine what to close across all panes
14289 // (it reads the active item from the active pane, and split_pane
14290 // creates an empty pane).
14291 let item_c = cx.new(|cx| {
14292 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14293 });
14294 pane_c.update_in(cx, |pane, window, cx| {
14295 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14296 });
14297
14298 // close_pinned: true should close the pinned copy too
14299 workspace.update_in(cx, |workspace, window, cx| {
14300 let panes_count = workspace.panes().len();
14301 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14302
14303 workspace.close_item_in_all_panes(
14304 &CloseItemInAllPanes {
14305 save_intent: Some(SaveIntent::Close),
14306 close_pinned: true,
14307 },
14308 window,
14309 cx,
14310 )
14311 });
14312 cx.executor().run_until_parked();
14313
14314 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14315 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14316 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14317 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14318 }
14319
14320 mod register_project_item_tests {
14321
14322 use super::*;
14323
14324 // View
14325 struct TestPngItemView {
14326 focus_handle: FocusHandle,
14327 }
14328 // Model
14329 struct TestPngItem {}
14330
14331 impl project::ProjectItem for TestPngItem {
14332 fn try_open(
14333 _project: &Entity<Project>,
14334 path: &ProjectPath,
14335 cx: &mut App,
14336 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14337 if path.path.extension().unwrap() == "png" {
14338 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14339 } else {
14340 None
14341 }
14342 }
14343
14344 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14345 None
14346 }
14347
14348 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14349 None
14350 }
14351
14352 fn is_dirty(&self) -> bool {
14353 false
14354 }
14355 }
14356
14357 impl Item for TestPngItemView {
14358 type Event = ();
14359 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14360 "".into()
14361 }
14362 }
14363 impl EventEmitter<()> for TestPngItemView {}
14364 impl Focusable for TestPngItemView {
14365 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14366 self.focus_handle.clone()
14367 }
14368 }
14369
14370 impl Render for TestPngItemView {
14371 fn render(
14372 &mut self,
14373 _window: &mut Window,
14374 _cx: &mut Context<Self>,
14375 ) -> impl IntoElement {
14376 Empty
14377 }
14378 }
14379
14380 impl ProjectItem for TestPngItemView {
14381 type Item = TestPngItem;
14382
14383 fn for_project_item(
14384 _project: Entity<Project>,
14385 _pane: Option<&Pane>,
14386 _item: Entity<Self::Item>,
14387 _: &mut Window,
14388 cx: &mut Context<Self>,
14389 ) -> Self
14390 where
14391 Self: Sized,
14392 {
14393 Self {
14394 focus_handle: cx.focus_handle(),
14395 }
14396 }
14397 }
14398
14399 // View
14400 struct TestIpynbItemView {
14401 focus_handle: FocusHandle,
14402 }
14403 // Model
14404 struct TestIpynbItem {}
14405
14406 impl project::ProjectItem for TestIpynbItem {
14407 fn try_open(
14408 _project: &Entity<Project>,
14409 path: &ProjectPath,
14410 cx: &mut App,
14411 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14412 if path.path.extension().unwrap() == "ipynb" {
14413 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14414 } else {
14415 None
14416 }
14417 }
14418
14419 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14420 None
14421 }
14422
14423 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14424 None
14425 }
14426
14427 fn is_dirty(&self) -> bool {
14428 false
14429 }
14430 }
14431
14432 impl Item for TestIpynbItemView {
14433 type Event = ();
14434 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14435 "".into()
14436 }
14437 }
14438 impl EventEmitter<()> for TestIpynbItemView {}
14439 impl Focusable for TestIpynbItemView {
14440 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14441 self.focus_handle.clone()
14442 }
14443 }
14444
14445 impl Render for TestIpynbItemView {
14446 fn render(
14447 &mut self,
14448 _window: &mut Window,
14449 _cx: &mut Context<Self>,
14450 ) -> impl IntoElement {
14451 Empty
14452 }
14453 }
14454
14455 impl ProjectItem for TestIpynbItemView {
14456 type Item = TestIpynbItem;
14457
14458 fn for_project_item(
14459 _project: Entity<Project>,
14460 _pane: Option<&Pane>,
14461 _item: Entity<Self::Item>,
14462 _: &mut Window,
14463 cx: &mut Context<Self>,
14464 ) -> Self
14465 where
14466 Self: Sized,
14467 {
14468 Self {
14469 focus_handle: cx.focus_handle(),
14470 }
14471 }
14472 }
14473
14474 struct TestAlternatePngItemView {
14475 focus_handle: FocusHandle,
14476 }
14477
14478 impl Item for TestAlternatePngItemView {
14479 type Event = ();
14480 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14481 "".into()
14482 }
14483 }
14484
14485 impl EventEmitter<()> for TestAlternatePngItemView {}
14486 impl Focusable for TestAlternatePngItemView {
14487 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14488 self.focus_handle.clone()
14489 }
14490 }
14491
14492 impl Render for TestAlternatePngItemView {
14493 fn render(
14494 &mut self,
14495 _window: &mut Window,
14496 _cx: &mut Context<Self>,
14497 ) -> impl IntoElement {
14498 Empty
14499 }
14500 }
14501
14502 impl ProjectItem for TestAlternatePngItemView {
14503 type Item = TestPngItem;
14504
14505 fn for_project_item(
14506 _project: Entity<Project>,
14507 _pane: Option<&Pane>,
14508 _item: Entity<Self::Item>,
14509 _: &mut Window,
14510 cx: &mut Context<Self>,
14511 ) -> Self
14512 where
14513 Self: Sized,
14514 {
14515 Self {
14516 focus_handle: cx.focus_handle(),
14517 }
14518 }
14519 }
14520
14521 #[gpui::test]
14522 async fn test_register_project_item(cx: &mut TestAppContext) {
14523 init_test(cx);
14524
14525 cx.update(|cx| {
14526 register_project_item::<TestPngItemView>(cx);
14527 register_project_item::<TestIpynbItemView>(cx);
14528 });
14529
14530 let fs = FakeFs::new(cx.executor());
14531 fs.insert_tree(
14532 "/root1",
14533 json!({
14534 "one.png": "BINARYDATAHERE",
14535 "two.ipynb": "{ totally a notebook }",
14536 "three.txt": "editing text, sure why not?"
14537 }),
14538 )
14539 .await;
14540
14541 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14542 let (workspace, cx) =
14543 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14544
14545 let worktree_id = project.update(cx, |project, cx| {
14546 project.worktrees(cx).next().unwrap().read(cx).id()
14547 });
14548
14549 let handle = workspace
14550 .update_in(cx, |workspace, window, cx| {
14551 let project_path = (worktree_id, rel_path("one.png"));
14552 workspace.open_path(project_path, None, true, window, cx)
14553 })
14554 .await
14555 .unwrap();
14556
14557 // Now we can check if the handle we got back errored or not
14558 assert_eq!(
14559 handle.to_any_view().entity_type(),
14560 TypeId::of::<TestPngItemView>()
14561 );
14562
14563 let handle = workspace
14564 .update_in(cx, |workspace, window, cx| {
14565 let project_path = (worktree_id, rel_path("two.ipynb"));
14566 workspace.open_path(project_path, None, true, window, cx)
14567 })
14568 .await
14569 .unwrap();
14570
14571 assert_eq!(
14572 handle.to_any_view().entity_type(),
14573 TypeId::of::<TestIpynbItemView>()
14574 );
14575
14576 let handle = workspace
14577 .update_in(cx, |workspace, window, cx| {
14578 let project_path = (worktree_id, rel_path("three.txt"));
14579 workspace.open_path(project_path, None, true, window, cx)
14580 })
14581 .await;
14582 assert!(handle.is_err());
14583 }
14584
14585 #[gpui::test]
14586 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14587 init_test(cx);
14588
14589 cx.update(|cx| {
14590 register_project_item::<TestPngItemView>(cx);
14591 register_project_item::<TestAlternatePngItemView>(cx);
14592 });
14593
14594 let fs = FakeFs::new(cx.executor());
14595 fs.insert_tree(
14596 "/root1",
14597 json!({
14598 "one.png": "BINARYDATAHERE",
14599 "two.ipynb": "{ totally a notebook }",
14600 "three.txt": "editing text, sure why not?"
14601 }),
14602 )
14603 .await;
14604 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14605 let (workspace, cx) =
14606 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14607 let worktree_id = project.update(cx, |project, cx| {
14608 project.worktrees(cx).next().unwrap().read(cx).id()
14609 });
14610
14611 let handle = workspace
14612 .update_in(cx, |workspace, window, cx| {
14613 let project_path = (worktree_id, rel_path("one.png"));
14614 workspace.open_path(project_path, None, true, window, cx)
14615 })
14616 .await
14617 .unwrap();
14618
14619 // This _must_ be the second item registered
14620 assert_eq!(
14621 handle.to_any_view().entity_type(),
14622 TypeId::of::<TestAlternatePngItemView>()
14623 );
14624
14625 let handle = workspace
14626 .update_in(cx, |workspace, window, cx| {
14627 let project_path = (worktree_id, rel_path("three.txt"));
14628 workspace.open_path(project_path, None, true, window, cx)
14629 })
14630 .await;
14631 assert!(handle.is_err());
14632 }
14633 }
14634
14635 #[gpui::test]
14636 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14637 init_test(cx);
14638
14639 let fs = FakeFs::new(cx.executor());
14640 let project = Project::test(fs, [], cx).await;
14641 let (workspace, _cx) =
14642 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14643
14644 // Test with status bar shown (default)
14645 workspace.read_with(cx, |workspace, cx| {
14646 let visible = workspace.status_bar_visible(cx);
14647 assert!(visible, "Status bar should be visible by default");
14648 });
14649
14650 // Test with status bar hidden
14651 cx.update_global(|store: &mut SettingsStore, cx| {
14652 store.update_user_settings(cx, |settings| {
14653 settings.status_bar.get_or_insert_default().show = Some(false);
14654 });
14655 });
14656
14657 workspace.read_with(cx, |workspace, cx| {
14658 let visible = workspace.status_bar_visible(cx);
14659 assert!(!visible, "Status bar should be hidden when show is false");
14660 });
14661
14662 // Test with status bar shown explicitly
14663 cx.update_global(|store: &mut SettingsStore, cx| {
14664 store.update_user_settings(cx, |settings| {
14665 settings.status_bar.get_or_insert_default().show = Some(true);
14666 });
14667 });
14668
14669 workspace.read_with(cx, |workspace, cx| {
14670 let visible = workspace.status_bar_visible(cx);
14671 assert!(visible, "Status bar should be visible when show is true");
14672 });
14673 }
14674
14675 #[gpui::test]
14676 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14677 init_test(cx);
14678
14679 let fs = FakeFs::new(cx.executor());
14680 let project = Project::test(fs, [], cx).await;
14681 let (multi_workspace, cx) =
14682 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14683 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14684 let panel = workspace.update_in(cx, |workspace, window, cx| {
14685 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14686 workspace.add_panel(panel.clone(), window, cx);
14687
14688 workspace
14689 .right_dock()
14690 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14691
14692 panel
14693 });
14694
14695 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14696 let item_a = cx.new(TestItem::new);
14697 let item_b = cx.new(TestItem::new);
14698 let item_a_id = item_a.entity_id();
14699 let item_b_id = item_b.entity_id();
14700
14701 pane.update_in(cx, |pane, window, cx| {
14702 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14703 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14704 });
14705
14706 pane.read_with(cx, |pane, _| {
14707 assert_eq!(pane.items_len(), 2);
14708 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14709 });
14710
14711 workspace.update_in(cx, |workspace, window, cx| {
14712 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14713 });
14714
14715 workspace.update_in(cx, |_, window, cx| {
14716 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14717 });
14718
14719 // Assert that the `pane::CloseActiveItem` action is handled at the
14720 // workspace level when one of the dock panels is focused and, in that
14721 // case, the center pane's active item is closed but the focus is not
14722 // moved.
14723 cx.dispatch_action(pane::CloseActiveItem::default());
14724 cx.run_until_parked();
14725
14726 pane.read_with(cx, |pane, _| {
14727 assert_eq!(pane.items_len(), 1);
14728 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14729 });
14730
14731 workspace.update_in(cx, |workspace, window, cx| {
14732 assert!(workspace.right_dock().read(cx).is_open());
14733 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14734 });
14735 }
14736
14737 #[gpui::test]
14738 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14739 init_test(cx);
14740 let fs = FakeFs::new(cx.executor());
14741
14742 let project_a = Project::test(fs.clone(), [], cx).await;
14743 let project_b = Project::test(fs, [], cx).await;
14744
14745 let multi_workspace_handle =
14746 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14747 cx.run_until_parked();
14748
14749 multi_workspace_handle
14750 .update(cx, |mw, _window, cx| {
14751 mw.open_sidebar(cx);
14752 })
14753 .unwrap();
14754
14755 let workspace_a = multi_workspace_handle
14756 .read_with(cx, |mw, _| mw.workspace().clone())
14757 .unwrap();
14758
14759 let _workspace_b = multi_workspace_handle
14760 .update(cx, |mw, window, cx| {
14761 mw.test_add_workspace(project_b, window, cx)
14762 })
14763 .unwrap();
14764
14765 // Switch to workspace A
14766 multi_workspace_handle
14767 .update(cx, |mw, window, cx| {
14768 let workspace = mw.workspaces().next().unwrap().clone();
14769 mw.activate(workspace, window, cx);
14770 })
14771 .unwrap();
14772
14773 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14774
14775 // Add a panel to workspace A's right dock and open the dock
14776 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14777 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14778 workspace.add_panel(panel.clone(), window, cx);
14779 workspace
14780 .right_dock()
14781 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14782 panel
14783 });
14784
14785 // Focus the panel through the workspace (matching existing test pattern)
14786 workspace_a.update_in(cx, |workspace, window, cx| {
14787 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14788 });
14789
14790 // Zoom the panel
14791 panel.update_in(cx, |panel, window, cx| {
14792 panel.set_zoomed(true, window, cx);
14793 });
14794
14795 // Verify the panel is zoomed and the dock is open
14796 workspace_a.update_in(cx, |workspace, window, cx| {
14797 assert!(
14798 workspace.right_dock().read(cx).is_open(),
14799 "dock should be open before switch"
14800 );
14801 assert!(
14802 panel.is_zoomed(window, cx),
14803 "panel should be zoomed before switch"
14804 );
14805 assert!(
14806 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14807 "panel should be focused before switch"
14808 );
14809 });
14810
14811 // Switch to workspace B
14812 multi_workspace_handle
14813 .update(cx, |mw, window, cx| {
14814 let workspace = mw.workspaces().nth(1).unwrap().clone();
14815 mw.activate(workspace, window, cx);
14816 })
14817 .unwrap();
14818 cx.run_until_parked();
14819
14820 // Switch back to workspace A
14821 multi_workspace_handle
14822 .update(cx, |mw, window, cx| {
14823 let workspace = mw.workspaces().next().unwrap().clone();
14824 mw.activate(workspace, window, cx);
14825 })
14826 .unwrap();
14827 cx.run_until_parked();
14828
14829 // Verify the panel is still zoomed and the dock is still open
14830 workspace_a.update_in(cx, |workspace, window, cx| {
14831 assert!(
14832 workspace.right_dock().read(cx).is_open(),
14833 "dock should still be open after switching back"
14834 );
14835 assert!(
14836 panel.is_zoomed(window, cx),
14837 "panel should still be zoomed after switching back"
14838 );
14839 });
14840 }
14841
14842 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14843 pane.read(cx)
14844 .items()
14845 .flat_map(|item| {
14846 item.project_paths(cx)
14847 .into_iter()
14848 .map(|path| path.path.display(PathStyle::local()).into_owned())
14849 })
14850 .collect()
14851 }
14852
14853 pub fn init_test(cx: &mut TestAppContext) {
14854 cx.update(|cx| {
14855 let settings_store = SettingsStore::test(cx);
14856 cx.set_global(settings_store);
14857 cx.set_global(db::AppDatabase::test_new());
14858 theme_settings::init(theme::LoadThemes::JustBase, cx);
14859 });
14860 }
14861
14862 #[gpui::test]
14863 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14864 use settings::{ThemeName, ThemeSelection};
14865 use theme::SystemAppearance;
14866 use zed_actions::theme::ToggleMode;
14867
14868 init_test(cx);
14869
14870 let fs = FakeFs::new(cx.executor());
14871 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14872
14873 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14874 .await;
14875
14876 // Build a test project and workspace view so the test can invoke
14877 // the workspace action handler the same way the UI would.
14878 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14879 let (workspace, cx) =
14880 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14881
14882 // Seed the settings file with a plain static light theme so the
14883 // first toggle always starts from a known persisted state.
14884 workspace.update_in(cx, |_workspace, _window, cx| {
14885 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14886 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14887 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14888 });
14889 });
14890 cx.executor().advance_clock(Duration::from_millis(200));
14891 cx.run_until_parked();
14892
14893 // Confirm the initial persisted settings contain the static theme
14894 // we just wrote before any toggling happens.
14895 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14896 assert!(settings_text.contains(r#""theme": "One Light""#));
14897
14898 // Toggle once. This should migrate the persisted theme settings
14899 // into light/dark slots and enable system mode.
14900 workspace.update_in(cx, |workspace, window, cx| {
14901 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14902 });
14903 cx.executor().advance_clock(Duration::from_millis(200));
14904 cx.run_until_parked();
14905
14906 // 1. Static -> Dynamic
14907 // this assertion checks theme changed from static to dynamic.
14908 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14909 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14910 assert_eq!(
14911 parsed["theme"],
14912 serde_json::json!({
14913 "mode": "system",
14914 "light": "One Light",
14915 "dark": "One Dark"
14916 })
14917 );
14918
14919 // 2. Toggle again, suppose it will change the mode to light
14920 workspace.update_in(cx, |workspace, window, cx| {
14921 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14922 });
14923 cx.executor().advance_clock(Duration::from_millis(200));
14924 cx.run_until_parked();
14925
14926 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14927 assert!(settings_text.contains(r#""mode": "light""#));
14928 }
14929
14930 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14931 let item = TestProjectItem::new(id, path, cx);
14932 item.update(cx, |item, _| {
14933 item.is_dirty = true;
14934 });
14935 item
14936 }
14937
14938 #[gpui::test]
14939 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14940 cx: &mut gpui::TestAppContext,
14941 ) {
14942 init_test(cx);
14943 let fs = FakeFs::new(cx.executor());
14944
14945 let project = Project::test(fs, [], cx).await;
14946 let (workspace, cx) =
14947 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14948
14949 let panel = workspace.update_in(cx, |workspace, window, cx| {
14950 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14951 workspace.add_panel(panel.clone(), window, cx);
14952 workspace
14953 .right_dock()
14954 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14955 panel
14956 });
14957
14958 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14959 pane.update_in(cx, |pane, window, cx| {
14960 let item = cx.new(TestItem::new);
14961 pane.add_item(Box::new(item), true, true, None, window, cx);
14962 });
14963
14964 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14965 // mirrors the real-world flow and avoids side effects from directly
14966 // focusing the panel while the center pane is active.
14967 workspace.update_in(cx, |workspace, window, cx| {
14968 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14969 });
14970
14971 panel.update_in(cx, |panel, window, cx| {
14972 panel.set_zoomed(true, window, cx);
14973 });
14974
14975 workspace.update_in(cx, |workspace, window, cx| {
14976 assert!(workspace.right_dock().read(cx).is_open());
14977 assert!(panel.is_zoomed(window, cx));
14978 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14979 });
14980
14981 // Simulate a spurious pane::Event::Focus on the center pane while the
14982 // panel still has focus. This mirrors what happens during macOS window
14983 // activation: the center pane fires a focus event even though actual
14984 // focus remains on the dock panel.
14985 pane.update_in(cx, |_, _, cx| {
14986 cx.emit(pane::Event::Focus);
14987 });
14988
14989 // The dock must remain open because the panel had focus at the time the
14990 // event was processed. Before the fix, dock_to_preserve was None for
14991 // panels that don't implement pane(), causing the dock to close.
14992 workspace.update_in(cx, |workspace, window, cx| {
14993 assert!(
14994 workspace.right_dock().read(cx).is_open(),
14995 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14996 );
14997 assert!(panel.is_zoomed(window, cx));
14998 });
14999 }
15000
15001 #[gpui::test]
15002 async fn test_panels_stay_open_after_position_change_and_settings_update(
15003 cx: &mut gpui::TestAppContext,
15004 ) {
15005 init_test(cx);
15006 let fs = FakeFs::new(cx.executor());
15007 let project = Project::test(fs, [], cx).await;
15008 let (workspace, cx) =
15009 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
15010
15011 // Add two panels to the left dock and open it.
15012 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
15013 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
15014 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
15015 workspace.add_panel(panel_a.clone(), window, cx);
15016 workspace.add_panel(panel_b.clone(), window, cx);
15017 workspace.left_dock().update(cx, |dock, cx| {
15018 dock.set_open(true, window, cx);
15019 dock.activate_panel(0, window, cx);
15020 });
15021 (panel_a, panel_b)
15022 });
15023
15024 workspace.update_in(cx, |workspace, _, cx| {
15025 assert!(workspace.left_dock().read(cx).is_open());
15026 });
15027
15028 // Simulate a feature flag changing default dock positions: both panels
15029 // move from Left to Right.
15030 workspace.update_in(cx, |_workspace, _window, cx| {
15031 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
15032 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
15033 cx.update_global::<SettingsStore, _>(|_, _| {});
15034 });
15035
15036 // Both panels should now be in the right dock.
15037 workspace.update_in(cx, |workspace, _, cx| {
15038 let right_dock = workspace.right_dock().read(cx);
15039 assert_eq!(right_dock.panels_len(), 2);
15040 });
15041
15042 // Open the right dock and activate panel_b (simulating the user
15043 // opening the panel after it moved).
15044 workspace.update_in(cx, |workspace, window, cx| {
15045 workspace.right_dock().update(cx, |dock, cx| {
15046 dock.set_open(true, window, cx);
15047 dock.activate_panel(1, window, cx);
15048 });
15049 });
15050
15051 // Now trigger another SettingsStore change
15052 workspace.update_in(cx, |_workspace, _window, cx| {
15053 cx.update_global::<SettingsStore, _>(|_, _| {});
15054 });
15055
15056 workspace.update_in(cx, |workspace, _, cx| {
15057 assert!(
15058 workspace.right_dock().read(cx).is_open(),
15059 "Right dock should still be open after a settings change"
15060 );
15061 assert_eq!(
15062 workspace.right_dock().read(cx).panels_len(),
15063 2,
15064 "Both panels should still be in the right dock"
15065 );
15066 });
15067 }
15068}