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, MoveProjectToNewWindow,
35 MultiWorkspace, MultiWorkspaceEvent, NewThread, NextProject, NextThread, PreviousProject,
36 PreviousThread, ProjectGroup, ProjectGroupKey, SerializedProjectGroupState, ShowFewerThreads,
37 ShowMoreThreads, Sidebar, SidebarEvent, SidebarHandle, SidebarRenderState, SidebarSide,
38 ToggleWorkspaceSidebar, sidebar_side_context_menu,
39};
40pub use path_list::{PathList, SerializedPathList};
41pub use toast_layer::{ToastAction, ToastLayer, ToastView};
42
43use anyhow::{Context as _, Result, anyhow};
44use client::{
45 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
46 proto::{self, ErrorCode, PanelId, PeerId},
47};
48use collections::{HashMap, HashSet, hash_map};
49use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
50use fs::Fs;
51use futures::{
52 Future, FutureExt, StreamExt,
53 channel::{
54 mpsc::{self, UnboundedReceiver, UnboundedSender},
55 oneshot,
56 },
57 future::{Shared, try_join_all},
58};
59use gpui::{
60 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
61 Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
62 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
63 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
64 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
65 WindowOptions, actions, canvas, point, relative, size, transparent_black,
66};
67pub use history_manager::*;
68pub use item::{
69 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
70 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
71};
72use itertools::Itertools;
73use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
74pub use modal_layer::*;
75use node_runtime::NodeRuntime;
76use notifications::{
77 DetachAndPromptErr, Notifications, dismiss_app_notification,
78 simple_message_notification::MessageNotification,
79};
80pub use pane::*;
81pub use pane_group::{
82 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
83 SplitDirection,
84};
85use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
86pub use persistence::{
87 WorkspaceDb, delete_unloaded_items,
88 model::{
89 DockStructure, ItemId, MultiWorkspaceState, SerializedMultiWorkspace,
90 SerializedProjectGroup, SerializedWorkspaceLocation, SessionWorkspace,
91 },
92 read_serialized_multi_workspaces, resolve_worktree_workspaces,
93};
94use postage::stream::Stream;
95use project::{
96 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
97 WorktreeSettings,
98 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
99 project_settings::ProjectSettings,
100 toolchain_store::ToolchainStoreEvent,
101 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
102};
103use remote::{
104 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
105 remote_client::ConnectionIdentifier,
106};
107use schemars::JsonSchema;
108use serde::Deserialize;
109use session::AppSession;
110use settings::{
111 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
112};
113
114use sqlez::{
115 bindable::{Bind, Column, StaticColumnCount},
116 statement::Statement,
117};
118use status_bar::StatusBar;
119pub use status_bar::StatusItemView;
120use std::{
121 any::TypeId,
122 borrow::Cow,
123 cell::RefCell,
124 cmp,
125 collections::VecDeque,
126 env,
127 hash::Hash,
128 path::{Path, PathBuf},
129 process::ExitStatus,
130 rc::Rc,
131 sync::{
132 Arc, LazyLock,
133 atomic::{AtomicBool, AtomicUsize},
134 },
135 time::Duration,
136};
137use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
138use theme::{ActiveTheme, SystemAppearance};
139use theme_settings::ThemeSettings;
140pub use toolbar::{
141 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
142};
143pub use ui;
144use ui::{Window, prelude::*};
145use util::{
146 ResultExt, TryFutureExt,
147 paths::{PathStyle, SanitizedPath},
148 rel_path::RelPath,
149 serde::default_true,
150};
151use uuid::Uuid;
152pub use workspace_settings::{
153 AutosaveSetting, BottomDockLayout, FocusFollowsMouse, RestoreOnStartupBehavior,
154 StatusBarSettings, TabBarSettings, WorkspaceSettings,
155};
156use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
157
158use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
159use crate::{
160 persistence::{
161 SerializedAxis,
162 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
163 },
164 security_modal::SecurityModal,
165};
166
167pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
168
169static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
170 env::var("ZED_WINDOW_SIZE")
171 .ok()
172 .as_deref()
173 .and_then(parse_pixel_size_env_var)
174});
175
176static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
177 env::var("ZED_WINDOW_POSITION")
178 .ok()
179 .as_deref()
180 .and_then(parse_pixel_position_env_var)
181});
182
183pub trait TerminalProvider {
184 fn spawn(
185 &self,
186 task: SpawnInTerminal,
187 window: &mut Window,
188 cx: &mut App,
189 ) -> Task<Option<Result<ExitStatus>>>;
190}
191
192pub trait DebuggerProvider {
193 // `active_buffer` is used to resolve build task's name against language-specific tasks.
194 fn start_session(
195 &self,
196 definition: DebugScenario,
197 task_context: SharedTaskContext,
198 active_buffer: Option<Entity<Buffer>>,
199 worktree_id: Option<WorktreeId>,
200 window: &mut Window,
201 cx: &mut App,
202 );
203
204 fn spawn_task_or_modal(
205 &self,
206 workspace: &mut Workspace,
207 action: &Spawn,
208 window: &mut Window,
209 cx: &mut Context<Workspace>,
210 );
211
212 fn task_scheduled(&self, cx: &mut App);
213 fn debug_scenario_scheduled(&self, cx: &mut App);
214 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
215
216 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
217}
218
219/// Opens a file or directory.
220#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
221#[action(namespace = workspace)]
222pub struct Open {
223 /// When true, opens in a new window. When false, adds to the current
224 /// window as a new workspace (multi-workspace).
225 #[serde(default = "Open::default_create_new_window")]
226 pub create_new_window: bool,
227}
228
229impl Open {
230 pub const DEFAULT: Self = Self {
231 create_new_window: true,
232 };
233
234 /// Used by `#[serde(default)]` on the `create_new_window` field so that
235 /// the serde default and `Open::DEFAULT` stay in sync.
236 fn default_create_new_window() -> bool {
237 Self::DEFAULT.create_new_window
238 }
239}
240
241impl Default for Open {
242 fn default() -> Self {
243 Self::DEFAULT
244 }
245}
246
247actions!(
248 workspace,
249 [
250 /// Activates the next pane in the workspace.
251 ActivateNextPane,
252 /// Activates the previous pane in the workspace.
253 ActivatePreviousPane,
254 /// Activates the last pane in the workspace.
255 ActivateLastPane,
256 /// Switches to the next window.
257 ActivateNextWindow,
258 /// Switches to the previous window.
259 ActivatePreviousWindow,
260 /// Adds a folder to the current project.
261 AddFolderToProject,
262 /// Clears all notifications.
263 ClearAllNotifications,
264 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
265 ClearNavigationHistory,
266 /// Closes the active dock.
267 CloseActiveDock,
268 /// Closes all docks.
269 CloseAllDocks,
270 /// Toggles all docks.
271 ToggleAllDocks,
272 /// Closes the current window.
273 CloseWindow,
274 /// Closes the current project.
275 CloseProject,
276 /// Opens the feedback dialog.
277 Feedback,
278 /// Follows the next collaborator in the session.
279 FollowNextCollaborator,
280 /// Moves the focused panel to the next position.
281 MoveFocusedPanelToNextPosition,
282 /// Creates a new file.
283 NewFile,
284 /// Creates a new file in a vertical split.
285 NewFileSplitVertical,
286 /// Creates a new file in a horizontal split.
287 NewFileSplitHorizontal,
288 /// Opens a new search.
289 NewSearch,
290 /// Opens a new window.
291 NewWindow,
292 /// Opens multiple files.
293 OpenFiles,
294 /// Opens the current location in terminal.
295 OpenInTerminal,
296 /// Opens the component preview.
297 OpenComponentPreview,
298 /// Reloads the active item.
299 ReloadActiveItem,
300 /// Resets the active dock to its default size.
301 ResetActiveDockSize,
302 /// Resets all open docks to their default sizes.
303 ResetOpenDocksSize,
304 /// Reloads the application
305 Reload,
306 /// Saves the current file with a new name.
307 SaveAs,
308 /// Saves without formatting.
309 SaveWithoutFormat,
310 /// Shuts down all debug adapters.
311 ShutdownDebugAdapters,
312 /// Suppresses the current notification.
313 SuppressNotification,
314 /// Toggles the bottom dock.
315 ToggleBottomDock,
316 /// Toggles centered layout mode.
317 ToggleCenteredLayout,
318 /// Toggles edit prediction feature globally for all files.
319 ToggleEditPrediction,
320 /// Toggles the left dock.
321 ToggleLeftDock,
322 /// Toggles the right dock.
323 ToggleRightDock,
324 /// Toggles zoom on the active pane.
325 ToggleZoom,
326 /// Toggles read-only mode for the active item (if supported by that item).
327 ToggleReadOnlyFile,
328 /// Zooms in on the active pane.
329 ZoomIn,
330 /// Zooms out of the active pane.
331 ZoomOut,
332 /// If any worktrees are in restricted mode, shows a modal with possible actions.
333 /// If the modal is shown already, closes it without trusting any worktree.
334 ToggleWorktreeSecurity,
335 /// Clears all trusted worktrees, placing them in restricted mode on next open.
336 /// Requires restart to take effect on already opened projects.
337 ClearTrustedWorktrees,
338 /// Stops following a collaborator.
339 Unfollow,
340 /// Restores the banner.
341 RestoreBanner,
342 /// Toggles expansion of the selected item.
343 ToggleExpandItem,
344 ]
345);
346
347/// Activates a specific pane by its index.
348#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
349#[action(namespace = workspace)]
350pub struct ActivatePane(pub usize);
351
352/// Moves an item to a specific pane by index.
353#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
354#[action(namespace = workspace)]
355#[serde(deny_unknown_fields)]
356pub struct MoveItemToPane {
357 #[serde(default = "default_1")]
358 pub destination: usize,
359 #[serde(default = "default_true")]
360 pub focus: bool,
361 #[serde(default)]
362 pub clone: bool,
363}
364
365fn default_1() -> usize {
366 1
367}
368
369/// Moves an item to a pane in the specified direction.
370#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
371#[action(namespace = workspace)]
372#[serde(deny_unknown_fields)]
373pub struct MoveItemToPaneInDirection {
374 #[serde(default = "default_right")]
375 pub direction: SplitDirection,
376 #[serde(default = "default_true")]
377 pub focus: bool,
378 #[serde(default)]
379 pub clone: bool,
380}
381
382/// Creates a new file in a split of the desired direction.
383#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
384#[action(namespace = workspace)]
385#[serde(deny_unknown_fields)]
386pub struct NewFileSplit(pub SplitDirection);
387
388fn default_right() -> SplitDirection {
389 SplitDirection::Right
390}
391
392/// Saves all open files in the workspace.
393#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
394#[action(namespace = workspace)]
395#[serde(deny_unknown_fields)]
396pub struct SaveAll {
397 #[serde(default)]
398 pub save_intent: Option<SaveIntent>,
399}
400
401/// Saves the current file with the specified options.
402#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
403#[action(namespace = workspace)]
404#[serde(deny_unknown_fields)]
405pub struct Save {
406 #[serde(default)]
407 pub save_intent: Option<SaveIntent>,
408}
409
410/// Moves Focus to the central panes in the workspace.
411#[derive(Clone, Debug, PartialEq, Eq, Action)]
412#[action(namespace = workspace)]
413pub struct FocusCenterPane;
414
415/// Closes all items and panes in the workspace.
416#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
417#[action(namespace = workspace)]
418#[serde(deny_unknown_fields)]
419pub struct CloseAllItemsAndPanes {
420 #[serde(default)]
421 pub save_intent: Option<SaveIntent>,
422}
423
424/// Closes all inactive tabs and panes in the workspace.
425#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
426#[action(namespace = workspace)]
427#[serde(deny_unknown_fields)]
428pub struct CloseInactiveTabsAndPanes {
429 #[serde(default)]
430 pub save_intent: Option<SaveIntent>,
431}
432
433/// Closes the active item across all panes.
434#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
435#[action(namespace = workspace)]
436#[serde(deny_unknown_fields)]
437pub struct CloseItemInAllPanes {
438 #[serde(default)]
439 pub save_intent: Option<SaveIntent>,
440 #[serde(default)]
441 pub close_pinned: bool,
442}
443
444/// Sends a sequence of keystrokes to the active element.
445#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
446#[action(namespace = workspace)]
447pub struct SendKeystrokes(pub String);
448
449actions!(
450 project_symbols,
451 [
452 /// Toggles the project symbols search.
453 #[action(name = "Toggle")]
454 ToggleProjectSymbols
455 ]
456);
457
458/// Toggles the file finder interface.
459#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
460#[action(namespace = file_finder, name = "Toggle")]
461#[serde(deny_unknown_fields)]
462pub struct ToggleFileFinder {
463 #[serde(default)]
464 pub separate_history: bool,
465}
466
467/// Opens a new terminal in the center.
468#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
469#[action(namespace = workspace)]
470#[serde(deny_unknown_fields)]
471pub struct NewCenterTerminal {
472 /// If true, creates a local terminal even in remote projects.
473 #[serde(default)]
474 pub local: bool,
475}
476
477/// Opens a new terminal.
478#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
479#[action(namespace = workspace)]
480#[serde(deny_unknown_fields)]
481pub struct NewTerminal {
482 /// If true, creates a local terminal even in remote projects.
483 #[serde(default)]
484 pub local: bool,
485}
486
487/// Increases size of a currently focused dock by a given amount of pixels.
488#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
489#[action(namespace = workspace)]
490#[serde(deny_unknown_fields)]
491pub struct IncreaseActiveDockSize {
492 /// For 0px parameter, uses UI font size value.
493 #[serde(default)]
494 pub px: u32,
495}
496
497/// Decreases size of a currently focused dock by a given amount of pixels.
498#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
499#[action(namespace = workspace)]
500#[serde(deny_unknown_fields)]
501pub struct DecreaseActiveDockSize {
502 /// For 0px parameter, uses UI font size value.
503 #[serde(default)]
504 pub px: u32,
505}
506
507/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
508#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
509#[action(namespace = workspace)]
510#[serde(deny_unknown_fields)]
511pub struct IncreaseOpenDocksSize {
512 /// For 0px parameter, uses UI font size value.
513 #[serde(default)]
514 pub px: u32,
515}
516
517/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
518#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
519#[action(namespace = workspace)]
520#[serde(deny_unknown_fields)]
521pub struct DecreaseOpenDocksSize {
522 /// For 0px parameter, uses UI font size value.
523 #[serde(default)]
524 pub px: u32,
525}
526
527actions!(
528 workspace,
529 [
530 /// Activates the pane to the left.
531 ActivatePaneLeft,
532 /// Activates the pane to the right.
533 ActivatePaneRight,
534 /// Activates the pane above.
535 ActivatePaneUp,
536 /// Activates the pane below.
537 ActivatePaneDown,
538 /// Swaps the current pane with the one to the left.
539 SwapPaneLeft,
540 /// Swaps the current pane with the one to the right.
541 SwapPaneRight,
542 /// Swaps the current pane with the one above.
543 SwapPaneUp,
544 /// Swaps the current pane with the one below.
545 SwapPaneDown,
546 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
547 SwapPaneAdjacent,
548 /// Move the current pane to be at the far left.
549 MovePaneLeft,
550 /// Move the current pane to be at the far right.
551 MovePaneRight,
552 /// Move the current pane to be at the very top.
553 MovePaneUp,
554 /// Move the current pane to be at the very bottom.
555 MovePaneDown,
556 ]
557);
558
559#[derive(PartialEq, Eq, Debug)]
560pub enum CloseIntent {
561 /// Quit the program entirely.
562 Quit,
563 /// Close a window.
564 CloseWindow,
565 /// Replace the workspace in an existing window.
566 ReplaceWindow,
567}
568
569#[derive(Clone)]
570pub struct Toast {
571 id: NotificationId,
572 msg: Cow<'static, str>,
573 autohide: bool,
574 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
575}
576
577impl Toast {
578 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
579 Toast {
580 id,
581 msg: msg.into(),
582 on_click: None,
583 autohide: false,
584 }
585 }
586
587 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
588 where
589 M: Into<Cow<'static, str>>,
590 F: Fn(&mut Window, &mut App) + 'static,
591 {
592 self.on_click = Some((message.into(), Arc::new(on_click)));
593 self
594 }
595
596 pub fn autohide(mut self) -> Self {
597 self.autohide = true;
598 self
599 }
600}
601
602impl PartialEq for Toast {
603 fn eq(&self, other: &Self) -> bool {
604 self.id == other.id
605 && self.msg == other.msg
606 && self.on_click.is_some() == other.on_click.is_some()
607 }
608}
609
610/// Opens a new terminal with the specified working directory.
611#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
612#[action(namespace = workspace)]
613#[serde(deny_unknown_fields)]
614pub struct OpenTerminal {
615 pub working_directory: PathBuf,
616 /// If true, creates a local terminal even in remote projects.
617 #[serde(default)]
618 pub local: bool,
619}
620
621#[derive(
622 Clone,
623 Copy,
624 Debug,
625 Default,
626 Hash,
627 PartialEq,
628 Eq,
629 PartialOrd,
630 Ord,
631 serde::Serialize,
632 serde::Deserialize,
633)]
634pub struct WorkspaceId(i64);
635
636impl WorkspaceId {
637 pub fn from_i64(value: i64) -> Self {
638 Self(value)
639 }
640}
641
642impl StaticColumnCount for WorkspaceId {}
643impl Bind for WorkspaceId {
644 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
645 self.0.bind(statement, start_index)
646 }
647}
648impl Column for WorkspaceId {
649 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
650 i64::column(statement, start_index)
651 .map(|(i, next_index)| (Self(i), next_index))
652 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
653 }
654}
655impl From<WorkspaceId> for i64 {
656 fn from(val: WorkspaceId) -> Self {
657 val.0
658 }
659}
660
661fn prompt_and_open_paths(
662 app_state: Arc<AppState>,
663 options: PathPromptOptions,
664 create_new_window: bool,
665 cx: &mut App,
666) {
667 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
668 workspace_window
669 .update(cx, |multi_workspace, window, cx| {
670 let workspace = multi_workspace.workspace().clone();
671 workspace.update(cx, |workspace, cx| {
672 prompt_for_open_path_and_open(
673 workspace,
674 app_state,
675 options,
676 create_new_window,
677 window,
678 cx,
679 );
680 });
681 })
682 .ok();
683 } else {
684 let task = Workspace::new_local(
685 Vec::new(),
686 app_state.clone(),
687 None,
688 None,
689 None,
690 OpenMode::Activate,
691 cx,
692 );
693 cx.spawn(async move |cx| {
694 let OpenResult { window, .. } = task.await?;
695 window.update(cx, |multi_workspace, window, cx| {
696 window.activate_window();
697 let workspace = multi_workspace.workspace().clone();
698 workspace.update(cx, |workspace, cx| {
699 prompt_for_open_path_and_open(
700 workspace,
701 app_state,
702 options,
703 create_new_window,
704 window,
705 cx,
706 );
707 });
708 })?;
709 anyhow::Ok(())
710 })
711 .detach_and_log_err(cx);
712 }
713}
714
715pub fn prompt_for_open_path_and_open(
716 workspace: &mut Workspace,
717 app_state: Arc<AppState>,
718 options: PathPromptOptions,
719 create_new_window: bool,
720 window: &mut Window,
721 cx: &mut Context<Workspace>,
722) {
723 let paths = workspace.prompt_for_open_path(
724 options,
725 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
726 window,
727 cx,
728 );
729 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
730 cx.spawn_in(window, async move |this, cx| {
731 let Some(paths) = paths.await.log_err().flatten() else {
732 return;
733 };
734 if !create_new_window {
735 if let Some(handle) = multi_workspace_handle {
736 if let Some(task) = handle
737 .update(cx, |multi_workspace, window, cx| {
738 multi_workspace.open_project(paths, OpenMode::Activate, window, cx)
739 })
740 .log_err()
741 {
742 task.await.log_err();
743 }
744 return;
745 }
746 }
747 if let Some(task) = this
748 .update_in(cx, |this, window, cx| {
749 this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
750 })
751 .log_err()
752 {
753 task.await.log_err();
754 }
755 })
756 .detach();
757}
758
759pub fn init(app_state: Arc<AppState>, cx: &mut App) {
760 component::init();
761 theme_preview::init(cx);
762 toast_layer::init(cx);
763 history_manager::init(app_state.fs.clone(), cx);
764
765 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
766 .on_action(|_: &Reload, cx| reload(cx))
767 .on_action(|action: &Open, cx: &mut App| {
768 let app_state = AppState::global(cx);
769 prompt_and_open_paths(
770 app_state,
771 PathPromptOptions {
772 files: true,
773 directories: true,
774 multiple: true,
775 prompt: None,
776 },
777 action.create_new_window,
778 cx,
779 );
780 })
781 .on_action(|_: &OpenFiles, cx: &mut App| {
782 let directories = cx.can_select_mixed_files_and_dirs();
783 let app_state = AppState::global(cx);
784 prompt_and_open_paths(
785 app_state,
786 PathPromptOptions {
787 files: true,
788 directories,
789 multiple: true,
790 prompt: None,
791 },
792 true,
793 cx,
794 );
795 });
796}
797
798type BuildProjectItemFn =
799 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
800
801type BuildProjectItemForPathFn =
802 fn(
803 &Entity<Project>,
804 &ProjectPath,
805 &mut Window,
806 &mut App,
807 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
808
809#[derive(Clone, Default)]
810struct ProjectItemRegistry {
811 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
812 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
813}
814
815impl ProjectItemRegistry {
816 fn register<T: ProjectItem>(&mut self) {
817 self.build_project_item_fns_by_type.insert(
818 TypeId::of::<T::Item>(),
819 |item, project, pane, window, cx| {
820 let item = item.downcast().unwrap();
821 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
822 as Box<dyn ItemHandle>
823 },
824 );
825 self.build_project_item_for_path_fns
826 .push(|project, project_path, window, cx| {
827 let project_path = project_path.clone();
828 let is_file = project
829 .read(cx)
830 .entry_for_path(&project_path, cx)
831 .is_some_and(|entry| entry.is_file());
832 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
833 let is_local = project.read(cx).is_local();
834 let project_item =
835 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
836 let project = project.clone();
837 Some(window.spawn(cx, async move |cx| {
838 match project_item.await.with_context(|| {
839 format!(
840 "opening project path {:?}",
841 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
842 )
843 }) {
844 Ok(project_item) => {
845 let project_item = project_item;
846 let project_entry_id: Option<ProjectEntryId> =
847 project_item.read_with(cx, project::ProjectItem::entry_id);
848 let build_workspace_item = Box::new(
849 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
850 Box::new(cx.new(|cx| {
851 T::for_project_item(
852 project,
853 Some(pane),
854 project_item,
855 window,
856 cx,
857 )
858 })) as Box<dyn ItemHandle>
859 },
860 ) as Box<_>;
861 Ok((project_entry_id, build_workspace_item))
862 }
863 Err(e) => {
864 log::warn!("Failed to open a project item: {e:#}");
865 if e.error_code() == ErrorCode::Internal {
866 if let Some(abs_path) =
867 entry_abs_path.as_deref().filter(|_| is_file)
868 {
869 if let Some(broken_project_item_view) =
870 cx.update(|window, cx| {
871 T::for_broken_project_item(
872 abs_path, is_local, &e, window, cx,
873 )
874 })?
875 {
876 let build_workspace_item = Box::new(
877 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
878 cx.new(|_| broken_project_item_view).boxed_clone()
879 },
880 )
881 as Box<_>;
882 return Ok((None, build_workspace_item));
883 }
884 }
885 }
886 Err(e)
887 }
888 }
889 }))
890 });
891 }
892
893 fn open_path(
894 &self,
895 project: &Entity<Project>,
896 path: &ProjectPath,
897 window: &mut Window,
898 cx: &mut App,
899 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
900 let Some(open_project_item) = self
901 .build_project_item_for_path_fns
902 .iter()
903 .rev()
904 .find_map(|open_project_item| open_project_item(project, path, window, cx))
905 else {
906 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
907 };
908 open_project_item
909 }
910
911 fn build_item<T: project::ProjectItem>(
912 &self,
913 item: Entity<T>,
914 project: Entity<Project>,
915 pane: Option<&Pane>,
916 window: &mut Window,
917 cx: &mut App,
918 ) -> Option<Box<dyn ItemHandle>> {
919 let build = self
920 .build_project_item_fns_by_type
921 .get(&TypeId::of::<T>())?;
922 Some(build(item.into_any(), project, pane, window, cx))
923 }
924}
925
926type WorkspaceItemBuilder =
927 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
928
929impl Global for ProjectItemRegistry {}
930
931/// Registers a [ProjectItem] for the app. When opening a file, all the registered
932/// items will get a chance to open the file, starting from the project item that
933/// was added last.
934pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
935 cx.default_global::<ProjectItemRegistry>().register::<I>();
936}
937
938#[derive(Default)]
939pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
940
941struct FollowableViewDescriptor {
942 from_state_proto: fn(
943 Entity<Workspace>,
944 ViewId,
945 &mut Option<proto::view::Variant>,
946 &mut Window,
947 &mut App,
948 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
949 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
950}
951
952impl Global for FollowableViewRegistry {}
953
954impl FollowableViewRegistry {
955 pub fn register<I: FollowableItem>(cx: &mut App) {
956 cx.default_global::<Self>().0.insert(
957 TypeId::of::<I>(),
958 FollowableViewDescriptor {
959 from_state_proto: |workspace, id, state, window, cx| {
960 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
961 cx.foreground_executor()
962 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
963 })
964 },
965 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
966 },
967 );
968 }
969
970 pub fn from_state_proto(
971 workspace: Entity<Workspace>,
972 view_id: ViewId,
973 mut state: Option<proto::view::Variant>,
974 window: &mut Window,
975 cx: &mut App,
976 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
977 cx.update_default_global(|this: &mut Self, cx| {
978 this.0.values().find_map(|descriptor| {
979 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
980 })
981 })
982 }
983
984 pub fn to_followable_view(
985 view: impl Into<AnyView>,
986 cx: &App,
987 ) -> Option<Box<dyn FollowableItemHandle>> {
988 let this = cx.try_global::<Self>()?;
989 let view = view.into();
990 let descriptor = this.0.get(&view.entity_type())?;
991 Some((descriptor.to_followable_view)(&view))
992 }
993}
994
995#[derive(Copy, Clone)]
996struct SerializableItemDescriptor {
997 deserialize: fn(
998 Entity<Project>,
999 WeakEntity<Workspace>,
1000 WorkspaceId,
1001 ItemId,
1002 &mut Window,
1003 &mut Context<Pane>,
1004 ) -> Task<Result<Box<dyn ItemHandle>>>,
1005 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
1006 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
1007}
1008
1009#[derive(Default)]
1010struct SerializableItemRegistry {
1011 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
1012 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
1013}
1014
1015impl Global for SerializableItemRegistry {}
1016
1017impl SerializableItemRegistry {
1018 fn deserialize(
1019 item_kind: &str,
1020 project: Entity<Project>,
1021 workspace: WeakEntity<Workspace>,
1022 workspace_id: WorkspaceId,
1023 item_item: ItemId,
1024 window: &mut Window,
1025 cx: &mut Context<Pane>,
1026 ) -> Task<Result<Box<dyn ItemHandle>>> {
1027 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1028 return Task::ready(Err(anyhow!(
1029 "cannot deserialize {}, descriptor not found",
1030 item_kind
1031 )));
1032 };
1033
1034 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1035 }
1036
1037 fn cleanup(
1038 item_kind: &str,
1039 workspace_id: WorkspaceId,
1040 loaded_items: Vec<ItemId>,
1041 window: &mut Window,
1042 cx: &mut App,
1043 ) -> Task<Result<()>> {
1044 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1045 return Task::ready(Err(anyhow!(
1046 "cannot cleanup {}, descriptor not found",
1047 item_kind
1048 )));
1049 };
1050
1051 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1052 }
1053
1054 fn view_to_serializable_item_handle(
1055 view: AnyView,
1056 cx: &App,
1057 ) -> Option<Box<dyn SerializableItemHandle>> {
1058 let this = cx.try_global::<Self>()?;
1059 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1060 Some((descriptor.view_to_serializable_item)(view))
1061 }
1062
1063 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1064 let this = cx.try_global::<Self>()?;
1065 this.descriptors_by_kind.get(item_kind).copied()
1066 }
1067}
1068
1069pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1070 let serialized_item_kind = I::serialized_item_kind();
1071
1072 let registry = cx.default_global::<SerializableItemRegistry>();
1073 let descriptor = SerializableItemDescriptor {
1074 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1075 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1076 cx.foreground_executor()
1077 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1078 },
1079 cleanup: |workspace_id, loaded_items, window, cx| {
1080 I::cleanup(workspace_id, loaded_items, window, cx)
1081 },
1082 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1083 };
1084 registry
1085 .descriptors_by_kind
1086 .insert(Arc::from(serialized_item_kind), descriptor);
1087 registry
1088 .descriptors_by_type
1089 .insert(TypeId::of::<I>(), descriptor);
1090}
1091
1092pub struct AppState {
1093 pub languages: Arc<LanguageRegistry>,
1094 pub client: Arc<Client>,
1095 pub user_store: Entity<UserStore>,
1096 pub workspace_store: Entity<WorkspaceStore>,
1097 pub fs: Arc<dyn fs::Fs>,
1098 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1099 pub node_runtime: NodeRuntime,
1100 pub session: Entity<AppSession>,
1101}
1102
1103struct GlobalAppState(Arc<AppState>);
1104
1105impl Global for GlobalAppState {}
1106
1107pub struct WorkspaceStore {
1108 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1109 client: Arc<Client>,
1110 _subscriptions: Vec<client::Subscription>,
1111}
1112
1113#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1114pub enum CollaboratorId {
1115 PeerId(PeerId),
1116 Agent,
1117}
1118
1119impl From<PeerId> for CollaboratorId {
1120 fn from(peer_id: PeerId) -> Self {
1121 CollaboratorId::PeerId(peer_id)
1122 }
1123}
1124
1125impl From<&PeerId> for CollaboratorId {
1126 fn from(peer_id: &PeerId) -> Self {
1127 CollaboratorId::PeerId(*peer_id)
1128 }
1129}
1130
1131#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1132struct Follower {
1133 project_id: Option<u64>,
1134 peer_id: PeerId,
1135}
1136
1137impl AppState {
1138 #[track_caller]
1139 pub fn global(cx: &App) -> Arc<Self> {
1140 cx.global::<GlobalAppState>().0.clone()
1141 }
1142 pub fn try_global(cx: &App) -> Option<Arc<Self>> {
1143 cx.try_global::<GlobalAppState>()
1144 .map(|state| state.0.clone())
1145 }
1146 pub fn set_global(state: Arc<AppState>, cx: &mut App) {
1147 cx.set_global(GlobalAppState(state));
1148 }
1149
1150 #[cfg(any(test, feature = "test-support"))]
1151 pub fn test(cx: &mut App) -> Arc<Self> {
1152 use fs::Fs;
1153 use node_runtime::NodeRuntime;
1154 use session::Session;
1155 use settings::SettingsStore;
1156
1157 if !cx.has_global::<SettingsStore>() {
1158 let settings_store = SettingsStore::test(cx);
1159 cx.set_global(settings_store);
1160 }
1161
1162 let fs = fs::FakeFs::new(cx.background_executor().clone());
1163 <dyn Fs>::set_global(fs.clone(), cx);
1164 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1165 let clock = Arc::new(clock::FakeSystemClock::new());
1166 let http_client = http_client::FakeHttpClient::with_404_response();
1167 let client = Client::new(clock, http_client, cx);
1168 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1169 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1170 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1171
1172 theme_settings::init(theme::LoadThemes::JustBase, cx);
1173 client::init(&client, cx);
1174
1175 Arc::new(Self {
1176 client,
1177 fs,
1178 languages,
1179 user_store,
1180 workspace_store,
1181 node_runtime: NodeRuntime::unavailable(),
1182 build_window_options: |_, _| Default::default(),
1183 session,
1184 })
1185 }
1186}
1187
1188struct DelayedDebouncedEditAction {
1189 task: Option<Task<()>>,
1190 cancel_channel: Option<oneshot::Sender<()>>,
1191}
1192
1193impl DelayedDebouncedEditAction {
1194 fn new() -> DelayedDebouncedEditAction {
1195 DelayedDebouncedEditAction {
1196 task: None,
1197 cancel_channel: None,
1198 }
1199 }
1200
1201 fn fire_new<F>(
1202 &mut self,
1203 delay: Duration,
1204 window: &mut Window,
1205 cx: &mut Context<Workspace>,
1206 func: F,
1207 ) where
1208 F: 'static
1209 + Send
1210 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1211 {
1212 if let Some(channel) = self.cancel_channel.take() {
1213 _ = channel.send(());
1214 }
1215
1216 let (sender, mut receiver) = oneshot::channel::<()>();
1217 self.cancel_channel = Some(sender);
1218
1219 let previous_task = self.task.take();
1220 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1221 let mut timer = cx.background_executor().timer(delay).fuse();
1222 if let Some(previous_task) = previous_task {
1223 previous_task.await;
1224 }
1225
1226 futures::select_biased! {
1227 _ = receiver => return,
1228 _ = timer => {}
1229 }
1230
1231 if let Some(result) = workspace
1232 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1233 .log_err()
1234 {
1235 result.await.log_err();
1236 }
1237 }));
1238 }
1239}
1240
1241pub enum Event {
1242 PaneAdded(Entity<Pane>),
1243 PaneRemoved,
1244 ItemAdded {
1245 item: Box<dyn ItemHandle>,
1246 },
1247 ActiveItemChanged,
1248 ItemRemoved {
1249 item_id: EntityId,
1250 },
1251 UserSavedItem {
1252 pane: WeakEntity<Pane>,
1253 item: Box<dyn WeakItemHandle>,
1254 save_intent: SaveIntent,
1255 },
1256 ContactRequestedJoin(u64),
1257 WorkspaceCreated(WeakEntity<Workspace>),
1258 OpenBundledFile {
1259 text: Cow<'static, str>,
1260 title: &'static str,
1261 language: &'static str,
1262 },
1263 ZoomChanged,
1264 ModalOpened,
1265 Activate,
1266 PanelAdded(AnyView),
1267}
1268
1269#[derive(Debug, Clone)]
1270pub enum OpenVisible {
1271 All,
1272 None,
1273 OnlyFiles,
1274 OnlyDirectories,
1275}
1276
1277enum WorkspaceLocation {
1278 // Valid local paths or SSH project to serialize
1279 Location(SerializedWorkspaceLocation, PathList),
1280 // No valid location found hence clear session id
1281 DetachFromSession,
1282 // No valid location found to serialize
1283 None,
1284}
1285
1286type PromptForNewPath = Box<
1287 dyn Fn(
1288 &mut Workspace,
1289 DirectoryLister,
1290 Option<String>,
1291 &mut Window,
1292 &mut Context<Workspace>,
1293 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1294>;
1295
1296type PromptForOpenPath = Box<
1297 dyn Fn(
1298 &mut Workspace,
1299 DirectoryLister,
1300 &mut Window,
1301 &mut Context<Workspace>,
1302 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1303>;
1304
1305#[derive(Default)]
1306struct DispatchingKeystrokes {
1307 dispatched: HashSet<Vec<Keystroke>>,
1308 queue: VecDeque<Keystroke>,
1309 task: Option<Shared<Task<()>>>,
1310}
1311
1312/// Collects everything project-related for a certain window opened.
1313/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1314///
1315/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1316/// The `Workspace` owns everybody's state and serves as a default, "global context",
1317/// that can be used to register a global action to be triggered from any place in the window.
1318pub struct Workspace {
1319 weak_self: WeakEntity<Self>,
1320 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1321 zoomed: Option<AnyWeakView>,
1322 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1323 zoomed_position: Option<DockPosition>,
1324 center: PaneGroup,
1325 left_dock: Entity<Dock>,
1326 bottom_dock: Entity<Dock>,
1327 right_dock: Entity<Dock>,
1328 panes: Vec<Entity<Pane>>,
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 notifications: Notifications::default(),
1762 suppressed_notifications: HashSet::default(),
1763 left_dock,
1764 bottom_dock,
1765 right_dock,
1766 _panels_task: None,
1767 project: project.clone(),
1768 follower_states: Default::default(),
1769 last_leaders_by_pane: Default::default(),
1770 dispatching_keystrokes: Default::default(),
1771 window_edited: false,
1772 last_window_title: None,
1773 dirty_items: Default::default(),
1774 active_call,
1775 database_id: workspace_id,
1776 app_state,
1777 _observe_current_user,
1778 _apply_leader_updates,
1779 _schedule_serialize_workspace: None,
1780 _serialize_workspace_task: None,
1781 _schedule_serialize_ssh_paths: None,
1782 leader_updates_tx,
1783 _subscriptions: subscriptions,
1784 pane_history_timestamp,
1785 workspace_actions: Default::default(),
1786 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1787 bounds: Default::default(),
1788 centered_layout: false,
1789 bounds_save_task_queued: None,
1790 on_prompt_for_new_path: None,
1791 on_prompt_for_open_path: None,
1792 terminal_provider: None,
1793 debugger_provider: None,
1794 serializable_items_tx,
1795 _items_serializer,
1796 session_id: Some(session_id),
1797
1798 scheduled_tasks: Vec::new(),
1799 last_open_dock_positions: Vec::new(),
1800 removing: false,
1801 sidebar_focus_handle: None,
1802 multi_workspace,
1803 open_in_dev_container: false,
1804 _dev_container_task: None,
1805 }
1806 }
1807
1808 pub fn new_local(
1809 abs_paths: Vec<PathBuf>,
1810 app_state: Arc<AppState>,
1811 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1812 env: Option<HashMap<String, String>>,
1813 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1814 open_mode: OpenMode,
1815 cx: &mut App,
1816 ) -> Task<anyhow::Result<OpenResult>> {
1817 let project_handle = Project::local(
1818 app_state.client.clone(),
1819 app_state.node_runtime.clone(),
1820 app_state.user_store.clone(),
1821 app_state.languages.clone(),
1822 app_state.fs.clone(),
1823 env,
1824 Default::default(),
1825 cx,
1826 );
1827
1828 let db = WorkspaceDb::global(cx);
1829 let kvp = db::kvp::KeyValueStore::global(cx);
1830 cx.spawn(async move |cx| {
1831 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1832 for path in abs_paths.into_iter() {
1833 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1834 paths_to_open.push(canonical)
1835 } else {
1836 paths_to_open.push(path)
1837 }
1838 }
1839
1840 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1841
1842 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1843 paths_to_open = paths.ordered_paths().cloned().collect();
1844 if !paths.is_lexicographically_ordered() {
1845 project_handle.update(cx, |project, cx| {
1846 project.set_worktrees_reordered(true, cx);
1847 });
1848 }
1849 }
1850
1851 // Get project paths for all of the abs_paths
1852 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1853 Vec::with_capacity(paths_to_open.len());
1854
1855 for path in paths_to_open.into_iter() {
1856 if let Some((_, project_entry)) = cx
1857 .update(|cx| {
1858 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1859 })
1860 .await
1861 .log_err()
1862 {
1863 project_paths.push((path, Some(project_entry)));
1864 } else {
1865 project_paths.push((path, None));
1866 }
1867 }
1868
1869 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1870 serialized_workspace.id
1871 } else {
1872 db.next_id().await.unwrap_or_else(|_| Default::default())
1873 };
1874
1875 let toolchains = db.toolchains(workspace_id).await?;
1876
1877 for (toolchain, worktree_path, path) in toolchains {
1878 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1879 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1880 this.find_worktree(&worktree_path, cx)
1881 .and_then(|(worktree, rel_path)| {
1882 if rel_path.is_empty() {
1883 Some(worktree.read(cx).id())
1884 } else {
1885 None
1886 }
1887 })
1888 }) else {
1889 // We did not find a worktree with a given path, but that's whatever.
1890 continue;
1891 };
1892 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1893 continue;
1894 }
1895
1896 project_handle
1897 .update(cx, |this, cx| {
1898 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1899 })
1900 .await;
1901 }
1902 if let Some(workspace) = serialized_workspace.as_ref() {
1903 project_handle.update(cx, |this, cx| {
1904 for (scope, toolchains) in &workspace.user_toolchains {
1905 for toolchain in toolchains {
1906 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1907 }
1908 }
1909 });
1910 }
1911
1912 let window_to_replace = match open_mode {
1913 OpenMode::NewWindow => None,
1914 _ => requesting_window,
1915 };
1916
1917 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1918 if let Some(window) = window_to_replace {
1919 let centered_layout = serialized_workspace
1920 .as_ref()
1921 .map(|w| w.centered_layout)
1922 .unwrap_or(false);
1923
1924 let workspace = window.update(cx, |multi_workspace, window, cx| {
1925 let workspace = cx.new(|cx| {
1926 let mut workspace = Workspace::new(
1927 Some(workspace_id),
1928 project_handle.clone(),
1929 app_state.clone(),
1930 window,
1931 cx,
1932 );
1933
1934 workspace.centered_layout = centered_layout;
1935
1936 // Call init callback to add items before window renders
1937 if let Some(init) = init {
1938 init(&mut workspace, window, cx);
1939 }
1940
1941 workspace
1942 });
1943 match open_mode {
1944 OpenMode::Activate => {
1945 multi_workspace.activate(workspace.clone(), window, cx);
1946 }
1947 OpenMode::Add => {
1948 multi_workspace.add(workspace.clone(), &*window, cx);
1949 }
1950 OpenMode::NewWindow => {
1951 unreachable!()
1952 }
1953 }
1954 workspace
1955 })?;
1956 (window, workspace)
1957 } else {
1958 let window_bounds_override = window_bounds_env_override();
1959
1960 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1961 (Some(WindowBounds::Windowed(bounds)), None)
1962 } else if let Some(workspace) = serialized_workspace.as_ref()
1963 && let Some(display) = workspace.display
1964 && let Some(bounds) = workspace.window_bounds.as_ref()
1965 {
1966 // Reopening an existing workspace - restore its saved bounds
1967 (Some(bounds.0), Some(display))
1968 } else if let Some((display, bounds)) =
1969 persistence::read_default_window_bounds(&kvp)
1970 {
1971 // New or empty workspace - use the last known window bounds
1972 (Some(bounds), Some(display))
1973 } else {
1974 // New window - let GPUI's default_bounds() handle cascading
1975 (None, None)
1976 };
1977
1978 // Use the serialized workspace to construct the new window
1979 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1980 options.window_bounds = window_bounds;
1981 let centered_layout = serialized_workspace
1982 .as_ref()
1983 .map(|w| w.centered_layout)
1984 .unwrap_or(false);
1985 let window = cx.open_window(options, {
1986 let app_state = app_state.clone();
1987 let project_handle = project_handle.clone();
1988 move |window, cx| {
1989 let workspace = cx.new(|cx| {
1990 let mut workspace = Workspace::new(
1991 Some(workspace_id),
1992 project_handle,
1993 app_state,
1994 window,
1995 cx,
1996 );
1997 workspace.centered_layout = centered_layout;
1998
1999 // Call init callback to add items before window renders
2000 if let Some(init) = init {
2001 init(&mut workspace, window, cx);
2002 }
2003
2004 workspace
2005 });
2006 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
2007 }
2008 })?;
2009 let workspace =
2010 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
2011 multi_workspace.workspace().clone()
2012 })?;
2013 (window, workspace)
2014 };
2015
2016 notify_if_database_failed(window, cx);
2017 // Check if this is an empty workspace (no paths to open)
2018 // An empty workspace is one where project_paths is empty
2019 let is_empty_workspace = project_paths.is_empty();
2020 // Check if serialized workspace has paths before it's moved
2021 let serialized_workspace_has_paths = serialized_workspace
2022 .as_ref()
2023 .map(|ws| !ws.paths.is_empty())
2024 .unwrap_or(false);
2025
2026 let opened_items = window
2027 .update(cx, |_, window, cx| {
2028 workspace.update(cx, |_workspace: &mut Workspace, cx| {
2029 open_items(serialized_workspace, project_paths, window, cx)
2030 })
2031 })?
2032 .await
2033 .unwrap_or_default();
2034
2035 // Restore default dock state for empty workspaces
2036 // Only restore if:
2037 // 1. This is an empty workspace (no paths), AND
2038 // 2. The serialized workspace either doesn't exist or has no paths
2039 if is_empty_workspace && !serialized_workspace_has_paths {
2040 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
2041 window
2042 .update(cx, |_, window, cx| {
2043 workspace.update(cx, |workspace, cx| {
2044 for (dock, serialized_dock) in [
2045 (&workspace.right_dock, &default_docks.right),
2046 (&workspace.left_dock, &default_docks.left),
2047 (&workspace.bottom_dock, &default_docks.bottom),
2048 ] {
2049 dock.update(cx, |dock, cx| {
2050 dock.serialized_dock = Some(serialized_dock.clone());
2051 dock.restore_state(window, cx);
2052 });
2053 }
2054 cx.notify();
2055 });
2056 })
2057 .log_err();
2058 }
2059 }
2060
2061 window
2062 .update(cx, |_, _window, cx| {
2063 workspace.update(cx, |this: &mut Workspace, cx| {
2064 this.update_history(cx);
2065 });
2066 })
2067 .log_err();
2068 Ok(OpenResult {
2069 window,
2070 workspace,
2071 opened_items,
2072 })
2073 })
2074 }
2075
2076 pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
2077 self.project.read(cx).project_group_key(cx)
2078 }
2079
2080 pub fn weak_handle(&self) -> WeakEntity<Self> {
2081 self.weak_self.clone()
2082 }
2083
2084 pub fn left_dock(&self) -> &Entity<Dock> {
2085 &self.left_dock
2086 }
2087
2088 pub fn bottom_dock(&self) -> &Entity<Dock> {
2089 &self.bottom_dock
2090 }
2091
2092 pub fn set_bottom_dock_layout(
2093 &mut self,
2094 layout: BottomDockLayout,
2095 window: &mut Window,
2096 cx: &mut Context<Self>,
2097 ) {
2098 let fs = self.project().read(cx).fs();
2099 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2100 content.workspace.bottom_dock_layout = Some(layout);
2101 });
2102
2103 cx.notify();
2104 self.serialize_workspace(window, cx);
2105 }
2106
2107 pub fn right_dock(&self) -> &Entity<Dock> {
2108 &self.right_dock
2109 }
2110
2111 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2112 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2113 }
2114
2115 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2116 let left_dock = self.left_dock.read(cx);
2117 let left_visible = left_dock.is_open();
2118 let left_active_panel = left_dock
2119 .active_panel()
2120 .map(|panel| panel.persistent_name().to_string());
2121 // `zoomed_position` is kept in sync with individual panel zoom state
2122 // by the dock code in `Dock::new` and `Dock::add_panel`.
2123 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2124
2125 let right_dock = self.right_dock.read(cx);
2126 let right_visible = right_dock.is_open();
2127 let right_active_panel = right_dock
2128 .active_panel()
2129 .map(|panel| panel.persistent_name().to_string());
2130 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2131
2132 let bottom_dock = self.bottom_dock.read(cx);
2133 let bottom_visible = bottom_dock.is_open();
2134 let bottom_active_panel = bottom_dock
2135 .active_panel()
2136 .map(|panel| panel.persistent_name().to_string());
2137 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2138
2139 DockStructure {
2140 left: DockData {
2141 visible: left_visible,
2142 active_panel: left_active_panel,
2143 zoom: left_dock_zoom,
2144 },
2145 right: DockData {
2146 visible: right_visible,
2147 active_panel: right_active_panel,
2148 zoom: right_dock_zoom,
2149 },
2150 bottom: DockData {
2151 visible: bottom_visible,
2152 active_panel: bottom_active_panel,
2153 zoom: bottom_dock_zoom,
2154 },
2155 }
2156 }
2157
2158 pub fn set_dock_structure(
2159 &self,
2160 docks: DockStructure,
2161 window: &mut Window,
2162 cx: &mut Context<Self>,
2163 ) {
2164 for (dock, data) in [
2165 (&self.left_dock, docks.left),
2166 (&self.bottom_dock, docks.bottom),
2167 (&self.right_dock, docks.right),
2168 ] {
2169 dock.update(cx, |dock, cx| {
2170 dock.serialized_dock = Some(data);
2171 dock.restore_state(window, cx);
2172 });
2173 }
2174 }
2175
2176 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2177 self.items(cx)
2178 .filter_map(|item| {
2179 let project_path = item.project_path(cx)?;
2180 self.project.read(cx).absolute_path(&project_path, cx)
2181 })
2182 .collect()
2183 }
2184
2185 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2186 match position {
2187 DockPosition::Left => &self.left_dock,
2188 DockPosition::Bottom => &self.bottom_dock,
2189 DockPosition::Right => &self.right_dock,
2190 }
2191 }
2192
2193 pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
2194 self.all_docks().into_iter().find_map(|dock| {
2195 let dock = dock.read(cx);
2196 dock.has_agent_panel(cx).then_some(dock.position())
2197 })
2198 }
2199
2200 pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
2201 self.all_docks().into_iter().find_map(|dock| {
2202 let dock = dock.read(cx);
2203 let panel = dock.panel::<T>()?;
2204 dock.stored_panel_size_state(&panel)
2205 })
2206 }
2207
2208 pub fn persisted_panel_size_state(
2209 &self,
2210 panel_key: &'static str,
2211 cx: &App,
2212 ) -> Option<dock::PanelSizeState> {
2213 dock::Dock::load_persisted_size_state(self, panel_key, cx)
2214 }
2215
2216 pub fn persist_panel_size_state(
2217 &self,
2218 panel_key: &str,
2219 size_state: dock::PanelSizeState,
2220 cx: &mut App,
2221 ) {
2222 let Some(workspace_id) = self
2223 .database_id()
2224 .map(|id| i64::from(id).to_string())
2225 .or(self.session_id())
2226 else {
2227 return;
2228 };
2229
2230 let kvp = db::kvp::KeyValueStore::global(cx);
2231 let panel_key = panel_key.to_string();
2232 cx.background_spawn(async move {
2233 let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
2234 scope
2235 .write(
2236 format!("{workspace_id}:{panel_key}"),
2237 serde_json::to_string(&size_state)?,
2238 )
2239 .await
2240 })
2241 .detach_and_log_err(cx);
2242 }
2243
2244 pub fn set_panel_size_state<T: Panel>(
2245 &mut self,
2246 size_state: dock::PanelSizeState,
2247 window: &mut Window,
2248 cx: &mut Context<Self>,
2249 ) -> bool {
2250 let Some(panel) = self.panel::<T>(cx) else {
2251 return false;
2252 };
2253
2254 let dock = self.dock_at_position(panel.position(window, cx));
2255 let did_set = dock.update(cx, |dock, cx| {
2256 dock.set_panel_size_state(&panel, size_state, cx)
2257 });
2258
2259 if did_set {
2260 self.persist_panel_size_state(T::panel_key(), size_state, cx);
2261 }
2262
2263 did_set
2264 }
2265
2266 pub fn toggle_dock_panel_flexible_size(
2267 &self,
2268 dock: &Entity<Dock>,
2269 panel: &dyn PanelHandle,
2270 window: &mut Window,
2271 cx: &mut App,
2272 ) {
2273 let position = dock.read(cx).position();
2274 let current_size = self.dock_size(&dock.read(cx), window, cx);
2275 let current_flex =
2276 current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
2277 dock.update(cx, |dock, cx| {
2278 dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
2279 });
2280 }
2281
2282 fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
2283 let panel = dock.active_panel()?;
2284 let size_state = dock
2285 .stored_panel_size_state(panel.as_ref())
2286 .unwrap_or_default();
2287 let position = dock.position();
2288
2289 let use_flex = panel.has_flexible_size(window, cx);
2290
2291 if position.axis() == Axis::Horizontal
2292 && use_flex
2293 && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
2294 {
2295 let workspace_width = self.bounds.size.width;
2296 if workspace_width <= Pixels::ZERO {
2297 return None;
2298 }
2299 let flex = flex.max(0.001);
2300 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2301 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2302 // Both docks are flex items sharing the full workspace width.
2303 let total_flex = flex + 1.0 + opposite_flex;
2304 return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
2305 } else {
2306 // Opposite dock is fixed-width; flex items share (W - fixed).
2307 let opposite_fixed = opposite
2308 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2309 .unwrap_or_default();
2310 let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
2311 return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
2312 }
2313 }
2314
2315 Some(
2316 size_state
2317 .size
2318 .unwrap_or_else(|| panel.default_size(window, cx)),
2319 )
2320 }
2321
2322 pub fn dock_flex_for_size(
2323 &self,
2324 position: DockPosition,
2325 size: Pixels,
2326 window: &Window,
2327 cx: &App,
2328 ) -> Option<f32> {
2329 if position.axis() != Axis::Horizontal {
2330 return None;
2331 }
2332
2333 let workspace_width = self.bounds.size.width;
2334 if workspace_width <= Pixels::ZERO {
2335 return None;
2336 }
2337
2338 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2339 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2340 let size = size.clamp(px(0.), workspace_width - px(1.));
2341 Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
2342 } else {
2343 let opposite_width = opposite
2344 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2345 .unwrap_or_default();
2346 let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
2347 let remaining = (available - size).max(px(1.));
2348 Some((size / remaining).max(0.0))
2349 }
2350 }
2351
2352 fn opposite_dock_panel_and_size_state(
2353 &self,
2354 position: DockPosition,
2355 window: &Window,
2356 cx: &App,
2357 ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
2358 let opposite_position = match position {
2359 DockPosition::Left => DockPosition::Right,
2360 DockPosition::Right => DockPosition::Left,
2361 DockPosition::Bottom => return None,
2362 };
2363
2364 let opposite_dock = self.dock_at_position(opposite_position).read(cx);
2365 let panel = opposite_dock.visible_panel()?;
2366 let mut size_state = opposite_dock
2367 .stored_panel_size_state(panel.as_ref())
2368 .unwrap_or_default();
2369 if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
2370 size_state.flex = self.default_dock_flex(opposite_position);
2371 }
2372 Some((panel.clone(), size_state))
2373 }
2374
2375 pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
2376 if position.axis() != Axis::Horizontal {
2377 return None;
2378 }
2379
2380 let pane = self.last_active_center_pane.clone()?.upgrade()?;
2381 Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
2382 }
2383
2384 pub fn is_edited(&self) -> bool {
2385 self.window_edited
2386 }
2387
2388 pub fn add_panel<T: Panel>(
2389 &mut self,
2390 panel: Entity<T>,
2391 window: &mut Window,
2392 cx: &mut Context<Self>,
2393 ) {
2394 let focus_handle = panel.panel_focus_handle(cx);
2395 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2396 .detach();
2397
2398 let dock_position = panel.position(window, cx);
2399 let dock = self.dock_at_position(dock_position);
2400 let any_panel = panel.to_any();
2401 let persisted_size_state =
2402 self.persisted_panel_size_state(T::panel_key(), cx)
2403 .or_else(|| {
2404 load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
2405 let state = dock::PanelSizeState {
2406 size: Some(size),
2407 flex: None,
2408 };
2409 self.persist_panel_size_state(T::panel_key(), state, cx);
2410 state
2411 })
2412 });
2413
2414 dock.update(cx, |dock, cx| {
2415 let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
2416 if let Some(size_state) = persisted_size_state {
2417 dock.set_panel_size_state(&panel, size_state, cx);
2418 }
2419 index
2420 });
2421
2422 cx.emit(Event::PanelAdded(any_panel));
2423 }
2424
2425 pub fn remove_panel<T: Panel>(
2426 &mut self,
2427 panel: &Entity<T>,
2428 window: &mut Window,
2429 cx: &mut Context<Self>,
2430 ) {
2431 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2432 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2433 }
2434 }
2435
2436 pub fn status_bar(&self) -> &Entity<StatusBar> {
2437 &self.status_bar
2438 }
2439
2440 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2441 self.sidebar_focus_handle = handle;
2442 }
2443
2444 pub fn status_bar_visible(&self, cx: &App) -> bool {
2445 StatusBarSettings::get_global(cx).show
2446 }
2447
2448 pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
2449 self.multi_workspace.as_ref()
2450 }
2451
2452 pub fn set_multi_workspace(
2453 &mut self,
2454 multi_workspace: WeakEntity<MultiWorkspace>,
2455 cx: &mut App,
2456 ) {
2457 self.status_bar.update(cx, |status_bar, cx| {
2458 status_bar.set_multi_workspace(multi_workspace.clone(), cx);
2459 });
2460 self.multi_workspace = Some(multi_workspace);
2461 }
2462
2463 pub fn app_state(&self) -> &Arc<AppState> {
2464 &self.app_state
2465 }
2466
2467 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2468 self._panels_task = Some(task);
2469 }
2470
2471 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2472 self._panels_task.take()
2473 }
2474
2475 pub fn user_store(&self) -> &Entity<UserStore> {
2476 &self.app_state.user_store
2477 }
2478
2479 pub fn project(&self) -> &Entity<Project> {
2480 &self.project
2481 }
2482
2483 pub fn path_style(&self, cx: &App) -> PathStyle {
2484 self.project.read(cx).path_style(cx)
2485 }
2486
2487 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2488 let mut history: HashMap<EntityId, usize> = HashMap::default();
2489
2490 for pane_handle in &self.panes {
2491 let pane = pane_handle.read(cx);
2492
2493 for entry in pane.activation_history() {
2494 history.insert(
2495 entry.entity_id,
2496 history
2497 .get(&entry.entity_id)
2498 .cloned()
2499 .unwrap_or(0)
2500 .max(entry.timestamp),
2501 );
2502 }
2503 }
2504
2505 history
2506 }
2507
2508 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2509 let mut recent_item: Option<Entity<T>> = None;
2510 let mut recent_timestamp = 0;
2511 for pane_handle in &self.panes {
2512 let pane = pane_handle.read(cx);
2513 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2514 pane.items().map(|item| (item.item_id(), item)).collect();
2515 for entry in pane.activation_history() {
2516 if entry.timestamp > recent_timestamp
2517 && let Some(&item) = item_map.get(&entry.entity_id)
2518 && let Some(typed_item) = item.act_as::<T>(cx)
2519 {
2520 recent_timestamp = entry.timestamp;
2521 recent_item = Some(typed_item);
2522 }
2523 }
2524 }
2525 recent_item
2526 }
2527
2528 pub fn recent_navigation_history_iter(
2529 &self,
2530 cx: &App,
2531 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2532 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2533 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2534
2535 for pane in &self.panes {
2536 let pane = pane.read(cx);
2537
2538 pane.nav_history()
2539 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2540 if let Some(fs_path) = &fs_path {
2541 abs_paths_opened
2542 .entry(fs_path.clone())
2543 .or_default()
2544 .insert(project_path.clone());
2545 }
2546 let timestamp = entry.timestamp;
2547 match history.entry(project_path) {
2548 hash_map::Entry::Occupied(mut entry) => {
2549 let (_, old_timestamp) = entry.get();
2550 if ×tamp > old_timestamp {
2551 entry.insert((fs_path, timestamp));
2552 }
2553 }
2554 hash_map::Entry::Vacant(entry) => {
2555 entry.insert((fs_path, timestamp));
2556 }
2557 }
2558 });
2559
2560 if let Some(item) = pane.active_item()
2561 && let Some(project_path) = item.project_path(cx)
2562 {
2563 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2564
2565 if let Some(fs_path) = &fs_path {
2566 abs_paths_opened
2567 .entry(fs_path.clone())
2568 .or_default()
2569 .insert(project_path.clone());
2570 }
2571
2572 history.insert(project_path, (fs_path, std::usize::MAX));
2573 }
2574 }
2575
2576 history
2577 .into_iter()
2578 .sorted_by_key(|(_, (_, order))| *order)
2579 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2580 .rev()
2581 .filter(move |(history_path, abs_path)| {
2582 let latest_project_path_opened = abs_path
2583 .as_ref()
2584 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2585 .and_then(|project_paths| {
2586 project_paths
2587 .iter()
2588 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2589 });
2590
2591 latest_project_path_opened.is_none_or(|path| path == history_path)
2592 })
2593 }
2594
2595 pub fn recent_navigation_history(
2596 &self,
2597 limit: Option<usize>,
2598 cx: &App,
2599 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2600 self.recent_navigation_history_iter(cx)
2601 .take(limit.unwrap_or(usize::MAX))
2602 .collect()
2603 }
2604
2605 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2606 for pane in &self.panes {
2607 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2608 }
2609 }
2610
2611 fn navigate_history(
2612 &mut self,
2613 pane: WeakEntity<Pane>,
2614 mode: NavigationMode,
2615 window: &mut Window,
2616 cx: &mut Context<Workspace>,
2617 ) -> Task<Result<()>> {
2618 self.navigate_history_impl(
2619 pane,
2620 mode,
2621 window,
2622 &mut |history, cx| history.pop(mode, cx),
2623 cx,
2624 )
2625 }
2626
2627 fn navigate_tag_history(
2628 &mut self,
2629 pane: WeakEntity<Pane>,
2630 mode: TagNavigationMode,
2631 window: &mut Window,
2632 cx: &mut Context<Workspace>,
2633 ) -> Task<Result<()>> {
2634 self.navigate_history_impl(
2635 pane,
2636 NavigationMode::Normal,
2637 window,
2638 &mut |history, _cx| history.pop_tag(mode),
2639 cx,
2640 )
2641 }
2642
2643 fn navigate_history_impl(
2644 &mut self,
2645 pane: WeakEntity<Pane>,
2646 mode: NavigationMode,
2647 window: &mut Window,
2648 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2649 cx: &mut Context<Workspace>,
2650 ) -> Task<Result<()>> {
2651 let to_load = if let Some(pane) = pane.upgrade() {
2652 pane.update(cx, |pane, cx| {
2653 window.focus(&pane.focus_handle(cx), cx);
2654 loop {
2655 // Retrieve the weak item handle from the history.
2656 let entry = cb(pane.nav_history_mut(), cx)?;
2657
2658 // If the item is still present in this pane, then activate it.
2659 if let Some(index) = entry
2660 .item
2661 .upgrade()
2662 .and_then(|v| pane.index_for_item(v.as_ref()))
2663 {
2664 let prev_active_item_index = pane.active_item_index();
2665 pane.nav_history_mut().set_mode(mode);
2666 pane.activate_item(index, true, true, window, cx);
2667 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2668
2669 let mut navigated = prev_active_item_index != pane.active_item_index();
2670 if let Some(data) = entry.data {
2671 navigated |= pane.active_item()?.navigate(data, window, cx);
2672 }
2673
2674 if navigated {
2675 break None;
2676 }
2677 } else {
2678 // If the item is no longer present in this pane, then retrieve its
2679 // path info in order to reopen it.
2680 break pane
2681 .nav_history()
2682 .path_for_item(entry.item.id())
2683 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2684 }
2685 }
2686 })
2687 } else {
2688 None
2689 };
2690
2691 if let Some((project_path, abs_path, entry)) = to_load {
2692 // If the item was no longer present, then load it again from its previous path, first try the local path
2693 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2694
2695 cx.spawn_in(window, async move |workspace, cx| {
2696 let open_by_project_path = open_by_project_path.await;
2697 let mut navigated = false;
2698 match open_by_project_path
2699 .with_context(|| format!("Navigating to {project_path:?}"))
2700 {
2701 Ok((project_entry_id, build_item)) => {
2702 let prev_active_item_id = pane.update(cx, |pane, _| {
2703 pane.nav_history_mut().set_mode(mode);
2704 pane.active_item().map(|p| p.item_id())
2705 })?;
2706
2707 pane.update_in(cx, |pane, window, cx| {
2708 let item = pane.open_item(
2709 project_entry_id,
2710 project_path,
2711 true,
2712 entry.is_preview,
2713 true,
2714 None,
2715 window, cx,
2716 build_item,
2717 );
2718 navigated |= Some(item.item_id()) != prev_active_item_id;
2719 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2720 if let Some(data) = entry.data {
2721 navigated |= item.navigate(data, window, cx);
2722 }
2723 })?;
2724 }
2725 Err(open_by_project_path_e) => {
2726 // Fall back to opening by abs path, in case an external file was opened and closed,
2727 // and its worktree is now dropped
2728 if let Some(abs_path) = abs_path {
2729 let prev_active_item_id = pane.update(cx, |pane, _| {
2730 pane.nav_history_mut().set_mode(mode);
2731 pane.active_item().map(|p| p.item_id())
2732 })?;
2733 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2734 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2735 })?;
2736 match open_by_abs_path
2737 .await
2738 .with_context(|| format!("Navigating to {abs_path:?}"))
2739 {
2740 Ok(item) => {
2741 pane.update_in(cx, |pane, window, cx| {
2742 navigated |= Some(item.item_id()) != prev_active_item_id;
2743 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2744 if let Some(data) = entry.data {
2745 navigated |= item.navigate(data, window, cx);
2746 }
2747 })?;
2748 }
2749 Err(open_by_abs_path_e) => {
2750 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2751 }
2752 }
2753 }
2754 }
2755 }
2756
2757 if !navigated {
2758 workspace
2759 .update_in(cx, |workspace, window, cx| {
2760 Self::navigate_history(workspace, pane, mode, window, cx)
2761 })?
2762 .await?;
2763 }
2764
2765 Ok(())
2766 })
2767 } else {
2768 Task::ready(Ok(()))
2769 }
2770 }
2771
2772 pub fn go_back(
2773 &mut self,
2774 pane: WeakEntity<Pane>,
2775 window: &mut Window,
2776 cx: &mut Context<Workspace>,
2777 ) -> Task<Result<()>> {
2778 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2779 }
2780
2781 pub fn go_forward(
2782 &mut self,
2783 pane: WeakEntity<Pane>,
2784 window: &mut Window,
2785 cx: &mut Context<Workspace>,
2786 ) -> Task<Result<()>> {
2787 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2788 }
2789
2790 pub fn reopen_closed_item(
2791 &mut self,
2792 window: &mut Window,
2793 cx: &mut Context<Workspace>,
2794 ) -> Task<Result<()>> {
2795 self.navigate_history(
2796 self.active_pane().downgrade(),
2797 NavigationMode::ReopeningClosedItem,
2798 window,
2799 cx,
2800 )
2801 }
2802
2803 pub fn client(&self) -> &Arc<Client> {
2804 &self.app_state.client
2805 }
2806
2807 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2808 self.titlebar_item = Some(item);
2809 cx.notify();
2810 }
2811
2812 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2813 self.on_prompt_for_new_path = Some(prompt)
2814 }
2815
2816 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2817 self.on_prompt_for_open_path = Some(prompt)
2818 }
2819
2820 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2821 self.terminal_provider = Some(Box::new(provider));
2822 }
2823
2824 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2825 self.debugger_provider = Some(Arc::new(provider));
2826 }
2827
2828 pub fn set_open_in_dev_container(&mut self, value: bool) {
2829 self.open_in_dev_container = value;
2830 }
2831
2832 pub fn open_in_dev_container(&self) -> bool {
2833 self.open_in_dev_container
2834 }
2835
2836 pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
2837 self._dev_container_task = Some(task);
2838 }
2839
2840 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2841 self.debugger_provider.clone()
2842 }
2843
2844 pub fn prompt_for_open_path(
2845 &mut self,
2846 path_prompt_options: PathPromptOptions,
2847 lister: DirectoryLister,
2848 window: &mut Window,
2849 cx: &mut Context<Self>,
2850 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2851 // TODO: If `on_prompt_for_open_path` is set, we should always use it
2852 // rather than gating on `use_system_path_prompts`. This would let tests
2853 // inject a mock without also having to disable the setting.
2854 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2855 let prompt = self.on_prompt_for_open_path.take().unwrap();
2856 let rx = prompt(self, lister, window, cx);
2857 self.on_prompt_for_open_path = Some(prompt);
2858 rx
2859 } else {
2860 let (tx, rx) = oneshot::channel();
2861 let abs_path = cx.prompt_for_paths(path_prompt_options);
2862
2863 cx.spawn_in(window, async move |workspace, cx| {
2864 let Ok(result) = abs_path.await else {
2865 return Ok(());
2866 };
2867
2868 match result {
2869 Ok(result) => {
2870 tx.send(result).ok();
2871 }
2872 Err(err) => {
2873 let rx = workspace.update_in(cx, |workspace, window, cx| {
2874 workspace.show_portal_error(err.to_string(), cx);
2875 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2876 let rx = prompt(workspace, lister, window, cx);
2877 workspace.on_prompt_for_open_path = Some(prompt);
2878 rx
2879 })?;
2880 if let Ok(path) = rx.await {
2881 tx.send(path).ok();
2882 }
2883 }
2884 };
2885 anyhow::Ok(())
2886 })
2887 .detach();
2888
2889 rx
2890 }
2891 }
2892
2893 pub fn prompt_for_new_path(
2894 &mut self,
2895 lister: DirectoryLister,
2896 suggested_name: Option<String>,
2897 window: &mut Window,
2898 cx: &mut Context<Self>,
2899 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2900 if self.project.read(cx).is_via_collab()
2901 || self.project.read(cx).is_via_remote_server()
2902 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2903 {
2904 let prompt = self.on_prompt_for_new_path.take().unwrap();
2905 let rx = prompt(self, lister, suggested_name, window, cx);
2906 self.on_prompt_for_new_path = Some(prompt);
2907 return rx;
2908 }
2909
2910 let (tx, rx) = oneshot::channel();
2911 cx.spawn_in(window, async move |workspace, cx| {
2912 let abs_path = workspace.update(cx, |workspace, cx| {
2913 let relative_to = workspace
2914 .most_recent_active_path(cx)
2915 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2916 .or_else(|| {
2917 let project = workspace.project.read(cx);
2918 project.visible_worktrees(cx).find_map(|worktree| {
2919 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2920 })
2921 })
2922 .or_else(std::env::home_dir)
2923 .unwrap_or_else(|| PathBuf::from(""));
2924 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2925 })?;
2926 let abs_path = match abs_path.await? {
2927 Ok(path) => path,
2928 Err(err) => {
2929 let rx = workspace.update_in(cx, |workspace, window, cx| {
2930 workspace.show_portal_error(err.to_string(), cx);
2931
2932 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2933 let rx = prompt(workspace, lister, suggested_name, window, cx);
2934 workspace.on_prompt_for_new_path = Some(prompt);
2935 rx
2936 })?;
2937 if let Ok(path) = rx.await {
2938 tx.send(path).ok();
2939 }
2940 return anyhow::Ok(());
2941 }
2942 };
2943
2944 tx.send(abs_path.map(|path| vec![path])).ok();
2945 anyhow::Ok(())
2946 })
2947 .detach();
2948
2949 rx
2950 }
2951
2952 pub fn titlebar_item(&self) -> Option<AnyView> {
2953 self.titlebar_item.clone()
2954 }
2955
2956 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2957 ///
2958 /// If the given workspace has a local project, then it will be passed
2959 /// to the callback. Otherwise, a new empty window will be created.
2960 pub fn with_local_workspace<T, F>(
2961 &mut self,
2962 window: &mut Window,
2963 cx: &mut Context<Self>,
2964 callback: F,
2965 ) -> Task<Result<T>>
2966 where
2967 T: 'static,
2968 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2969 {
2970 if self.project.read(cx).is_local() {
2971 Task::ready(Ok(callback(self, window, cx)))
2972 } else {
2973 let env = self.project.read(cx).cli_environment(cx);
2974 let task = Self::new_local(
2975 Vec::new(),
2976 self.app_state.clone(),
2977 None,
2978 env,
2979 None,
2980 OpenMode::Activate,
2981 cx,
2982 );
2983 cx.spawn_in(window, async move |_vh, cx| {
2984 let OpenResult {
2985 window: multi_workspace_window,
2986 ..
2987 } = task.await?;
2988 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2989 let workspace = multi_workspace.workspace().clone();
2990 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2991 })
2992 })
2993 }
2994 }
2995
2996 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2997 ///
2998 /// If the given workspace has a local project, then it will be passed
2999 /// to the callback. Otherwise, a new empty window will be created.
3000 pub fn with_local_or_wsl_workspace<T, F>(
3001 &mut self,
3002 window: &mut Window,
3003 cx: &mut Context<Self>,
3004 callback: F,
3005 ) -> Task<Result<T>>
3006 where
3007 T: 'static,
3008 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
3009 {
3010 let project = self.project.read(cx);
3011 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
3012 Task::ready(Ok(callback(self, window, cx)))
3013 } else {
3014 let env = self.project.read(cx).cli_environment(cx);
3015 let task = Self::new_local(
3016 Vec::new(),
3017 self.app_state.clone(),
3018 None,
3019 env,
3020 None,
3021 OpenMode::Activate,
3022 cx,
3023 );
3024 cx.spawn_in(window, async move |_vh, cx| {
3025 let OpenResult {
3026 window: multi_workspace_window,
3027 ..
3028 } = task.await?;
3029 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3030 let workspace = multi_workspace.workspace().clone();
3031 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3032 })
3033 })
3034 }
3035 }
3036
3037 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3038 self.project.read(cx).worktrees(cx)
3039 }
3040
3041 pub fn visible_worktrees<'a>(
3042 &self,
3043 cx: &'a App,
3044 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3045 self.project.read(cx).visible_worktrees(cx)
3046 }
3047
3048 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
3049 let futures = self
3050 .worktrees(cx)
3051 .filter_map(|worktree| worktree.read(cx).as_local())
3052 .map(|worktree| worktree.scan_complete())
3053 .collect::<Vec<_>>();
3054 async move {
3055 for future in futures {
3056 future.await;
3057 }
3058 }
3059 }
3060
3061 pub fn close_global(cx: &mut App) {
3062 cx.defer(|cx| {
3063 cx.windows().iter().find(|window| {
3064 window
3065 .update(cx, |_, window, _| {
3066 if window.is_window_active() {
3067 //This can only get called when the window's project connection has been lost
3068 //so we don't need to prompt the user for anything and instead just close the window
3069 window.remove_window();
3070 true
3071 } else {
3072 false
3073 }
3074 })
3075 .unwrap_or(false)
3076 });
3077 });
3078 }
3079
3080 pub fn move_focused_panel_to_next_position(
3081 &mut self,
3082 _: &MoveFocusedPanelToNextPosition,
3083 window: &mut Window,
3084 cx: &mut Context<Self>,
3085 ) {
3086 let docks = self.all_docks();
3087 let active_dock = docks
3088 .into_iter()
3089 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3090
3091 if let Some(dock) = active_dock {
3092 dock.update(cx, |dock, cx| {
3093 let active_panel = dock
3094 .active_panel()
3095 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
3096
3097 if let Some(panel) = active_panel {
3098 panel.move_to_next_position(window, cx);
3099 }
3100 })
3101 }
3102 }
3103
3104 pub fn prepare_to_close(
3105 &mut self,
3106 close_intent: CloseIntent,
3107 window: &mut Window,
3108 cx: &mut Context<Self>,
3109 ) -> Task<Result<bool>> {
3110 let active_call = self.active_global_call();
3111
3112 cx.spawn_in(window, async move |this, cx| {
3113 this.update(cx, |this, _| {
3114 if close_intent == CloseIntent::CloseWindow {
3115 this.removing = true;
3116 }
3117 })?;
3118
3119 let workspace_count = cx.update(|_window, cx| {
3120 cx.windows()
3121 .iter()
3122 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
3123 .count()
3124 })?;
3125
3126 #[cfg(target_os = "macos")]
3127 let save_last_workspace = false;
3128
3129 // On Linux and Windows, closing the last window should restore the last workspace.
3130 #[cfg(not(target_os = "macos"))]
3131 let save_last_workspace = {
3132 let remaining_workspaces = cx.update(|_window, cx| {
3133 cx.windows()
3134 .iter()
3135 .filter_map(|window| window.downcast::<MultiWorkspace>())
3136 .filter_map(|multi_workspace| {
3137 multi_workspace
3138 .update(cx, |multi_workspace, _, cx| {
3139 multi_workspace.workspace().read(cx).removing
3140 })
3141 .ok()
3142 })
3143 .filter(|removing| !removing)
3144 .count()
3145 })?;
3146
3147 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
3148 };
3149
3150 if let Some(active_call) = active_call
3151 && workspace_count == 1
3152 && cx
3153 .update(|_window, cx| active_call.0.is_in_room(cx))
3154 .unwrap_or(false)
3155 {
3156 if close_intent == CloseIntent::CloseWindow {
3157 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
3158 let answer = cx.update(|window, cx| {
3159 window.prompt(
3160 PromptLevel::Warning,
3161 "Do you want to leave the current call?",
3162 None,
3163 &["Close window and hang up", "Cancel"],
3164 cx,
3165 )
3166 })?;
3167
3168 if answer.await.log_err() == Some(1) {
3169 return anyhow::Ok(false);
3170 } else {
3171 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
3172 task.await.log_err();
3173 }
3174 }
3175 }
3176 if close_intent == CloseIntent::ReplaceWindow {
3177 _ = cx.update(|_window, cx| {
3178 let multi_workspace = cx
3179 .windows()
3180 .iter()
3181 .filter_map(|window| window.downcast::<MultiWorkspace>())
3182 .next()
3183 .unwrap();
3184 let project = multi_workspace
3185 .read(cx)?
3186 .workspace()
3187 .read(cx)
3188 .project
3189 .clone();
3190 if project.read(cx).is_shared() {
3191 active_call.0.unshare_project(project, cx)?;
3192 }
3193 Ok::<_, anyhow::Error>(())
3194 });
3195 }
3196 }
3197
3198 let save_result = this
3199 .update_in(cx, |this, window, cx| {
3200 this.save_all_internal(SaveIntent::Close, window, cx)
3201 })?
3202 .await;
3203
3204 // If we're not quitting, but closing, we remove the workspace from
3205 // the current session.
3206 if close_intent != CloseIntent::Quit
3207 && !save_last_workspace
3208 && save_result.as_ref().is_ok_and(|&res| res)
3209 {
3210 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
3211 .await;
3212 }
3213
3214 save_result
3215 })
3216 }
3217
3218 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
3219 self.save_all_internal(
3220 action.save_intent.unwrap_or(SaveIntent::SaveAll),
3221 window,
3222 cx,
3223 )
3224 .detach_and_log_err(cx);
3225 }
3226
3227 fn send_keystrokes(
3228 &mut self,
3229 action: &SendKeystrokes,
3230 window: &mut Window,
3231 cx: &mut Context<Self>,
3232 ) {
3233 let keystrokes: Vec<Keystroke> = action
3234 .0
3235 .split(' ')
3236 .flat_map(|k| Keystroke::parse(k).log_err())
3237 .map(|k| {
3238 cx.keyboard_mapper()
3239 .map_key_equivalent(k, false)
3240 .inner()
3241 .clone()
3242 })
3243 .collect();
3244 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
3245 }
3246
3247 pub fn send_keystrokes_impl(
3248 &mut self,
3249 keystrokes: Vec<Keystroke>,
3250 window: &mut Window,
3251 cx: &mut Context<Self>,
3252 ) -> Shared<Task<()>> {
3253 let mut state = self.dispatching_keystrokes.borrow_mut();
3254 if !state.dispatched.insert(keystrokes.clone()) {
3255 cx.propagate();
3256 return state.task.clone().unwrap();
3257 }
3258
3259 state.queue.extend(keystrokes);
3260
3261 let keystrokes = self.dispatching_keystrokes.clone();
3262 if state.task.is_none() {
3263 state.task = Some(
3264 window
3265 .spawn(cx, async move |cx| {
3266 // limit to 100 keystrokes to avoid infinite recursion.
3267 for _ in 0..100 {
3268 let keystroke = {
3269 let mut state = keystrokes.borrow_mut();
3270 let Some(keystroke) = state.queue.pop_front() else {
3271 state.dispatched.clear();
3272 state.task.take();
3273 return;
3274 };
3275 keystroke
3276 };
3277 cx.update(|window, cx| {
3278 let focused = window.focused(cx);
3279 window.dispatch_keystroke(keystroke.clone(), cx);
3280 if window.focused(cx) != focused {
3281 // dispatch_keystroke may cause the focus to change.
3282 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3283 // And we need that to happen before the next keystroke to keep vim mode happy...
3284 // (Note that the tests always do this implicitly, so you must manually test with something like:
3285 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3286 // )
3287 window.draw(cx).clear();
3288 }
3289 })
3290 .ok();
3291
3292 // Yield between synthetic keystrokes so deferred focus and
3293 // other effects can settle before dispatching the next key.
3294 yield_now().await;
3295 }
3296
3297 *keystrokes.borrow_mut() = Default::default();
3298 log::error!("over 100 keystrokes passed to send_keystrokes");
3299 })
3300 .shared(),
3301 );
3302 }
3303 state.task.clone().unwrap()
3304 }
3305
3306 /// Prompts the user to save or discard each dirty item, returning
3307 /// `true` if they confirmed (saved/discarded everything) or `false`
3308 /// if they cancelled. Used before removing worktree roots during
3309 /// thread archival.
3310 pub fn prompt_to_save_or_discard_dirty_items(
3311 &mut self,
3312 window: &mut Window,
3313 cx: &mut Context<Self>,
3314 ) -> Task<Result<bool>> {
3315 self.save_all_internal(SaveIntent::Close, window, cx)
3316 }
3317
3318 fn save_all_internal(
3319 &mut self,
3320 mut save_intent: SaveIntent,
3321 window: &mut Window,
3322 cx: &mut Context<Self>,
3323 ) -> Task<Result<bool>> {
3324 if self.project.read(cx).is_disconnected(cx) {
3325 return Task::ready(Ok(true));
3326 }
3327 let dirty_items = self
3328 .panes
3329 .iter()
3330 .flat_map(|pane| {
3331 pane.read(cx).items().filter_map(|item| {
3332 if item.is_dirty(cx) {
3333 item.tab_content_text(0, cx);
3334 Some((pane.downgrade(), item.boxed_clone()))
3335 } else {
3336 None
3337 }
3338 })
3339 })
3340 .collect::<Vec<_>>();
3341
3342 let project = self.project.clone();
3343 cx.spawn_in(window, async move |workspace, cx| {
3344 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3345 let (serialize_tasks, remaining_dirty_items) =
3346 workspace.update_in(cx, |workspace, window, cx| {
3347 let mut remaining_dirty_items = Vec::new();
3348 let mut serialize_tasks = Vec::new();
3349 for (pane, item) in dirty_items {
3350 if let Some(task) = item
3351 .to_serializable_item_handle(cx)
3352 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3353 {
3354 serialize_tasks.push(task);
3355 } else {
3356 remaining_dirty_items.push((pane, item));
3357 }
3358 }
3359 (serialize_tasks, remaining_dirty_items)
3360 })?;
3361
3362 futures::future::try_join_all(serialize_tasks).await?;
3363
3364 if !remaining_dirty_items.is_empty() {
3365 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3366 }
3367
3368 if remaining_dirty_items.len() > 1 {
3369 let answer = workspace.update_in(cx, |_, window, cx| {
3370 cx.emit(Event::Activate);
3371 let detail = Pane::file_names_for_prompt(
3372 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3373 cx,
3374 );
3375 window.prompt(
3376 PromptLevel::Warning,
3377 "Do you want to save all changes in the following files?",
3378 Some(&detail),
3379 &["Save all", "Discard all", "Cancel"],
3380 cx,
3381 )
3382 })?;
3383 match answer.await.log_err() {
3384 Some(0) => save_intent = SaveIntent::SaveAll,
3385 Some(1) => save_intent = SaveIntent::Skip,
3386 Some(2) => return Ok(false),
3387 _ => {}
3388 }
3389 }
3390
3391 remaining_dirty_items
3392 } else {
3393 dirty_items
3394 };
3395
3396 for (pane, item) in dirty_items {
3397 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3398 (
3399 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3400 item.project_entry_ids(cx),
3401 )
3402 })?;
3403 if (singleton || !project_entry_ids.is_empty())
3404 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3405 {
3406 return Ok(false);
3407 }
3408 }
3409 Ok(true)
3410 })
3411 }
3412
3413 pub fn open_workspace_for_paths(
3414 &mut self,
3415 // replace_current_window: bool,
3416 mut open_mode: OpenMode,
3417 paths: Vec<PathBuf>,
3418 window: &mut Window,
3419 cx: &mut Context<Self>,
3420 ) -> Task<Result<Entity<Workspace>>> {
3421 let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
3422 let is_remote = self.project.read(cx).is_via_collab();
3423 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3424 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3425
3426 let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
3427 if workspace_is_empty {
3428 open_mode = OpenMode::Activate;
3429 }
3430
3431 let app_state = self.app_state.clone();
3432
3433 cx.spawn(async move |_, cx| {
3434 let OpenResult { workspace, .. } = cx
3435 .update(|cx| {
3436 open_paths(
3437 &paths,
3438 app_state,
3439 OpenOptions {
3440 requesting_window,
3441 open_mode,
3442 ..Default::default()
3443 },
3444 cx,
3445 )
3446 })
3447 .await?;
3448 Ok(workspace)
3449 })
3450 }
3451
3452 #[allow(clippy::type_complexity)]
3453 pub fn open_paths(
3454 &mut self,
3455 mut abs_paths: Vec<PathBuf>,
3456 options: OpenOptions,
3457 pane: Option<WeakEntity<Pane>>,
3458 window: &mut Window,
3459 cx: &mut Context<Self>,
3460 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3461 let fs = self.app_state.fs.clone();
3462
3463 let caller_ordered_abs_paths = abs_paths.clone();
3464
3465 // Sort the paths to ensure we add worktrees for parents before their children.
3466 abs_paths.sort_unstable();
3467 cx.spawn_in(window, async move |this, cx| {
3468 let mut tasks = Vec::with_capacity(abs_paths.len());
3469
3470 for abs_path in &abs_paths {
3471 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3472 OpenVisible::All => Some(true),
3473 OpenVisible::None => Some(false),
3474 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3475 Some(Some(metadata)) => Some(!metadata.is_dir),
3476 Some(None) => Some(true),
3477 None => None,
3478 },
3479 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3480 Some(Some(metadata)) => Some(metadata.is_dir),
3481 Some(None) => Some(false),
3482 None => None,
3483 },
3484 };
3485 let project_path = match visible {
3486 Some(visible) => match this
3487 .update(cx, |this, cx| {
3488 Workspace::project_path_for_path(
3489 this.project.clone(),
3490 abs_path,
3491 visible,
3492 cx,
3493 )
3494 })
3495 .log_err()
3496 {
3497 Some(project_path) => project_path.await.log_err(),
3498 None => None,
3499 },
3500 None => None,
3501 };
3502
3503 let this = this.clone();
3504 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3505 let fs = fs.clone();
3506 let pane = pane.clone();
3507 let task = cx.spawn(async move |cx| {
3508 let (_worktree, project_path) = project_path?;
3509 if fs.is_dir(&abs_path).await {
3510 // Opening a directory should not race to update the active entry.
3511 // We'll select/reveal a deterministic final entry after all paths finish opening.
3512 None
3513 } else {
3514 Some(
3515 this.update_in(cx, |this, window, cx| {
3516 this.open_path(
3517 project_path,
3518 pane,
3519 options.focus.unwrap_or(true),
3520 window,
3521 cx,
3522 )
3523 })
3524 .ok()?
3525 .await,
3526 )
3527 }
3528 });
3529 tasks.push(task);
3530 }
3531
3532 let results = futures::future::join_all(tasks).await;
3533
3534 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3535 let mut winner: Option<(PathBuf, bool)> = None;
3536 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3537 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3538 if !metadata.is_dir {
3539 winner = Some((abs_path, false));
3540 break;
3541 }
3542 if winner.is_none() {
3543 winner = Some((abs_path, true));
3544 }
3545 } else if winner.is_none() {
3546 winner = Some((abs_path, false));
3547 }
3548 }
3549
3550 // Compute the winner entry id on the foreground thread and emit once, after all
3551 // paths finish opening. This avoids races between concurrently-opening paths
3552 // (directories in particular) and makes the resulting project panel selection
3553 // deterministic.
3554 if let Some((winner_abs_path, winner_is_dir)) = winner {
3555 'emit_winner: {
3556 let winner_abs_path: Arc<Path> =
3557 SanitizedPath::new(&winner_abs_path).as_path().into();
3558
3559 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3560 OpenVisible::All => true,
3561 OpenVisible::None => false,
3562 OpenVisible::OnlyFiles => !winner_is_dir,
3563 OpenVisible::OnlyDirectories => winner_is_dir,
3564 };
3565
3566 let Some(worktree_task) = this
3567 .update(cx, |workspace, cx| {
3568 workspace.project.update(cx, |project, cx| {
3569 project.find_or_create_worktree(
3570 winner_abs_path.as_ref(),
3571 visible,
3572 cx,
3573 )
3574 })
3575 })
3576 .ok()
3577 else {
3578 break 'emit_winner;
3579 };
3580
3581 let Ok((worktree, _)) = worktree_task.await else {
3582 break 'emit_winner;
3583 };
3584
3585 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3586 let worktree = worktree.read(cx);
3587 let worktree_abs_path = worktree.abs_path();
3588 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3589 worktree.root_entry()
3590 } else {
3591 winner_abs_path
3592 .strip_prefix(worktree_abs_path.as_ref())
3593 .ok()
3594 .and_then(|relative_path| {
3595 let relative_path =
3596 RelPath::new(relative_path, PathStyle::local())
3597 .log_err()?;
3598 worktree.entry_for_path(&relative_path)
3599 })
3600 }?;
3601 Some(entry.id)
3602 }) else {
3603 break 'emit_winner;
3604 };
3605
3606 this.update(cx, |workspace, cx| {
3607 workspace.project.update(cx, |_, cx| {
3608 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3609 });
3610 })
3611 .ok();
3612 }
3613 }
3614
3615 results
3616 })
3617 }
3618
3619 pub fn open_resolved_path(
3620 &mut self,
3621 path: ResolvedPath,
3622 window: &mut Window,
3623 cx: &mut Context<Self>,
3624 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3625 match path {
3626 ResolvedPath::ProjectPath { project_path, .. } => {
3627 self.open_path(project_path, None, true, window, cx)
3628 }
3629 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3630 PathBuf::from(path),
3631 OpenOptions {
3632 visible: Some(OpenVisible::None),
3633 ..Default::default()
3634 },
3635 window,
3636 cx,
3637 ),
3638 }
3639 }
3640
3641 pub fn absolute_path_of_worktree(
3642 &self,
3643 worktree_id: WorktreeId,
3644 cx: &mut Context<Self>,
3645 ) -> Option<PathBuf> {
3646 self.project
3647 .read(cx)
3648 .worktree_for_id(worktree_id, cx)
3649 // TODO: use `abs_path` or `root_dir`
3650 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3651 }
3652
3653 pub fn add_folder_to_project(
3654 &mut self,
3655 _: &AddFolderToProject,
3656 window: &mut Window,
3657 cx: &mut Context<Self>,
3658 ) {
3659 let project = self.project.read(cx);
3660 if project.is_via_collab() {
3661 self.show_error(
3662 &anyhow!("You cannot add folders to someone else's project"),
3663 cx,
3664 );
3665 return;
3666 }
3667 let paths = self.prompt_for_open_path(
3668 PathPromptOptions {
3669 files: false,
3670 directories: true,
3671 multiple: true,
3672 prompt: None,
3673 },
3674 DirectoryLister::Project(self.project.clone()),
3675 window,
3676 cx,
3677 );
3678 cx.spawn_in(window, async move |this, cx| {
3679 if let Some(paths) = paths.await.log_err().flatten() {
3680 let results = this
3681 .update_in(cx, |this, window, cx| {
3682 this.open_paths(
3683 paths,
3684 OpenOptions {
3685 visible: Some(OpenVisible::All),
3686 ..Default::default()
3687 },
3688 None,
3689 window,
3690 cx,
3691 )
3692 })?
3693 .await;
3694 for result in results.into_iter().flatten() {
3695 result.log_err();
3696 }
3697 }
3698 anyhow::Ok(())
3699 })
3700 .detach_and_log_err(cx);
3701 }
3702
3703 pub fn project_path_for_path(
3704 project: Entity<Project>,
3705 abs_path: &Path,
3706 visible: bool,
3707 cx: &mut App,
3708 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3709 let entry = project.update(cx, |project, cx| {
3710 project.find_or_create_worktree(abs_path, visible, cx)
3711 });
3712 cx.spawn(async move |cx| {
3713 let (worktree, path) = entry.await?;
3714 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3715 Ok((worktree, ProjectPath { worktree_id, path }))
3716 })
3717 }
3718
3719 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3720 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3721 }
3722
3723 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3724 self.items_of_type(cx).max_by_key(|item| item.item_id())
3725 }
3726
3727 pub fn items_of_type<'a, T: Item>(
3728 &'a self,
3729 cx: &'a App,
3730 ) -> impl 'a + Iterator<Item = Entity<T>> {
3731 self.panes
3732 .iter()
3733 .flat_map(|pane| pane.read(cx).items_of_type())
3734 }
3735
3736 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3737 self.active_pane().read(cx).active_item()
3738 }
3739
3740 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3741 let item = self.active_item(cx)?;
3742 item.to_any_view().downcast::<I>().ok()
3743 }
3744
3745 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3746 self.active_item(cx).and_then(|item| item.project_path(cx))
3747 }
3748
3749 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3750 self.recent_navigation_history_iter(cx)
3751 .filter_map(|(path, abs_path)| {
3752 let worktree = self
3753 .project
3754 .read(cx)
3755 .worktree_for_id(path.worktree_id, cx)?;
3756 if worktree.read(cx).is_visible() {
3757 abs_path
3758 } else {
3759 None
3760 }
3761 })
3762 .next()
3763 }
3764
3765 pub fn save_active_item(
3766 &mut self,
3767 save_intent: SaveIntent,
3768 window: &mut Window,
3769 cx: &mut App,
3770 ) -> Task<Result<()>> {
3771 let project = self.project.clone();
3772 let pane = self.active_pane();
3773 let item = pane.read(cx).active_item();
3774 let pane = pane.downgrade();
3775
3776 window.spawn(cx, async move |cx| {
3777 if let Some(item) = item {
3778 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3779 .await
3780 .map(|_| ())
3781 } else {
3782 Ok(())
3783 }
3784 })
3785 }
3786
3787 pub fn close_inactive_items_and_panes(
3788 &mut self,
3789 action: &CloseInactiveTabsAndPanes,
3790 window: &mut Window,
3791 cx: &mut Context<Self>,
3792 ) {
3793 if let Some(task) = self.close_all_internal(
3794 true,
3795 action.save_intent.unwrap_or(SaveIntent::Close),
3796 window,
3797 cx,
3798 ) {
3799 task.detach_and_log_err(cx)
3800 }
3801 }
3802
3803 pub fn close_all_items_and_panes(
3804 &mut self,
3805 action: &CloseAllItemsAndPanes,
3806 window: &mut Window,
3807 cx: &mut Context<Self>,
3808 ) {
3809 if let Some(task) = self.close_all_internal(
3810 false,
3811 action.save_intent.unwrap_or(SaveIntent::Close),
3812 window,
3813 cx,
3814 ) {
3815 task.detach_and_log_err(cx)
3816 }
3817 }
3818
3819 /// Closes the active item across all panes.
3820 pub fn close_item_in_all_panes(
3821 &mut self,
3822 action: &CloseItemInAllPanes,
3823 window: &mut Window,
3824 cx: &mut Context<Self>,
3825 ) {
3826 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3827 return;
3828 };
3829
3830 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3831 let close_pinned = action.close_pinned;
3832
3833 if let Some(project_path) = active_item.project_path(cx) {
3834 self.close_items_with_project_path(
3835 &project_path,
3836 save_intent,
3837 close_pinned,
3838 window,
3839 cx,
3840 );
3841 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3842 let item_id = active_item.item_id();
3843 self.active_pane().update(cx, |pane, cx| {
3844 pane.close_item_by_id(item_id, save_intent, window, cx)
3845 .detach_and_log_err(cx);
3846 });
3847 }
3848 }
3849
3850 /// Closes all items with the given project path across all panes.
3851 pub fn close_items_with_project_path(
3852 &mut self,
3853 project_path: &ProjectPath,
3854 save_intent: SaveIntent,
3855 close_pinned: bool,
3856 window: &mut Window,
3857 cx: &mut Context<Self>,
3858 ) {
3859 let panes = self.panes().to_vec();
3860 for pane in panes {
3861 pane.update(cx, |pane, cx| {
3862 pane.close_items_for_project_path(
3863 project_path,
3864 save_intent,
3865 close_pinned,
3866 window,
3867 cx,
3868 )
3869 .detach_and_log_err(cx);
3870 });
3871 }
3872 }
3873
3874 fn close_all_internal(
3875 &mut self,
3876 retain_active_pane: bool,
3877 save_intent: SaveIntent,
3878 window: &mut Window,
3879 cx: &mut Context<Self>,
3880 ) -> Option<Task<Result<()>>> {
3881 let current_pane = self.active_pane();
3882
3883 let mut tasks = Vec::new();
3884
3885 if retain_active_pane {
3886 let current_pane_close = current_pane.update(cx, |pane, cx| {
3887 pane.close_other_items(
3888 &CloseOtherItems {
3889 save_intent: None,
3890 close_pinned: false,
3891 },
3892 None,
3893 window,
3894 cx,
3895 )
3896 });
3897
3898 tasks.push(current_pane_close);
3899 }
3900
3901 for pane in self.panes() {
3902 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3903 continue;
3904 }
3905
3906 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3907 pane.close_all_items(
3908 &CloseAllItems {
3909 save_intent: Some(save_intent),
3910 close_pinned: false,
3911 },
3912 window,
3913 cx,
3914 )
3915 });
3916
3917 tasks.push(close_pane_items)
3918 }
3919
3920 if tasks.is_empty() {
3921 None
3922 } else {
3923 Some(cx.spawn_in(window, async move |_, _| {
3924 for task in tasks {
3925 task.await?
3926 }
3927 Ok(())
3928 }))
3929 }
3930 }
3931
3932 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3933 self.dock_at_position(position).read(cx).is_open()
3934 }
3935
3936 pub fn toggle_dock(
3937 &mut self,
3938 dock_side: DockPosition,
3939 window: &mut Window,
3940 cx: &mut Context<Self>,
3941 ) {
3942 let mut focus_center = false;
3943 let mut reveal_dock = false;
3944
3945 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3946 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3947
3948 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3949 telemetry::event!(
3950 "Panel Button Clicked",
3951 name = panel.persistent_name(),
3952 toggle_state = !was_visible
3953 );
3954 }
3955 if was_visible {
3956 self.save_open_dock_positions(cx);
3957 }
3958
3959 let dock = self.dock_at_position(dock_side);
3960 dock.update(cx, |dock, cx| {
3961 dock.set_open(!was_visible, window, cx);
3962
3963 if dock.active_panel().is_none() {
3964 let Some(panel_ix) = dock
3965 .first_enabled_panel_idx(cx)
3966 .log_with_level(log::Level::Info)
3967 else {
3968 return;
3969 };
3970 dock.activate_panel(panel_ix, window, cx);
3971 }
3972
3973 if let Some(active_panel) = dock.active_panel() {
3974 if was_visible {
3975 if active_panel
3976 .panel_focus_handle(cx)
3977 .contains_focused(window, cx)
3978 {
3979 focus_center = true;
3980 }
3981 } else {
3982 let focus_handle = &active_panel.panel_focus_handle(cx);
3983 window.focus(focus_handle, cx);
3984 reveal_dock = true;
3985 }
3986 }
3987 });
3988
3989 if reveal_dock {
3990 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3991 }
3992
3993 if focus_center {
3994 self.active_pane
3995 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3996 }
3997
3998 cx.notify();
3999 self.serialize_workspace(window, cx);
4000 }
4001
4002 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
4003 self.all_docks().into_iter().find(|&dock| {
4004 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
4005 })
4006 }
4007
4008 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
4009 if let Some(dock) = self.active_dock(window, cx).cloned() {
4010 self.save_open_dock_positions(cx);
4011 dock.update(cx, |dock, cx| {
4012 dock.set_open(false, window, cx);
4013 });
4014 return true;
4015 }
4016 false
4017 }
4018
4019 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4020 self.save_open_dock_positions(cx);
4021 for dock in self.all_docks() {
4022 dock.update(cx, |dock, cx| {
4023 dock.set_open(false, window, cx);
4024 });
4025 }
4026
4027 cx.focus_self(window);
4028 cx.notify();
4029 self.serialize_workspace(window, cx);
4030 }
4031
4032 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
4033 self.all_docks()
4034 .into_iter()
4035 .filter_map(|dock| {
4036 let dock_ref = dock.read(cx);
4037 if dock_ref.is_open() {
4038 Some(dock_ref.position())
4039 } else {
4040 None
4041 }
4042 })
4043 .collect()
4044 }
4045
4046 /// Saves the positions of currently open docks.
4047 ///
4048 /// Updates `last_open_dock_positions` with positions of all currently open
4049 /// docks, to later be restored by the 'Toggle All Docks' action.
4050 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
4051 let open_dock_positions = self.get_open_dock_positions(cx);
4052 if !open_dock_positions.is_empty() {
4053 self.last_open_dock_positions = open_dock_positions;
4054 }
4055 }
4056
4057 /// Toggles all docks between open and closed states.
4058 ///
4059 /// If any docks are open, closes all and remembers their positions. If all
4060 /// docks are closed, restores the last remembered dock configuration.
4061 fn toggle_all_docks(
4062 &mut self,
4063 _: &ToggleAllDocks,
4064 window: &mut Window,
4065 cx: &mut Context<Self>,
4066 ) {
4067 let open_dock_positions = self.get_open_dock_positions(cx);
4068
4069 if !open_dock_positions.is_empty() {
4070 self.close_all_docks(window, cx);
4071 } else if !self.last_open_dock_positions.is_empty() {
4072 self.restore_last_open_docks(window, cx);
4073 }
4074 }
4075
4076 /// Reopens docks from the most recently remembered configuration.
4077 ///
4078 /// Opens all docks whose positions are stored in `last_open_dock_positions`
4079 /// and clears the stored positions.
4080 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4081 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
4082
4083 for position in positions_to_open {
4084 let dock = self.dock_at_position(position);
4085 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
4086 }
4087
4088 cx.focus_self(window);
4089 cx.notify();
4090 self.serialize_workspace(window, cx);
4091 }
4092
4093 /// Transfer focus to the panel of the given type.
4094 pub fn focus_panel<T: Panel>(
4095 &mut self,
4096 window: &mut Window,
4097 cx: &mut Context<Self>,
4098 ) -> Option<Entity<T>> {
4099 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
4100 panel.to_any().downcast().ok()
4101 }
4102
4103 /// Focus the panel of the given type if it isn't already focused. If it is
4104 /// already focused, then transfer focus back to the workspace center.
4105 /// When the `close_panel_on_toggle` setting is enabled, also closes the
4106 /// panel when transferring focus back to the center.
4107 pub fn toggle_panel_focus<T: Panel>(
4108 &mut self,
4109 window: &mut Window,
4110 cx: &mut Context<Self>,
4111 ) -> bool {
4112 let mut did_focus_panel = false;
4113 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
4114 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
4115 did_focus_panel
4116 });
4117
4118 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
4119 self.close_panel::<T>(window, cx);
4120 }
4121
4122 telemetry::event!(
4123 "Panel Button Clicked",
4124 name = T::persistent_name(),
4125 toggle_state = did_focus_panel
4126 );
4127
4128 did_focus_panel
4129 }
4130
4131 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4132 if let Some(item) = self.active_item(cx) {
4133 item.item_focus_handle(cx).focus(window, cx);
4134 } else {
4135 log::error!("Could not find a focus target when switching focus to the center panes",);
4136 }
4137 }
4138
4139 pub fn activate_panel_for_proto_id(
4140 &mut self,
4141 panel_id: PanelId,
4142 window: &mut Window,
4143 cx: &mut Context<Self>,
4144 ) -> Option<Arc<dyn PanelHandle>> {
4145 let mut panel = None;
4146 for dock in self.all_docks() {
4147 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
4148 panel = dock.update(cx, |dock, cx| {
4149 dock.activate_panel(panel_index, window, cx);
4150 dock.set_open(true, window, cx);
4151 dock.active_panel().cloned()
4152 });
4153 break;
4154 }
4155 }
4156
4157 if panel.is_some() {
4158 cx.notify();
4159 self.serialize_workspace(window, cx);
4160 }
4161
4162 panel
4163 }
4164
4165 /// Focus or unfocus the given panel type, depending on the given callback.
4166 fn focus_or_unfocus_panel<T: Panel>(
4167 &mut self,
4168 window: &mut Window,
4169 cx: &mut Context<Self>,
4170 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
4171 ) -> Option<Arc<dyn PanelHandle>> {
4172 let mut result_panel = None;
4173 let mut serialize = false;
4174 for dock in self.all_docks() {
4175 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4176 let mut focus_center = false;
4177 let panel = dock.update(cx, |dock, cx| {
4178 dock.activate_panel(panel_index, window, cx);
4179
4180 let panel = dock.active_panel().cloned();
4181 if let Some(panel) = panel.as_ref() {
4182 if should_focus(&**panel, window, cx) {
4183 dock.set_open(true, window, cx);
4184 panel.panel_focus_handle(cx).focus(window, cx);
4185 } else {
4186 focus_center = true;
4187 }
4188 }
4189 panel
4190 });
4191
4192 if focus_center {
4193 self.active_pane
4194 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4195 }
4196
4197 result_panel = panel;
4198 serialize = true;
4199 break;
4200 }
4201 }
4202
4203 if serialize {
4204 self.serialize_workspace(window, cx);
4205 }
4206
4207 cx.notify();
4208 result_panel
4209 }
4210
4211 /// Open the panel of the given type
4212 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4213 for dock in self.all_docks() {
4214 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4215 dock.update(cx, |dock, cx| {
4216 dock.activate_panel(panel_index, window, cx);
4217 dock.set_open(true, window, cx);
4218 });
4219 }
4220 }
4221 }
4222
4223 /// Open the panel of the given type, dismissing any zoomed items that
4224 /// would obscure it (e.g. a zoomed terminal).
4225 pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4226 let dock_position = self.all_docks().iter().find_map(|dock| {
4227 let dock = dock.read(cx);
4228 dock.panel_index_for_type::<T>().map(|_| dock.position())
4229 });
4230 self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
4231 self.open_panel::<T>(window, cx);
4232 }
4233
4234 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4235 for dock in self.all_docks().iter() {
4236 dock.update(cx, |dock, cx| {
4237 if dock.panel::<T>().is_some() {
4238 dock.set_open(false, window, cx)
4239 }
4240 })
4241 }
4242 }
4243
4244 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4245 self.all_docks()
4246 .iter()
4247 .find_map(|dock| dock.read(cx).panel::<T>())
4248 }
4249
4250 fn dismiss_zoomed_items_to_reveal(
4251 &mut self,
4252 dock_to_reveal: Option<DockPosition>,
4253 window: &mut Window,
4254 cx: &mut Context<Self>,
4255 ) {
4256 // If a center pane is zoomed, unzoom it.
4257 for pane in &self.panes {
4258 if pane != &self.active_pane || dock_to_reveal.is_some() {
4259 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4260 }
4261 }
4262
4263 // If another dock is zoomed, hide it.
4264 let mut focus_center = false;
4265 for dock in self.all_docks() {
4266 dock.update(cx, |dock, cx| {
4267 if Some(dock.position()) != dock_to_reveal
4268 && let Some(panel) = dock.active_panel()
4269 && panel.is_zoomed(window, cx)
4270 {
4271 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4272 dock.set_open(false, window, cx);
4273 }
4274 });
4275 }
4276
4277 if focus_center {
4278 self.active_pane
4279 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4280 }
4281
4282 if self.zoomed_position != dock_to_reveal {
4283 self.zoomed = None;
4284 self.zoomed_position = None;
4285 cx.emit(Event::ZoomChanged);
4286 }
4287
4288 cx.notify();
4289 }
4290
4291 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4292 let pane = cx.new(|cx| {
4293 let mut pane = Pane::new(
4294 self.weak_handle(),
4295 self.project.clone(),
4296 self.pane_history_timestamp.clone(),
4297 None,
4298 NewFile.boxed_clone(),
4299 true,
4300 window,
4301 cx,
4302 );
4303 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4304 pane
4305 });
4306 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4307 .detach();
4308 self.panes.push(pane.clone());
4309
4310 window.focus(&pane.focus_handle(cx), cx);
4311
4312 cx.emit(Event::PaneAdded(pane.clone()));
4313 pane
4314 }
4315
4316 pub fn add_item_to_center(
4317 &mut self,
4318 item: Box<dyn ItemHandle>,
4319 window: &mut Window,
4320 cx: &mut Context<Self>,
4321 ) -> bool {
4322 if let Some(center_pane) = self.last_active_center_pane.clone() {
4323 if let Some(center_pane) = center_pane.upgrade() {
4324 center_pane.update(cx, |pane, cx| {
4325 pane.add_item(item, true, true, None, window, cx)
4326 });
4327 true
4328 } else {
4329 false
4330 }
4331 } else {
4332 false
4333 }
4334 }
4335
4336 pub fn add_item_to_active_pane(
4337 &mut self,
4338 item: Box<dyn ItemHandle>,
4339 destination_index: Option<usize>,
4340 focus_item: bool,
4341 window: &mut Window,
4342 cx: &mut App,
4343 ) {
4344 self.add_item(
4345 self.active_pane.clone(),
4346 item,
4347 destination_index,
4348 false,
4349 focus_item,
4350 window,
4351 cx,
4352 )
4353 }
4354
4355 pub fn add_item(
4356 &mut self,
4357 pane: Entity<Pane>,
4358 item: Box<dyn ItemHandle>,
4359 destination_index: Option<usize>,
4360 activate_pane: bool,
4361 focus_item: bool,
4362 window: &mut Window,
4363 cx: &mut App,
4364 ) {
4365 pane.update(cx, |pane, cx| {
4366 pane.add_item(
4367 item,
4368 activate_pane,
4369 focus_item,
4370 destination_index,
4371 window,
4372 cx,
4373 )
4374 });
4375 }
4376
4377 pub fn split_item(
4378 &mut self,
4379 split_direction: SplitDirection,
4380 item: Box<dyn ItemHandle>,
4381 window: &mut Window,
4382 cx: &mut Context<Self>,
4383 ) {
4384 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4385 self.add_item(new_pane, item, None, true, true, window, cx);
4386 }
4387
4388 pub fn open_abs_path(
4389 &mut self,
4390 abs_path: PathBuf,
4391 options: OpenOptions,
4392 window: &mut Window,
4393 cx: &mut Context<Self>,
4394 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4395 cx.spawn_in(window, async move |workspace, cx| {
4396 let open_paths_task_result = workspace
4397 .update_in(cx, |workspace, window, cx| {
4398 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4399 })
4400 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4401 .await;
4402 anyhow::ensure!(
4403 open_paths_task_result.len() == 1,
4404 "open abs path {abs_path:?} task returned incorrect number of results"
4405 );
4406 match open_paths_task_result
4407 .into_iter()
4408 .next()
4409 .expect("ensured single task result")
4410 {
4411 Some(open_result) => {
4412 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4413 }
4414 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4415 }
4416 })
4417 }
4418
4419 pub fn split_abs_path(
4420 &mut self,
4421 abs_path: PathBuf,
4422 visible: bool,
4423 window: &mut Window,
4424 cx: &mut Context<Self>,
4425 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4426 let project_path_task =
4427 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4428 cx.spawn_in(window, async move |this, cx| {
4429 let (_, path) = project_path_task.await?;
4430 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4431 .await
4432 })
4433 }
4434
4435 pub fn open_path(
4436 &mut self,
4437 path: impl Into<ProjectPath>,
4438 pane: Option<WeakEntity<Pane>>,
4439 focus_item: bool,
4440 window: &mut Window,
4441 cx: &mut App,
4442 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4443 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4444 }
4445
4446 pub fn open_path_preview(
4447 &mut self,
4448 path: impl Into<ProjectPath>,
4449 pane: Option<WeakEntity<Pane>>,
4450 focus_item: bool,
4451 allow_preview: bool,
4452 activate: bool,
4453 window: &mut Window,
4454 cx: &mut App,
4455 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4456 let pane = pane.unwrap_or_else(|| {
4457 self.last_active_center_pane.clone().unwrap_or_else(|| {
4458 self.panes
4459 .first()
4460 .expect("There must be an active pane")
4461 .downgrade()
4462 })
4463 });
4464
4465 let project_path = path.into();
4466 let task = self.load_path(project_path.clone(), window, cx);
4467 window.spawn(cx, async move |cx| {
4468 let (project_entry_id, build_item) = task.await?;
4469
4470 pane.update_in(cx, |pane, window, cx| {
4471 pane.open_item(
4472 project_entry_id,
4473 project_path,
4474 focus_item,
4475 allow_preview,
4476 activate,
4477 None,
4478 window,
4479 cx,
4480 build_item,
4481 )
4482 })
4483 })
4484 }
4485
4486 pub fn split_path(
4487 &mut self,
4488 path: impl Into<ProjectPath>,
4489 window: &mut Window,
4490 cx: &mut Context<Self>,
4491 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4492 self.split_path_preview(path, false, None, window, cx)
4493 }
4494
4495 pub fn split_path_preview(
4496 &mut self,
4497 path: impl Into<ProjectPath>,
4498 allow_preview: bool,
4499 split_direction: Option<SplitDirection>,
4500 window: &mut Window,
4501 cx: &mut Context<Self>,
4502 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4503 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4504 self.panes
4505 .first()
4506 .expect("There must be an active pane")
4507 .downgrade()
4508 });
4509
4510 if let Member::Pane(center_pane) = &self.center.root
4511 && center_pane.read(cx).items_len() == 0
4512 {
4513 return self.open_path(path, Some(pane), true, window, cx);
4514 }
4515
4516 let project_path = path.into();
4517 let task = self.load_path(project_path.clone(), window, cx);
4518 cx.spawn_in(window, async move |this, cx| {
4519 let (project_entry_id, build_item) = task.await?;
4520 this.update_in(cx, move |this, window, cx| -> Option<_> {
4521 let pane = pane.upgrade()?;
4522 let new_pane = this.split_pane(
4523 pane,
4524 split_direction.unwrap_or(SplitDirection::Right),
4525 window,
4526 cx,
4527 );
4528 new_pane.update(cx, |new_pane, cx| {
4529 Some(new_pane.open_item(
4530 project_entry_id,
4531 project_path,
4532 true,
4533 allow_preview,
4534 true,
4535 None,
4536 window,
4537 cx,
4538 build_item,
4539 ))
4540 })
4541 })
4542 .map(|option| option.context("pane was dropped"))?
4543 })
4544 }
4545
4546 fn load_path(
4547 &mut self,
4548 path: ProjectPath,
4549 window: &mut Window,
4550 cx: &mut App,
4551 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4552 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4553 registry.open_path(self.project(), &path, window, cx)
4554 }
4555
4556 pub fn find_project_item<T>(
4557 &self,
4558 pane: &Entity<Pane>,
4559 project_item: &Entity<T::Item>,
4560 cx: &App,
4561 ) -> Option<Entity<T>>
4562 where
4563 T: ProjectItem,
4564 {
4565 use project::ProjectItem as _;
4566 let project_item = project_item.read(cx);
4567 let entry_id = project_item.entry_id(cx);
4568 let project_path = project_item.project_path(cx);
4569
4570 let mut item = None;
4571 if let Some(entry_id) = entry_id {
4572 item = pane.read(cx).item_for_entry(entry_id, cx);
4573 }
4574 if item.is_none()
4575 && let Some(project_path) = project_path
4576 {
4577 item = pane.read(cx).item_for_path(project_path, cx);
4578 }
4579
4580 item.and_then(|item| item.downcast::<T>())
4581 }
4582
4583 pub fn is_project_item_open<T>(
4584 &self,
4585 pane: &Entity<Pane>,
4586 project_item: &Entity<T::Item>,
4587 cx: &App,
4588 ) -> bool
4589 where
4590 T: ProjectItem,
4591 {
4592 self.find_project_item::<T>(pane, project_item, cx)
4593 .is_some()
4594 }
4595
4596 pub fn open_project_item<T>(
4597 &mut self,
4598 pane: Entity<Pane>,
4599 project_item: Entity<T::Item>,
4600 activate_pane: bool,
4601 focus_item: bool,
4602 keep_old_preview: bool,
4603 allow_new_preview: bool,
4604 window: &mut Window,
4605 cx: &mut Context<Self>,
4606 ) -> Entity<T>
4607 where
4608 T: ProjectItem,
4609 {
4610 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4611
4612 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4613 if !keep_old_preview
4614 && let Some(old_id) = old_item_id
4615 && old_id != item.item_id()
4616 {
4617 // switching to a different item, so unpreview old active item
4618 pane.update(cx, |pane, _| {
4619 pane.unpreview_item_if_preview(old_id);
4620 });
4621 }
4622
4623 self.activate_item(&item, activate_pane, focus_item, window, cx);
4624 if !allow_new_preview {
4625 pane.update(cx, |pane, _| {
4626 pane.unpreview_item_if_preview(item.item_id());
4627 });
4628 }
4629 return item;
4630 }
4631
4632 let item = pane.update(cx, |pane, cx| {
4633 cx.new(|cx| {
4634 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4635 })
4636 });
4637 let mut destination_index = None;
4638 pane.update(cx, |pane, cx| {
4639 if !keep_old_preview && let Some(old_id) = old_item_id {
4640 pane.unpreview_item_if_preview(old_id);
4641 }
4642 if allow_new_preview {
4643 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4644 }
4645 });
4646
4647 self.add_item(
4648 pane,
4649 Box::new(item.clone()),
4650 destination_index,
4651 activate_pane,
4652 focus_item,
4653 window,
4654 cx,
4655 );
4656 item
4657 }
4658
4659 pub fn open_shared_screen(
4660 &mut self,
4661 peer_id: PeerId,
4662 window: &mut Window,
4663 cx: &mut Context<Self>,
4664 ) {
4665 if let Some(shared_screen) =
4666 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4667 {
4668 self.active_pane.update(cx, |pane, cx| {
4669 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4670 });
4671 }
4672 }
4673
4674 pub fn activate_item(
4675 &mut self,
4676 item: &dyn ItemHandle,
4677 activate_pane: bool,
4678 focus_item: bool,
4679 window: &mut Window,
4680 cx: &mut App,
4681 ) -> bool {
4682 let result = self.panes.iter().find_map(|pane| {
4683 pane.read(cx)
4684 .index_for_item(item)
4685 .map(|ix| (pane.clone(), ix))
4686 });
4687 if let Some((pane, ix)) = result {
4688 pane.update(cx, |pane, cx| {
4689 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4690 });
4691 true
4692 } else {
4693 false
4694 }
4695 }
4696
4697 fn activate_pane_at_index(
4698 &mut self,
4699 action: &ActivatePane,
4700 window: &mut Window,
4701 cx: &mut Context<Self>,
4702 ) {
4703 let panes = self.center.panes();
4704 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4705 window.focus(&pane.focus_handle(cx), cx);
4706 } else {
4707 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4708 .detach();
4709 }
4710 }
4711
4712 fn move_item_to_pane_at_index(
4713 &mut self,
4714 action: &MoveItemToPane,
4715 window: &mut Window,
4716 cx: &mut Context<Self>,
4717 ) {
4718 let panes = self.center.panes();
4719 let destination = match panes.get(action.destination) {
4720 Some(&destination) => destination.clone(),
4721 None => {
4722 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4723 return;
4724 }
4725 let direction = SplitDirection::Right;
4726 let split_off_pane = self
4727 .find_pane_in_direction(direction, cx)
4728 .unwrap_or_else(|| self.active_pane.clone());
4729 let new_pane = self.add_pane(window, cx);
4730 self.center.split(&split_off_pane, &new_pane, direction, cx);
4731 new_pane
4732 }
4733 };
4734
4735 if action.clone {
4736 if self
4737 .active_pane
4738 .read(cx)
4739 .active_item()
4740 .is_some_and(|item| item.can_split(cx))
4741 {
4742 clone_active_item(
4743 self.database_id(),
4744 &self.active_pane,
4745 &destination,
4746 action.focus,
4747 window,
4748 cx,
4749 );
4750 return;
4751 }
4752 }
4753 move_active_item(
4754 &self.active_pane,
4755 &destination,
4756 action.focus,
4757 true,
4758 window,
4759 cx,
4760 )
4761 }
4762
4763 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4764 let panes = self.center.panes();
4765 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4766 let next_ix = (ix + 1) % panes.len();
4767 let next_pane = panes[next_ix].clone();
4768 window.focus(&next_pane.focus_handle(cx), cx);
4769 }
4770 }
4771
4772 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4773 let panes = self.center.panes();
4774 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4775 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4776 let prev_pane = panes[prev_ix].clone();
4777 window.focus(&prev_pane.focus_handle(cx), cx);
4778 }
4779 }
4780
4781 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4782 let last_pane = self.center.last_pane();
4783 window.focus(&last_pane.focus_handle(cx), cx);
4784 }
4785
4786 pub fn activate_pane_in_direction(
4787 &mut self,
4788 direction: SplitDirection,
4789 window: &mut Window,
4790 cx: &mut App,
4791 ) {
4792 use ActivateInDirectionTarget as Target;
4793 enum Origin {
4794 Sidebar,
4795 LeftDock,
4796 RightDock,
4797 BottomDock,
4798 Center,
4799 }
4800
4801 let origin: Origin = if self
4802 .sidebar_focus_handle
4803 .as_ref()
4804 .is_some_and(|h| h.contains_focused(window, cx))
4805 {
4806 Origin::Sidebar
4807 } else {
4808 [
4809 (&self.left_dock, Origin::LeftDock),
4810 (&self.right_dock, Origin::RightDock),
4811 (&self.bottom_dock, Origin::BottomDock),
4812 ]
4813 .into_iter()
4814 .find_map(|(dock, origin)| {
4815 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4816 Some(origin)
4817 } else {
4818 None
4819 }
4820 })
4821 .unwrap_or(Origin::Center)
4822 };
4823
4824 let get_last_active_pane = || {
4825 let pane = self
4826 .last_active_center_pane
4827 .clone()
4828 .unwrap_or_else(|| {
4829 self.panes
4830 .first()
4831 .expect("There must be an active pane")
4832 .downgrade()
4833 })
4834 .upgrade()?;
4835 (pane.read(cx).items_len() != 0).then_some(pane)
4836 };
4837
4838 let try_dock =
4839 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4840
4841 let sidebar_target = self
4842 .sidebar_focus_handle
4843 .as_ref()
4844 .map(|h| Target::Sidebar(h.clone()));
4845
4846 let sidebar_on_right = self
4847 .multi_workspace
4848 .as_ref()
4849 .and_then(|mw| mw.upgrade())
4850 .map_or(false, |mw| {
4851 mw.read(cx).sidebar_side(cx) == SidebarSide::Right
4852 });
4853
4854 let away_from_sidebar = if sidebar_on_right {
4855 SplitDirection::Left
4856 } else {
4857 SplitDirection::Right
4858 };
4859
4860 let (near_dock, far_dock) = if sidebar_on_right {
4861 (&self.right_dock, &self.left_dock)
4862 } else {
4863 (&self.left_dock, &self.right_dock)
4864 };
4865
4866 let target = match (origin, direction) {
4867 (Origin::Sidebar, dir) if dir == away_from_sidebar => try_dock(near_dock)
4868 .or_else(|| get_last_active_pane().map(Target::Pane))
4869 .or_else(|| try_dock(&self.bottom_dock))
4870 .or_else(|| try_dock(far_dock)),
4871
4872 (Origin::Sidebar, _) => None,
4873
4874 // We're in the center, so we first try to go to a different pane,
4875 // otherwise try to go to a dock.
4876 (Origin::Center, direction) => {
4877 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4878 Some(Target::Pane(pane))
4879 } else {
4880 match direction {
4881 SplitDirection::Up => None,
4882 SplitDirection::Down => try_dock(&self.bottom_dock),
4883 SplitDirection::Left => {
4884 let dock_target = try_dock(&self.left_dock);
4885 if sidebar_on_right {
4886 dock_target
4887 } else {
4888 dock_target.or(sidebar_target)
4889 }
4890 }
4891 SplitDirection::Right => {
4892 let dock_target = try_dock(&self.right_dock);
4893 if sidebar_on_right {
4894 dock_target.or(sidebar_target)
4895 } else {
4896 dock_target
4897 }
4898 }
4899 }
4900 }
4901 }
4902
4903 (Origin::LeftDock, SplitDirection::Right) => {
4904 if let Some(last_active_pane) = get_last_active_pane() {
4905 Some(Target::Pane(last_active_pane))
4906 } else {
4907 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4908 }
4909 }
4910
4911 (Origin::LeftDock, SplitDirection::Left) => {
4912 if sidebar_on_right {
4913 None
4914 } else {
4915 sidebar_target
4916 }
4917 }
4918
4919 (Origin::LeftDock, SplitDirection::Down)
4920 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4921
4922 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4923 (Origin::BottomDock, SplitDirection::Left) => {
4924 let dock_target = try_dock(&self.left_dock);
4925 if sidebar_on_right {
4926 dock_target
4927 } else {
4928 dock_target.or(sidebar_target)
4929 }
4930 }
4931 (Origin::BottomDock, SplitDirection::Right) => {
4932 let dock_target = try_dock(&self.right_dock);
4933 if sidebar_on_right {
4934 dock_target.or(sidebar_target)
4935 } else {
4936 dock_target
4937 }
4938 }
4939
4940 (Origin::RightDock, SplitDirection::Left) => {
4941 if let Some(last_active_pane) = get_last_active_pane() {
4942 Some(Target::Pane(last_active_pane))
4943 } else {
4944 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
4945 }
4946 }
4947
4948 (Origin::RightDock, SplitDirection::Right) => {
4949 if sidebar_on_right {
4950 sidebar_target
4951 } else {
4952 None
4953 }
4954 }
4955
4956 _ => None,
4957 };
4958
4959 match target {
4960 Some(ActivateInDirectionTarget::Pane(pane)) => {
4961 let pane = pane.read(cx);
4962 if let Some(item) = pane.active_item() {
4963 item.item_focus_handle(cx).focus(window, cx);
4964 } else {
4965 log::error!(
4966 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4967 );
4968 }
4969 }
4970 Some(ActivateInDirectionTarget::Dock(dock)) => {
4971 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4972 window.defer(cx, move |window, cx| {
4973 let dock = dock.read(cx);
4974 if let Some(panel) = dock.active_panel() {
4975 panel.panel_focus_handle(cx).focus(window, cx);
4976 } else {
4977 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4978 }
4979 })
4980 }
4981 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4982 focus_handle.focus(window, cx);
4983 }
4984 None => {}
4985 }
4986 }
4987
4988 pub fn move_item_to_pane_in_direction(
4989 &mut self,
4990 action: &MoveItemToPaneInDirection,
4991 window: &mut Window,
4992 cx: &mut Context<Self>,
4993 ) {
4994 let destination = match self.find_pane_in_direction(action.direction, cx) {
4995 Some(destination) => destination,
4996 None => {
4997 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4998 return;
4999 }
5000 let new_pane = self.add_pane(window, cx);
5001 self.center
5002 .split(&self.active_pane, &new_pane, action.direction, cx);
5003 new_pane
5004 }
5005 };
5006
5007 if action.clone {
5008 if self
5009 .active_pane
5010 .read(cx)
5011 .active_item()
5012 .is_some_and(|item| item.can_split(cx))
5013 {
5014 clone_active_item(
5015 self.database_id(),
5016 &self.active_pane,
5017 &destination,
5018 action.focus,
5019 window,
5020 cx,
5021 );
5022 return;
5023 }
5024 }
5025 move_active_item(
5026 &self.active_pane,
5027 &destination,
5028 action.focus,
5029 true,
5030 window,
5031 cx,
5032 );
5033 }
5034
5035 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
5036 self.center.bounding_box_for_pane(pane)
5037 }
5038
5039 pub fn find_pane_in_direction(
5040 &mut self,
5041 direction: SplitDirection,
5042 cx: &App,
5043 ) -> Option<Entity<Pane>> {
5044 self.center
5045 .find_pane_in_direction(&self.active_pane, direction, cx)
5046 .cloned()
5047 }
5048
5049 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
5050 if let Some(to) = self.find_pane_in_direction(direction, cx) {
5051 self.center.swap(&self.active_pane, &to, cx);
5052 cx.notify();
5053 }
5054 }
5055
5056 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
5057 if self
5058 .center
5059 .move_to_border(&self.active_pane, direction, cx)
5060 .unwrap()
5061 {
5062 cx.notify();
5063 }
5064 }
5065
5066 pub fn resize_pane(
5067 &mut self,
5068 axis: gpui::Axis,
5069 amount: Pixels,
5070 window: &mut Window,
5071 cx: &mut Context<Self>,
5072 ) {
5073 let docks = self.all_docks();
5074 let active_dock = docks
5075 .into_iter()
5076 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
5077
5078 if let Some(dock_entity) = active_dock {
5079 let dock = dock_entity.read(cx);
5080 let Some(panel_size) = self.dock_size(&dock, window, cx) else {
5081 return;
5082 };
5083 match dock.position() {
5084 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
5085 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
5086 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
5087 }
5088 } else {
5089 self.center
5090 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
5091 }
5092 cx.notify();
5093 }
5094
5095 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
5096 self.center.reset_pane_sizes(cx);
5097 cx.notify();
5098 }
5099
5100 fn handle_pane_focused(
5101 &mut self,
5102 pane: Entity<Pane>,
5103 window: &mut Window,
5104 cx: &mut Context<Self>,
5105 ) {
5106 // This is explicitly hoisted out of the following check for pane identity as
5107 // terminal panel panes are not registered as a center panes.
5108 self.status_bar.update(cx, |status_bar, cx| {
5109 status_bar.set_active_pane(&pane, window, cx);
5110 });
5111 if self.active_pane != pane {
5112 self.set_active_pane(&pane, window, cx);
5113 }
5114
5115 if self.last_active_center_pane.is_none() {
5116 self.last_active_center_pane = Some(pane.downgrade());
5117 }
5118
5119 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
5120 // This prevents the dock from closing when focus events fire during window activation.
5121 // We also preserve any dock whose active panel itself has focus — this covers
5122 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
5123 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
5124 let dock_read = dock.read(cx);
5125 if let Some(panel) = dock_read.active_panel() {
5126 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
5127 || panel.panel_focus_handle(cx).contains_focused(window, cx)
5128 {
5129 return Some(dock_read.position());
5130 }
5131 }
5132 None
5133 });
5134
5135 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
5136 if pane.read(cx).is_zoomed() {
5137 self.zoomed = Some(pane.downgrade().into());
5138 } else {
5139 self.zoomed = None;
5140 }
5141 self.zoomed_position = None;
5142 cx.emit(Event::ZoomChanged);
5143 self.update_active_view_for_followers(window, cx);
5144 pane.update(cx, |pane, _| {
5145 pane.track_alternate_file_items();
5146 });
5147
5148 cx.notify();
5149 }
5150
5151 fn set_active_pane(
5152 &mut self,
5153 pane: &Entity<Pane>,
5154 window: &mut Window,
5155 cx: &mut Context<Self>,
5156 ) {
5157 self.active_pane = pane.clone();
5158 self.active_item_path_changed(true, window, cx);
5159 self.last_active_center_pane = Some(pane.downgrade());
5160 }
5161
5162 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5163 self.update_active_view_for_followers(window, cx);
5164 }
5165
5166 fn handle_pane_event(
5167 &mut self,
5168 pane: &Entity<Pane>,
5169 event: &pane::Event,
5170 window: &mut Window,
5171 cx: &mut Context<Self>,
5172 ) {
5173 let mut serialize_workspace = true;
5174 match event {
5175 pane::Event::AddItem { item } => {
5176 item.added_to_pane(self, pane.clone(), window, cx);
5177 cx.emit(Event::ItemAdded {
5178 item: item.boxed_clone(),
5179 });
5180 }
5181 pane::Event::Split { direction, mode } => {
5182 match mode {
5183 SplitMode::ClonePane => {
5184 self.split_and_clone(pane.clone(), *direction, window, cx)
5185 .detach();
5186 }
5187 SplitMode::EmptyPane => {
5188 self.split_pane(pane.clone(), *direction, window, cx);
5189 }
5190 SplitMode::MovePane => {
5191 self.split_and_move(pane.clone(), *direction, window, cx);
5192 }
5193 };
5194 }
5195 pane::Event::JoinIntoNext => {
5196 self.join_pane_into_next(pane.clone(), window, cx);
5197 }
5198 pane::Event::JoinAll => {
5199 self.join_all_panes(window, cx);
5200 }
5201 pane::Event::Remove { focus_on_pane } => {
5202 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5203 }
5204 pane::Event::ActivateItem {
5205 local,
5206 focus_changed,
5207 } => {
5208 window.invalidate_character_coordinates();
5209
5210 pane.update(cx, |pane, _| {
5211 pane.track_alternate_file_items();
5212 });
5213 if *local {
5214 self.unfollow_in_pane(pane, window, cx);
5215 }
5216 serialize_workspace = *focus_changed || pane != self.active_pane();
5217 if pane == self.active_pane() {
5218 self.active_item_path_changed(*focus_changed, window, cx);
5219 self.update_active_view_for_followers(window, cx);
5220 } else if *local {
5221 self.set_active_pane(pane, window, cx);
5222 }
5223 }
5224 pane::Event::UserSavedItem { item, save_intent } => {
5225 cx.emit(Event::UserSavedItem {
5226 pane: pane.downgrade(),
5227 item: item.boxed_clone(),
5228 save_intent: *save_intent,
5229 });
5230 serialize_workspace = false;
5231 }
5232 pane::Event::ChangeItemTitle => {
5233 if *pane == self.active_pane {
5234 self.active_item_path_changed(false, window, cx);
5235 }
5236 serialize_workspace = false;
5237 }
5238 pane::Event::RemovedItem { item } => {
5239 cx.emit(Event::ActiveItemChanged);
5240 self.update_window_edited(window, cx);
5241 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5242 && entry.get().entity_id() == pane.entity_id()
5243 {
5244 entry.remove();
5245 }
5246 cx.emit(Event::ItemRemoved {
5247 item_id: item.item_id(),
5248 });
5249 }
5250 pane::Event::Focus => {
5251 window.invalidate_character_coordinates();
5252 self.handle_pane_focused(pane.clone(), window, cx);
5253 }
5254 pane::Event::ZoomIn => {
5255 if *pane == self.active_pane {
5256 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5257 if pane.read(cx).has_focus(window, cx) {
5258 self.zoomed = Some(pane.downgrade().into());
5259 self.zoomed_position = None;
5260 cx.emit(Event::ZoomChanged);
5261 }
5262 cx.notify();
5263 }
5264 }
5265 pane::Event::ZoomOut => {
5266 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5267 if self.zoomed_position.is_none() {
5268 self.zoomed = None;
5269 cx.emit(Event::ZoomChanged);
5270 }
5271 cx.notify();
5272 }
5273 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5274 }
5275
5276 if serialize_workspace {
5277 self.serialize_workspace(window, cx);
5278 }
5279 }
5280
5281 pub fn unfollow_in_pane(
5282 &mut self,
5283 pane: &Entity<Pane>,
5284 window: &mut Window,
5285 cx: &mut Context<Workspace>,
5286 ) -> Option<CollaboratorId> {
5287 let leader_id = self.leader_for_pane(pane)?;
5288 self.unfollow(leader_id, window, cx);
5289 Some(leader_id)
5290 }
5291
5292 pub fn split_pane(
5293 &mut self,
5294 pane_to_split: Entity<Pane>,
5295 split_direction: SplitDirection,
5296 window: &mut Window,
5297 cx: &mut Context<Self>,
5298 ) -> Entity<Pane> {
5299 let new_pane = self.add_pane(window, cx);
5300 self.center
5301 .split(&pane_to_split, &new_pane, split_direction, cx);
5302 cx.notify();
5303 new_pane
5304 }
5305
5306 pub fn split_and_move(
5307 &mut self,
5308 pane: Entity<Pane>,
5309 direction: SplitDirection,
5310 window: &mut Window,
5311 cx: &mut Context<Self>,
5312 ) {
5313 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5314 return;
5315 };
5316 let new_pane = self.add_pane(window, cx);
5317 new_pane.update(cx, |pane, cx| {
5318 pane.add_item(item, true, true, None, window, cx)
5319 });
5320 self.center.split(&pane, &new_pane, direction, cx);
5321 cx.notify();
5322 }
5323
5324 pub fn split_and_clone(
5325 &mut self,
5326 pane: Entity<Pane>,
5327 direction: SplitDirection,
5328 window: &mut Window,
5329 cx: &mut Context<Self>,
5330 ) -> Task<Option<Entity<Pane>>> {
5331 let Some(item) = pane.read(cx).active_item() else {
5332 return Task::ready(None);
5333 };
5334 if !item.can_split(cx) {
5335 return Task::ready(None);
5336 }
5337 let task = item.clone_on_split(self.database_id(), window, cx);
5338 cx.spawn_in(window, async move |this, cx| {
5339 if let Some(clone) = task.await {
5340 this.update_in(cx, |this, window, cx| {
5341 let new_pane = this.add_pane(window, cx);
5342 let nav_history = pane.read(cx).fork_nav_history();
5343 new_pane.update(cx, |pane, cx| {
5344 pane.set_nav_history(nav_history, cx);
5345 pane.add_item(clone, true, true, None, window, cx)
5346 });
5347 this.center.split(&pane, &new_pane, direction, cx);
5348 cx.notify();
5349 new_pane
5350 })
5351 .ok()
5352 } else {
5353 None
5354 }
5355 })
5356 }
5357
5358 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5359 let active_item = self.active_pane.read(cx).active_item();
5360 for pane in &self.panes {
5361 join_pane_into_active(&self.active_pane, pane, window, cx);
5362 }
5363 if let Some(active_item) = active_item {
5364 self.activate_item(active_item.as_ref(), true, true, window, cx);
5365 }
5366 cx.notify();
5367 }
5368
5369 pub fn join_pane_into_next(
5370 &mut self,
5371 pane: Entity<Pane>,
5372 window: &mut Window,
5373 cx: &mut Context<Self>,
5374 ) {
5375 let next_pane = self
5376 .find_pane_in_direction(SplitDirection::Right, cx)
5377 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5378 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5379 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5380 let Some(next_pane) = next_pane else {
5381 return;
5382 };
5383 move_all_items(&pane, &next_pane, window, cx);
5384 cx.notify();
5385 }
5386
5387 fn remove_pane(
5388 &mut self,
5389 pane: Entity<Pane>,
5390 focus_on: Option<Entity<Pane>>,
5391 window: &mut Window,
5392 cx: &mut Context<Self>,
5393 ) {
5394 if self.center.remove(&pane, cx).unwrap() {
5395 self.force_remove_pane(&pane, &focus_on, window, cx);
5396 self.unfollow_in_pane(&pane, window, cx);
5397 self.last_leaders_by_pane.remove(&pane.downgrade());
5398 for removed_item in pane.read(cx).items() {
5399 self.panes_by_item.remove(&removed_item.item_id());
5400 }
5401
5402 cx.notify();
5403 } else {
5404 self.active_item_path_changed(true, window, cx);
5405 }
5406 cx.emit(Event::PaneRemoved);
5407 }
5408
5409 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5410 &mut self.panes
5411 }
5412
5413 pub fn panes(&self) -> &[Entity<Pane>] {
5414 &self.panes
5415 }
5416
5417 pub fn active_pane(&self) -> &Entity<Pane> {
5418 &self.active_pane
5419 }
5420
5421 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5422 for dock in self.all_docks() {
5423 if dock.focus_handle(cx).contains_focused(window, cx)
5424 && let Some(pane) = dock
5425 .read(cx)
5426 .active_panel()
5427 .and_then(|panel| panel.pane(cx))
5428 {
5429 return pane;
5430 }
5431 }
5432 self.active_pane().clone()
5433 }
5434
5435 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5436 self.find_pane_in_direction(SplitDirection::Right, cx)
5437 .unwrap_or_else(|| {
5438 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5439 })
5440 }
5441
5442 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5443 self.pane_for_item_id(handle.item_id())
5444 }
5445
5446 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5447 let weak_pane = self.panes_by_item.get(&item_id)?;
5448 weak_pane.upgrade()
5449 }
5450
5451 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5452 self.panes
5453 .iter()
5454 .find(|pane| pane.entity_id() == entity_id)
5455 .cloned()
5456 }
5457
5458 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5459 self.follower_states.retain(|leader_id, state| {
5460 if *leader_id == CollaboratorId::PeerId(peer_id) {
5461 for item in state.items_by_leader_view_id.values() {
5462 item.view.set_leader_id(None, window, cx);
5463 }
5464 false
5465 } else {
5466 true
5467 }
5468 });
5469 cx.notify();
5470 }
5471
5472 pub fn start_following(
5473 &mut self,
5474 leader_id: impl Into<CollaboratorId>,
5475 window: &mut Window,
5476 cx: &mut Context<Self>,
5477 ) -> Option<Task<Result<()>>> {
5478 let leader_id = leader_id.into();
5479 let pane = self.active_pane().clone();
5480
5481 self.last_leaders_by_pane
5482 .insert(pane.downgrade(), leader_id);
5483 self.unfollow(leader_id, window, cx);
5484 self.unfollow_in_pane(&pane, window, cx);
5485 self.follower_states.insert(
5486 leader_id,
5487 FollowerState {
5488 center_pane: pane.clone(),
5489 dock_pane: None,
5490 active_view_id: None,
5491 items_by_leader_view_id: Default::default(),
5492 },
5493 );
5494 cx.notify();
5495
5496 match leader_id {
5497 CollaboratorId::PeerId(leader_peer_id) => {
5498 let room_id = self.active_call()?.room_id(cx)?;
5499 let project_id = self.project.read(cx).remote_id();
5500 let request = self.app_state.client.request(proto::Follow {
5501 room_id,
5502 project_id,
5503 leader_id: Some(leader_peer_id),
5504 });
5505
5506 Some(cx.spawn_in(window, async move |this, cx| {
5507 let response = request.await?;
5508 this.update(cx, |this, _| {
5509 let state = this
5510 .follower_states
5511 .get_mut(&leader_id)
5512 .context("following interrupted")?;
5513 state.active_view_id = response
5514 .active_view
5515 .as_ref()
5516 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5517 anyhow::Ok(())
5518 })??;
5519 if let Some(view) = response.active_view {
5520 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5521 }
5522 this.update_in(cx, |this, window, cx| {
5523 this.leader_updated(leader_id, window, cx)
5524 })?;
5525 Ok(())
5526 }))
5527 }
5528 CollaboratorId::Agent => {
5529 self.leader_updated(leader_id, window, cx)?;
5530 Some(Task::ready(Ok(())))
5531 }
5532 }
5533 }
5534
5535 pub fn follow_next_collaborator(
5536 &mut self,
5537 _: &FollowNextCollaborator,
5538 window: &mut Window,
5539 cx: &mut Context<Self>,
5540 ) {
5541 let collaborators = self.project.read(cx).collaborators();
5542 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5543 let mut collaborators = collaborators.keys().copied();
5544 for peer_id in collaborators.by_ref() {
5545 if CollaboratorId::PeerId(peer_id) == leader_id {
5546 break;
5547 }
5548 }
5549 collaborators.next().map(CollaboratorId::PeerId)
5550 } else if let Some(last_leader_id) =
5551 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5552 {
5553 match last_leader_id {
5554 CollaboratorId::PeerId(peer_id) => {
5555 if collaborators.contains_key(peer_id) {
5556 Some(*last_leader_id)
5557 } else {
5558 None
5559 }
5560 }
5561 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5562 }
5563 } else {
5564 None
5565 };
5566
5567 let pane = self.active_pane.clone();
5568 let Some(leader_id) = next_leader_id.or_else(|| {
5569 Some(CollaboratorId::PeerId(
5570 collaborators.keys().copied().next()?,
5571 ))
5572 }) else {
5573 return;
5574 };
5575 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5576 return;
5577 }
5578 if let Some(task) = self.start_following(leader_id, window, cx) {
5579 task.detach_and_log_err(cx)
5580 }
5581 }
5582
5583 pub fn follow(
5584 &mut self,
5585 leader_id: impl Into<CollaboratorId>,
5586 window: &mut Window,
5587 cx: &mut Context<Self>,
5588 ) {
5589 let leader_id = leader_id.into();
5590
5591 if let CollaboratorId::PeerId(peer_id) = leader_id {
5592 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5593 return;
5594 };
5595 let Some(remote_participant) =
5596 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5597 else {
5598 return;
5599 };
5600
5601 let project = self.project.read(cx);
5602
5603 let other_project_id = match remote_participant.location {
5604 ParticipantLocation::External => None,
5605 ParticipantLocation::UnsharedProject => None,
5606 ParticipantLocation::SharedProject { project_id } => {
5607 if Some(project_id) == project.remote_id() {
5608 None
5609 } else {
5610 Some(project_id)
5611 }
5612 }
5613 };
5614
5615 // if they are active in another project, follow there.
5616 if let Some(project_id) = other_project_id {
5617 let app_state = self.app_state.clone();
5618 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5619 .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
5620 Some(format!("{error:#}"))
5621 });
5622 }
5623 }
5624
5625 // if you're already following, find the right pane and focus it.
5626 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5627 window.focus(&follower_state.pane().focus_handle(cx), cx);
5628
5629 return;
5630 }
5631
5632 // Otherwise, follow.
5633 if let Some(task) = self.start_following(leader_id, window, cx) {
5634 task.detach_and_log_err(cx)
5635 }
5636 }
5637
5638 pub fn unfollow(
5639 &mut self,
5640 leader_id: impl Into<CollaboratorId>,
5641 window: &mut Window,
5642 cx: &mut Context<Self>,
5643 ) -> Option<()> {
5644 cx.notify();
5645
5646 let leader_id = leader_id.into();
5647 let state = self.follower_states.remove(&leader_id)?;
5648 for (_, item) in state.items_by_leader_view_id {
5649 item.view.set_leader_id(None, window, cx);
5650 }
5651
5652 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5653 let project_id = self.project.read(cx).remote_id();
5654 let room_id = self.active_call()?.room_id(cx)?;
5655 self.app_state
5656 .client
5657 .send(proto::Unfollow {
5658 room_id,
5659 project_id,
5660 leader_id: Some(leader_peer_id),
5661 })
5662 .log_err();
5663 }
5664
5665 Some(())
5666 }
5667
5668 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5669 self.follower_states.contains_key(&id.into())
5670 }
5671
5672 fn active_item_path_changed(
5673 &mut self,
5674 focus_changed: bool,
5675 window: &mut Window,
5676 cx: &mut Context<Self>,
5677 ) {
5678 cx.emit(Event::ActiveItemChanged);
5679 let active_entry = self.active_project_path(cx);
5680 self.project.update(cx, |project, cx| {
5681 project.set_active_path(active_entry.clone(), cx)
5682 });
5683
5684 if focus_changed && let Some(project_path) = &active_entry {
5685 let git_store_entity = self.project.read(cx).git_store().clone();
5686 git_store_entity.update(cx, |git_store, cx| {
5687 git_store.set_active_repo_for_path(project_path, cx);
5688 });
5689 }
5690
5691 self.update_window_title(window, cx);
5692 }
5693
5694 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5695 let project = self.project().read(cx);
5696 let mut title = String::new();
5697
5698 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5699 let name = {
5700 let settings_location = SettingsLocation {
5701 worktree_id: worktree.read(cx).id(),
5702 path: RelPath::empty(),
5703 };
5704
5705 let settings = WorktreeSettings::get(Some(settings_location), cx);
5706 match &settings.project_name {
5707 Some(name) => name.as_str(),
5708 None => worktree.read(cx).root_name_str(),
5709 }
5710 };
5711 if i > 0 {
5712 title.push_str(", ");
5713 }
5714 title.push_str(name);
5715 }
5716
5717 if title.is_empty() {
5718 title = "empty project".to_string();
5719 }
5720
5721 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5722 let filename = path.path.file_name().or_else(|| {
5723 Some(
5724 project
5725 .worktree_for_id(path.worktree_id, cx)?
5726 .read(cx)
5727 .root_name_str(),
5728 )
5729 });
5730
5731 if let Some(filename) = filename {
5732 title.push_str(" — ");
5733 title.push_str(filename.as_ref());
5734 }
5735 }
5736
5737 if project.is_via_collab() {
5738 title.push_str(" ↙");
5739 } else if project.is_shared() {
5740 title.push_str(" ↗");
5741 }
5742
5743 if let Some(last_title) = self.last_window_title.as_ref()
5744 && &title == last_title
5745 {
5746 return;
5747 }
5748 window.set_window_title(&title);
5749 SystemWindowTabController::update_tab_title(
5750 cx,
5751 window.window_handle().window_id(),
5752 SharedString::from(&title),
5753 );
5754 self.last_window_title = Some(title);
5755 }
5756
5757 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5758 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5759 if is_edited != self.window_edited {
5760 self.window_edited = is_edited;
5761 window.set_window_edited(self.window_edited)
5762 }
5763 }
5764
5765 fn update_item_dirty_state(
5766 &mut self,
5767 item: &dyn ItemHandle,
5768 window: &mut Window,
5769 cx: &mut App,
5770 ) {
5771 let is_dirty = item.is_dirty(cx);
5772 let item_id = item.item_id();
5773 let was_dirty = self.dirty_items.contains_key(&item_id);
5774 if is_dirty == was_dirty {
5775 return;
5776 }
5777 if was_dirty {
5778 self.dirty_items.remove(&item_id);
5779 self.update_window_edited(window, cx);
5780 return;
5781 }
5782
5783 let workspace = self.weak_handle();
5784 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5785 return;
5786 };
5787 let on_release_callback = Box::new(move |cx: &mut App| {
5788 window_handle
5789 .update(cx, |_, window, cx| {
5790 workspace
5791 .update(cx, |workspace, cx| {
5792 workspace.dirty_items.remove(&item_id);
5793 workspace.update_window_edited(window, cx)
5794 })
5795 .ok();
5796 })
5797 .ok();
5798 });
5799
5800 let s = item.on_release(cx, on_release_callback);
5801 self.dirty_items.insert(item_id, s);
5802 self.update_window_edited(window, cx);
5803 }
5804
5805 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5806 if self.notifications.is_empty() {
5807 None
5808 } else {
5809 Some(
5810 div()
5811 .absolute()
5812 .right_3()
5813 .bottom_3()
5814 .w_112()
5815 .h_full()
5816 .flex()
5817 .flex_col()
5818 .justify_end()
5819 .gap_2()
5820 .children(
5821 self.notifications
5822 .iter()
5823 .map(|(_, notification)| notification.clone().into_any()),
5824 ),
5825 )
5826 }
5827 }
5828
5829 // RPC handlers
5830
5831 fn active_view_for_follower(
5832 &self,
5833 follower_project_id: Option<u64>,
5834 window: &mut Window,
5835 cx: &mut Context<Self>,
5836 ) -> Option<proto::View> {
5837 let (item, panel_id) = self.active_item_for_followers(window, cx);
5838 let item = item?;
5839 let leader_id = self
5840 .pane_for(&*item)
5841 .and_then(|pane| self.leader_for_pane(&pane));
5842 let leader_peer_id = match leader_id {
5843 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5844 Some(CollaboratorId::Agent) | None => None,
5845 };
5846
5847 let item_handle = item.to_followable_item_handle(cx)?;
5848 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5849 let variant = item_handle.to_state_proto(window, cx)?;
5850
5851 if item_handle.is_project_item(window, cx)
5852 && (follower_project_id.is_none()
5853 || follower_project_id != self.project.read(cx).remote_id())
5854 {
5855 return None;
5856 }
5857
5858 Some(proto::View {
5859 id: id.to_proto(),
5860 leader_id: leader_peer_id,
5861 variant: Some(variant),
5862 panel_id: panel_id.map(|id| id as i32),
5863 })
5864 }
5865
5866 fn handle_follow(
5867 &mut self,
5868 follower_project_id: Option<u64>,
5869 window: &mut Window,
5870 cx: &mut Context<Self>,
5871 ) -> proto::FollowResponse {
5872 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5873
5874 cx.notify();
5875 proto::FollowResponse {
5876 views: active_view.iter().cloned().collect(),
5877 active_view,
5878 }
5879 }
5880
5881 fn handle_update_followers(
5882 &mut self,
5883 leader_id: PeerId,
5884 message: proto::UpdateFollowers,
5885 _window: &mut Window,
5886 _cx: &mut Context<Self>,
5887 ) {
5888 self.leader_updates_tx
5889 .unbounded_send((leader_id, message))
5890 .ok();
5891 }
5892
5893 async fn process_leader_update(
5894 this: &WeakEntity<Self>,
5895 leader_id: PeerId,
5896 update: proto::UpdateFollowers,
5897 cx: &mut AsyncWindowContext,
5898 ) -> Result<()> {
5899 match update.variant.context("invalid update")? {
5900 proto::update_followers::Variant::CreateView(view) => {
5901 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5902 let should_add_view = this.update(cx, |this, _| {
5903 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5904 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5905 } else {
5906 anyhow::Ok(false)
5907 }
5908 })??;
5909
5910 if should_add_view {
5911 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5912 }
5913 }
5914 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5915 let should_add_view = this.update(cx, |this, _| {
5916 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5917 state.active_view_id = update_active_view
5918 .view
5919 .as_ref()
5920 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5921
5922 if state.active_view_id.is_some_and(|view_id| {
5923 !state.items_by_leader_view_id.contains_key(&view_id)
5924 }) {
5925 anyhow::Ok(true)
5926 } else {
5927 anyhow::Ok(false)
5928 }
5929 } else {
5930 anyhow::Ok(false)
5931 }
5932 })??;
5933
5934 if should_add_view && let Some(view) = update_active_view.view {
5935 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5936 }
5937 }
5938 proto::update_followers::Variant::UpdateView(update_view) => {
5939 let variant = update_view.variant.context("missing update view variant")?;
5940 let id = update_view.id.context("missing update view id")?;
5941 let mut tasks = Vec::new();
5942 this.update_in(cx, |this, window, cx| {
5943 let project = this.project.clone();
5944 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5945 let view_id = ViewId::from_proto(id.clone())?;
5946 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5947 tasks.push(item.view.apply_update_proto(
5948 &project,
5949 variant.clone(),
5950 window,
5951 cx,
5952 ));
5953 }
5954 }
5955 anyhow::Ok(())
5956 })??;
5957 try_join_all(tasks).await.log_err();
5958 }
5959 }
5960 this.update_in(cx, |this, window, cx| {
5961 this.leader_updated(leader_id, window, cx)
5962 })?;
5963 Ok(())
5964 }
5965
5966 async fn add_view_from_leader(
5967 this: WeakEntity<Self>,
5968 leader_id: PeerId,
5969 view: &proto::View,
5970 cx: &mut AsyncWindowContext,
5971 ) -> Result<()> {
5972 let this = this.upgrade().context("workspace dropped")?;
5973
5974 let Some(id) = view.id.clone() else {
5975 anyhow::bail!("no id for view");
5976 };
5977 let id = ViewId::from_proto(id)?;
5978 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5979
5980 let pane = this.update(cx, |this, _cx| {
5981 let state = this
5982 .follower_states
5983 .get(&leader_id.into())
5984 .context("stopped following")?;
5985 anyhow::Ok(state.pane().clone())
5986 })?;
5987 let existing_item = pane.update_in(cx, |pane, window, cx| {
5988 let client = this.read(cx).client().clone();
5989 pane.items().find_map(|item| {
5990 let item = item.to_followable_item_handle(cx)?;
5991 if item.remote_id(&client, window, cx) == Some(id) {
5992 Some(item)
5993 } else {
5994 None
5995 }
5996 })
5997 })?;
5998 let item = if let Some(existing_item) = existing_item {
5999 existing_item
6000 } else {
6001 let variant = view.variant.clone();
6002 anyhow::ensure!(variant.is_some(), "missing view variant");
6003
6004 let task = cx.update(|window, cx| {
6005 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
6006 })?;
6007
6008 let Some(task) = task else {
6009 anyhow::bail!(
6010 "failed to construct view from leader (maybe from a different version of zed?)"
6011 );
6012 };
6013
6014 let mut new_item = task.await?;
6015 pane.update_in(cx, |pane, window, cx| {
6016 let mut item_to_remove = None;
6017 for (ix, item) in pane.items().enumerate() {
6018 if let Some(item) = item.to_followable_item_handle(cx) {
6019 match new_item.dedup(item.as_ref(), window, cx) {
6020 Some(item::Dedup::KeepExisting) => {
6021 new_item =
6022 item.boxed_clone().to_followable_item_handle(cx).unwrap();
6023 break;
6024 }
6025 Some(item::Dedup::ReplaceExisting) => {
6026 item_to_remove = Some((ix, item.item_id()));
6027 break;
6028 }
6029 None => {}
6030 }
6031 }
6032 }
6033
6034 if let Some((ix, id)) = item_to_remove {
6035 pane.remove_item(id, false, false, window, cx);
6036 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
6037 }
6038 })?;
6039
6040 new_item
6041 };
6042
6043 this.update_in(cx, |this, window, cx| {
6044 let state = this.follower_states.get_mut(&leader_id.into())?;
6045 item.set_leader_id(Some(leader_id.into()), window, cx);
6046 state.items_by_leader_view_id.insert(
6047 id,
6048 FollowerView {
6049 view: item,
6050 location: panel_id,
6051 },
6052 );
6053
6054 Some(())
6055 })
6056 .context("no follower state")?;
6057
6058 Ok(())
6059 }
6060
6061 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6062 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
6063 return;
6064 };
6065
6066 if let Some(agent_location) = self.project.read(cx).agent_location() {
6067 let buffer_entity_id = agent_location.buffer.entity_id();
6068 let view_id = ViewId {
6069 creator: CollaboratorId::Agent,
6070 id: buffer_entity_id.as_u64(),
6071 };
6072 follower_state.active_view_id = Some(view_id);
6073
6074 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
6075 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
6076 hash_map::Entry::Vacant(entry) => {
6077 let existing_view =
6078 follower_state
6079 .center_pane
6080 .read(cx)
6081 .items()
6082 .find_map(|item| {
6083 let item = item.to_followable_item_handle(cx)?;
6084 if item.buffer_kind(cx) == ItemBufferKind::Singleton
6085 && item.project_item_model_ids(cx).as_slice()
6086 == [buffer_entity_id]
6087 {
6088 Some(item)
6089 } else {
6090 None
6091 }
6092 });
6093 let view = existing_view.or_else(|| {
6094 agent_location.buffer.upgrade().and_then(|buffer| {
6095 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
6096 registry.build_item(buffer, self.project.clone(), None, window, cx)
6097 })?
6098 .to_followable_item_handle(cx)
6099 })
6100 });
6101
6102 view.map(|view| {
6103 entry.insert(FollowerView {
6104 view,
6105 location: None,
6106 })
6107 })
6108 }
6109 };
6110
6111 if let Some(item) = item {
6112 item.view
6113 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
6114 item.view
6115 .update_agent_location(agent_location.position, window, cx);
6116 }
6117 } else {
6118 follower_state.active_view_id = None;
6119 }
6120
6121 self.leader_updated(CollaboratorId::Agent, window, cx);
6122 }
6123
6124 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
6125 let mut is_project_item = true;
6126 let mut update = proto::UpdateActiveView::default();
6127 if window.is_window_active() {
6128 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
6129
6130 if let Some(item) = active_item
6131 && item.item_focus_handle(cx).contains_focused(window, cx)
6132 {
6133 let leader_id = self
6134 .pane_for(&*item)
6135 .and_then(|pane| self.leader_for_pane(&pane));
6136 let leader_peer_id = match leader_id {
6137 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
6138 Some(CollaboratorId::Agent) | None => None,
6139 };
6140
6141 if let Some(item) = item.to_followable_item_handle(cx) {
6142 let id = item
6143 .remote_id(&self.app_state.client, window, cx)
6144 .map(|id| id.to_proto());
6145
6146 if let Some(id) = id
6147 && let Some(variant) = item.to_state_proto(window, cx)
6148 {
6149 let view = Some(proto::View {
6150 id,
6151 leader_id: leader_peer_id,
6152 variant: Some(variant),
6153 panel_id: panel_id.map(|id| id as i32),
6154 });
6155
6156 is_project_item = item.is_project_item(window, cx);
6157 update = proto::UpdateActiveView { view };
6158 };
6159 }
6160 }
6161 }
6162
6163 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
6164 if active_view_id != self.last_active_view_id.as_ref() {
6165 self.last_active_view_id = active_view_id.cloned();
6166 self.update_followers(
6167 is_project_item,
6168 proto::update_followers::Variant::UpdateActiveView(update),
6169 window,
6170 cx,
6171 );
6172 }
6173 }
6174
6175 fn active_item_for_followers(
6176 &self,
6177 window: &mut Window,
6178 cx: &mut App,
6179 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
6180 let mut active_item = None;
6181 let mut panel_id = None;
6182 for dock in self.all_docks() {
6183 if dock.focus_handle(cx).contains_focused(window, cx)
6184 && let Some(panel) = dock.read(cx).active_panel()
6185 && let Some(pane) = panel.pane(cx)
6186 && let Some(item) = pane.read(cx).active_item()
6187 {
6188 active_item = Some(item);
6189 panel_id = panel.remote_id();
6190 break;
6191 }
6192 }
6193
6194 if active_item.is_none() {
6195 active_item = self.active_pane().read(cx).active_item();
6196 }
6197 (active_item, panel_id)
6198 }
6199
6200 fn update_followers(
6201 &self,
6202 project_only: bool,
6203 update: proto::update_followers::Variant,
6204 _: &mut Window,
6205 cx: &mut App,
6206 ) -> Option<()> {
6207 // If this update only applies to for followers in the current project,
6208 // then skip it unless this project is shared. If it applies to all
6209 // followers, regardless of project, then set `project_id` to none,
6210 // indicating that it goes to all followers.
6211 let project_id = if project_only {
6212 Some(self.project.read(cx).remote_id()?)
6213 } else {
6214 None
6215 };
6216 self.app_state().workspace_store.update(cx, |store, cx| {
6217 store.update_followers(project_id, update, cx)
6218 })
6219 }
6220
6221 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6222 self.follower_states.iter().find_map(|(leader_id, state)| {
6223 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6224 Some(*leader_id)
6225 } else {
6226 None
6227 }
6228 })
6229 }
6230
6231 fn leader_updated(
6232 &mut self,
6233 leader_id: impl Into<CollaboratorId>,
6234 window: &mut Window,
6235 cx: &mut Context<Self>,
6236 ) -> Option<Box<dyn ItemHandle>> {
6237 cx.notify();
6238
6239 let leader_id = leader_id.into();
6240 let (panel_id, item) = match leader_id {
6241 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6242 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6243 };
6244
6245 let state = self.follower_states.get(&leader_id)?;
6246 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6247 let pane;
6248 if let Some(panel_id) = panel_id {
6249 pane = self
6250 .activate_panel_for_proto_id(panel_id, window, cx)?
6251 .pane(cx)?;
6252 let state = self.follower_states.get_mut(&leader_id)?;
6253 state.dock_pane = Some(pane.clone());
6254 } else {
6255 pane = state.center_pane.clone();
6256 let state = self.follower_states.get_mut(&leader_id)?;
6257 if let Some(dock_pane) = state.dock_pane.take() {
6258 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6259 }
6260 }
6261
6262 pane.update(cx, |pane, cx| {
6263 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6264 if let Some(index) = pane.index_for_item(item.as_ref()) {
6265 pane.activate_item(index, false, false, window, cx);
6266 } else {
6267 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6268 }
6269
6270 if focus_active_item {
6271 pane.focus_active_item(window, cx)
6272 }
6273 });
6274
6275 Some(item)
6276 }
6277
6278 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6279 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6280 let active_view_id = state.active_view_id?;
6281 Some(
6282 state
6283 .items_by_leader_view_id
6284 .get(&active_view_id)?
6285 .view
6286 .boxed_clone(),
6287 )
6288 }
6289
6290 fn active_item_for_peer(
6291 &self,
6292 peer_id: PeerId,
6293 window: &mut Window,
6294 cx: &mut Context<Self>,
6295 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6296 let call = self.active_call()?;
6297 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6298 let leader_in_this_app;
6299 let leader_in_this_project;
6300 match participant.location {
6301 ParticipantLocation::SharedProject { project_id } => {
6302 leader_in_this_app = true;
6303 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6304 }
6305 ParticipantLocation::UnsharedProject => {
6306 leader_in_this_app = true;
6307 leader_in_this_project = false;
6308 }
6309 ParticipantLocation::External => {
6310 leader_in_this_app = false;
6311 leader_in_this_project = false;
6312 }
6313 };
6314 let state = self.follower_states.get(&peer_id.into())?;
6315 let mut item_to_activate = None;
6316 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6317 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6318 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6319 {
6320 item_to_activate = Some((item.location, item.view.boxed_clone()));
6321 }
6322 } else if let Some(shared_screen) =
6323 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6324 {
6325 item_to_activate = Some((None, Box::new(shared_screen)));
6326 }
6327 item_to_activate
6328 }
6329
6330 fn shared_screen_for_peer(
6331 &self,
6332 peer_id: PeerId,
6333 pane: &Entity<Pane>,
6334 window: &mut Window,
6335 cx: &mut App,
6336 ) -> Option<Entity<SharedScreen>> {
6337 self.active_call()?
6338 .create_shared_screen(peer_id, pane, window, cx)
6339 }
6340
6341 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6342 if window.is_window_active() {
6343 self.update_active_view_for_followers(window, cx);
6344
6345 if let Some(database_id) = self.database_id {
6346 let db = WorkspaceDb::global(cx);
6347 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6348 .detach();
6349 }
6350 } else {
6351 for pane in &self.panes {
6352 pane.update(cx, |pane, cx| {
6353 if let Some(item) = pane.active_item() {
6354 item.workspace_deactivated(window, cx);
6355 }
6356 for item in pane.items() {
6357 if matches!(
6358 item.workspace_settings(cx).autosave,
6359 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6360 ) {
6361 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6362 .detach_and_log_err(cx);
6363 }
6364 }
6365 });
6366 }
6367 }
6368 }
6369
6370 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6371 self.active_call.as_ref().map(|(call, _)| &*call.0)
6372 }
6373
6374 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6375 self.active_call.as_ref().map(|(call, _)| call.clone())
6376 }
6377
6378 fn on_active_call_event(
6379 &mut self,
6380 event: &ActiveCallEvent,
6381 window: &mut Window,
6382 cx: &mut Context<Self>,
6383 ) {
6384 match event {
6385 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6386 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6387 self.leader_updated(participant_id, window, cx);
6388 }
6389 }
6390 }
6391
6392 pub fn database_id(&self) -> Option<WorkspaceId> {
6393 self.database_id
6394 }
6395
6396 #[cfg(any(test, feature = "test-support"))]
6397 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6398 self.database_id = Some(id);
6399 }
6400
6401 pub fn session_id(&self) -> Option<String> {
6402 self.session_id.clone()
6403 }
6404
6405 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6406 let Some(display) = window.display(cx) else {
6407 return Task::ready(());
6408 };
6409 let Ok(display_uuid) = display.uuid() else {
6410 return Task::ready(());
6411 };
6412
6413 let window_bounds = window.inner_window_bounds();
6414 let database_id = self.database_id;
6415 let has_paths = !self.root_paths(cx).is_empty();
6416 let db = WorkspaceDb::global(cx);
6417 let kvp = db::kvp::KeyValueStore::global(cx);
6418
6419 cx.background_executor().spawn(async move {
6420 if !has_paths {
6421 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6422 .await
6423 .log_err();
6424 }
6425 if let Some(database_id) = database_id {
6426 db.set_window_open_status(
6427 database_id,
6428 SerializedWindowBounds(window_bounds),
6429 display_uuid,
6430 )
6431 .await
6432 .log_err();
6433 } else {
6434 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6435 .await
6436 .log_err();
6437 }
6438 })
6439 }
6440
6441 /// Bypass the 200ms serialization throttle and write workspace state to
6442 /// the DB immediately. Returns a task the caller can await to ensure the
6443 /// write completes. Used by the quit handler so the most recent state
6444 /// isn't lost to a pending throttle timer when the process exits.
6445 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6446 self._schedule_serialize_workspace.take();
6447 self._serialize_workspace_task.take();
6448 self.bounds_save_task_queued.take();
6449
6450 let bounds_task = self.save_window_bounds(window, cx);
6451 let serialize_task = self.serialize_workspace_internal(window, cx);
6452 cx.spawn(async move |_| {
6453 bounds_task.await;
6454 serialize_task.await;
6455 })
6456 }
6457
6458 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6459 let project = self.project().read(cx);
6460 project
6461 .visible_worktrees(cx)
6462 .map(|worktree| worktree.read(cx).abs_path())
6463 .collect::<Vec<_>>()
6464 }
6465
6466 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6467 match member {
6468 Member::Axis(PaneAxis { members, .. }) => {
6469 for child in members.iter() {
6470 self.remove_panes(child.clone(), window, cx)
6471 }
6472 }
6473 Member::Pane(pane) => {
6474 self.force_remove_pane(&pane, &None, window, cx);
6475 }
6476 }
6477 }
6478
6479 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6480 self.session_id.take();
6481 self.serialize_workspace_internal(window, cx)
6482 }
6483
6484 fn force_remove_pane(
6485 &mut self,
6486 pane: &Entity<Pane>,
6487 focus_on: &Option<Entity<Pane>>,
6488 window: &mut Window,
6489 cx: &mut Context<Workspace>,
6490 ) {
6491 self.panes.retain(|p| p != pane);
6492 if let Some(focus_on) = focus_on {
6493 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6494 } else if self.active_pane() == pane {
6495 self.panes
6496 .last()
6497 .unwrap()
6498 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6499 }
6500 if self.last_active_center_pane == Some(pane.downgrade()) {
6501 self.last_active_center_pane = None;
6502 }
6503 cx.notify();
6504 }
6505
6506 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6507 if self._schedule_serialize_workspace.is_none() {
6508 self._schedule_serialize_workspace =
6509 Some(cx.spawn_in(window, async move |this, cx| {
6510 cx.background_executor()
6511 .timer(SERIALIZATION_THROTTLE_TIME)
6512 .await;
6513 this.update_in(cx, |this, window, cx| {
6514 this._serialize_workspace_task =
6515 Some(this.serialize_workspace_internal(window, cx));
6516 this._schedule_serialize_workspace.take();
6517 })
6518 .log_err();
6519 }));
6520 }
6521 }
6522
6523 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6524 let Some(database_id) = self.database_id() else {
6525 return Task::ready(());
6526 };
6527
6528 fn serialize_pane_handle(
6529 pane_handle: &Entity<Pane>,
6530 window: &mut Window,
6531 cx: &mut App,
6532 ) -> SerializedPane {
6533 let (items, active, pinned_count) = {
6534 let pane = pane_handle.read(cx);
6535 let active_item_id = pane.active_item().map(|item| item.item_id());
6536 (
6537 pane.items()
6538 .filter_map(|handle| {
6539 let handle = handle.to_serializable_item_handle(cx)?;
6540
6541 Some(SerializedItem {
6542 kind: Arc::from(handle.serialized_item_kind()),
6543 item_id: handle.item_id().as_u64(),
6544 active: Some(handle.item_id()) == active_item_id,
6545 preview: pane.is_active_preview_item(handle.item_id()),
6546 })
6547 })
6548 .collect::<Vec<_>>(),
6549 pane.has_focus(window, cx),
6550 pane.pinned_count(),
6551 )
6552 };
6553
6554 SerializedPane::new(items, active, pinned_count)
6555 }
6556
6557 fn build_serialized_pane_group(
6558 pane_group: &Member,
6559 window: &mut Window,
6560 cx: &mut App,
6561 ) -> SerializedPaneGroup {
6562 match pane_group {
6563 Member::Axis(PaneAxis {
6564 axis,
6565 members,
6566 flexes,
6567 bounding_boxes: _,
6568 }) => SerializedPaneGroup::Group {
6569 axis: SerializedAxis(*axis),
6570 children: members
6571 .iter()
6572 .map(|member| build_serialized_pane_group(member, window, cx))
6573 .collect::<Vec<_>>(),
6574 flexes: Some(flexes.lock().clone()),
6575 },
6576 Member::Pane(pane_handle) => {
6577 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6578 }
6579 }
6580 }
6581
6582 fn build_serialized_docks(
6583 this: &Workspace,
6584 window: &mut Window,
6585 cx: &mut App,
6586 ) -> DockStructure {
6587 this.capture_dock_state(window, cx)
6588 }
6589
6590 match self.workspace_location(cx) {
6591 WorkspaceLocation::Location(location, paths) => {
6592 let breakpoints = self.project.update(cx, |project, cx| {
6593 project
6594 .breakpoint_store()
6595 .read(cx)
6596 .all_source_breakpoints(cx)
6597 });
6598 let user_toolchains = self
6599 .project
6600 .read(cx)
6601 .user_toolchains(cx)
6602 .unwrap_or_default();
6603
6604 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6605 let docks = build_serialized_docks(self, window, cx);
6606 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6607
6608 let serialized_workspace = SerializedWorkspace {
6609 id: database_id,
6610 location,
6611 paths,
6612 center_group,
6613 window_bounds,
6614 display: Default::default(),
6615 docks,
6616 centered_layout: self.centered_layout,
6617 session_id: self.session_id.clone(),
6618 breakpoints,
6619 window_id: Some(window.window_handle().window_id().as_u64()),
6620 user_toolchains,
6621 };
6622
6623 let db = WorkspaceDb::global(cx);
6624 window.spawn(cx, async move |_| {
6625 db.save_workspace(serialized_workspace).await;
6626 })
6627 }
6628 WorkspaceLocation::DetachFromSession => {
6629 let window_bounds = SerializedWindowBounds(window.window_bounds());
6630 let display = window.display(cx).and_then(|d| d.uuid().ok());
6631 // Save dock state for empty local workspaces
6632 let docks = build_serialized_docks(self, window, cx);
6633 let db = WorkspaceDb::global(cx);
6634 let kvp = db::kvp::KeyValueStore::global(cx);
6635 window.spawn(cx, async move |_| {
6636 db.set_window_open_status(
6637 database_id,
6638 window_bounds,
6639 display.unwrap_or_default(),
6640 )
6641 .await
6642 .log_err();
6643 db.set_session_id(database_id, None).await.log_err();
6644 persistence::write_default_dock_state(&kvp, docks)
6645 .await
6646 .log_err();
6647 })
6648 }
6649 WorkspaceLocation::None => {
6650 // Save dock state for empty non-local workspaces
6651 let docks = build_serialized_docks(self, window, cx);
6652 let kvp = db::kvp::KeyValueStore::global(cx);
6653 window.spawn(cx, async move |_| {
6654 persistence::write_default_dock_state(&kvp, docks)
6655 .await
6656 .log_err();
6657 })
6658 }
6659 }
6660 }
6661
6662 fn has_any_items_open(&self, cx: &App) -> bool {
6663 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6664 }
6665
6666 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6667 let paths = PathList::new(&self.root_paths(cx));
6668 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6669 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6670 } else if self.project.read(cx).is_local() {
6671 if !paths.is_empty() || self.has_any_items_open(cx) {
6672 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6673 } else {
6674 WorkspaceLocation::DetachFromSession
6675 }
6676 } else {
6677 WorkspaceLocation::None
6678 }
6679 }
6680
6681 fn update_history(&self, cx: &mut App) {
6682 let Some(id) = self.database_id() else {
6683 return;
6684 };
6685 if !self.project.read(cx).is_local() {
6686 return;
6687 }
6688 if let Some(manager) = HistoryManager::global(cx) {
6689 let paths = PathList::new(&self.root_paths(cx));
6690 manager.update(cx, |this, cx| {
6691 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6692 });
6693 }
6694 }
6695
6696 async fn serialize_items(
6697 this: &WeakEntity<Self>,
6698 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6699 cx: &mut AsyncWindowContext,
6700 ) -> Result<()> {
6701 const CHUNK_SIZE: usize = 200;
6702
6703 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6704
6705 while let Some(items_received) = serializable_items.next().await {
6706 let unique_items =
6707 items_received
6708 .into_iter()
6709 .fold(HashMap::default(), |mut acc, item| {
6710 acc.entry(item.item_id()).or_insert(item);
6711 acc
6712 });
6713
6714 // We use into_iter() here so that the references to the items are moved into
6715 // the tasks and not kept alive while we're sleeping.
6716 for (_, item) in unique_items.into_iter() {
6717 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6718 item.serialize(workspace, false, window, cx)
6719 }) {
6720 cx.background_spawn(async move { task.await.log_err() })
6721 .detach();
6722 }
6723 }
6724
6725 cx.background_executor()
6726 .timer(SERIALIZATION_THROTTLE_TIME)
6727 .await;
6728 }
6729
6730 Ok(())
6731 }
6732
6733 pub(crate) fn enqueue_item_serialization(
6734 &mut self,
6735 item: Box<dyn SerializableItemHandle>,
6736 ) -> Result<()> {
6737 self.serializable_items_tx
6738 .unbounded_send(item)
6739 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6740 }
6741
6742 pub(crate) fn load_workspace(
6743 serialized_workspace: SerializedWorkspace,
6744 paths_to_open: Vec<Option<ProjectPath>>,
6745 window: &mut Window,
6746 cx: &mut Context<Workspace>,
6747 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6748 cx.spawn_in(window, async move |workspace, cx| {
6749 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6750
6751 let mut center_group = None;
6752 let mut center_items = None;
6753
6754 // Traverse the splits tree and add to things
6755 if let Some((group, active_pane, items)) = serialized_workspace
6756 .center_group
6757 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6758 .await
6759 {
6760 center_items = Some(items);
6761 center_group = Some((group, active_pane))
6762 }
6763
6764 let mut items_by_project_path = HashMap::default();
6765 let mut item_ids_by_kind = HashMap::default();
6766 let mut all_deserialized_items = Vec::default();
6767 cx.update(|_, cx| {
6768 for item in center_items.unwrap_or_default().into_iter().flatten() {
6769 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6770 item_ids_by_kind
6771 .entry(serializable_item_handle.serialized_item_kind())
6772 .or_insert(Vec::new())
6773 .push(item.item_id().as_u64() as ItemId);
6774 }
6775
6776 if let Some(project_path) = item.project_path(cx) {
6777 items_by_project_path.insert(project_path, item.clone());
6778 }
6779 all_deserialized_items.push(item);
6780 }
6781 })?;
6782
6783 let opened_items = paths_to_open
6784 .into_iter()
6785 .map(|path_to_open| {
6786 path_to_open
6787 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6788 })
6789 .collect::<Vec<_>>();
6790
6791 // Remove old panes from workspace panes list
6792 workspace.update_in(cx, |workspace, window, cx| {
6793 if let Some((center_group, active_pane)) = center_group {
6794 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6795
6796 // Swap workspace center group
6797 workspace.center = PaneGroup::with_root(center_group);
6798 workspace.center.set_is_center(true);
6799 workspace.center.mark_positions(cx);
6800
6801 if let Some(active_pane) = active_pane {
6802 workspace.set_active_pane(&active_pane, window, cx);
6803 cx.focus_self(window);
6804 } else {
6805 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6806 }
6807 }
6808
6809 let docks = serialized_workspace.docks;
6810
6811 for (dock, serialized_dock) in [
6812 (&mut workspace.right_dock, docks.right),
6813 (&mut workspace.left_dock, docks.left),
6814 (&mut workspace.bottom_dock, docks.bottom),
6815 ]
6816 .iter_mut()
6817 {
6818 dock.update(cx, |dock, cx| {
6819 dock.serialized_dock = Some(serialized_dock.clone());
6820 dock.restore_state(window, cx);
6821 });
6822 }
6823
6824 cx.notify();
6825 })?;
6826
6827 let _ = project
6828 .update(cx, |project, cx| {
6829 project
6830 .breakpoint_store()
6831 .update(cx, |breakpoint_store, cx| {
6832 breakpoint_store
6833 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6834 })
6835 })
6836 .await;
6837
6838 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6839 // after loading the items, we might have different items and in order to avoid
6840 // the database filling up, we delete items that haven't been loaded now.
6841 //
6842 // The items that have been loaded, have been saved after they've been added to the workspace.
6843 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6844 item_ids_by_kind
6845 .into_iter()
6846 .map(|(item_kind, loaded_items)| {
6847 SerializableItemRegistry::cleanup(
6848 item_kind,
6849 serialized_workspace.id,
6850 loaded_items,
6851 window,
6852 cx,
6853 )
6854 .log_err()
6855 })
6856 .collect::<Vec<_>>()
6857 })?;
6858
6859 futures::future::join_all(clean_up_tasks).await;
6860
6861 workspace
6862 .update_in(cx, |workspace, window, cx| {
6863 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6864 workspace.serialize_workspace_internal(window, cx).detach();
6865
6866 // Ensure that we mark the window as edited if we did load dirty items
6867 workspace.update_window_edited(window, cx);
6868 })
6869 .ok();
6870
6871 Ok(opened_items)
6872 })
6873 }
6874
6875 pub fn key_context(&self, cx: &App) -> KeyContext {
6876 let mut context = KeyContext::new_with_defaults();
6877 context.add("Workspace");
6878 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6879 if let Some(status) = self
6880 .debugger_provider
6881 .as_ref()
6882 .and_then(|provider| provider.active_thread_state(cx))
6883 {
6884 match status {
6885 ThreadStatus::Running | ThreadStatus::Stepping => {
6886 context.add("debugger_running");
6887 }
6888 ThreadStatus::Stopped => context.add("debugger_stopped"),
6889 ThreadStatus::Exited | ThreadStatus::Ended => {}
6890 }
6891 }
6892
6893 if self.left_dock.read(cx).is_open() {
6894 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6895 context.set("left_dock", active_panel.panel_key());
6896 }
6897 }
6898
6899 if self.right_dock.read(cx).is_open() {
6900 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6901 context.set("right_dock", active_panel.panel_key());
6902 }
6903 }
6904
6905 if self.bottom_dock.read(cx).is_open() {
6906 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6907 context.set("bottom_dock", active_panel.panel_key());
6908 }
6909 }
6910
6911 context
6912 }
6913
6914 /// Multiworkspace uses this to add workspace action handling to itself
6915 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6916 self.add_workspace_actions_listeners(div, window, cx)
6917 .on_action(cx.listener(
6918 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6919 for action in &action_sequence.0 {
6920 window.dispatch_action(action.boxed_clone(), cx);
6921 }
6922 },
6923 ))
6924 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6925 .on_action(cx.listener(Self::close_all_items_and_panes))
6926 .on_action(cx.listener(Self::close_item_in_all_panes))
6927 .on_action(cx.listener(Self::save_all))
6928 .on_action(cx.listener(Self::send_keystrokes))
6929 .on_action(cx.listener(Self::add_folder_to_project))
6930 .on_action(cx.listener(Self::follow_next_collaborator))
6931 .on_action(cx.listener(Self::activate_pane_at_index))
6932 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6933 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6934 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6935 .on_action(cx.listener(Self::toggle_theme_mode))
6936 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6937 let pane = workspace.active_pane().clone();
6938 workspace.unfollow_in_pane(&pane, window, cx);
6939 }))
6940 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6941 workspace
6942 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6943 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6944 }))
6945 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6946 workspace
6947 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6948 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6949 }))
6950 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6951 workspace
6952 .save_active_item(SaveIntent::SaveAs, window, cx)
6953 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6954 }))
6955 .on_action(
6956 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6957 workspace.activate_previous_pane(window, cx)
6958 }),
6959 )
6960 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6961 workspace.activate_next_pane(window, cx)
6962 }))
6963 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6964 workspace.activate_last_pane(window, cx)
6965 }))
6966 .on_action(
6967 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6968 workspace.activate_next_window(cx)
6969 }),
6970 )
6971 .on_action(
6972 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6973 workspace.activate_previous_window(cx)
6974 }),
6975 )
6976 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6977 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6978 }))
6979 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6980 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6981 }))
6982 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6983 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6984 }))
6985 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6986 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6987 }))
6988 .on_action(cx.listener(
6989 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6990 workspace.move_item_to_pane_in_direction(action, window, cx)
6991 },
6992 ))
6993 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6994 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6995 }))
6996 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6997 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6998 }))
6999 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
7000 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
7001 }))
7002 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
7003 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
7004 }))
7005 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
7006 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
7007 SplitDirection::Down,
7008 SplitDirection::Up,
7009 SplitDirection::Right,
7010 SplitDirection::Left,
7011 ];
7012 for dir in DIRECTION_PRIORITY {
7013 if workspace.find_pane_in_direction(dir, cx).is_some() {
7014 workspace.swap_pane_in_direction(dir, cx);
7015 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
7016 break;
7017 }
7018 }
7019 }))
7020 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
7021 workspace.move_pane_to_border(SplitDirection::Left, cx)
7022 }))
7023 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
7024 workspace.move_pane_to_border(SplitDirection::Right, cx)
7025 }))
7026 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
7027 workspace.move_pane_to_border(SplitDirection::Up, cx)
7028 }))
7029 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
7030 workspace.move_pane_to_border(SplitDirection::Down, cx)
7031 }))
7032 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
7033 this.toggle_dock(DockPosition::Left, window, cx);
7034 }))
7035 .on_action(cx.listener(
7036 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
7037 workspace.toggle_dock(DockPosition::Right, window, cx);
7038 },
7039 ))
7040 .on_action(cx.listener(
7041 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
7042 workspace.toggle_dock(DockPosition::Bottom, window, cx);
7043 },
7044 ))
7045 .on_action(cx.listener(
7046 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
7047 if !workspace.close_active_dock(window, cx) {
7048 cx.propagate();
7049 }
7050 },
7051 ))
7052 .on_action(
7053 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
7054 workspace.close_all_docks(window, cx);
7055 }),
7056 )
7057 .on_action(cx.listener(Self::toggle_all_docks))
7058 .on_action(cx.listener(
7059 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
7060 workspace.clear_all_notifications(cx);
7061 },
7062 ))
7063 .on_action(cx.listener(
7064 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
7065 workspace.clear_navigation_history(window, cx);
7066 },
7067 ))
7068 .on_action(cx.listener(
7069 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
7070 if let Some((notification_id, _)) = workspace.notifications.pop() {
7071 workspace.suppress_notification(¬ification_id, cx);
7072 }
7073 },
7074 ))
7075 .on_action(cx.listener(
7076 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
7077 workspace.show_worktree_trust_security_modal(true, window, cx);
7078 },
7079 ))
7080 .on_action(
7081 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
7082 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
7083 trusted_worktrees.update(cx, |trusted_worktrees, _| {
7084 trusted_worktrees.clear_trusted_paths()
7085 });
7086 let db = WorkspaceDb::global(cx);
7087 cx.spawn(async move |_, cx| {
7088 if db.clear_trusted_worktrees().await.log_err().is_some() {
7089 cx.update(|cx| reload(cx));
7090 }
7091 })
7092 .detach();
7093 }
7094 }),
7095 )
7096 .on_action(cx.listener(
7097 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
7098 workspace.reopen_closed_item(window, cx).detach();
7099 },
7100 ))
7101 .on_action(cx.listener(
7102 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
7103 for dock in workspace.all_docks() {
7104 if dock.focus_handle(cx).contains_focused(window, cx) {
7105 let panel = dock.read(cx).active_panel().cloned();
7106 if let Some(panel) = panel {
7107 dock.update(cx, |dock, cx| {
7108 dock.set_panel_size_state(
7109 panel.as_ref(),
7110 dock::PanelSizeState::default(),
7111 cx,
7112 );
7113 });
7114 }
7115 return;
7116 }
7117 }
7118 },
7119 ))
7120 .on_action(cx.listener(
7121 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
7122 for dock in workspace.all_docks() {
7123 let panel = dock.read(cx).visible_panel().cloned();
7124 if let Some(panel) = panel {
7125 dock.update(cx, |dock, cx| {
7126 dock.set_panel_size_state(
7127 panel.as_ref(),
7128 dock::PanelSizeState::default(),
7129 cx,
7130 );
7131 });
7132 }
7133 }
7134 },
7135 ))
7136 .on_action(cx.listener(
7137 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
7138 adjust_active_dock_size_by_px(
7139 px_with_ui_font_fallback(act.px, cx),
7140 workspace,
7141 window,
7142 cx,
7143 );
7144 },
7145 ))
7146 .on_action(cx.listener(
7147 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
7148 adjust_active_dock_size_by_px(
7149 px_with_ui_font_fallback(act.px, cx) * -1.,
7150 workspace,
7151 window,
7152 cx,
7153 );
7154 },
7155 ))
7156 .on_action(cx.listener(
7157 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
7158 adjust_open_docks_size_by_px(
7159 px_with_ui_font_fallback(act.px, cx),
7160 workspace,
7161 window,
7162 cx,
7163 );
7164 },
7165 ))
7166 .on_action(cx.listener(
7167 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
7168 adjust_open_docks_size_by_px(
7169 px_with_ui_font_fallback(act.px, cx) * -1.,
7170 workspace,
7171 window,
7172 cx,
7173 );
7174 },
7175 ))
7176 .on_action(cx.listener(Workspace::toggle_centered_layout))
7177 .on_action(cx.listener(
7178 |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
7179 if let Some(active_dock) = workspace.active_dock(window, cx) {
7180 let dock = active_dock.read(cx);
7181 if let Some(active_panel) = dock.active_panel() {
7182 if active_panel.pane(cx).is_none() {
7183 let mut recent_pane: Option<Entity<Pane>> = None;
7184 let mut recent_timestamp = 0;
7185 for pane_handle in workspace.panes() {
7186 let pane = pane_handle.read(cx);
7187 for entry in pane.activation_history() {
7188 if entry.timestamp > recent_timestamp {
7189 recent_timestamp = entry.timestamp;
7190 recent_pane = Some(pane_handle.clone());
7191 }
7192 }
7193 }
7194
7195 if let Some(pane) = recent_pane {
7196 let wrap_around = action.wrap_around;
7197 pane.update(cx, |pane, cx| {
7198 let current_index = pane.active_item_index();
7199 let items_len = pane.items_len();
7200 if items_len > 0 {
7201 let next_index = if current_index + 1 < items_len {
7202 current_index + 1
7203 } else if wrap_around {
7204 0
7205 } else {
7206 return;
7207 };
7208 pane.activate_item(
7209 next_index, false, false, window, cx,
7210 );
7211 }
7212 });
7213 return;
7214 }
7215 }
7216 }
7217 }
7218 cx.propagate();
7219 },
7220 ))
7221 .on_action(cx.listener(
7222 |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
7223 if let Some(active_dock) = workspace.active_dock(window, cx) {
7224 let dock = active_dock.read(cx);
7225 if let Some(active_panel) = dock.active_panel() {
7226 if active_panel.pane(cx).is_none() {
7227 let mut recent_pane: Option<Entity<Pane>> = None;
7228 let mut recent_timestamp = 0;
7229 for pane_handle in workspace.panes() {
7230 let pane = pane_handle.read(cx);
7231 for entry in pane.activation_history() {
7232 if entry.timestamp > recent_timestamp {
7233 recent_timestamp = entry.timestamp;
7234 recent_pane = Some(pane_handle.clone());
7235 }
7236 }
7237 }
7238
7239 if let Some(pane) = recent_pane {
7240 let wrap_around = action.wrap_around;
7241 pane.update(cx, |pane, cx| {
7242 let current_index = pane.active_item_index();
7243 let items_len = pane.items_len();
7244 if items_len > 0 {
7245 let prev_index = if current_index > 0 {
7246 current_index - 1
7247 } else if wrap_around {
7248 items_len.saturating_sub(1)
7249 } else {
7250 return;
7251 };
7252 pane.activate_item(
7253 prev_index, false, false, window, cx,
7254 );
7255 }
7256 });
7257 return;
7258 }
7259 }
7260 }
7261 }
7262 cx.propagate();
7263 },
7264 ))
7265 .on_action(cx.listener(
7266 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7267 if let Some(active_dock) = workspace.active_dock(window, cx) {
7268 let dock = active_dock.read(cx);
7269 if let Some(active_panel) = dock.active_panel() {
7270 if active_panel.pane(cx).is_none() {
7271 let active_pane = workspace.active_pane().clone();
7272 active_pane.update(cx, |pane, cx| {
7273 pane.close_active_item(action, window, cx)
7274 .detach_and_log_err(cx);
7275 });
7276 return;
7277 }
7278 }
7279 }
7280 cx.propagate();
7281 },
7282 ))
7283 .on_action(
7284 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7285 let pane = workspace.active_pane().clone();
7286 if let Some(item) = pane.read(cx).active_item() {
7287 item.toggle_read_only(window, cx);
7288 }
7289 }),
7290 )
7291 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7292 workspace.focus_center_pane(window, cx);
7293 }))
7294 .on_action(cx.listener(Workspace::cancel))
7295 }
7296
7297 #[cfg(any(test, feature = "test-support"))]
7298 pub fn set_random_database_id(&mut self) {
7299 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7300 }
7301
7302 #[cfg(any(test, feature = "test-support"))]
7303 pub(crate) fn test_new(
7304 project: Entity<Project>,
7305 window: &mut Window,
7306 cx: &mut Context<Self>,
7307 ) -> Self {
7308 use node_runtime::NodeRuntime;
7309 use session::Session;
7310
7311 let client = project.read(cx).client();
7312 let user_store = project.read(cx).user_store();
7313 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7314 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7315 window.activate_window();
7316 let app_state = Arc::new(AppState {
7317 languages: project.read(cx).languages().clone(),
7318 workspace_store,
7319 client,
7320 user_store,
7321 fs: project.read(cx).fs().clone(),
7322 build_window_options: |_, _| Default::default(),
7323 node_runtime: NodeRuntime::unavailable(),
7324 session,
7325 });
7326 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7327 workspace
7328 .active_pane
7329 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7330 workspace
7331 }
7332
7333 pub fn register_action<A: Action>(
7334 &mut self,
7335 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7336 ) -> &mut Self {
7337 let callback = Arc::new(callback);
7338
7339 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7340 let callback = callback.clone();
7341 div.on_action(cx.listener(move |workspace, event, window, cx| {
7342 (callback)(workspace, event, window, cx)
7343 }))
7344 }));
7345 self
7346 }
7347 pub fn register_action_renderer(
7348 &mut self,
7349 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7350 ) -> &mut Self {
7351 self.workspace_actions.push(Box::new(callback));
7352 self
7353 }
7354
7355 fn add_workspace_actions_listeners(
7356 &self,
7357 mut div: Div,
7358 window: &mut Window,
7359 cx: &mut Context<Self>,
7360 ) -> Div {
7361 for action in self.workspace_actions.iter() {
7362 div = (action)(div, self, window, cx)
7363 }
7364 div
7365 }
7366
7367 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7368 self.modal_layer.read(cx).has_active_modal()
7369 }
7370
7371 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7372 self.modal_layer
7373 .read(cx)
7374 .is_active_modal_command_palette(cx)
7375 }
7376
7377 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7378 self.modal_layer.read(cx).active_modal()
7379 }
7380
7381 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7382 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7383 /// If no modal is active, the new modal will be shown.
7384 ///
7385 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7386 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7387 /// will not be shown.
7388 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7389 where
7390 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7391 {
7392 self.modal_layer.update(cx, |modal_layer, cx| {
7393 modal_layer.toggle_modal(window, cx, build)
7394 })
7395 }
7396
7397 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7398 self.modal_layer
7399 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7400 }
7401
7402 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7403 self.toast_layer
7404 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7405 }
7406
7407 pub fn toggle_centered_layout(
7408 &mut self,
7409 _: &ToggleCenteredLayout,
7410 _: &mut Window,
7411 cx: &mut Context<Self>,
7412 ) {
7413 self.centered_layout = !self.centered_layout;
7414 if let Some(database_id) = self.database_id() {
7415 let db = WorkspaceDb::global(cx);
7416 let centered_layout = self.centered_layout;
7417 cx.background_spawn(async move {
7418 db.set_centered_layout(database_id, centered_layout).await
7419 })
7420 .detach_and_log_err(cx);
7421 }
7422 cx.notify();
7423 }
7424
7425 fn adjust_padding(padding: Option<f32>) -> f32 {
7426 padding
7427 .unwrap_or(CenteredPaddingSettings::default().0)
7428 .clamp(
7429 CenteredPaddingSettings::MIN_PADDING,
7430 CenteredPaddingSettings::MAX_PADDING,
7431 )
7432 }
7433
7434 fn render_dock(
7435 &self,
7436 position: DockPosition,
7437 dock: &Entity<Dock>,
7438 window: &mut Window,
7439 cx: &mut App,
7440 ) -> Option<Div> {
7441 if self.zoomed_position == Some(position) {
7442 return None;
7443 }
7444
7445 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7446 let pane = panel.pane(cx)?;
7447 let follower_states = &self.follower_states;
7448 leader_border_for_pane(follower_states, &pane, window, cx)
7449 });
7450
7451 let mut container = div()
7452 .flex()
7453 .overflow_hidden()
7454 .flex_none()
7455 .child(dock.clone())
7456 .children(leader_border);
7457
7458 // Apply sizing only when the dock is open. When closed the dock is still
7459 // included in the element tree so its focus handle remains mounted — without
7460 // this, toggle_panel_focus cannot focus the panel when the dock is closed.
7461 let dock = dock.read(cx);
7462 if let Some(panel) = dock.visible_panel() {
7463 let size_state = dock.stored_panel_size_state(panel.as_ref());
7464 let min_size = panel.min_size(window, cx);
7465 if position.axis() == Axis::Horizontal {
7466 let use_flexible = panel.has_flexible_size(window, cx);
7467 let flex_grow = if use_flexible {
7468 size_state
7469 .and_then(|state| state.flex)
7470 .or_else(|| self.default_dock_flex(position))
7471 } else {
7472 None
7473 };
7474 if let Some(grow) = flex_grow {
7475 let grow = grow.max(0.001);
7476 let style = container.style();
7477 style.flex_grow = Some(grow);
7478 style.flex_shrink = Some(1.0);
7479 style.flex_basis = Some(relative(0.).into());
7480 } else {
7481 let size = size_state
7482 .and_then(|state| state.size)
7483 .unwrap_or_else(|| panel.default_size(window, cx));
7484 container = container.w(size);
7485 }
7486 if let Some(min) = min_size {
7487 container = container.min_w(min);
7488 }
7489 } else {
7490 let size = size_state
7491 .and_then(|state| state.size)
7492 .unwrap_or_else(|| panel.default_size(window, cx));
7493 container = container.h(size);
7494 }
7495 }
7496
7497 Some(container)
7498 }
7499
7500 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7501 window
7502 .root::<MultiWorkspace>()
7503 .flatten()
7504 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7505 }
7506
7507 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7508 self.zoomed.as_ref()
7509 }
7510
7511 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7512 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7513 return;
7514 };
7515 let windows = cx.windows();
7516 let next_window =
7517 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7518 || {
7519 windows
7520 .iter()
7521 .cycle()
7522 .skip_while(|window| window.window_id() != current_window_id)
7523 .nth(1)
7524 },
7525 );
7526
7527 if let Some(window) = next_window {
7528 window
7529 .update(cx, |_, window, _| window.activate_window())
7530 .ok();
7531 }
7532 }
7533
7534 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7535 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7536 return;
7537 };
7538 let windows = cx.windows();
7539 let prev_window =
7540 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7541 || {
7542 windows
7543 .iter()
7544 .rev()
7545 .cycle()
7546 .skip_while(|window| window.window_id() != current_window_id)
7547 .nth(1)
7548 },
7549 );
7550
7551 if let Some(window) = prev_window {
7552 window
7553 .update(cx, |_, window, _| window.activate_window())
7554 .ok();
7555 }
7556 }
7557
7558 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7559 if cx.stop_active_drag(window) {
7560 } else if let Some((notification_id, _)) = self.notifications.pop() {
7561 dismiss_app_notification(¬ification_id, cx);
7562 } else {
7563 cx.propagate();
7564 }
7565 }
7566
7567 fn resize_dock(
7568 &mut self,
7569 dock_pos: DockPosition,
7570 new_size: Pixels,
7571 window: &mut Window,
7572 cx: &mut Context<Self>,
7573 ) {
7574 match dock_pos {
7575 DockPosition::Left => self.resize_left_dock(new_size, window, cx),
7576 DockPosition::Right => self.resize_right_dock(new_size, window, cx),
7577 DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
7578 }
7579 }
7580
7581 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7582 let workspace_width = self.bounds.size.width;
7583 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7584
7585 self.right_dock.read_with(cx, |right_dock, cx| {
7586 let right_dock_size = right_dock
7587 .stored_active_panel_size(window, cx)
7588 .unwrap_or(Pixels::ZERO);
7589 if right_dock_size + size > workspace_width {
7590 size = workspace_width - right_dock_size
7591 }
7592 });
7593
7594 let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
7595 self.left_dock.update(cx, |left_dock, cx| {
7596 if WorkspaceSettings::get_global(cx)
7597 .resize_all_panels_in_dock
7598 .contains(&DockPosition::Left)
7599 {
7600 left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7601 } else {
7602 left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7603 }
7604 });
7605 }
7606
7607 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7608 let workspace_width = self.bounds.size.width;
7609 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7610 self.left_dock.read_with(cx, |left_dock, cx| {
7611 let left_dock_size = left_dock
7612 .stored_active_panel_size(window, cx)
7613 .unwrap_or(Pixels::ZERO);
7614 if left_dock_size + size > workspace_width {
7615 size = workspace_width - left_dock_size
7616 }
7617 });
7618 let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
7619 self.right_dock.update(cx, |right_dock, cx| {
7620 if WorkspaceSettings::get_global(cx)
7621 .resize_all_panels_in_dock
7622 .contains(&DockPosition::Right)
7623 {
7624 right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7625 } else {
7626 right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7627 }
7628 });
7629 }
7630
7631 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7632 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7633 self.bottom_dock.update(cx, |bottom_dock, cx| {
7634 if WorkspaceSettings::get_global(cx)
7635 .resize_all_panels_in_dock
7636 .contains(&DockPosition::Bottom)
7637 {
7638 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7639 } else {
7640 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7641 }
7642 });
7643 }
7644
7645 fn toggle_edit_predictions_all_files(
7646 &mut self,
7647 _: &ToggleEditPrediction,
7648 _window: &mut Window,
7649 cx: &mut Context<Self>,
7650 ) {
7651 let fs = self.project().read(cx).fs().clone();
7652 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7653 update_settings_file(fs, cx, move |file, _| {
7654 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7655 });
7656 }
7657
7658 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7659 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7660 let next_mode = match current_mode {
7661 Some(theme_settings::ThemeAppearanceMode::Light) => {
7662 theme_settings::ThemeAppearanceMode::Dark
7663 }
7664 Some(theme_settings::ThemeAppearanceMode::Dark) => {
7665 theme_settings::ThemeAppearanceMode::Light
7666 }
7667 Some(theme_settings::ThemeAppearanceMode::System) | None => {
7668 match cx.theme().appearance() {
7669 theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
7670 theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
7671 }
7672 }
7673 };
7674
7675 let fs = self.project().read(cx).fs().clone();
7676 settings::update_settings_file(fs, cx, move |settings, _cx| {
7677 theme_settings::set_mode(settings, next_mode);
7678 });
7679 }
7680
7681 pub fn show_worktree_trust_security_modal(
7682 &mut self,
7683 toggle: bool,
7684 window: &mut Window,
7685 cx: &mut Context<Self>,
7686 ) {
7687 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7688 if toggle {
7689 security_modal.update(cx, |security_modal, cx| {
7690 security_modal.dismiss(cx);
7691 })
7692 } else {
7693 security_modal.update(cx, |security_modal, cx| {
7694 security_modal.refresh_restricted_paths(cx);
7695 });
7696 }
7697 } else {
7698 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7699 .map(|trusted_worktrees| {
7700 trusted_worktrees
7701 .read(cx)
7702 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7703 })
7704 .unwrap_or(false);
7705 if has_restricted_worktrees {
7706 let project = self.project().read(cx);
7707 let remote_host = project
7708 .remote_connection_options(cx)
7709 .map(RemoteHostLocation::from);
7710 let worktree_store = project.worktree_store().downgrade();
7711 self.toggle_modal(window, cx, |_, cx| {
7712 SecurityModal::new(worktree_store, remote_host, cx)
7713 });
7714 }
7715 }
7716 }
7717}
7718
7719pub trait AnyActiveCall {
7720 fn entity(&self) -> AnyEntity;
7721 fn is_in_room(&self, _: &App) -> bool;
7722 fn room_id(&self, _: &App) -> Option<u64>;
7723 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7724 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7725 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7726 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7727 fn is_sharing_project(&self, _: &App) -> bool;
7728 fn has_remote_participants(&self, _: &App) -> bool;
7729 fn local_participant_is_guest(&self, _: &App) -> bool;
7730 fn client(&self, _: &App) -> Arc<Client>;
7731 fn share_on_join(&self, _: &App) -> bool;
7732 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7733 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7734 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7735 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7736 fn join_project(
7737 &self,
7738 _: u64,
7739 _: Arc<LanguageRegistry>,
7740 _: Arc<dyn Fs>,
7741 _: &mut App,
7742 ) -> Task<Result<Entity<Project>>>;
7743 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7744 fn subscribe(
7745 &self,
7746 _: &mut Window,
7747 _: &mut Context<Workspace>,
7748 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7749 ) -> Subscription;
7750 fn create_shared_screen(
7751 &self,
7752 _: PeerId,
7753 _: &Entity<Pane>,
7754 _: &mut Window,
7755 _: &mut App,
7756 ) -> Option<Entity<SharedScreen>>;
7757}
7758
7759#[derive(Clone)]
7760pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7761impl Global for GlobalAnyActiveCall {}
7762
7763impl GlobalAnyActiveCall {
7764 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7765 cx.try_global()
7766 }
7767
7768 pub(crate) fn global(cx: &App) -> &Self {
7769 cx.global()
7770 }
7771}
7772
7773/// Workspace-local view of a remote participant's location.
7774#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7775pub enum ParticipantLocation {
7776 SharedProject { project_id: u64 },
7777 UnsharedProject,
7778 External,
7779}
7780
7781impl ParticipantLocation {
7782 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7783 match location
7784 .and_then(|l| l.variant)
7785 .context("participant location was not provided")?
7786 {
7787 proto::participant_location::Variant::SharedProject(project) => {
7788 Ok(Self::SharedProject {
7789 project_id: project.id,
7790 })
7791 }
7792 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7793 proto::participant_location::Variant::External(_) => Ok(Self::External),
7794 }
7795 }
7796}
7797/// Workspace-local view of a remote collaborator's state.
7798/// This is the subset of `call::RemoteParticipant` that workspace needs.
7799#[derive(Clone)]
7800pub struct RemoteCollaborator {
7801 pub user: Arc<User>,
7802 pub peer_id: PeerId,
7803 pub location: ParticipantLocation,
7804 pub participant_index: ParticipantIndex,
7805}
7806
7807pub enum ActiveCallEvent {
7808 ParticipantLocationChanged { participant_id: PeerId },
7809 RemoteVideoTracksChanged { participant_id: PeerId },
7810}
7811
7812fn leader_border_for_pane(
7813 follower_states: &HashMap<CollaboratorId, FollowerState>,
7814 pane: &Entity<Pane>,
7815 _: &Window,
7816 cx: &App,
7817) -> Option<Div> {
7818 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7819 if state.pane() == pane {
7820 Some((*leader_id, state))
7821 } else {
7822 None
7823 }
7824 })?;
7825
7826 let mut leader_color = match leader_id {
7827 CollaboratorId::PeerId(leader_peer_id) => {
7828 let leader = GlobalAnyActiveCall::try_global(cx)?
7829 .0
7830 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7831
7832 cx.theme()
7833 .players()
7834 .color_for_participant(leader.participant_index.0)
7835 .cursor
7836 }
7837 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7838 };
7839 leader_color.fade_out(0.3);
7840 Some(
7841 div()
7842 .absolute()
7843 .size_full()
7844 .left_0()
7845 .top_0()
7846 .border_2()
7847 .border_color(leader_color),
7848 )
7849}
7850
7851fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7852 ZED_WINDOW_POSITION
7853 .zip(*ZED_WINDOW_SIZE)
7854 .map(|(position, size)| Bounds {
7855 origin: position,
7856 size,
7857 })
7858}
7859
7860fn open_items(
7861 serialized_workspace: Option<SerializedWorkspace>,
7862 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7863 window: &mut Window,
7864 cx: &mut Context<Workspace>,
7865) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7866 let restored_items = serialized_workspace.map(|serialized_workspace| {
7867 Workspace::load_workspace(
7868 serialized_workspace,
7869 project_paths_to_open
7870 .iter()
7871 .map(|(_, project_path)| project_path)
7872 .cloned()
7873 .collect(),
7874 window,
7875 cx,
7876 )
7877 });
7878
7879 cx.spawn_in(window, async move |workspace, cx| {
7880 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7881
7882 if let Some(restored_items) = restored_items {
7883 let restored_items = restored_items.await?;
7884
7885 let restored_project_paths = restored_items
7886 .iter()
7887 .filter_map(|item| {
7888 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7889 .ok()
7890 .flatten()
7891 })
7892 .collect::<HashSet<_>>();
7893
7894 for restored_item in restored_items {
7895 opened_items.push(restored_item.map(Ok));
7896 }
7897
7898 project_paths_to_open
7899 .iter_mut()
7900 .for_each(|(_, project_path)| {
7901 if let Some(project_path_to_open) = project_path
7902 && restored_project_paths.contains(project_path_to_open)
7903 {
7904 *project_path = None;
7905 }
7906 });
7907 } else {
7908 for _ in 0..project_paths_to_open.len() {
7909 opened_items.push(None);
7910 }
7911 }
7912 assert!(opened_items.len() == project_paths_to_open.len());
7913
7914 let tasks =
7915 project_paths_to_open
7916 .into_iter()
7917 .enumerate()
7918 .map(|(ix, (abs_path, project_path))| {
7919 let workspace = workspace.clone();
7920 cx.spawn(async move |cx| {
7921 let file_project_path = project_path?;
7922 let abs_path_task = workspace.update(cx, |workspace, cx| {
7923 workspace.project().update(cx, |project, cx| {
7924 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7925 })
7926 });
7927
7928 // We only want to open file paths here. If one of the items
7929 // here is a directory, it was already opened further above
7930 // with a `find_or_create_worktree`.
7931 if let Ok(task) = abs_path_task
7932 && task.await.is_none_or(|p| p.is_file())
7933 {
7934 return Some((
7935 ix,
7936 workspace
7937 .update_in(cx, |workspace, window, cx| {
7938 workspace.open_path(
7939 file_project_path,
7940 None,
7941 true,
7942 window,
7943 cx,
7944 )
7945 })
7946 .log_err()?
7947 .await,
7948 ));
7949 }
7950 None
7951 })
7952 });
7953
7954 let tasks = tasks.collect::<Vec<_>>();
7955
7956 let tasks = futures::future::join_all(tasks);
7957 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7958 opened_items[ix] = Some(path_open_result);
7959 }
7960
7961 Ok(opened_items)
7962 })
7963}
7964
7965#[derive(Clone)]
7966enum ActivateInDirectionTarget {
7967 Pane(Entity<Pane>),
7968 Dock(Entity<Dock>),
7969 Sidebar(FocusHandle),
7970}
7971
7972fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7973 window
7974 .update(cx, |multi_workspace, _, cx| {
7975 let workspace = multi_workspace.workspace().clone();
7976 workspace.update(cx, |workspace, cx| {
7977 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7978 struct DatabaseFailedNotification;
7979
7980 workspace.show_notification(
7981 NotificationId::unique::<DatabaseFailedNotification>(),
7982 cx,
7983 |cx| {
7984 cx.new(|cx| {
7985 MessageNotification::new("Failed to load the database file.", cx)
7986 .primary_message("File an Issue")
7987 .primary_icon(IconName::Plus)
7988 .primary_on_click(|window, cx| {
7989 window.dispatch_action(Box::new(FileBugReport), cx)
7990 })
7991 })
7992 },
7993 );
7994 }
7995 });
7996 })
7997 .log_err();
7998}
7999
8000fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
8001 if val == 0 {
8002 ThemeSettings::get_global(cx).ui_font_size(cx)
8003 } else {
8004 px(val as f32)
8005 }
8006}
8007
8008fn adjust_active_dock_size_by_px(
8009 px: Pixels,
8010 workspace: &mut Workspace,
8011 window: &mut Window,
8012 cx: &mut Context<Workspace>,
8013) {
8014 let Some(active_dock) = workspace
8015 .all_docks()
8016 .into_iter()
8017 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
8018 else {
8019 return;
8020 };
8021 let dock = active_dock.read(cx);
8022 let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
8023 return;
8024 };
8025 workspace.resize_dock(dock.position(), panel_size + px, window, cx);
8026}
8027
8028fn adjust_open_docks_size_by_px(
8029 px: Pixels,
8030 workspace: &mut Workspace,
8031 window: &mut Window,
8032 cx: &mut Context<Workspace>,
8033) {
8034 let docks = workspace
8035 .all_docks()
8036 .into_iter()
8037 .filter_map(|dock_entity| {
8038 let dock = dock_entity.read(cx);
8039 if dock.is_open() {
8040 let dock_pos = dock.position();
8041 let panel_size = workspace.dock_size(&dock, window, cx)?;
8042 Some((dock_pos, panel_size + px))
8043 } else {
8044 None
8045 }
8046 })
8047 .collect::<Vec<_>>();
8048
8049 for (position, new_size) in docks {
8050 workspace.resize_dock(position, new_size, window, cx);
8051 }
8052}
8053
8054impl Focusable for Workspace {
8055 fn focus_handle(&self, cx: &App) -> FocusHandle {
8056 self.active_pane.focus_handle(cx)
8057 }
8058}
8059
8060#[derive(Clone)]
8061struct DraggedDock(DockPosition);
8062
8063impl Render for DraggedDock {
8064 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8065 gpui::Empty
8066 }
8067}
8068
8069impl Render for Workspace {
8070 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8071 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
8072 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
8073 log::info!("Rendered first frame");
8074 }
8075
8076 let centered_layout = self.centered_layout
8077 && self.center.panes().len() == 1
8078 && self.active_item(cx).is_some();
8079 let render_padding = |size| {
8080 (size > 0.0).then(|| {
8081 div()
8082 .h_full()
8083 .w(relative(size))
8084 .bg(cx.theme().colors().editor_background)
8085 .border_color(cx.theme().colors().pane_group_border)
8086 })
8087 };
8088 let paddings = if centered_layout {
8089 let settings = WorkspaceSettings::get_global(cx).centered_layout;
8090 (
8091 render_padding(Self::adjust_padding(
8092 settings.left_padding.map(|padding| padding.0),
8093 )),
8094 render_padding(Self::adjust_padding(
8095 settings.right_padding.map(|padding| padding.0),
8096 )),
8097 )
8098 } else {
8099 (None, None)
8100 };
8101 let ui_font = theme_settings::setup_ui_font(window, cx);
8102
8103 let theme = cx.theme().clone();
8104 let colors = theme.colors();
8105 let notification_entities = self
8106 .notifications
8107 .iter()
8108 .map(|(_, notification)| notification.entity_id())
8109 .collect::<Vec<_>>();
8110 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
8111
8112 div()
8113 .relative()
8114 .size_full()
8115 .flex()
8116 .flex_col()
8117 .font(ui_font)
8118 .gap_0()
8119 .justify_start()
8120 .items_start()
8121 .text_color(colors.text)
8122 .overflow_hidden()
8123 .children(self.titlebar_item.clone())
8124 .on_modifiers_changed(move |_, _, cx| {
8125 for &id in ¬ification_entities {
8126 cx.notify(id);
8127 }
8128 })
8129 .child(
8130 div()
8131 .size_full()
8132 .relative()
8133 .flex_1()
8134 .flex()
8135 .flex_col()
8136 .child(
8137 div()
8138 .id("workspace")
8139 .bg(colors.background)
8140 .relative()
8141 .flex_1()
8142 .w_full()
8143 .flex()
8144 .flex_col()
8145 .overflow_hidden()
8146 .border_t_1()
8147 .border_b_1()
8148 .border_color(colors.border)
8149 .child({
8150 let this = cx.entity();
8151 canvas(
8152 move |bounds, window, cx| {
8153 this.update(cx, |this, cx| {
8154 let bounds_changed = this.bounds != bounds;
8155 this.bounds = bounds;
8156
8157 if bounds_changed {
8158 this.left_dock.update(cx, |dock, cx| {
8159 dock.clamp_panel_size(
8160 bounds.size.width,
8161 window,
8162 cx,
8163 )
8164 });
8165
8166 this.right_dock.update(cx, |dock, cx| {
8167 dock.clamp_panel_size(
8168 bounds.size.width,
8169 window,
8170 cx,
8171 )
8172 });
8173
8174 this.bottom_dock.update(cx, |dock, cx| {
8175 dock.clamp_panel_size(
8176 bounds.size.height,
8177 window,
8178 cx,
8179 )
8180 });
8181 }
8182 })
8183 },
8184 |_, _, _, _| {},
8185 )
8186 .absolute()
8187 .size_full()
8188 })
8189 .when(self.zoomed.is_none(), |this| {
8190 this.on_drag_move(cx.listener(
8191 move |workspace,
8192 e: &DragMoveEvent<DraggedDock>,
8193 window,
8194 cx| {
8195 if workspace.previous_dock_drag_coordinates
8196 != Some(e.event.position)
8197 {
8198 workspace.previous_dock_drag_coordinates =
8199 Some(e.event.position);
8200
8201 match e.drag(cx).0 {
8202 DockPosition::Left => {
8203 workspace.resize_left_dock(
8204 e.event.position.x
8205 - workspace.bounds.left(),
8206 window,
8207 cx,
8208 );
8209 }
8210 DockPosition::Right => {
8211 workspace.resize_right_dock(
8212 workspace.bounds.right()
8213 - e.event.position.x,
8214 window,
8215 cx,
8216 );
8217 }
8218 DockPosition::Bottom => {
8219 workspace.resize_bottom_dock(
8220 workspace.bounds.bottom()
8221 - e.event.position.y,
8222 window,
8223 cx,
8224 );
8225 }
8226 };
8227 workspace.serialize_workspace(window, cx);
8228 }
8229 },
8230 ))
8231
8232 })
8233 .child({
8234 match bottom_dock_layout {
8235 BottomDockLayout::Full => div()
8236 .flex()
8237 .flex_col()
8238 .h_full()
8239 .child(
8240 div()
8241 .flex()
8242 .flex_row()
8243 .flex_1()
8244 .overflow_hidden()
8245 .children(self.render_dock(
8246 DockPosition::Left,
8247 &self.left_dock,
8248 window,
8249 cx,
8250 ))
8251
8252 .child(
8253 div()
8254 .flex()
8255 .flex_col()
8256 .flex_1()
8257 .overflow_hidden()
8258 .child(
8259 h_flex()
8260 .flex_1()
8261 .when_some(
8262 paddings.0,
8263 |this, p| {
8264 this.child(
8265 p.border_r_1(),
8266 )
8267 },
8268 )
8269 .child(self.center.render(
8270 self.zoomed.as_ref(),
8271 &PaneRenderContext {
8272 follower_states:
8273 &self.follower_states,
8274 active_call: self.active_call(),
8275 active_pane: &self.active_pane,
8276 app_state: &self.app_state,
8277 project: &self.project,
8278 workspace: &self.weak_self,
8279 },
8280 window,
8281 cx,
8282 ))
8283 .when_some(
8284 paddings.1,
8285 |this, p| {
8286 this.child(
8287 p.border_l_1(),
8288 )
8289 },
8290 ),
8291 ),
8292 )
8293
8294 .children(self.render_dock(
8295 DockPosition::Right,
8296 &self.right_dock,
8297 window,
8298 cx,
8299 )),
8300 )
8301 .child(div().w_full().children(self.render_dock(
8302 DockPosition::Bottom,
8303 &self.bottom_dock,
8304 window,
8305 cx
8306 ))),
8307
8308 BottomDockLayout::LeftAligned => div()
8309 .flex()
8310 .flex_row()
8311 .h_full()
8312 .child(
8313 div()
8314 .flex()
8315 .flex_col()
8316 .flex_1()
8317 .h_full()
8318 .child(
8319 div()
8320 .flex()
8321 .flex_row()
8322 .flex_1()
8323 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8324
8325 .child(
8326 div()
8327 .flex()
8328 .flex_col()
8329 .flex_1()
8330 .overflow_hidden()
8331 .child(
8332 h_flex()
8333 .flex_1()
8334 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8335 .child(self.center.render(
8336 self.zoomed.as_ref(),
8337 &PaneRenderContext {
8338 follower_states:
8339 &self.follower_states,
8340 active_call: self.active_call(),
8341 active_pane: &self.active_pane,
8342 app_state: &self.app_state,
8343 project: &self.project,
8344 workspace: &self.weak_self,
8345 },
8346 window,
8347 cx,
8348 ))
8349 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8350 )
8351 )
8352
8353 )
8354 .child(
8355 div()
8356 .w_full()
8357 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8358 ),
8359 )
8360 .children(self.render_dock(
8361 DockPosition::Right,
8362 &self.right_dock,
8363 window,
8364 cx,
8365 )),
8366 BottomDockLayout::RightAligned => div()
8367 .flex()
8368 .flex_row()
8369 .h_full()
8370 .children(self.render_dock(
8371 DockPosition::Left,
8372 &self.left_dock,
8373 window,
8374 cx,
8375 ))
8376
8377 .child(
8378 div()
8379 .flex()
8380 .flex_col()
8381 .flex_1()
8382 .h_full()
8383 .child(
8384 div()
8385 .flex()
8386 .flex_row()
8387 .flex_1()
8388 .child(
8389 div()
8390 .flex()
8391 .flex_col()
8392 .flex_1()
8393 .overflow_hidden()
8394 .child(
8395 h_flex()
8396 .flex_1()
8397 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8398 .child(self.center.render(
8399 self.zoomed.as_ref(),
8400 &PaneRenderContext {
8401 follower_states:
8402 &self.follower_states,
8403 active_call: self.active_call(),
8404 active_pane: &self.active_pane,
8405 app_state: &self.app_state,
8406 project: &self.project,
8407 workspace: &self.weak_self,
8408 },
8409 window,
8410 cx,
8411 ))
8412 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8413 )
8414 )
8415
8416 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8417 )
8418 .child(
8419 div()
8420 .w_full()
8421 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8422 ),
8423 ),
8424 BottomDockLayout::Contained => div()
8425 .flex()
8426 .flex_row()
8427 .h_full()
8428 .children(self.render_dock(
8429 DockPosition::Left,
8430 &self.left_dock,
8431 window,
8432 cx,
8433 ))
8434
8435 .child(
8436 div()
8437 .flex()
8438 .flex_col()
8439 .flex_1()
8440 .overflow_hidden()
8441 .child(
8442 h_flex()
8443 .flex_1()
8444 .when_some(paddings.0, |this, p| {
8445 this.child(p.border_r_1())
8446 })
8447 .child(self.center.render(
8448 self.zoomed.as_ref(),
8449 &PaneRenderContext {
8450 follower_states:
8451 &self.follower_states,
8452 active_call: self.active_call(),
8453 active_pane: &self.active_pane,
8454 app_state: &self.app_state,
8455 project: &self.project,
8456 workspace: &self.weak_self,
8457 },
8458 window,
8459 cx,
8460 ))
8461 .when_some(paddings.1, |this, p| {
8462 this.child(p.border_l_1())
8463 }),
8464 )
8465 .children(self.render_dock(
8466 DockPosition::Bottom,
8467 &self.bottom_dock,
8468 window,
8469 cx,
8470 )),
8471 )
8472
8473 .children(self.render_dock(
8474 DockPosition::Right,
8475 &self.right_dock,
8476 window,
8477 cx,
8478 )),
8479 }
8480 })
8481 .children(self.zoomed.as_ref().and_then(|view| {
8482 let zoomed_view = view.upgrade()?;
8483 let div = div()
8484 .occlude()
8485 .absolute()
8486 .overflow_hidden()
8487 .border_color(colors.border)
8488 .bg(colors.background)
8489 .child(zoomed_view)
8490 .inset_0()
8491 .shadow_lg();
8492
8493 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8494 return Some(div);
8495 }
8496
8497 Some(match self.zoomed_position {
8498 Some(DockPosition::Left) => div.right_2().border_r_1(),
8499 Some(DockPosition::Right) => div.left_2().border_l_1(),
8500 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8501 None => {
8502 div.top_2().bottom_2().left_2().right_2().border_1()
8503 }
8504 })
8505 }))
8506 .children(self.render_notifications(window, cx)),
8507 )
8508 .when(self.status_bar_visible(cx), |parent| {
8509 parent.child(self.status_bar.clone())
8510 })
8511 .child(self.toast_layer.clone()),
8512 )
8513 }
8514}
8515
8516impl WorkspaceStore {
8517 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8518 Self {
8519 workspaces: Default::default(),
8520 _subscriptions: vec![
8521 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8522 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8523 ],
8524 client,
8525 }
8526 }
8527
8528 pub fn update_followers(
8529 &self,
8530 project_id: Option<u64>,
8531 update: proto::update_followers::Variant,
8532 cx: &App,
8533 ) -> Option<()> {
8534 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8535 let room_id = active_call.0.room_id(cx)?;
8536 self.client
8537 .send(proto::UpdateFollowers {
8538 room_id,
8539 project_id,
8540 variant: Some(update),
8541 })
8542 .log_err()
8543 }
8544
8545 pub async fn handle_follow(
8546 this: Entity<Self>,
8547 envelope: TypedEnvelope<proto::Follow>,
8548 mut cx: AsyncApp,
8549 ) -> Result<proto::FollowResponse> {
8550 this.update(&mut cx, |this, cx| {
8551 let follower = Follower {
8552 project_id: envelope.payload.project_id,
8553 peer_id: envelope.original_sender_id()?,
8554 };
8555
8556 let mut response = proto::FollowResponse::default();
8557
8558 this.workspaces.retain(|(window_handle, weak_workspace)| {
8559 let Some(workspace) = weak_workspace.upgrade() else {
8560 return false;
8561 };
8562 window_handle
8563 .update(cx, |_, window, cx| {
8564 workspace.update(cx, |workspace, cx| {
8565 let handler_response =
8566 workspace.handle_follow(follower.project_id, window, cx);
8567 if let Some(active_view) = handler_response.active_view
8568 && workspace.project.read(cx).remote_id() == follower.project_id
8569 {
8570 response.active_view = Some(active_view)
8571 }
8572 });
8573 })
8574 .is_ok()
8575 });
8576
8577 Ok(response)
8578 })
8579 }
8580
8581 async fn handle_update_followers(
8582 this: Entity<Self>,
8583 envelope: TypedEnvelope<proto::UpdateFollowers>,
8584 mut cx: AsyncApp,
8585 ) -> Result<()> {
8586 let leader_id = envelope.original_sender_id()?;
8587 let update = envelope.payload;
8588
8589 this.update(&mut cx, |this, cx| {
8590 this.workspaces.retain(|(window_handle, weak_workspace)| {
8591 let Some(workspace) = weak_workspace.upgrade() else {
8592 return false;
8593 };
8594 window_handle
8595 .update(cx, |_, window, cx| {
8596 workspace.update(cx, |workspace, cx| {
8597 let project_id = workspace.project.read(cx).remote_id();
8598 if update.project_id != project_id && update.project_id.is_some() {
8599 return;
8600 }
8601 workspace.handle_update_followers(
8602 leader_id,
8603 update.clone(),
8604 window,
8605 cx,
8606 );
8607 });
8608 })
8609 .is_ok()
8610 });
8611 Ok(())
8612 })
8613 }
8614
8615 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8616 self.workspaces.iter().map(|(_, weak)| weak)
8617 }
8618
8619 pub fn workspaces_with_windows(
8620 &self,
8621 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8622 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8623 }
8624}
8625
8626impl ViewId {
8627 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8628 Ok(Self {
8629 creator: message
8630 .creator
8631 .map(CollaboratorId::PeerId)
8632 .context("creator is missing")?,
8633 id: message.id,
8634 })
8635 }
8636
8637 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8638 if let CollaboratorId::PeerId(peer_id) = self.creator {
8639 Some(proto::ViewId {
8640 creator: Some(peer_id),
8641 id: self.id,
8642 })
8643 } else {
8644 None
8645 }
8646 }
8647}
8648
8649impl FollowerState {
8650 fn pane(&self) -> &Entity<Pane> {
8651 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8652 }
8653}
8654
8655pub trait WorkspaceHandle {
8656 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8657}
8658
8659impl WorkspaceHandle for Entity<Workspace> {
8660 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8661 self.read(cx)
8662 .worktrees(cx)
8663 .flat_map(|worktree| {
8664 let worktree_id = worktree.read(cx).id();
8665 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8666 worktree_id,
8667 path: f.path.clone(),
8668 })
8669 })
8670 .collect::<Vec<_>>()
8671 }
8672}
8673
8674pub async fn last_opened_workspace_location(
8675 db: &WorkspaceDb,
8676 fs: &dyn fs::Fs,
8677) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8678 db.last_workspace(fs)
8679 .await
8680 .log_err()
8681 .flatten()
8682 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8683}
8684
8685pub async fn last_session_workspace_locations(
8686 db: &WorkspaceDb,
8687 last_session_id: &str,
8688 last_session_window_stack: Option<Vec<WindowId>>,
8689 fs: &dyn fs::Fs,
8690) -> Option<Vec<SessionWorkspace>> {
8691 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8692 .await
8693 .log_err()
8694}
8695
8696pub async fn restore_multiworkspace(
8697 multi_workspace: SerializedMultiWorkspace,
8698 app_state: Arc<AppState>,
8699 cx: &mut AsyncApp,
8700) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8701 let SerializedMultiWorkspace {
8702 active_workspace,
8703 state,
8704 } = multi_workspace;
8705
8706 let workspace_result = if active_workspace.paths.is_empty() {
8707 cx.update(|cx| {
8708 open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx)
8709 })
8710 .await
8711 } else {
8712 cx.update(|cx| {
8713 Workspace::new_local(
8714 active_workspace.paths.paths().to_vec(),
8715 app_state.clone(),
8716 None,
8717 None,
8718 None,
8719 OpenMode::Activate,
8720 cx,
8721 )
8722 })
8723 .await
8724 .map(|result| result.window)
8725 };
8726
8727 let window_handle = match workspace_result {
8728 Ok(handle) => handle,
8729 Err(err) => {
8730 log::error!("Failed to restore active workspace: {err:#}");
8731
8732 let mut fallback_handle = None;
8733 for key in &state.project_groups {
8734 let key: ProjectGroupKey = key.clone().into();
8735 let paths = key.path_list().paths().to_vec();
8736 match cx
8737 .update(|cx| {
8738 Workspace::new_local(
8739 paths,
8740 app_state.clone(),
8741 None,
8742 None,
8743 None,
8744 OpenMode::Activate,
8745 cx,
8746 )
8747 })
8748 .await
8749 {
8750 Ok(OpenResult { window, .. }) => {
8751 fallback_handle = Some(window);
8752 break;
8753 }
8754 Err(fallback_err) => {
8755 log::error!("Fallback project group also failed: {fallback_err:#}");
8756 }
8757 }
8758 }
8759
8760 fallback_handle.ok_or(err)?
8761 }
8762 };
8763
8764 apply_restored_multiworkspace_state(window_handle, &state, app_state.fs.clone(), cx).await;
8765
8766 window_handle
8767 .update(cx, |_, window, _cx| {
8768 window.activate_window();
8769 })
8770 .ok();
8771
8772 Ok(window_handle)
8773}
8774
8775pub async fn apply_restored_multiworkspace_state(
8776 window_handle: WindowHandle<MultiWorkspace>,
8777 state: &MultiWorkspaceState,
8778 fs: Arc<dyn fs::Fs>,
8779 cx: &mut AsyncApp,
8780) {
8781 let MultiWorkspaceState {
8782 sidebar_open,
8783 project_groups,
8784 sidebar_state,
8785 ..
8786 } = state;
8787
8788 if !project_groups.is_empty() {
8789 // Resolve linked worktree paths to their main repo paths so
8790 // stale keys from previous sessions get normalized and deduped.
8791 let mut resolved_groups: Vec<SerializedProjectGroupState> = Vec::new();
8792 for serialized in project_groups.iter().cloned() {
8793 let SerializedProjectGroupState {
8794 key,
8795 expanded,
8796 visible_thread_count,
8797 } = serialized.into_restored_state();
8798 if key.path_list().paths().is_empty() {
8799 continue;
8800 }
8801 let mut resolved_paths = Vec::new();
8802 for path in key.path_list().paths() {
8803 if key.host().is_none()
8804 && let Some(common_dir) =
8805 project::discover_root_repo_common_dir(path, fs.as_ref()).await
8806 {
8807 let main_path = common_dir.parent().unwrap_or(&common_dir);
8808 resolved_paths.push(main_path.to_path_buf());
8809 } else {
8810 resolved_paths.push(path.to_path_buf());
8811 }
8812 }
8813 let resolved = ProjectGroupKey::new(key.host(), PathList::new(&resolved_paths));
8814 if !resolved_groups.iter().any(|g| g.key == resolved) {
8815 resolved_groups.push(SerializedProjectGroupState {
8816 key: resolved,
8817 expanded,
8818 visible_thread_count,
8819 });
8820 }
8821 }
8822
8823 window_handle
8824 .update(cx, |multi_workspace, _window, cx| {
8825 multi_workspace.restore_project_groups(resolved_groups, cx);
8826 })
8827 .ok();
8828 }
8829
8830 if *sidebar_open {
8831 window_handle
8832 .update(cx, |multi_workspace, _, cx| {
8833 multi_workspace.open_sidebar(cx);
8834 })
8835 .ok();
8836 }
8837
8838 if let Some(sidebar_state) = sidebar_state {
8839 window_handle
8840 .update(cx, |multi_workspace, window, cx| {
8841 if let Some(sidebar) = multi_workspace.sidebar() {
8842 sidebar.restore_serialized_state(sidebar_state, window, cx);
8843 }
8844 multi_workspace.serialize(cx);
8845 })
8846 .ok();
8847 }
8848}
8849
8850actions!(
8851 collab,
8852 [
8853 /// Opens the channel notes for the current call.
8854 ///
8855 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8856 /// channel in the collab panel.
8857 ///
8858 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8859 /// can be copied via "Copy link to section" in the context menu of the channel notes
8860 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8861 OpenChannelNotes,
8862 /// Mutes your microphone.
8863 Mute,
8864 /// Deafens yourself (mute both microphone and speakers).
8865 Deafen,
8866 /// Leaves the current call.
8867 LeaveCall,
8868 /// Shares the current project with collaborators.
8869 ShareProject,
8870 /// Shares your screen with collaborators.
8871 ScreenShare,
8872 /// Copies the current room name and session id for debugging purposes.
8873 CopyRoomId,
8874 ]
8875);
8876
8877/// Opens the channel notes for a specific channel by its ID.
8878#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8879#[action(namespace = collab)]
8880#[serde(deny_unknown_fields)]
8881pub struct OpenChannelNotesById {
8882 pub channel_id: u64,
8883}
8884
8885actions!(
8886 zed,
8887 [
8888 /// Opens the Zed log file.
8889 OpenLog,
8890 /// Reveals the Zed log file in the system file manager.
8891 RevealLogInFileManager
8892 ]
8893);
8894
8895async fn join_channel_internal(
8896 channel_id: ChannelId,
8897 app_state: &Arc<AppState>,
8898 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8899 requesting_workspace: Option<WeakEntity<Workspace>>,
8900 active_call: &dyn AnyActiveCall,
8901 cx: &mut AsyncApp,
8902) -> Result<bool> {
8903 let (should_prompt, already_in_channel) = cx.update(|cx| {
8904 if !active_call.is_in_room(cx) {
8905 return (false, false);
8906 }
8907
8908 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8909 let should_prompt = active_call.is_sharing_project(cx)
8910 && active_call.has_remote_participants(cx)
8911 && !already_in_channel;
8912 (should_prompt, already_in_channel)
8913 });
8914
8915 if already_in_channel {
8916 let task = cx.update(|cx| {
8917 if let Some((project, host)) = active_call.most_active_project(cx) {
8918 Some(join_in_room_project(project, host, app_state.clone(), cx))
8919 } else {
8920 None
8921 }
8922 });
8923 if let Some(task) = task {
8924 task.await?;
8925 }
8926 return anyhow::Ok(true);
8927 }
8928
8929 if should_prompt {
8930 if let Some(multi_workspace) = requesting_window {
8931 let answer = multi_workspace
8932 .update(cx, |_, window, cx| {
8933 window.prompt(
8934 PromptLevel::Warning,
8935 "Do you want to switch channels?",
8936 Some("Leaving this call will unshare your current project."),
8937 &["Yes, Join Channel", "Cancel"],
8938 cx,
8939 )
8940 })?
8941 .await;
8942
8943 if answer == Ok(1) {
8944 return Ok(false);
8945 }
8946 } else {
8947 return Ok(false);
8948 }
8949 }
8950
8951 let client = cx.update(|cx| active_call.client(cx));
8952
8953 let mut client_status = client.status();
8954
8955 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8956 'outer: loop {
8957 let Some(status) = client_status.recv().await else {
8958 anyhow::bail!("error connecting");
8959 };
8960
8961 match status {
8962 Status::Connecting
8963 | Status::Authenticating
8964 | Status::Authenticated
8965 | Status::Reconnecting
8966 | Status::Reauthenticating
8967 | Status::Reauthenticated => continue,
8968 Status::Connected { .. } => break 'outer,
8969 Status::SignedOut | Status::AuthenticationError => {
8970 return Err(ErrorCode::SignedOut.into());
8971 }
8972 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8973 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8974 return Err(ErrorCode::Disconnected.into());
8975 }
8976 }
8977 }
8978
8979 let joined = cx
8980 .update(|cx| active_call.join_channel(channel_id, cx))
8981 .await?;
8982
8983 if !joined {
8984 return anyhow::Ok(true);
8985 }
8986
8987 cx.update(|cx| active_call.room_update_completed(cx)).await;
8988
8989 let task = cx.update(|cx| {
8990 if let Some((project, host)) = active_call.most_active_project(cx) {
8991 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8992 }
8993
8994 // If you are the first to join a channel, see if you should share your project.
8995 if !active_call.has_remote_participants(cx)
8996 && !active_call.local_participant_is_guest(cx)
8997 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8998 {
8999 let project = workspace.update(cx, |workspace, cx| {
9000 let project = workspace.project.read(cx);
9001
9002 if !active_call.share_on_join(cx) {
9003 return None;
9004 }
9005
9006 if (project.is_local() || project.is_via_remote_server())
9007 && project.visible_worktrees(cx).any(|tree| {
9008 tree.read(cx)
9009 .root_entry()
9010 .is_some_and(|entry| entry.is_dir())
9011 })
9012 {
9013 Some(workspace.project.clone())
9014 } else {
9015 None
9016 }
9017 });
9018 if let Some(project) = project {
9019 let share_task = active_call.share_project(project, cx);
9020 return Some(cx.spawn(async move |_cx| -> Result<()> {
9021 share_task.await?;
9022 Ok(())
9023 }));
9024 }
9025 }
9026
9027 None
9028 });
9029 if let Some(task) = task {
9030 task.await?;
9031 return anyhow::Ok(true);
9032 }
9033 anyhow::Ok(false)
9034}
9035
9036pub fn join_channel(
9037 channel_id: ChannelId,
9038 app_state: Arc<AppState>,
9039 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9040 requesting_workspace: Option<WeakEntity<Workspace>>,
9041 cx: &mut App,
9042) -> Task<Result<()>> {
9043 let active_call = GlobalAnyActiveCall::global(cx).clone();
9044 cx.spawn(async move |cx| {
9045 let result = join_channel_internal(
9046 channel_id,
9047 &app_state,
9048 requesting_window,
9049 requesting_workspace,
9050 &*active_call.0,
9051 cx,
9052 )
9053 .await;
9054
9055 // join channel succeeded, and opened a window
9056 if matches!(result, Ok(true)) {
9057 return anyhow::Ok(());
9058 }
9059
9060 // find an existing workspace to focus and show call controls
9061 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
9062 if active_window.is_none() {
9063 // no open workspaces, make one to show the error in (blergh)
9064 let OpenResult {
9065 window: window_handle,
9066 ..
9067 } = cx
9068 .update(|cx| {
9069 Workspace::new_local(
9070 vec![],
9071 app_state.clone(),
9072 requesting_window,
9073 None,
9074 None,
9075 OpenMode::Activate,
9076 cx,
9077 )
9078 })
9079 .await?;
9080
9081 window_handle
9082 .update(cx, |_, window, _cx| {
9083 window.activate_window();
9084 })
9085 .ok();
9086
9087 if result.is_ok() {
9088 cx.update(|cx| {
9089 cx.dispatch_action(&OpenChannelNotes);
9090 });
9091 }
9092
9093 active_window = Some(window_handle);
9094 }
9095
9096 if let Err(err) = result {
9097 log::error!("failed to join channel: {}", err);
9098 if let Some(active_window) = active_window {
9099 active_window
9100 .update(cx, |_, window, cx| {
9101 let detail: SharedString = match err.error_code() {
9102 ErrorCode::SignedOut => "Please sign in to continue.".into(),
9103 ErrorCode::UpgradeRequired => concat!(
9104 "Your are running an unsupported version of Zed. ",
9105 "Please update to continue."
9106 )
9107 .into(),
9108 ErrorCode::NoSuchChannel => concat!(
9109 "No matching channel was found. ",
9110 "Please check the link and try again."
9111 )
9112 .into(),
9113 ErrorCode::Forbidden => concat!(
9114 "This channel is private, and you do not have access. ",
9115 "Please ask someone to add you and try again."
9116 )
9117 .into(),
9118 ErrorCode::Disconnected => {
9119 "Please check your internet connection and try again.".into()
9120 }
9121 _ => format!("{}\n\nPlease try again.", err).into(),
9122 };
9123 window.prompt(
9124 PromptLevel::Critical,
9125 "Failed to join channel",
9126 Some(&detail),
9127 &["Ok"],
9128 cx,
9129 )
9130 })?
9131 .await
9132 .ok();
9133 }
9134 }
9135
9136 // return ok, we showed the error to the user.
9137 anyhow::Ok(())
9138 })
9139}
9140
9141pub async fn get_any_active_multi_workspace(
9142 app_state: Arc<AppState>,
9143 mut cx: AsyncApp,
9144) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
9145 // find an existing workspace to focus and show call controls
9146 let active_window = activate_any_workspace_window(&mut cx);
9147 if active_window.is_none() {
9148 cx.update(|cx| {
9149 Workspace::new_local(
9150 vec![],
9151 app_state.clone(),
9152 None,
9153 None,
9154 None,
9155 OpenMode::Activate,
9156 cx,
9157 )
9158 })
9159 .await?;
9160 }
9161 activate_any_workspace_window(&mut cx).context("could not open zed")
9162}
9163
9164fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
9165 cx.update(|cx| {
9166 if let Some(workspace_window) = cx
9167 .active_window()
9168 .and_then(|window| window.downcast::<MultiWorkspace>())
9169 {
9170 return Some(workspace_window);
9171 }
9172
9173 for window in cx.windows() {
9174 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
9175 workspace_window
9176 .update(cx, |_, window, _| window.activate_window())
9177 .ok();
9178 return Some(workspace_window);
9179 }
9180 }
9181 None
9182 })
9183}
9184
9185pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
9186 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
9187}
9188
9189pub fn workspace_windows_for_location(
9190 serialized_location: &SerializedWorkspaceLocation,
9191 cx: &App,
9192) -> Vec<WindowHandle<MultiWorkspace>> {
9193 cx.windows()
9194 .into_iter()
9195 .filter_map(|window| window.downcast::<MultiWorkspace>())
9196 .filter(|multi_workspace| {
9197 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
9198 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
9199 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
9200 }
9201 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
9202 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
9203 a.distro_name == b.distro_name
9204 }
9205 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
9206 a.container_id == b.container_id
9207 }
9208 #[cfg(any(test, feature = "test-support"))]
9209 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
9210 a.id == b.id
9211 }
9212 _ => false,
9213 };
9214
9215 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
9216 multi_workspace.workspaces().any(|workspace| {
9217 match workspace.read(cx).workspace_location(cx) {
9218 WorkspaceLocation::Location(location, _) => {
9219 match (&location, serialized_location) {
9220 (
9221 SerializedWorkspaceLocation::Local,
9222 SerializedWorkspaceLocation::Local,
9223 ) => true,
9224 (
9225 SerializedWorkspaceLocation::Remote(a),
9226 SerializedWorkspaceLocation::Remote(b),
9227 ) => same_host(a, b),
9228 _ => false,
9229 }
9230 }
9231 _ => false,
9232 }
9233 })
9234 })
9235 })
9236 .collect()
9237}
9238
9239pub async fn find_existing_workspace(
9240 abs_paths: &[PathBuf],
9241 open_options: &OpenOptions,
9242 location: &SerializedWorkspaceLocation,
9243 cx: &mut AsyncApp,
9244) -> (
9245 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
9246 OpenVisible,
9247) {
9248 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9249 let mut open_visible = OpenVisible::All;
9250 let mut best_match = None;
9251
9252 cx.update(|cx| {
9253 for window in workspace_windows_for_location(location, cx) {
9254 if let Ok(multi_workspace) = window.read(cx) {
9255 for workspace in multi_workspace.workspaces() {
9256 let project = workspace.read(cx).project.read(cx);
9257 let m = project.visibility_for_paths(
9258 abs_paths,
9259 open_options.open_new_workspace == None,
9260 cx,
9261 );
9262 if m > best_match {
9263 existing = Some((window, workspace.clone()));
9264 best_match = m;
9265 } else if best_match.is_none() && open_options.open_new_workspace == Some(false)
9266 {
9267 existing = Some((window, workspace.clone()))
9268 }
9269 }
9270 }
9271 }
9272 });
9273
9274 // With -n, only reuse a window if the path is genuinely contained
9275 // within an existing worktree (don't fall back to any arbitrary window).
9276 if open_options.open_new_workspace == Some(true) && best_match.is_none() {
9277 existing = None;
9278 }
9279
9280 if open_options.open_new_workspace != Some(true) {
9281 let all_paths_are_files = existing
9282 .as_ref()
9283 .and_then(|(_, target_workspace)| {
9284 cx.update(|cx| {
9285 let workspace = target_workspace.read(cx);
9286 let project = workspace.project.read(cx);
9287 let path_style = workspace.path_style(cx);
9288 Some(!abs_paths.iter().any(|path| {
9289 let path = util::paths::SanitizedPath::new(path);
9290 project.worktrees(cx).any(|worktree| {
9291 let worktree = worktree.read(cx);
9292 let abs_path = worktree.abs_path();
9293 path_style
9294 .strip_prefix(path.as_ref(), abs_path.as_ref())
9295 .and_then(|rel| worktree.entry_for_path(&rel))
9296 .is_some_and(|e| e.is_dir())
9297 })
9298 }))
9299 })
9300 })
9301 .unwrap_or(false);
9302
9303 if open_options.open_new_workspace.is_none()
9304 && existing.is_some()
9305 && open_options.wait
9306 && all_paths_are_files
9307 {
9308 cx.update(|cx| {
9309 let windows = workspace_windows_for_location(location, cx);
9310 let window = cx
9311 .active_window()
9312 .and_then(|window| window.downcast::<MultiWorkspace>())
9313 .filter(|window| windows.contains(window))
9314 .or_else(|| windows.into_iter().next());
9315 if let Some(window) = window {
9316 if let Ok(multi_workspace) = window.read(cx) {
9317 let active_workspace = multi_workspace.workspace().clone();
9318 existing = Some((window, active_workspace));
9319 open_visible = OpenVisible::None;
9320 }
9321 }
9322 });
9323 }
9324 }
9325 (existing, open_visible)
9326}
9327
9328#[derive(Default, Clone)]
9329pub struct OpenOptions {
9330 pub visible: Option<OpenVisible>,
9331 pub focus: Option<bool>,
9332 pub open_new_workspace: Option<bool>,
9333 pub force_existing_window: bool,
9334 pub wait: bool,
9335 pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
9336 pub open_mode: OpenMode,
9337 pub env: Option<HashMap<String, String>>,
9338 pub open_in_dev_container: bool,
9339}
9340
9341impl OpenOptions {
9342 fn should_reuse_existing_window(&self) -> bool {
9343 self.open_new_workspace.is_none() && self.open_mode != OpenMode::NewWindow
9344 }
9345}
9346
9347/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9348/// or [`Workspace::open_workspace_for_paths`].
9349pub struct OpenResult {
9350 pub window: WindowHandle<MultiWorkspace>,
9351 pub workspace: Entity<Workspace>,
9352 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9353}
9354
9355/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9356pub fn open_workspace_by_id(
9357 workspace_id: WorkspaceId,
9358 app_state: Arc<AppState>,
9359 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9360 cx: &mut App,
9361) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9362 let project_handle = Project::local(
9363 app_state.client.clone(),
9364 app_state.node_runtime.clone(),
9365 app_state.user_store.clone(),
9366 app_state.languages.clone(),
9367 app_state.fs.clone(),
9368 None,
9369 project::LocalProjectFlags {
9370 init_worktree_trust: true,
9371 ..project::LocalProjectFlags::default()
9372 },
9373 cx,
9374 );
9375
9376 let db = WorkspaceDb::global(cx);
9377 let kvp = db::kvp::KeyValueStore::global(cx);
9378 cx.spawn(async move |cx| {
9379 let serialized_workspace = db
9380 .workspace_for_id(workspace_id)
9381 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9382
9383 let centered_layout = serialized_workspace.centered_layout;
9384
9385 let (window, workspace) = if let Some(window) = requesting_window {
9386 let workspace = window.update(cx, |multi_workspace, window, cx| {
9387 let workspace = cx.new(|cx| {
9388 let mut workspace = Workspace::new(
9389 Some(workspace_id),
9390 project_handle.clone(),
9391 app_state.clone(),
9392 window,
9393 cx,
9394 );
9395 workspace.centered_layout = centered_layout;
9396 workspace
9397 });
9398 multi_workspace.add(workspace.clone(), &*window, cx);
9399 workspace
9400 })?;
9401 (window, workspace)
9402 } else {
9403 let window_bounds_override = window_bounds_env_override();
9404
9405 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9406 (Some(WindowBounds::Windowed(bounds)), None)
9407 } else if let Some(display) = serialized_workspace.display
9408 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9409 {
9410 (Some(bounds.0), Some(display))
9411 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9412 (Some(bounds), Some(display))
9413 } else {
9414 (None, None)
9415 };
9416
9417 let options = cx.update(|cx| {
9418 let mut options = (app_state.build_window_options)(display, cx);
9419 options.window_bounds = window_bounds;
9420 options
9421 });
9422
9423 let window = cx.open_window(options, {
9424 let app_state = app_state.clone();
9425 let project_handle = project_handle.clone();
9426 move |window, cx| {
9427 let workspace = cx.new(|cx| {
9428 let mut workspace = Workspace::new(
9429 Some(workspace_id),
9430 project_handle,
9431 app_state,
9432 window,
9433 cx,
9434 );
9435 workspace.centered_layout = centered_layout;
9436 workspace
9437 });
9438 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9439 }
9440 })?;
9441
9442 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9443 multi_workspace.workspace().clone()
9444 })?;
9445
9446 (window, workspace)
9447 };
9448
9449 notify_if_database_failed(window, cx);
9450
9451 // Restore items from the serialized workspace
9452 window
9453 .update(cx, |_, window, cx| {
9454 workspace.update(cx, |_workspace, cx| {
9455 open_items(Some(serialized_workspace), vec![], window, cx)
9456 })
9457 })?
9458 .await?;
9459
9460 window.update(cx, |_, window, cx| {
9461 workspace.update(cx, |workspace, cx| {
9462 workspace.serialize_workspace(window, cx);
9463 });
9464 })?;
9465
9466 Ok(window)
9467 })
9468}
9469
9470#[allow(clippy::type_complexity)]
9471pub fn open_paths(
9472 abs_paths: &[PathBuf],
9473 app_state: Arc<AppState>,
9474 mut open_options: OpenOptions,
9475 cx: &mut App,
9476) -> Task<anyhow::Result<OpenResult>> {
9477 let abs_paths = abs_paths.to_vec();
9478 #[cfg(target_os = "windows")]
9479 let wsl_path = abs_paths
9480 .iter()
9481 .find_map(|p| util::paths::WslPath::from_path(p));
9482
9483 cx.spawn(async move |cx| {
9484 let (mut existing, mut open_visible) = find_existing_workspace(
9485 &abs_paths,
9486 &open_options,
9487 &SerializedWorkspaceLocation::Local,
9488 cx,
9489 )
9490 .await;
9491
9492 // Fallback: if no workspace contains the paths and all paths are files,
9493 // prefer an existing local workspace window (active window first).
9494 if open_options.should_reuse_existing_window() && existing.is_none() {
9495 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9496 let all_metadatas = futures::future::join_all(all_paths)
9497 .await
9498 .into_iter()
9499 .filter_map(|result| result.ok().flatten());
9500
9501 if all_metadatas.into_iter().all(|file| !file.is_dir) {
9502 cx.update(|cx| {
9503 let windows = workspace_windows_for_location(
9504 &SerializedWorkspaceLocation::Local,
9505 cx,
9506 );
9507 let window = cx
9508 .active_window()
9509 .and_then(|window| window.downcast::<MultiWorkspace>())
9510 .filter(|window| windows.contains(window))
9511 .or_else(|| windows.into_iter().next());
9512 if let Some(window) = window {
9513 if let Ok(multi_workspace) = window.read(cx) {
9514 let active_workspace = multi_workspace.workspace().clone();
9515 existing = Some((window, active_workspace));
9516 open_visible = OpenVisible::None;
9517 }
9518 }
9519 });
9520 }
9521 }
9522
9523 // Fallback for directories: when no flag is specified and no existing
9524 // workspace matched, check the user's setting to decide whether to add
9525 // the directory as a new workspace in the active window's MultiWorkspace
9526 // or open a new window.
9527 // Skip when requesting_window is already set: the caller (e.g.
9528 // open_workspace_for_paths reusing an empty window) already chose the
9529 // target window, so we must not open the sidebar as a side-effect.
9530 if open_options.should_reuse_existing_window()
9531 && existing.is_none()
9532 && open_options.requesting_window.is_none()
9533 {
9534 let use_existing_window = open_options.force_existing_window
9535 || cx.update(|cx| {
9536 WorkspaceSettings::get_global(cx).cli_default_open_behavior
9537 == settings::CliDefaultOpenBehavior::ExistingWindow
9538 });
9539
9540 if use_existing_window {
9541 let target_window = cx.update(|cx| {
9542 let windows = workspace_windows_for_location(
9543 &SerializedWorkspaceLocation::Local,
9544 cx,
9545 );
9546 let window = cx
9547 .active_window()
9548 .and_then(|window| window.downcast::<MultiWorkspace>())
9549 .filter(|window| windows.contains(window))
9550 .or_else(|| windows.into_iter().next());
9551 window.filter(|window| {
9552 window
9553 .read(cx)
9554 .is_ok_and(|mw| mw.multi_workspace_enabled(cx))
9555 })
9556 });
9557
9558 if let Some(window) = target_window {
9559 open_options.requesting_window = Some(window);
9560 window
9561 .update(cx, |multi_workspace, _, cx| {
9562 multi_workspace.open_sidebar(cx);
9563 })
9564 .log_err();
9565 }
9566 }
9567 }
9568
9569 let open_in_dev_container = open_options.open_in_dev_container;
9570
9571 let result = if let Some((existing, target_workspace)) = existing {
9572 let open_task = existing
9573 .update(cx, |multi_workspace, window, cx| {
9574 window.activate_window();
9575 multi_workspace.activate(target_workspace.clone(), window, cx);
9576 target_workspace.update(cx, |workspace, cx| {
9577 if open_in_dev_container {
9578 workspace.set_open_in_dev_container(true);
9579 }
9580 workspace.open_paths(
9581 abs_paths,
9582 OpenOptions {
9583 visible: Some(open_visible),
9584 ..Default::default()
9585 },
9586 None,
9587 window,
9588 cx,
9589 )
9590 })
9591 })?
9592 .await;
9593
9594 _ = existing.update(cx, |multi_workspace, _, cx| {
9595 let workspace = multi_workspace.workspace().clone();
9596 workspace.update(cx, |workspace, cx| {
9597 for item in open_task.iter().flatten() {
9598 if let Err(e) = item {
9599 workspace.show_error(&e, cx);
9600 }
9601 }
9602 });
9603 });
9604
9605 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9606 } else {
9607 let init = if open_in_dev_container {
9608 Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
9609 workspace.set_open_in_dev_container(true);
9610 }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
9611 } else {
9612 None
9613 };
9614 let result = cx
9615 .update(move |cx| {
9616 Workspace::new_local(
9617 abs_paths,
9618 app_state.clone(),
9619 open_options.requesting_window,
9620 open_options.env,
9621 init,
9622 open_options.open_mode,
9623 cx,
9624 )
9625 })
9626 .await;
9627
9628 if let Ok(ref result) = result {
9629 result.window
9630 .update(cx, |_, window, _cx| {
9631 window.activate_window();
9632 })
9633 .log_err();
9634 }
9635
9636 result
9637 };
9638
9639 #[cfg(target_os = "windows")]
9640 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9641 && let Ok(ref result) = result
9642 {
9643 result.window
9644 .update(cx, move |multi_workspace, _window, cx| {
9645 struct OpenInWsl;
9646 let workspace = multi_workspace.workspace().clone();
9647 workspace.update(cx, |workspace, cx| {
9648 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9649 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9650 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9651 cx.new(move |cx| {
9652 MessageNotification::new(msg, cx)
9653 .primary_message("Open in WSL")
9654 .primary_icon(IconName::FolderOpen)
9655 .primary_on_click(move |window, cx| {
9656 window.dispatch_action(Box::new(remote::OpenWslPath {
9657 distro: remote::WslConnectionOptions {
9658 distro_name: distro.clone(),
9659 user: None,
9660 },
9661 paths: vec![path.clone().into()],
9662 }), cx)
9663 })
9664 })
9665 });
9666 });
9667 })
9668 .unwrap();
9669 };
9670 result
9671 })
9672}
9673
9674pub fn open_new(
9675 open_options: OpenOptions,
9676 app_state: Arc<AppState>,
9677 cx: &mut App,
9678 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9679) -> Task<anyhow::Result<()>> {
9680 let addition = open_options.open_mode;
9681 let task = Workspace::new_local(
9682 Vec::new(),
9683 app_state,
9684 open_options.requesting_window,
9685 open_options.env,
9686 Some(Box::new(init)),
9687 addition,
9688 cx,
9689 );
9690 cx.spawn(async move |cx| {
9691 let OpenResult { window, .. } = task.await?;
9692 window
9693 .update(cx, |_, window, _cx| {
9694 window.activate_window();
9695 })
9696 .ok();
9697 Ok(())
9698 })
9699}
9700
9701pub fn create_and_open_local_file(
9702 path: &'static Path,
9703 window: &mut Window,
9704 cx: &mut Context<Workspace>,
9705 default_content: impl 'static + Send + FnOnce() -> Rope,
9706) -> Task<Result<Box<dyn ItemHandle>>> {
9707 cx.spawn_in(window, async move |workspace, cx| {
9708 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9709 if !fs.is_file(path).await {
9710 fs.create_file(path, Default::default()).await?;
9711 fs.save(path, &default_content(), Default::default())
9712 .await?;
9713 }
9714
9715 workspace
9716 .update_in(cx, |workspace, window, cx| {
9717 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9718 let path = workspace
9719 .project
9720 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9721 cx.spawn_in(window, async move |workspace, cx| {
9722 let path = path.await?;
9723
9724 let path = fs.canonicalize(&path).await.unwrap_or(path);
9725
9726 let mut items = workspace
9727 .update_in(cx, |workspace, window, cx| {
9728 workspace.open_paths(
9729 vec![path.to_path_buf()],
9730 OpenOptions {
9731 visible: Some(OpenVisible::None),
9732 ..Default::default()
9733 },
9734 None,
9735 window,
9736 cx,
9737 )
9738 })?
9739 .await;
9740 let item = items.pop().flatten();
9741 item.with_context(|| format!("path {path:?} is not a file"))?
9742 })
9743 })
9744 })?
9745 .await?
9746 .await
9747 })
9748}
9749
9750pub fn open_remote_project_with_new_connection(
9751 window: WindowHandle<MultiWorkspace>,
9752 remote_connection: Arc<dyn RemoteConnection>,
9753 cancel_rx: oneshot::Receiver<()>,
9754 delegate: Arc<dyn RemoteClientDelegate>,
9755 app_state: Arc<AppState>,
9756 paths: Vec<PathBuf>,
9757 cx: &mut App,
9758) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9759 cx.spawn(async move |cx| {
9760 let (workspace_id, serialized_workspace) =
9761 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9762 .await?;
9763
9764 let session = match cx
9765 .update(|cx| {
9766 remote::RemoteClient::new(
9767 ConnectionIdentifier::Workspace(workspace_id.0),
9768 remote_connection,
9769 cancel_rx,
9770 delegate,
9771 cx,
9772 )
9773 })
9774 .await?
9775 {
9776 Some(result) => result,
9777 None => return Ok(Vec::new()),
9778 };
9779
9780 let project = cx.update(|cx| {
9781 project::Project::remote(
9782 session,
9783 app_state.client.clone(),
9784 app_state.node_runtime.clone(),
9785 app_state.user_store.clone(),
9786 app_state.languages.clone(),
9787 app_state.fs.clone(),
9788 true,
9789 cx,
9790 )
9791 });
9792
9793 open_remote_project_inner(
9794 project,
9795 paths,
9796 workspace_id,
9797 serialized_workspace,
9798 app_state,
9799 window,
9800 None,
9801 cx,
9802 )
9803 .await
9804 })
9805}
9806
9807pub fn open_remote_project_with_existing_connection(
9808 connection_options: RemoteConnectionOptions,
9809 project: Entity<Project>,
9810 paths: Vec<PathBuf>,
9811 app_state: Arc<AppState>,
9812 window: WindowHandle<MultiWorkspace>,
9813 provisional_project_group_key: Option<ProjectGroupKey>,
9814 cx: &mut AsyncApp,
9815) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9816 cx.spawn(async move |cx| {
9817 let (workspace_id, serialized_workspace) =
9818 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9819
9820 open_remote_project_inner(
9821 project,
9822 paths,
9823 workspace_id,
9824 serialized_workspace,
9825 app_state,
9826 window,
9827 provisional_project_group_key,
9828 cx,
9829 )
9830 .await
9831 })
9832}
9833
9834async fn open_remote_project_inner(
9835 project: Entity<Project>,
9836 paths: Vec<PathBuf>,
9837 workspace_id: WorkspaceId,
9838 serialized_workspace: Option<SerializedWorkspace>,
9839 app_state: Arc<AppState>,
9840 window: WindowHandle<MultiWorkspace>,
9841 provisional_project_group_key: Option<ProjectGroupKey>,
9842 cx: &mut AsyncApp,
9843) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9844 let db = cx.update(|cx| WorkspaceDb::global(cx));
9845 let toolchains = db.toolchains(workspace_id).await?;
9846 for (toolchain, worktree_path, path) in toolchains {
9847 project
9848 .update(cx, |this, cx| {
9849 let Some(worktree_id) =
9850 this.find_worktree(&worktree_path, cx)
9851 .and_then(|(worktree, rel_path)| {
9852 if rel_path.is_empty() {
9853 Some(worktree.read(cx).id())
9854 } else {
9855 None
9856 }
9857 })
9858 else {
9859 return Task::ready(None);
9860 };
9861
9862 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9863 })
9864 .await;
9865 }
9866 let mut project_paths_to_open = vec![];
9867 let mut project_path_errors = vec![];
9868
9869 for path in paths {
9870 let result = cx
9871 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9872 .await;
9873 match result {
9874 Ok((_, project_path)) => {
9875 project_paths_to_open.push((path.clone(), Some(project_path)));
9876 }
9877 Err(error) => {
9878 project_path_errors.push(error);
9879 }
9880 };
9881 }
9882
9883 if project_paths_to_open.is_empty() {
9884 return Err(project_path_errors.pop().context("no paths given")?);
9885 }
9886
9887 let workspace = window.update(cx, |multi_workspace, window, cx| {
9888 telemetry::event!("SSH Project Opened");
9889
9890 let new_workspace = cx.new(|cx| {
9891 let mut workspace =
9892 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9893 workspace.update_history(cx);
9894
9895 if let Some(ref serialized) = serialized_workspace {
9896 workspace.centered_layout = serialized.centered_layout;
9897 }
9898
9899 workspace
9900 });
9901
9902 if let Some(project_group_key) = provisional_project_group_key.clone() {
9903 multi_workspace.retain_workspace(new_workspace.clone(), project_group_key, cx);
9904 }
9905 multi_workspace.activate(new_workspace.clone(), window, cx);
9906 new_workspace
9907 })?;
9908
9909 let items = window
9910 .update(cx, |_, window, cx| {
9911 window.activate_window();
9912 workspace.update(cx, |_workspace, cx| {
9913 open_items(serialized_workspace, project_paths_to_open, window, cx)
9914 })
9915 })?
9916 .await?;
9917
9918 workspace.update(cx, |workspace, cx| {
9919 for error in project_path_errors {
9920 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9921 if let Some(path) = error.error_tag("path") {
9922 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9923 }
9924 } else {
9925 workspace.show_error(&error, cx)
9926 }
9927 }
9928 });
9929
9930 Ok(items.into_iter().map(|item| item?.ok()).collect())
9931}
9932
9933fn deserialize_remote_project(
9934 connection_options: RemoteConnectionOptions,
9935 paths: Vec<PathBuf>,
9936 cx: &AsyncApp,
9937) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9938 let db = cx.update(|cx| WorkspaceDb::global(cx));
9939 cx.background_spawn(async move {
9940 let remote_connection_id = db
9941 .get_or_create_remote_connection(connection_options)
9942 .await?;
9943
9944 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9945
9946 let workspace_id = if let Some(workspace_id) =
9947 serialized_workspace.as_ref().map(|workspace| workspace.id)
9948 {
9949 workspace_id
9950 } else {
9951 db.next_id().await?
9952 };
9953
9954 Ok((workspace_id, serialized_workspace))
9955 })
9956}
9957
9958pub fn join_in_room_project(
9959 project_id: u64,
9960 follow_user_id: u64,
9961 app_state: Arc<AppState>,
9962 cx: &mut App,
9963) -> Task<Result<()>> {
9964 let windows = cx.windows();
9965 cx.spawn(async move |cx| {
9966 let existing_window_and_workspace: Option<(
9967 WindowHandle<MultiWorkspace>,
9968 Entity<Workspace>,
9969 )> = windows.into_iter().find_map(|window_handle| {
9970 window_handle
9971 .downcast::<MultiWorkspace>()
9972 .and_then(|window_handle| {
9973 window_handle
9974 .update(cx, |multi_workspace, _window, cx| {
9975 multi_workspace
9976 .workspaces()
9977 .find(|workspace| {
9978 workspace.read(cx).project().read(cx).remote_id()
9979 == Some(project_id)
9980 })
9981 .map(|workspace| (window_handle, workspace.clone()))
9982 })
9983 .unwrap_or(None)
9984 })
9985 });
9986
9987 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9988 existing_window_and_workspace
9989 {
9990 existing_window
9991 .update(cx, |multi_workspace, window, cx| {
9992 multi_workspace.activate(target_workspace, window, cx);
9993 })
9994 .ok();
9995 existing_window
9996 } else {
9997 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9998 let project = cx
9999 .update(|cx| {
10000 active_call.0.join_project(
10001 project_id,
10002 app_state.languages.clone(),
10003 app_state.fs.clone(),
10004 cx,
10005 )
10006 })
10007 .await?;
10008
10009 let window_bounds_override = window_bounds_env_override();
10010 cx.update(|cx| {
10011 let mut options = (app_state.build_window_options)(None, cx);
10012 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
10013 cx.open_window(options, |window, cx| {
10014 let workspace = cx.new(|cx| {
10015 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
10016 });
10017 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
10018 })
10019 })?
10020 };
10021
10022 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
10023 cx.activate(true);
10024 window.activate_window();
10025
10026 // We set the active workspace above, so this is the correct workspace.
10027 let workspace = multi_workspace.workspace().clone();
10028 workspace.update(cx, |workspace, cx| {
10029 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
10030 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
10031 .or_else(|| {
10032 // If we couldn't follow the given user, follow the host instead.
10033 let collaborator = workspace
10034 .project()
10035 .read(cx)
10036 .collaborators()
10037 .values()
10038 .find(|collaborator| collaborator.is_host)?;
10039 Some(collaborator.peer_id)
10040 });
10041
10042 if let Some(follow_peer_id) = follow_peer_id {
10043 workspace.follow(follow_peer_id, window, cx);
10044 }
10045 });
10046 })?;
10047
10048 anyhow::Ok(())
10049 })
10050}
10051
10052pub fn reload(cx: &mut App) {
10053 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
10054 let mut workspace_windows = cx
10055 .windows()
10056 .into_iter()
10057 .filter_map(|window| window.downcast::<MultiWorkspace>())
10058 .collect::<Vec<_>>();
10059
10060 // If multiple windows have unsaved changes, and need a save prompt,
10061 // prompt in the active window before switching to a different window.
10062 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
10063
10064 let mut prompt = None;
10065 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
10066 prompt = window
10067 .update(cx, |_, window, cx| {
10068 window.prompt(
10069 PromptLevel::Info,
10070 "Are you sure you want to restart?",
10071 None,
10072 &["Restart", "Cancel"],
10073 cx,
10074 )
10075 })
10076 .ok();
10077 }
10078
10079 cx.spawn(async move |cx| {
10080 if let Some(prompt) = prompt {
10081 let answer = prompt.await?;
10082 if answer != 0 {
10083 return anyhow::Ok(());
10084 }
10085 }
10086
10087 // If the user cancels any save prompt, then keep the app open.
10088 for window in workspace_windows {
10089 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
10090 let workspace = multi_workspace.workspace().clone();
10091 workspace.update(cx, |workspace, cx| {
10092 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
10093 })
10094 }) && !should_close.await?
10095 {
10096 return anyhow::Ok(());
10097 }
10098 }
10099 cx.update(|cx| cx.restart());
10100 anyhow::Ok(())
10101 })
10102 .detach_and_log_err(cx);
10103}
10104
10105fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
10106 let mut parts = value.split(',');
10107 let x: usize = parts.next()?.parse().ok()?;
10108 let y: usize = parts.next()?.parse().ok()?;
10109 Some(point(px(x as f32), px(y as f32)))
10110}
10111
10112fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
10113 let mut parts = value.split(',');
10114 let width: usize = parts.next()?.parse().ok()?;
10115 let height: usize = parts.next()?.parse().ok()?;
10116 Some(size(px(width as f32), px(height as f32)))
10117}
10118
10119/// Add client-side decorations (rounded corners, shadows, resize handling) when
10120/// appropriate.
10121///
10122/// The `border_radius_tiling` parameter allows overriding which corners get
10123/// rounded, independently of the actual window tiling state. This is used
10124/// specifically for the workspace switcher sidebar: when the sidebar is open,
10125/// we want square corners on the left (so the sidebar appears flush with the
10126/// window edge) but we still need the shadow padding for proper visual
10127/// appearance. Unlike actual window tiling, this only affects border radius -
10128/// not padding or shadows.
10129pub fn client_side_decorations(
10130 element: impl IntoElement,
10131 window: &mut Window,
10132 cx: &mut App,
10133 border_radius_tiling: Tiling,
10134) -> Stateful<Div> {
10135 const BORDER_SIZE: Pixels = px(1.0);
10136 let decorations = window.window_decorations();
10137 let tiling = match decorations {
10138 Decorations::Server => Tiling::default(),
10139 Decorations::Client { tiling } => tiling,
10140 };
10141
10142 match decorations {
10143 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
10144 Decorations::Server => window.set_client_inset(px(0.0)),
10145 }
10146
10147 struct GlobalResizeEdge(ResizeEdge);
10148 impl Global for GlobalResizeEdge {}
10149
10150 div()
10151 .id("window-backdrop")
10152 .bg(transparent_black())
10153 .map(|div| match decorations {
10154 Decorations::Server => div,
10155 Decorations::Client { .. } => div
10156 .when(
10157 !(tiling.top
10158 || tiling.right
10159 || border_radius_tiling.top
10160 || border_radius_tiling.right),
10161 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10162 )
10163 .when(
10164 !(tiling.top
10165 || tiling.left
10166 || border_radius_tiling.top
10167 || border_radius_tiling.left),
10168 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10169 )
10170 .when(
10171 !(tiling.bottom
10172 || tiling.right
10173 || border_radius_tiling.bottom
10174 || border_radius_tiling.right),
10175 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10176 )
10177 .when(
10178 !(tiling.bottom
10179 || tiling.left
10180 || border_radius_tiling.bottom
10181 || border_radius_tiling.left),
10182 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10183 )
10184 .when(!tiling.top, |div| {
10185 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10186 })
10187 .when(!tiling.bottom, |div| {
10188 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10189 })
10190 .when(!tiling.left, |div| {
10191 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10192 })
10193 .when(!tiling.right, |div| {
10194 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10195 })
10196 .on_mouse_move(move |e, window, cx| {
10197 let size = window.window_bounds().get_bounds().size;
10198 let pos = e.position;
10199
10200 let new_edge =
10201 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10202
10203 let edge = cx.try_global::<GlobalResizeEdge>();
10204 if new_edge != edge.map(|edge| edge.0) {
10205 window
10206 .window_handle()
10207 .update(cx, |workspace, _, cx| {
10208 cx.notify(workspace.entity_id());
10209 })
10210 .ok();
10211 }
10212 })
10213 .on_mouse_down(MouseButton::Left, move |e, window, _| {
10214 let size = window.window_bounds().get_bounds().size;
10215 let pos = e.position;
10216
10217 let edge = match resize_edge(
10218 pos,
10219 theme::CLIENT_SIDE_DECORATION_SHADOW,
10220 size,
10221 tiling,
10222 ) {
10223 Some(value) => value,
10224 None => return,
10225 };
10226
10227 window.start_window_resize(edge);
10228 }),
10229 })
10230 .size_full()
10231 .child(
10232 div()
10233 .cursor(CursorStyle::Arrow)
10234 .map(|div| match decorations {
10235 Decorations::Server => div,
10236 Decorations::Client { .. } => div
10237 .border_color(cx.theme().colors().border)
10238 .when(
10239 !(tiling.top
10240 || tiling.right
10241 || border_radius_tiling.top
10242 || border_radius_tiling.right),
10243 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10244 )
10245 .when(
10246 !(tiling.top
10247 || tiling.left
10248 || border_radius_tiling.top
10249 || border_radius_tiling.left),
10250 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10251 )
10252 .when(
10253 !(tiling.bottom
10254 || tiling.right
10255 || border_radius_tiling.bottom
10256 || border_radius_tiling.right),
10257 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10258 )
10259 .when(
10260 !(tiling.bottom
10261 || tiling.left
10262 || border_radius_tiling.bottom
10263 || border_radius_tiling.left),
10264 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10265 )
10266 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10267 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10268 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10269 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10270 .when(!tiling.is_tiled(), |div| {
10271 div.shadow(vec![gpui::BoxShadow {
10272 color: Hsla {
10273 h: 0.,
10274 s: 0.,
10275 l: 0.,
10276 a: 0.4,
10277 },
10278 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10279 spread_radius: px(0.),
10280 offset: point(px(0.0), px(0.0)),
10281 }])
10282 }),
10283 })
10284 .on_mouse_move(|_e, _, cx| {
10285 cx.stop_propagation();
10286 })
10287 .size_full()
10288 .child(element),
10289 )
10290 .map(|div| match decorations {
10291 Decorations::Server => div,
10292 Decorations::Client { tiling, .. } => div.child(
10293 canvas(
10294 |_bounds, window, _| {
10295 window.insert_hitbox(
10296 Bounds::new(
10297 point(px(0.0), px(0.0)),
10298 window.window_bounds().get_bounds().size,
10299 ),
10300 HitboxBehavior::Normal,
10301 )
10302 },
10303 move |_bounds, hitbox, window, cx| {
10304 let mouse = window.mouse_position();
10305 let size = window.window_bounds().get_bounds().size;
10306 let Some(edge) =
10307 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10308 else {
10309 return;
10310 };
10311 cx.set_global(GlobalResizeEdge(edge));
10312 window.set_cursor_style(
10313 match edge {
10314 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10315 ResizeEdge::Left | ResizeEdge::Right => {
10316 CursorStyle::ResizeLeftRight
10317 }
10318 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10319 CursorStyle::ResizeUpLeftDownRight
10320 }
10321 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10322 CursorStyle::ResizeUpRightDownLeft
10323 }
10324 },
10325 &hitbox,
10326 );
10327 },
10328 )
10329 .size_full()
10330 .absolute(),
10331 ),
10332 })
10333}
10334
10335fn resize_edge(
10336 pos: Point<Pixels>,
10337 shadow_size: Pixels,
10338 window_size: Size<Pixels>,
10339 tiling: Tiling,
10340) -> Option<ResizeEdge> {
10341 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10342 if bounds.contains(&pos) {
10343 return None;
10344 }
10345
10346 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10347 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10348 if !tiling.top && top_left_bounds.contains(&pos) {
10349 return Some(ResizeEdge::TopLeft);
10350 }
10351
10352 let top_right_bounds = Bounds::new(
10353 Point::new(window_size.width - corner_size.width, px(0.)),
10354 corner_size,
10355 );
10356 if !tiling.top && top_right_bounds.contains(&pos) {
10357 return Some(ResizeEdge::TopRight);
10358 }
10359
10360 let bottom_left_bounds = Bounds::new(
10361 Point::new(px(0.), window_size.height - corner_size.height),
10362 corner_size,
10363 );
10364 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10365 return Some(ResizeEdge::BottomLeft);
10366 }
10367
10368 let bottom_right_bounds = Bounds::new(
10369 Point::new(
10370 window_size.width - corner_size.width,
10371 window_size.height - corner_size.height,
10372 ),
10373 corner_size,
10374 );
10375 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10376 return Some(ResizeEdge::BottomRight);
10377 }
10378
10379 if !tiling.top && pos.y < shadow_size {
10380 Some(ResizeEdge::Top)
10381 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10382 Some(ResizeEdge::Bottom)
10383 } else if !tiling.left && pos.x < shadow_size {
10384 Some(ResizeEdge::Left)
10385 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10386 Some(ResizeEdge::Right)
10387 } else {
10388 None
10389 }
10390}
10391
10392fn join_pane_into_active(
10393 active_pane: &Entity<Pane>,
10394 pane: &Entity<Pane>,
10395 window: &mut Window,
10396 cx: &mut App,
10397) {
10398 if pane == active_pane {
10399 } else if pane.read(cx).items_len() == 0 {
10400 pane.update(cx, |_, cx| {
10401 cx.emit(pane::Event::Remove {
10402 focus_on_pane: None,
10403 });
10404 })
10405 } else {
10406 move_all_items(pane, active_pane, window, cx);
10407 }
10408}
10409
10410fn move_all_items(
10411 from_pane: &Entity<Pane>,
10412 to_pane: &Entity<Pane>,
10413 window: &mut Window,
10414 cx: &mut App,
10415) {
10416 let destination_is_different = from_pane != to_pane;
10417 let mut moved_items = 0;
10418 for (item_ix, item_handle) in from_pane
10419 .read(cx)
10420 .items()
10421 .enumerate()
10422 .map(|(ix, item)| (ix, item.clone()))
10423 .collect::<Vec<_>>()
10424 {
10425 let ix = item_ix - moved_items;
10426 if destination_is_different {
10427 // Close item from previous pane
10428 from_pane.update(cx, |source, cx| {
10429 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10430 });
10431 moved_items += 1;
10432 }
10433
10434 // This automatically removes duplicate items in the pane
10435 to_pane.update(cx, |destination, cx| {
10436 destination.add_item(item_handle, true, true, None, window, cx);
10437 window.focus(&destination.focus_handle(cx), cx)
10438 });
10439 }
10440}
10441
10442pub fn move_item(
10443 source: &Entity<Pane>,
10444 destination: &Entity<Pane>,
10445 item_id_to_move: EntityId,
10446 destination_index: usize,
10447 activate: bool,
10448 window: &mut Window,
10449 cx: &mut App,
10450) {
10451 let Some((item_ix, item_handle)) = source
10452 .read(cx)
10453 .items()
10454 .enumerate()
10455 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10456 .map(|(ix, item)| (ix, item.clone()))
10457 else {
10458 // Tab was closed during drag
10459 return;
10460 };
10461
10462 if source != destination {
10463 // Close item from previous pane
10464 source.update(cx, |source, cx| {
10465 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10466 });
10467 }
10468
10469 // This automatically removes duplicate items in the pane
10470 destination.update(cx, |destination, cx| {
10471 destination.add_item_inner(
10472 item_handle,
10473 activate,
10474 activate,
10475 activate,
10476 Some(destination_index),
10477 window,
10478 cx,
10479 );
10480 if activate {
10481 window.focus(&destination.focus_handle(cx), cx)
10482 }
10483 });
10484}
10485
10486pub fn move_active_item(
10487 source: &Entity<Pane>,
10488 destination: &Entity<Pane>,
10489 focus_destination: bool,
10490 close_if_empty: bool,
10491 window: &mut Window,
10492 cx: &mut App,
10493) {
10494 if source == destination {
10495 return;
10496 }
10497 let Some(active_item) = source.read(cx).active_item() else {
10498 return;
10499 };
10500 source.update(cx, |source_pane, cx| {
10501 let item_id = active_item.item_id();
10502 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10503 destination.update(cx, |target_pane, cx| {
10504 target_pane.add_item(
10505 active_item,
10506 focus_destination,
10507 focus_destination,
10508 Some(target_pane.items_len()),
10509 window,
10510 cx,
10511 );
10512 });
10513 });
10514}
10515
10516pub fn clone_active_item(
10517 workspace_id: Option<WorkspaceId>,
10518 source: &Entity<Pane>,
10519 destination: &Entity<Pane>,
10520 focus_destination: bool,
10521 window: &mut Window,
10522 cx: &mut App,
10523) {
10524 if source == destination {
10525 return;
10526 }
10527 let Some(active_item) = source.read(cx).active_item() else {
10528 return;
10529 };
10530 if !active_item.can_split(cx) {
10531 return;
10532 }
10533 let destination = destination.downgrade();
10534 let task = active_item.clone_on_split(workspace_id, window, cx);
10535 window
10536 .spawn(cx, async move |cx| {
10537 let Some(clone) = task.await else {
10538 return;
10539 };
10540 destination
10541 .update_in(cx, |target_pane, window, cx| {
10542 target_pane.add_item(
10543 clone,
10544 focus_destination,
10545 focus_destination,
10546 Some(target_pane.items_len()),
10547 window,
10548 cx,
10549 );
10550 })
10551 .log_err();
10552 })
10553 .detach();
10554}
10555
10556#[derive(Debug)]
10557pub struct WorkspacePosition {
10558 pub window_bounds: Option<WindowBounds>,
10559 pub display: Option<Uuid>,
10560 pub centered_layout: bool,
10561}
10562
10563pub fn remote_workspace_position_from_db(
10564 connection_options: RemoteConnectionOptions,
10565 paths_to_open: &[PathBuf],
10566 cx: &App,
10567) -> Task<Result<WorkspacePosition>> {
10568 let paths = paths_to_open.to_vec();
10569 let db = WorkspaceDb::global(cx);
10570 let kvp = db::kvp::KeyValueStore::global(cx);
10571
10572 cx.background_spawn(async move {
10573 let remote_connection_id = db
10574 .get_or_create_remote_connection(connection_options)
10575 .await
10576 .context("fetching serialized ssh project")?;
10577 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10578
10579 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10580 (Some(WindowBounds::Windowed(bounds)), None)
10581 } else {
10582 let restorable_bounds = serialized_workspace
10583 .as_ref()
10584 .and_then(|workspace| {
10585 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10586 })
10587 .or_else(|| persistence::read_default_window_bounds(&kvp));
10588
10589 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10590 (Some(serialized_bounds), Some(serialized_display))
10591 } else {
10592 (None, None)
10593 }
10594 };
10595
10596 let centered_layout = serialized_workspace
10597 .as_ref()
10598 .map(|w| w.centered_layout)
10599 .unwrap_or(false);
10600
10601 Ok(WorkspacePosition {
10602 window_bounds,
10603 display,
10604 centered_layout,
10605 })
10606 })
10607}
10608
10609pub fn with_active_or_new_workspace(
10610 cx: &mut App,
10611 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10612) {
10613 match cx
10614 .active_window()
10615 .and_then(|w| w.downcast::<MultiWorkspace>())
10616 {
10617 Some(multi_workspace) => {
10618 cx.defer(move |cx| {
10619 multi_workspace
10620 .update(cx, |multi_workspace, window, cx| {
10621 let workspace = multi_workspace.workspace().clone();
10622 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10623 })
10624 .log_err();
10625 });
10626 }
10627 None => {
10628 let app_state = AppState::global(cx);
10629 open_new(
10630 OpenOptions::default(),
10631 app_state,
10632 cx,
10633 move |workspace, window, cx| f(workspace, window, cx),
10634 )
10635 .detach_and_log_err(cx);
10636 }
10637 }
10638}
10639
10640/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10641/// key. This migration path only runs once per panel per workspace.
10642fn load_legacy_panel_size(
10643 panel_key: &str,
10644 dock_position: DockPosition,
10645 workspace: &Workspace,
10646 cx: &mut App,
10647) -> Option<Pixels> {
10648 #[derive(Deserialize)]
10649 struct LegacyPanelState {
10650 #[serde(default)]
10651 width: Option<Pixels>,
10652 #[serde(default)]
10653 height: Option<Pixels>,
10654 }
10655
10656 let workspace_id = workspace
10657 .database_id()
10658 .map(|id| i64::from(id).to_string())
10659 .or_else(|| workspace.session_id())?;
10660
10661 let legacy_key = match panel_key {
10662 "ProjectPanel" => {
10663 format!("{}-{:?}", "ProjectPanel", workspace_id)
10664 }
10665 "OutlinePanel" => {
10666 format!("{}-{:?}", "OutlinePanel", workspace_id)
10667 }
10668 "GitPanel" => {
10669 format!("{}-{:?}", "GitPanel", workspace_id)
10670 }
10671 "TerminalPanel" => {
10672 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10673 }
10674 _ => return None,
10675 };
10676
10677 let kvp = db::kvp::KeyValueStore::global(cx);
10678 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10679 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10680 let size = match dock_position {
10681 DockPosition::Bottom => state.height,
10682 DockPosition::Left | DockPosition::Right => state.width,
10683 }?;
10684
10685 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10686 .detach_and_log_err(cx);
10687
10688 Some(size)
10689}
10690
10691#[cfg(test)]
10692mod tests {
10693 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10694
10695 use super::*;
10696 use crate::{
10697 dock::{PanelEvent, test::TestPanel},
10698 item::{
10699 ItemBufferKind, ItemEvent,
10700 test::{TestItem, TestProjectItem},
10701 },
10702 };
10703 use fs::FakeFs;
10704 use gpui::{
10705 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10706 UpdateGlobal, VisualTestContext, px,
10707 };
10708 use project::{Project, ProjectEntryId};
10709 use serde_json::json;
10710 use settings::SettingsStore;
10711 use util::path;
10712 use util::rel_path::rel_path;
10713
10714 #[gpui::test]
10715 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10716 init_test(cx);
10717
10718 let fs = FakeFs::new(cx.executor());
10719 let project = Project::test(fs, [], cx).await;
10720 let (workspace, cx) =
10721 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10722
10723 // Adding an item with no ambiguity renders the tab without detail.
10724 let item1 = cx.new(|cx| {
10725 let mut item = TestItem::new(cx);
10726 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10727 item
10728 });
10729 workspace.update_in(cx, |workspace, window, cx| {
10730 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10731 });
10732 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10733
10734 // Adding an item that creates ambiguity increases the level of detail on
10735 // both tabs.
10736 let item2 = cx.new_window_entity(|_window, cx| {
10737 let mut item = TestItem::new(cx);
10738 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10739 item
10740 });
10741 workspace.update_in(cx, |workspace, window, cx| {
10742 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10743 });
10744 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10745 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10746
10747 // Adding an item that creates ambiguity increases the level of detail only
10748 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10749 // we stop at the highest detail available.
10750 let item3 = cx.new(|cx| {
10751 let mut item = TestItem::new(cx);
10752 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10753 item
10754 });
10755 workspace.update_in(cx, |workspace, window, cx| {
10756 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10757 });
10758 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10759 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10760 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10761 }
10762
10763 #[gpui::test]
10764 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10765 init_test(cx);
10766
10767 let fs = FakeFs::new(cx.executor());
10768 fs.insert_tree(
10769 "/root1",
10770 json!({
10771 "one.txt": "",
10772 "two.txt": "",
10773 }),
10774 )
10775 .await;
10776 fs.insert_tree(
10777 "/root2",
10778 json!({
10779 "three.txt": "",
10780 }),
10781 )
10782 .await;
10783
10784 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10785 let (workspace, cx) =
10786 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10787 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10788 let worktree_id = project.update(cx, |project, cx| {
10789 project.worktrees(cx).next().unwrap().read(cx).id()
10790 });
10791
10792 let item1 = cx.new(|cx| {
10793 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10794 });
10795 let item2 = cx.new(|cx| {
10796 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10797 });
10798
10799 // Add an item to an empty pane
10800 workspace.update_in(cx, |workspace, window, cx| {
10801 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10802 });
10803 project.update(cx, |project, cx| {
10804 assert_eq!(
10805 project.active_entry(),
10806 project
10807 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10808 .map(|e| e.id)
10809 );
10810 });
10811 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10812
10813 // Add a second item to a non-empty pane
10814 workspace.update_in(cx, |workspace, window, cx| {
10815 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10816 });
10817 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10818 project.update(cx, |project, cx| {
10819 assert_eq!(
10820 project.active_entry(),
10821 project
10822 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10823 .map(|e| e.id)
10824 );
10825 });
10826
10827 // Close the active item
10828 pane.update_in(cx, |pane, window, cx| {
10829 pane.close_active_item(&Default::default(), window, cx)
10830 })
10831 .await
10832 .unwrap();
10833 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10834 project.update(cx, |project, cx| {
10835 assert_eq!(
10836 project.active_entry(),
10837 project
10838 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10839 .map(|e| e.id)
10840 );
10841 });
10842
10843 // Add a project folder
10844 project
10845 .update(cx, |project, cx| {
10846 project.find_or_create_worktree("root2", true, cx)
10847 })
10848 .await
10849 .unwrap();
10850 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10851
10852 // Remove a project folder
10853 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10854 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10855 }
10856
10857 #[gpui::test]
10858 async fn test_close_window(cx: &mut TestAppContext) {
10859 init_test(cx);
10860
10861 let fs = FakeFs::new(cx.executor());
10862 fs.insert_tree("/root", json!({ "one": "" })).await;
10863
10864 let project = Project::test(fs, ["root".as_ref()], cx).await;
10865 let (workspace, cx) =
10866 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10867
10868 // When there are no dirty items, there's nothing to do.
10869 let item1 = cx.new(TestItem::new);
10870 workspace.update_in(cx, |w, window, cx| {
10871 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10872 });
10873 let task = workspace.update_in(cx, |w, window, cx| {
10874 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10875 });
10876 assert!(task.await.unwrap());
10877
10878 // When there are dirty untitled items, prompt to save each one. If the user
10879 // cancels any prompt, then abort.
10880 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10881 let item3 = cx.new(|cx| {
10882 TestItem::new(cx)
10883 .with_dirty(true)
10884 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10885 });
10886 workspace.update_in(cx, |w, window, cx| {
10887 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10888 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10889 });
10890 let task = workspace.update_in(cx, |w, window, cx| {
10891 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10892 });
10893 cx.executor().run_until_parked();
10894 cx.simulate_prompt_answer("Cancel"); // cancel save all
10895 cx.executor().run_until_parked();
10896 assert!(!cx.has_pending_prompt());
10897 assert!(!task.await.unwrap());
10898 }
10899
10900 #[gpui::test]
10901 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10902 init_test(cx);
10903
10904 let fs = FakeFs::new(cx.executor());
10905 fs.insert_tree("/root", json!({ "one": "" })).await;
10906
10907 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10908 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10909 let multi_workspace_handle =
10910 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10911 cx.run_until_parked();
10912
10913 multi_workspace_handle
10914 .update(cx, |mw, _window, cx| {
10915 mw.open_sidebar(cx);
10916 })
10917 .unwrap();
10918
10919 let workspace_a = multi_workspace_handle
10920 .read_with(cx, |mw, _| mw.workspace().clone())
10921 .unwrap();
10922
10923 let workspace_b = multi_workspace_handle
10924 .update(cx, |mw, window, cx| {
10925 mw.test_add_workspace(project_b, window, cx)
10926 })
10927 .unwrap();
10928
10929 // Activate workspace A
10930 multi_workspace_handle
10931 .update(cx, |mw, window, cx| {
10932 mw.activate(workspace_a.clone(), window, cx);
10933 })
10934 .unwrap();
10935
10936 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10937
10938 // Workspace A has a clean item
10939 let item_a = cx.new(TestItem::new);
10940 workspace_a.update_in(cx, |w, window, cx| {
10941 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10942 });
10943
10944 // Workspace B has a dirty item
10945 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10946 workspace_b.update_in(cx, |w, window, cx| {
10947 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10948 });
10949
10950 // Verify workspace A is active
10951 multi_workspace_handle
10952 .read_with(cx, |mw, _| {
10953 assert_eq!(mw.workspace(), &workspace_a);
10954 })
10955 .unwrap();
10956
10957 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10958 multi_workspace_handle
10959 .update(cx, |mw, window, cx| {
10960 mw.close_window(&CloseWindow, window, cx);
10961 })
10962 .unwrap();
10963 cx.run_until_parked();
10964
10965 // Workspace B should now be active since it has dirty items that need attention
10966 multi_workspace_handle
10967 .read_with(cx, |mw, _| {
10968 assert_eq!(
10969 mw.workspace(),
10970 &workspace_b,
10971 "workspace B should be activated when it prompts"
10972 );
10973 })
10974 .unwrap();
10975
10976 // User cancels the save prompt from workspace B
10977 cx.simulate_prompt_answer("Cancel");
10978 cx.run_until_parked();
10979
10980 // Window should still exist because workspace B's close was cancelled
10981 assert!(
10982 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10983 "window should still exist after cancelling one workspace's close"
10984 );
10985 }
10986
10987 #[gpui::test]
10988 async fn test_remove_workspace_prompts_for_unsaved_changes(cx: &mut TestAppContext) {
10989 init_test(cx);
10990
10991 let fs = FakeFs::new(cx.executor());
10992 fs.insert_tree("/root", json!({ "one": "" })).await;
10993
10994 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10995 let project_b = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10996 let multi_workspace_handle =
10997 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10998 cx.run_until_parked();
10999
11000 multi_workspace_handle
11001 .update(cx, |mw, _window, cx| mw.open_sidebar(cx))
11002 .unwrap();
11003
11004 let workspace_a = multi_workspace_handle
11005 .read_with(cx, |mw, _| mw.workspace().clone())
11006 .unwrap();
11007
11008 let workspace_b = multi_workspace_handle
11009 .update(cx, |mw, window, cx| {
11010 mw.test_add_workspace(project_b, window, cx)
11011 })
11012 .unwrap();
11013
11014 // Activate workspace A.
11015 multi_workspace_handle
11016 .update(cx, |mw, window, cx| {
11017 mw.activate(workspace_a.clone(), window, cx);
11018 })
11019 .unwrap();
11020
11021 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
11022
11023 // Workspace B has a dirty item.
11024 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
11025 workspace_b.update_in(cx, |w, window, cx| {
11026 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
11027 });
11028
11029 // Try to remove workspace B. It should prompt because of the dirty item.
11030 let remove_task = multi_workspace_handle
11031 .update(cx, |mw, window, cx| {
11032 mw.remove([workspace_b.clone()], |_, _, _| unreachable!(), window, cx)
11033 })
11034 .unwrap();
11035 cx.run_until_parked();
11036
11037 // The prompt should have activated workspace B.
11038 multi_workspace_handle
11039 .read_with(cx, |mw, _| {
11040 assert_eq!(
11041 mw.workspace(),
11042 &workspace_b,
11043 "workspace B should be active while prompting"
11044 );
11045 })
11046 .unwrap();
11047
11048 // Cancel the prompt — user stays on workspace B.
11049 cx.simulate_prompt_answer("Cancel");
11050 cx.run_until_parked();
11051 let removed = remove_task.await.unwrap();
11052 assert!(!removed, "removal should have been cancelled");
11053
11054 multi_workspace_handle
11055 .read_with(cx, |mw, _cx| {
11056 assert_eq!(
11057 mw.workspace(),
11058 &workspace_b,
11059 "user should stay on workspace B after cancelling"
11060 );
11061 assert_eq!(mw.workspaces().count(), 2, "both workspaces should remain");
11062 })
11063 .unwrap();
11064
11065 // Try again. This time accept the prompt.
11066 let remove_task = multi_workspace_handle
11067 .update(cx, |mw, window, cx| {
11068 // First switch back to A.
11069 mw.activate(workspace_a.clone(), window, cx);
11070 mw.remove([workspace_b.clone()], |_, _, _| unreachable!(), window, cx)
11071 })
11072 .unwrap();
11073 cx.run_until_parked();
11074
11075 // Accept the save prompt.
11076 cx.simulate_prompt_answer("Don't Save");
11077 cx.run_until_parked();
11078 let removed = remove_task.await.unwrap();
11079 assert!(removed, "removal should have succeeded");
11080
11081 // Should be back on workspace A, and B should be gone.
11082 multi_workspace_handle
11083 .read_with(cx, |mw, _cx| {
11084 assert_eq!(
11085 mw.workspace(),
11086 &workspace_a,
11087 "should be back on workspace A after removing B"
11088 );
11089 assert_eq!(mw.workspaces().count(), 1, "only workspace A should remain");
11090 })
11091 .unwrap();
11092 }
11093
11094 #[gpui::test]
11095 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
11096 init_test(cx);
11097
11098 // Register TestItem as a serializable item
11099 cx.update(|cx| {
11100 register_serializable_item::<TestItem>(cx);
11101 });
11102
11103 let fs = FakeFs::new(cx.executor());
11104 fs.insert_tree("/root", json!({ "one": "" })).await;
11105
11106 let project = Project::test(fs, ["root".as_ref()], cx).await;
11107 let (workspace, cx) =
11108 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
11109
11110 // When there are dirty untitled items, but they can serialize, then there is no prompt.
11111 let item1 = cx.new(|cx| {
11112 TestItem::new(cx)
11113 .with_dirty(true)
11114 .with_serialize(|| Some(Task::ready(Ok(()))))
11115 });
11116 let item2 = cx.new(|cx| {
11117 TestItem::new(cx)
11118 .with_dirty(true)
11119 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11120 .with_serialize(|| Some(Task::ready(Ok(()))))
11121 });
11122 workspace.update_in(cx, |w, window, cx| {
11123 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
11124 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
11125 });
11126 let task = workspace.update_in(cx, |w, window, cx| {
11127 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
11128 });
11129 assert!(task.await.unwrap());
11130 }
11131
11132 #[gpui::test]
11133 async fn test_close_pane_items(cx: &mut TestAppContext) {
11134 init_test(cx);
11135
11136 let fs = FakeFs::new(cx.executor());
11137
11138 let project = Project::test(fs, None, cx).await;
11139 let (workspace, cx) =
11140 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11141
11142 let item1 = cx.new(|cx| {
11143 TestItem::new(cx)
11144 .with_dirty(true)
11145 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
11146 });
11147 let item2 = cx.new(|cx| {
11148 TestItem::new(cx)
11149 .with_dirty(true)
11150 .with_conflict(true)
11151 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
11152 });
11153 let item3 = cx.new(|cx| {
11154 TestItem::new(cx)
11155 .with_dirty(true)
11156 .with_conflict(true)
11157 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
11158 });
11159 let item4 = cx.new(|cx| {
11160 TestItem::new(cx).with_dirty(true).with_project_items(&[{
11161 let project_item = TestProjectItem::new_untitled(cx);
11162 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11163 project_item
11164 }])
11165 });
11166 let pane = workspace.update_in(cx, |workspace, window, cx| {
11167 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
11168 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
11169 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
11170 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
11171 workspace.active_pane().clone()
11172 });
11173
11174 let close_items = pane.update_in(cx, |pane, window, cx| {
11175 pane.activate_item(1, true, true, window, cx);
11176 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11177 let item1_id = item1.item_id();
11178 let item3_id = item3.item_id();
11179 let item4_id = item4.item_id();
11180 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
11181 [item1_id, item3_id, item4_id].contains(&id)
11182 })
11183 });
11184 cx.executor().run_until_parked();
11185
11186 assert!(cx.has_pending_prompt());
11187 cx.simulate_prompt_answer("Save all");
11188
11189 cx.executor().run_until_parked();
11190
11191 // Item 1 is saved. There's a prompt to save item 3.
11192 pane.update(cx, |pane, cx| {
11193 assert_eq!(item1.read(cx).save_count, 1);
11194 assert_eq!(item1.read(cx).save_as_count, 0);
11195 assert_eq!(item1.read(cx).reload_count, 0);
11196 assert_eq!(pane.items_len(), 3);
11197 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
11198 });
11199 assert!(cx.has_pending_prompt());
11200
11201 // Cancel saving item 3.
11202 cx.simulate_prompt_answer("Discard");
11203 cx.executor().run_until_parked();
11204
11205 // Item 3 is reloaded. There's a prompt to save item 4.
11206 pane.update(cx, |pane, cx| {
11207 assert_eq!(item3.read(cx).save_count, 0);
11208 assert_eq!(item3.read(cx).save_as_count, 0);
11209 assert_eq!(item3.read(cx).reload_count, 1);
11210 assert_eq!(pane.items_len(), 2);
11211 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
11212 });
11213
11214 // There's a prompt for a path for item 4.
11215 cx.simulate_new_path_selection(|_| Some(Default::default()));
11216 close_items.await.unwrap();
11217
11218 // The requested items are closed.
11219 pane.update(cx, |pane, cx| {
11220 assert_eq!(item4.read(cx).save_count, 0);
11221 assert_eq!(item4.read(cx).save_as_count, 1);
11222 assert_eq!(item4.read(cx).reload_count, 0);
11223 assert_eq!(pane.items_len(), 1);
11224 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11225 });
11226 }
11227
11228 #[gpui::test]
11229 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
11230 init_test(cx);
11231
11232 let fs = FakeFs::new(cx.executor());
11233 let project = Project::test(fs, [], cx).await;
11234 let (workspace, cx) =
11235 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11236
11237 // Create several workspace items with single project entries, and two
11238 // workspace items with multiple project entries.
11239 let single_entry_items = (0..=4)
11240 .map(|project_entry_id| {
11241 cx.new(|cx| {
11242 TestItem::new(cx)
11243 .with_dirty(true)
11244 .with_project_items(&[dirty_project_item(
11245 project_entry_id,
11246 &format!("{project_entry_id}.txt"),
11247 cx,
11248 )])
11249 })
11250 })
11251 .collect::<Vec<_>>();
11252 let item_2_3 = cx.new(|cx| {
11253 TestItem::new(cx)
11254 .with_dirty(true)
11255 .with_buffer_kind(ItemBufferKind::Multibuffer)
11256 .with_project_items(&[
11257 single_entry_items[2].read(cx).project_items[0].clone(),
11258 single_entry_items[3].read(cx).project_items[0].clone(),
11259 ])
11260 });
11261 let item_3_4 = cx.new(|cx| {
11262 TestItem::new(cx)
11263 .with_dirty(true)
11264 .with_buffer_kind(ItemBufferKind::Multibuffer)
11265 .with_project_items(&[
11266 single_entry_items[3].read(cx).project_items[0].clone(),
11267 single_entry_items[4].read(cx).project_items[0].clone(),
11268 ])
11269 });
11270
11271 // Create two panes that contain the following project entries:
11272 // left pane:
11273 // multi-entry items: (2, 3)
11274 // single-entry items: 0, 2, 3, 4
11275 // right pane:
11276 // single-entry items: 4, 1
11277 // multi-entry items: (3, 4)
11278 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11279 let left_pane = workspace.active_pane().clone();
11280 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11281 workspace.add_item_to_active_pane(
11282 single_entry_items[0].boxed_clone(),
11283 None,
11284 true,
11285 window,
11286 cx,
11287 );
11288 workspace.add_item_to_active_pane(
11289 single_entry_items[2].boxed_clone(),
11290 None,
11291 true,
11292 window,
11293 cx,
11294 );
11295 workspace.add_item_to_active_pane(
11296 single_entry_items[3].boxed_clone(),
11297 None,
11298 true,
11299 window,
11300 cx,
11301 );
11302 workspace.add_item_to_active_pane(
11303 single_entry_items[4].boxed_clone(),
11304 None,
11305 true,
11306 window,
11307 cx,
11308 );
11309
11310 let right_pane =
11311 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11312
11313 let boxed_clone = single_entry_items[1].boxed_clone();
11314 let right_pane = window.spawn(cx, async move |cx| {
11315 right_pane.await.inspect(|right_pane| {
11316 right_pane
11317 .update_in(cx, |pane, window, cx| {
11318 pane.add_item(boxed_clone, true, true, None, window, cx);
11319 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11320 })
11321 .unwrap();
11322 })
11323 });
11324
11325 (left_pane, right_pane)
11326 });
11327 let right_pane = right_pane.await.unwrap();
11328 cx.focus(&right_pane);
11329
11330 let close = right_pane.update_in(cx, |pane, window, cx| {
11331 pane.close_all_items(&CloseAllItems::default(), window, cx)
11332 .unwrap()
11333 });
11334 cx.executor().run_until_parked();
11335
11336 let msg = cx.pending_prompt().unwrap().0;
11337 assert!(msg.contains("1.txt"));
11338 assert!(!msg.contains("2.txt"));
11339 assert!(!msg.contains("3.txt"));
11340 assert!(!msg.contains("4.txt"));
11341
11342 // With best-effort close, cancelling item 1 keeps it open but items 4
11343 // and (3,4) still close since their entries exist in left pane.
11344 cx.simulate_prompt_answer("Cancel");
11345 close.await;
11346
11347 right_pane.read_with(cx, |pane, _| {
11348 assert_eq!(pane.items_len(), 1);
11349 });
11350
11351 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11352 left_pane
11353 .update_in(cx, |left_pane, window, cx| {
11354 left_pane.close_item_by_id(
11355 single_entry_items[3].entity_id(),
11356 SaveIntent::Skip,
11357 window,
11358 cx,
11359 )
11360 })
11361 .await
11362 .unwrap();
11363
11364 let close = left_pane.update_in(cx, |pane, window, cx| {
11365 pane.close_all_items(&CloseAllItems::default(), window, cx)
11366 .unwrap()
11367 });
11368 cx.executor().run_until_parked();
11369
11370 let details = cx.pending_prompt().unwrap().1;
11371 assert!(details.contains("0.txt"));
11372 assert!(details.contains("3.txt"));
11373 assert!(details.contains("4.txt"));
11374 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11375 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11376 // assert!(!details.contains("2.txt"));
11377
11378 cx.simulate_prompt_answer("Save all");
11379 cx.executor().run_until_parked();
11380 close.await;
11381
11382 left_pane.read_with(cx, |pane, _| {
11383 assert_eq!(pane.items_len(), 0);
11384 });
11385 }
11386
11387 #[gpui::test]
11388 async fn test_autosave(cx: &mut gpui::TestAppContext) {
11389 init_test(cx);
11390
11391 let fs = FakeFs::new(cx.executor());
11392 let project = Project::test(fs, [], cx).await;
11393 let (workspace, cx) =
11394 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11395 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11396
11397 let item = cx.new(|cx| {
11398 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11399 });
11400 let item_id = item.entity_id();
11401 workspace.update_in(cx, |workspace, window, cx| {
11402 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11403 });
11404
11405 // Autosave on window change.
11406 item.update(cx, |item, cx| {
11407 SettingsStore::update_global(cx, |settings, cx| {
11408 settings.update_user_settings(cx, |settings| {
11409 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11410 })
11411 });
11412 item.is_dirty = true;
11413 });
11414
11415 // Deactivating the window saves the file.
11416 cx.deactivate_window();
11417 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11418
11419 // Re-activating the window doesn't save the file.
11420 cx.update(|window, _| window.activate_window());
11421 cx.executor().run_until_parked();
11422 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11423
11424 // Autosave on focus change.
11425 item.update_in(cx, |item, window, cx| {
11426 cx.focus_self(window);
11427 SettingsStore::update_global(cx, |settings, cx| {
11428 settings.update_user_settings(cx, |settings| {
11429 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11430 })
11431 });
11432 item.is_dirty = true;
11433 });
11434 // Blurring the item saves the file.
11435 item.update_in(cx, |_, window, _| window.blur());
11436 cx.executor().run_until_parked();
11437 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11438
11439 // Deactivating the window still saves the file.
11440 item.update_in(cx, |item, window, cx| {
11441 cx.focus_self(window);
11442 item.is_dirty = true;
11443 });
11444 cx.deactivate_window();
11445 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11446
11447 // Autosave after delay.
11448 item.update(cx, |item, cx| {
11449 SettingsStore::update_global(cx, |settings, cx| {
11450 settings.update_user_settings(cx, |settings| {
11451 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11452 milliseconds: 500.into(),
11453 });
11454 })
11455 });
11456 item.is_dirty = true;
11457 cx.emit(ItemEvent::Edit);
11458 });
11459
11460 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11461 cx.executor().advance_clock(Duration::from_millis(250));
11462 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11463
11464 // After delay expires, the file is saved.
11465 cx.executor().advance_clock(Duration::from_millis(250));
11466 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11467
11468 // Autosave after delay, should save earlier than delay if tab is closed
11469 item.update(cx, |item, cx| {
11470 item.is_dirty = true;
11471 cx.emit(ItemEvent::Edit);
11472 });
11473 cx.executor().advance_clock(Duration::from_millis(250));
11474 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11475
11476 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11477 pane.update_in(cx, |pane, window, cx| {
11478 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11479 })
11480 .await
11481 .unwrap();
11482 assert!(!cx.has_pending_prompt());
11483 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11484
11485 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11486 workspace.update_in(cx, |workspace, window, cx| {
11487 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11488 });
11489 item.update_in(cx, |item, _window, cx| {
11490 item.is_dirty = true;
11491 for project_item in &mut item.project_items {
11492 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11493 }
11494 });
11495 cx.run_until_parked();
11496 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11497
11498 // Autosave on focus change, ensuring closing the tab counts as such.
11499 item.update(cx, |item, cx| {
11500 SettingsStore::update_global(cx, |settings, cx| {
11501 settings.update_user_settings(cx, |settings| {
11502 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11503 })
11504 });
11505 item.is_dirty = true;
11506 for project_item in &mut item.project_items {
11507 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11508 }
11509 });
11510
11511 pane.update_in(cx, |pane, window, cx| {
11512 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11513 })
11514 .await
11515 .unwrap();
11516 assert!(!cx.has_pending_prompt());
11517 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11518
11519 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11520 workspace.update_in(cx, |workspace, window, cx| {
11521 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11522 });
11523 item.update_in(cx, |item, window, cx| {
11524 item.project_items[0].update(cx, |item, _| {
11525 item.entry_id = None;
11526 });
11527 item.is_dirty = true;
11528 window.blur();
11529 });
11530 cx.run_until_parked();
11531 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11532
11533 // Ensure autosave is prevented for deleted files also when closing the buffer.
11534 let _close_items = pane.update_in(cx, |pane, window, cx| {
11535 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11536 });
11537 cx.run_until_parked();
11538 assert!(cx.has_pending_prompt());
11539 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11540 }
11541
11542 #[gpui::test]
11543 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11544 init_test(cx);
11545
11546 let fs = FakeFs::new(cx.executor());
11547 let project = Project::test(fs, [], cx).await;
11548 let (workspace, cx) =
11549 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11550
11551 // Create a multibuffer-like item with two child focus handles,
11552 // simulating individual buffer editors within a multibuffer.
11553 let item = cx.new(|cx| {
11554 TestItem::new(cx)
11555 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11556 .with_child_focus_handles(2, cx)
11557 });
11558 workspace.update_in(cx, |workspace, window, cx| {
11559 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11560 });
11561
11562 // Set autosave to OnFocusChange and focus the first child handle,
11563 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11564 item.update_in(cx, |item, window, cx| {
11565 SettingsStore::update_global(cx, |settings, cx| {
11566 settings.update_user_settings(cx, |settings| {
11567 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11568 })
11569 });
11570 item.is_dirty = true;
11571 window.focus(&item.child_focus_handles[0], cx);
11572 });
11573 cx.executor().run_until_parked();
11574 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11575
11576 // Moving focus from one child to another within the same item should
11577 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11578 item.update_in(cx, |item, window, cx| {
11579 window.focus(&item.child_focus_handles[1], cx);
11580 });
11581 cx.executor().run_until_parked();
11582 item.read_with(cx, |item, _| {
11583 assert_eq!(
11584 item.save_count, 0,
11585 "Switching focus between children within the same item should not autosave"
11586 );
11587 });
11588
11589 // Blurring the item saves the file. This is the core regression scenario:
11590 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11591 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11592 // the leaf is always a child focus handle, so `on_blur` never detected
11593 // focus leaving the item.
11594 item.update_in(cx, |_, window, _| window.blur());
11595 cx.executor().run_until_parked();
11596 item.read_with(cx, |item, _| {
11597 assert_eq!(
11598 item.save_count, 1,
11599 "Blurring should trigger autosave when focus was on a child of the item"
11600 );
11601 });
11602
11603 // Deactivating the window should also trigger autosave when a child of
11604 // the multibuffer item currently owns focus.
11605 item.update_in(cx, |item, window, cx| {
11606 item.is_dirty = true;
11607 window.focus(&item.child_focus_handles[0], cx);
11608 });
11609 cx.executor().run_until_parked();
11610 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11611
11612 cx.deactivate_window();
11613 item.read_with(cx, |item, _| {
11614 assert_eq!(
11615 item.save_count, 2,
11616 "Deactivating window should trigger autosave when focus was on a child"
11617 );
11618 });
11619 }
11620
11621 #[gpui::test]
11622 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11623 init_test(cx);
11624
11625 let fs = FakeFs::new(cx.executor());
11626
11627 let project = Project::test(fs, [], cx).await;
11628 let (workspace, cx) =
11629 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11630
11631 let item = cx.new(|cx| {
11632 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11633 });
11634 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11635 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11636 let toolbar_notify_count = Rc::new(RefCell::new(0));
11637
11638 workspace.update_in(cx, |workspace, window, cx| {
11639 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11640 let toolbar_notification_count = toolbar_notify_count.clone();
11641 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11642 *toolbar_notification_count.borrow_mut() += 1
11643 })
11644 .detach();
11645 });
11646
11647 pane.read_with(cx, |pane, _| {
11648 assert!(!pane.can_navigate_backward());
11649 assert!(!pane.can_navigate_forward());
11650 });
11651
11652 item.update_in(cx, |item, _, cx| {
11653 item.set_state("one".to_string(), cx);
11654 });
11655
11656 // Toolbar must be notified to re-render the navigation buttons
11657 assert_eq!(*toolbar_notify_count.borrow(), 1);
11658
11659 pane.read_with(cx, |pane, _| {
11660 assert!(pane.can_navigate_backward());
11661 assert!(!pane.can_navigate_forward());
11662 });
11663
11664 workspace
11665 .update_in(cx, |workspace, window, cx| {
11666 workspace.go_back(pane.downgrade(), window, cx)
11667 })
11668 .await
11669 .unwrap();
11670
11671 assert_eq!(*toolbar_notify_count.borrow(), 2);
11672 pane.read_with(cx, |pane, _| {
11673 assert!(!pane.can_navigate_backward());
11674 assert!(pane.can_navigate_forward());
11675 });
11676 }
11677
11678 /// Tests that the navigation history deduplicates entries for the same item.
11679 ///
11680 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11681 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11682 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11683 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11684 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11685 ///
11686 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11687 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11688 #[gpui::test]
11689 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11690 init_test(cx);
11691
11692 let fs = FakeFs::new(cx.executor());
11693 let project = Project::test(fs, [], cx).await;
11694 let (workspace, cx) =
11695 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11696
11697 let item_a = cx.new(|cx| {
11698 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11699 });
11700 let item_b = cx.new(|cx| {
11701 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11702 });
11703 let item_c = cx.new(|cx| {
11704 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11705 });
11706
11707 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11708
11709 workspace.update_in(cx, |workspace, window, cx| {
11710 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11711 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11712 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11713 });
11714
11715 workspace.update_in(cx, |workspace, window, cx| {
11716 workspace.activate_item(&item_a, false, false, window, cx);
11717 });
11718 cx.run_until_parked();
11719
11720 workspace.update_in(cx, |workspace, window, cx| {
11721 workspace.activate_item(&item_b, false, false, window, cx);
11722 });
11723 cx.run_until_parked();
11724
11725 workspace.update_in(cx, |workspace, window, cx| {
11726 workspace.activate_item(&item_a, false, false, window, cx);
11727 });
11728 cx.run_until_parked();
11729
11730 workspace.update_in(cx, |workspace, window, cx| {
11731 workspace.activate_item(&item_b, false, false, window, cx);
11732 });
11733 cx.run_until_parked();
11734
11735 workspace.update_in(cx, |workspace, window, cx| {
11736 workspace.activate_item(&item_a, false, false, window, cx);
11737 });
11738 cx.run_until_parked();
11739
11740 workspace.update_in(cx, |workspace, window, cx| {
11741 workspace.activate_item(&item_b, false, false, window, cx);
11742 });
11743 cx.run_until_parked();
11744
11745 workspace.update_in(cx, |workspace, window, cx| {
11746 workspace.activate_item(&item_c, false, false, window, cx);
11747 });
11748 cx.run_until_parked();
11749
11750 let backward_count = pane.read_with(cx, |pane, cx| {
11751 let mut count = 0;
11752 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11753 count += 1;
11754 });
11755 count
11756 });
11757 assert!(
11758 backward_count <= 4,
11759 "Should have at most 4 entries, got {}",
11760 backward_count
11761 );
11762
11763 workspace
11764 .update_in(cx, |workspace, window, cx| {
11765 workspace.go_back(pane.downgrade(), window, cx)
11766 })
11767 .await
11768 .unwrap();
11769
11770 let active_item = workspace.read_with(cx, |workspace, cx| {
11771 workspace.active_item(cx).unwrap().item_id()
11772 });
11773 assert_eq!(
11774 active_item,
11775 item_b.entity_id(),
11776 "After first go_back, should be at item B"
11777 );
11778
11779 workspace
11780 .update_in(cx, |workspace, window, cx| {
11781 workspace.go_back(pane.downgrade(), window, cx)
11782 })
11783 .await
11784 .unwrap();
11785
11786 let active_item = workspace.read_with(cx, |workspace, cx| {
11787 workspace.active_item(cx).unwrap().item_id()
11788 });
11789 assert_eq!(
11790 active_item,
11791 item_a.entity_id(),
11792 "After second go_back, should be at item A"
11793 );
11794
11795 pane.read_with(cx, |pane, _| {
11796 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11797 });
11798 }
11799
11800 #[gpui::test]
11801 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11802 init_test(cx);
11803 let fs = FakeFs::new(cx.executor());
11804 let project = Project::test(fs, [], cx).await;
11805 let (multi_workspace, cx) =
11806 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11807 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11808
11809 workspace.update_in(cx, |workspace, window, cx| {
11810 let first_item = cx.new(|cx| {
11811 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11812 });
11813 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11814 workspace.split_pane(
11815 workspace.active_pane().clone(),
11816 SplitDirection::Right,
11817 window,
11818 cx,
11819 );
11820 workspace.split_pane(
11821 workspace.active_pane().clone(),
11822 SplitDirection::Right,
11823 window,
11824 cx,
11825 );
11826 });
11827
11828 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11829 let panes = workspace.center.panes();
11830 assert!(panes.len() >= 2);
11831 (
11832 panes.first().expect("at least one pane").entity_id(),
11833 panes.last().expect("at least one pane").entity_id(),
11834 )
11835 });
11836
11837 workspace.update_in(cx, |workspace, window, cx| {
11838 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11839 });
11840 workspace.update(cx, |workspace, _| {
11841 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11842 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11843 });
11844
11845 cx.dispatch_action(ActivateLastPane);
11846
11847 workspace.update(cx, |workspace, _| {
11848 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11849 });
11850 }
11851
11852 #[gpui::test]
11853 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11854 init_test(cx);
11855 let fs = FakeFs::new(cx.executor());
11856
11857 let project = Project::test(fs, [], cx).await;
11858 let (workspace, cx) =
11859 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11860
11861 let panel = workspace.update_in(cx, |workspace, window, cx| {
11862 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11863 workspace.add_panel(panel.clone(), window, cx);
11864
11865 workspace
11866 .right_dock()
11867 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11868
11869 panel
11870 });
11871
11872 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11873 pane.update_in(cx, |pane, window, cx| {
11874 let item = cx.new(TestItem::new);
11875 pane.add_item(Box::new(item), true, true, None, window, cx);
11876 });
11877
11878 // Transfer focus from center to panel
11879 workspace.update_in(cx, |workspace, window, cx| {
11880 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11881 });
11882
11883 workspace.update_in(cx, |workspace, window, cx| {
11884 assert!(workspace.right_dock().read(cx).is_open());
11885 assert!(!panel.is_zoomed(window, cx));
11886 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11887 });
11888
11889 // Transfer focus from panel to center
11890 workspace.update_in(cx, |workspace, window, cx| {
11891 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11892 });
11893
11894 workspace.update_in(cx, |workspace, window, cx| {
11895 assert!(workspace.right_dock().read(cx).is_open());
11896 assert!(!panel.is_zoomed(window, cx));
11897 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11898 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11899 });
11900
11901 // Close the dock
11902 workspace.update_in(cx, |workspace, window, cx| {
11903 workspace.toggle_dock(DockPosition::Right, 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 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11911 });
11912
11913 // Open the dock
11914 workspace.update_in(cx, |workspace, window, cx| {
11915 workspace.toggle_dock(DockPosition::Right, window, cx);
11916 });
11917
11918 workspace.update_in(cx, |workspace, window, cx| {
11919 assert!(workspace.right_dock().read(cx).is_open());
11920 assert!(!panel.is_zoomed(window, cx));
11921 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11922 });
11923
11924 // Focus and zoom panel
11925 panel.update_in(cx, |panel, window, cx| {
11926 cx.focus_self(window);
11927 panel.set_zoomed(true, window, cx)
11928 });
11929
11930 workspace.update_in(cx, |workspace, window, cx| {
11931 assert!(workspace.right_dock().read(cx).is_open());
11932 assert!(panel.is_zoomed(window, cx));
11933 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11934 });
11935
11936 // Transfer focus to the center closes the dock
11937 workspace.update_in(cx, |workspace, window, cx| {
11938 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11939 });
11940
11941 workspace.update_in(cx, |workspace, window, cx| {
11942 assert!(!workspace.right_dock().read(cx).is_open());
11943 assert!(panel.is_zoomed(window, cx));
11944 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11945 });
11946
11947 // Transferring focus back to the panel keeps it zoomed
11948 workspace.update_in(cx, |workspace, window, cx| {
11949 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11950 });
11951
11952 workspace.update_in(cx, |workspace, window, cx| {
11953 assert!(workspace.right_dock().read(cx).is_open());
11954 assert!(panel.is_zoomed(window, cx));
11955 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11956 });
11957
11958 // Close the dock while it is zoomed
11959 workspace.update_in(cx, |workspace, window, cx| {
11960 workspace.toggle_dock(DockPosition::Right, window, cx)
11961 });
11962
11963 workspace.update_in(cx, |workspace, window, cx| {
11964 assert!(!workspace.right_dock().read(cx).is_open());
11965 assert!(panel.is_zoomed(window, cx));
11966 assert!(workspace.zoomed.is_none());
11967 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11968 });
11969
11970 // Opening the dock, when it's zoomed, retains focus
11971 workspace.update_in(cx, |workspace, window, cx| {
11972 workspace.toggle_dock(DockPosition::Right, window, cx)
11973 });
11974
11975 workspace.update_in(cx, |workspace, window, cx| {
11976 assert!(workspace.right_dock().read(cx).is_open());
11977 assert!(panel.is_zoomed(window, cx));
11978 assert!(workspace.zoomed.is_some());
11979 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11980 });
11981
11982 // Unzoom and close the panel, zoom the active pane.
11983 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11984 workspace.update_in(cx, |workspace, window, cx| {
11985 workspace.toggle_dock(DockPosition::Right, window, cx)
11986 });
11987 pane.update_in(cx, |pane, window, cx| {
11988 pane.toggle_zoom(&Default::default(), window, cx)
11989 });
11990
11991 // Opening a dock unzooms the pane.
11992 workspace.update_in(cx, |workspace, window, cx| {
11993 workspace.toggle_dock(DockPosition::Right, window, cx)
11994 });
11995 workspace.update_in(cx, |workspace, window, cx| {
11996 let pane = pane.read(cx);
11997 assert!(!pane.is_zoomed());
11998 assert!(!pane.focus_handle(cx).is_focused(window));
11999 assert!(workspace.right_dock().read(cx).is_open());
12000 assert!(workspace.zoomed.is_none());
12001 });
12002 }
12003
12004 #[gpui::test]
12005 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
12006 init_test(cx);
12007 let fs = FakeFs::new(cx.executor());
12008
12009 let project = Project::test(fs, [], cx).await;
12010 let (workspace, cx) =
12011 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12012
12013 let panel = workspace.update_in(cx, |workspace, window, cx| {
12014 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12015 workspace.add_panel(panel.clone(), window, cx);
12016 panel
12017 });
12018
12019 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12020 pane.update_in(cx, |pane, window, cx| {
12021 let item = cx.new(TestItem::new);
12022 pane.add_item(Box::new(item), true, true, None, window, cx);
12023 });
12024
12025 // Enable close_panel_on_toggle
12026 cx.update_global(|store: &mut SettingsStore, cx| {
12027 store.update_user_settings(cx, |settings| {
12028 settings.workspace.close_panel_on_toggle = Some(true);
12029 });
12030 });
12031
12032 // Panel starts closed. Toggling should open and focus it.
12033 workspace.update_in(cx, |workspace, window, cx| {
12034 assert!(!workspace.right_dock().read(cx).is_open());
12035 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12036 });
12037
12038 workspace.update_in(cx, |workspace, window, cx| {
12039 assert!(
12040 workspace.right_dock().read(cx).is_open(),
12041 "Dock should be open after toggling from center"
12042 );
12043 assert!(
12044 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12045 "Panel should be focused after toggling from center"
12046 );
12047 });
12048
12049 // Panel is open and focused. Toggling should close the panel and
12050 // return focus to the center.
12051 workspace.update_in(cx, |workspace, window, cx| {
12052 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12053 });
12054
12055 workspace.update_in(cx, |workspace, window, cx| {
12056 assert!(
12057 !workspace.right_dock().read(cx).is_open(),
12058 "Dock should be closed after toggling from focused panel"
12059 );
12060 assert!(
12061 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12062 "Panel should not be focused after toggling from focused panel"
12063 );
12064 });
12065
12066 // Open the dock and focus something else so the panel is open but not
12067 // focused. Toggling should focus the panel (not close it).
12068 workspace.update_in(cx, |workspace, window, cx| {
12069 workspace
12070 .right_dock()
12071 .update(cx, |dock, cx| dock.set_open(true, window, cx));
12072 window.focus(&pane.read(cx).focus_handle(cx), cx);
12073 });
12074
12075 workspace.update_in(cx, |workspace, window, cx| {
12076 assert!(workspace.right_dock().read(cx).is_open());
12077 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
12078 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12079 });
12080
12081 workspace.update_in(cx, |workspace, window, cx| {
12082 assert!(
12083 workspace.right_dock().read(cx).is_open(),
12084 "Dock should remain open when toggling focuses an open-but-unfocused panel"
12085 );
12086 assert!(
12087 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12088 "Panel should be focused after toggling an open-but-unfocused panel"
12089 );
12090 });
12091
12092 // Now disable the setting and verify the original behavior: toggling
12093 // from a focused panel moves focus to center but leaves the dock open.
12094 cx.update_global(|store: &mut SettingsStore, cx| {
12095 store.update_user_settings(cx, |settings| {
12096 settings.workspace.close_panel_on_toggle = Some(false);
12097 });
12098 });
12099
12100 workspace.update_in(cx, |workspace, window, cx| {
12101 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12102 });
12103
12104 workspace.update_in(cx, |workspace, window, cx| {
12105 assert!(
12106 workspace.right_dock().read(cx).is_open(),
12107 "Dock should remain open when setting is disabled"
12108 );
12109 assert!(
12110 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
12111 "Panel should not be focused after toggling with setting disabled"
12112 );
12113 });
12114 }
12115
12116 #[gpui::test]
12117 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
12118 init_test(cx);
12119 let fs = FakeFs::new(cx.executor());
12120
12121 let project = Project::test(fs, [], cx).await;
12122 let (workspace, cx) =
12123 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12124
12125 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
12126 workspace.active_pane().clone()
12127 });
12128
12129 // Add an item to the pane so it can be zoomed
12130 workspace.update_in(cx, |workspace, window, cx| {
12131 let item = cx.new(TestItem::new);
12132 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
12133 });
12134
12135 // Initially not zoomed
12136 workspace.update_in(cx, |workspace, _window, cx| {
12137 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
12138 assert!(
12139 workspace.zoomed.is_none(),
12140 "Workspace should track no zoomed pane"
12141 );
12142 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
12143 });
12144
12145 // Zoom In
12146 pane.update_in(cx, |pane, window, cx| {
12147 pane.zoom_in(&crate::ZoomIn, window, cx);
12148 });
12149
12150 workspace.update_in(cx, |workspace, window, cx| {
12151 assert!(
12152 pane.read(cx).is_zoomed(),
12153 "Pane should be zoomed after ZoomIn"
12154 );
12155 assert!(
12156 workspace.zoomed.is_some(),
12157 "Workspace should track the zoomed pane"
12158 );
12159 assert!(
12160 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
12161 "ZoomIn should focus the pane"
12162 );
12163 });
12164
12165 // Zoom In again is a no-op
12166 pane.update_in(cx, |pane, window, cx| {
12167 pane.zoom_in(&crate::ZoomIn, window, cx);
12168 });
12169
12170 workspace.update_in(cx, |workspace, window, cx| {
12171 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
12172 assert!(
12173 workspace.zoomed.is_some(),
12174 "Workspace still tracks zoomed pane"
12175 );
12176 assert!(
12177 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
12178 "Pane remains focused after repeated ZoomIn"
12179 );
12180 });
12181
12182 // Zoom Out
12183 pane.update_in(cx, |pane, window, cx| {
12184 pane.zoom_out(&crate::ZoomOut, window, cx);
12185 });
12186
12187 workspace.update_in(cx, |workspace, _window, cx| {
12188 assert!(
12189 !pane.read(cx).is_zoomed(),
12190 "Pane should unzoom after ZoomOut"
12191 );
12192 assert!(
12193 workspace.zoomed.is_none(),
12194 "Workspace clears zoom tracking after ZoomOut"
12195 );
12196 });
12197
12198 // Zoom Out again is a no-op
12199 pane.update_in(cx, |pane, window, cx| {
12200 pane.zoom_out(&crate::ZoomOut, window, cx);
12201 });
12202
12203 workspace.update_in(cx, |workspace, _window, cx| {
12204 assert!(
12205 !pane.read(cx).is_zoomed(),
12206 "Second ZoomOut keeps pane unzoomed"
12207 );
12208 assert!(
12209 workspace.zoomed.is_none(),
12210 "Workspace remains without zoomed pane"
12211 );
12212 });
12213 }
12214
12215 #[gpui::test]
12216 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
12217 init_test(cx);
12218 let fs = FakeFs::new(cx.executor());
12219
12220 let project = Project::test(fs, [], cx).await;
12221 let (workspace, cx) =
12222 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12223 workspace.update_in(cx, |workspace, window, cx| {
12224 // Open two docks
12225 let left_dock = workspace.dock_at_position(DockPosition::Left);
12226 let right_dock = workspace.dock_at_position(DockPosition::Right);
12227
12228 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12229 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12230
12231 assert!(left_dock.read(cx).is_open());
12232 assert!(right_dock.read(cx).is_open());
12233 });
12234
12235 workspace.update_in(cx, |workspace, window, cx| {
12236 // Toggle all docks - should close both
12237 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12238
12239 let left_dock = workspace.dock_at_position(DockPosition::Left);
12240 let right_dock = workspace.dock_at_position(DockPosition::Right);
12241 assert!(!left_dock.read(cx).is_open());
12242 assert!(!right_dock.read(cx).is_open());
12243 });
12244
12245 workspace.update_in(cx, |workspace, window, cx| {
12246 // Toggle again - should reopen both
12247 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12248
12249 let left_dock = workspace.dock_at_position(DockPosition::Left);
12250 let right_dock = workspace.dock_at_position(DockPosition::Right);
12251 assert!(left_dock.read(cx).is_open());
12252 assert!(right_dock.read(cx).is_open());
12253 });
12254 }
12255
12256 #[gpui::test]
12257 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
12258 init_test(cx);
12259 let fs = FakeFs::new(cx.executor());
12260
12261 let project = Project::test(fs, [], cx).await;
12262 let (workspace, cx) =
12263 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12264 workspace.update_in(cx, |workspace, window, cx| {
12265 // Open two docks
12266 let left_dock = workspace.dock_at_position(DockPosition::Left);
12267 let right_dock = workspace.dock_at_position(DockPosition::Right);
12268
12269 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12270 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12271
12272 assert!(left_dock.read(cx).is_open());
12273 assert!(right_dock.read(cx).is_open());
12274 });
12275
12276 workspace.update_in(cx, |workspace, window, cx| {
12277 // Close them manually
12278 workspace.toggle_dock(DockPosition::Left, window, cx);
12279 workspace.toggle_dock(DockPosition::Right, window, cx);
12280
12281 let left_dock = workspace.dock_at_position(DockPosition::Left);
12282 let right_dock = workspace.dock_at_position(DockPosition::Right);
12283 assert!(!left_dock.read(cx).is_open());
12284 assert!(!right_dock.read(cx).is_open());
12285 });
12286
12287 workspace.update_in(cx, |workspace, window, cx| {
12288 // Toggle all docks - only last closed (right dock) should reopen
12289 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12290
12291 let left_dock = workspace.dock_at_position(DockPosition::Left);
12292 let right_dock = workspace.dock_at_position(DockPosition::Right);
12293 assert!(!left_dock.read(cx).is_open());
12294 assert!(right_dock.read(cx).is_open());
12295 });
12296 }
12297
12298 #[gpui::test]
12299 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12300 init_test(cx);
12301 let fs = FakeFs::new(cx.executor());
12302 let project = Project::test(fs, [], cx).await;
12303 let (multi_workspace, cx) =
12304 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12305 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12306
12307 // Open two docks (left and right) with one panel each
12308 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12309 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12310 workspace.add_panel(left_panel.clone(), window, cx);
12311
12312 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12313 workspace.add_panel(right_panel.clone(), window, cx);
12314
12315 workspace.toggle_dock(DockPosition::Left, window, cx);
12316 workspace.toggle_dock(DockPosition::Right, window, cx);
12317
12318 // Verify initial state
12319 assert!(
12320 workspace.left_dock().read(cx).is_open(),
12321 "Left dock should be open"
12322 );
12323 assert_eq!(
12324 workspace
12325 .left_dock()
12326 .read(cx)
12327 .visible_panel()
12328 .unwrap()
12329 .panel_id(),
12330 left_panel.panel_id(),
12331 "Left panel should be visible in left dock"
12332 );
12333 assert!(
12334 workspace.right_dock().read(cx).is_open(),
12335 "Right dock should be open"
12336 );
12337 assert_eq!(
12338 workspace
12339 .right_dock()
12340 .read(cx)
12341 .visible_panel()
12342 .unwrap()
12343 .panel_id(),
12344 right_panel.panel_id(),
12345 "Right panel should be visible in right dock"
12346 );
12347 assert!(
12348 !workspace.bottom_dock().read(cx).is_open(),
12349 "Bottom dock should be closed"
12350 );
12351
12352 (left_panel, right_panel)
12353 });
12354
12355 // Focus the left panel and move it to the next position (bottom dock)
12356 workspace.update_in(cx, |workspace, window, cx| {
12357 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12358 assert!(
12359 left_panel.read(cx).focus_handle(cx).is_focused(window),
12360 "Left panel should be focused"
12361 );
12362 });
12363
12364 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12365
12366 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12367 workspace.update(cx, |workspace, cx| {
12368 assert!(
12369 !workspace.left_dock().read(cx).is_open(),
12370 "Left dock should be closed"
12371 );
12372 assert!(
12373 workspace.bottom_dock().read(cx).is_open(),
12374 "Bottom dock should now be open"
12375 );
12376 assert_eq!(
12377 left_panel.read(cx).position,
12378 DockPosition::Bottom,
12379 "Left panel should now be in the bottom dock"
12380 );
12381 assert_eq!(
12382 workspace
12383 .bottom_dock()
12384 .read(cx)
12385 .visible_panel()
12386 .unwrap()
12387 .panel_id(),
12388 left_panel.panel_id(),
12389 "Left panel should be the visible panel in the bottom dock"
12390 );
12391 });
12392
12393 // Toggle all docks off
12394 workspace.update_in(cx, |workspace, window, cx| {
12395 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12396 assert!(
12397 !workspace.left_dock().read(cx).is_open(),
12398 "Left dock should be closed"
12399 );
12400 assert!(
12401 !workspace.right_dock().read(cx).is_open(),
12402 "Right dock should be closed"
12403 );
12404 assert!(
12405 !workspace.bottom_dock().read(cx).is_open(),
12406 "Bottom dock should be closed"
12407 );
12408 });
12409
12410 // Toggle all docks back on and verify positions are restored
12411 workspace.update_in(cx, |workspace, window, cx| {
12412 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12413 assert!(
12414 !workspace.left_dock().read(cx).is_open(),
12415 "Left dock should remain closed"
12416 );
12417 assert!(
12418 workspace.right_dock().read(cx).is_open(),
12419 "Right dock should remain open"
12420 );
12421 assert!(
12422 workspace.bottom_dock().read(cx).is_open(),
12423 "Bottom dock should remain open"
12424 );
12425 assert_eq!(
12426 left_panel.read(cx).position,
12427 DockPosition::Bottom,
12428 "Left panel should remain in the bottom dock"
12429 );
12430 assert_eq!(
12431 right_panel.read(cx).position,
12432 DockPosition::Right,
12433 "Right panel should remain in the right dock"
12434 );
12435 assert_eq!(
12436 workspace
12437 .bottom_dock()
12438 .read(cx)
12439 .visible_panel()
12440 .unwrap()
12441 .panel_id(),
12442 left_panel.panel_id(),
12443 "Left panel should be the visible panel in the right dock"
12444 );
12445 });
12446 }
12447
12448 #[gpui::test]
12449 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12450 init_test(cx);
12451
12452 let fs = FakeFs::new(cx.executor());
12453
12454 let project = Project::test(fs, None, cx).await;
12455 let (workspace, cx) =
12456 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12457
12458 // Let's arrange the panes like this:
12459 //
12460 // +-----------------------+
12461 // | top |
12462 // +------+--------+-------+
12463 // | left | center | right |
12464 // +------+--------+-------+
12465 // | bottom |
12466 // +-----------------------+
12467
12468 let top_item = cx.new(|cx| {
12469 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12470 });
12471 let bottom_item = cx.new(|cx| {
12472 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12473 });
12474 let left_item = cx.new(|cx| {
12475 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12476 });
12477 let right_item = cx.new(|cx| {
12478 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12479 });
12480 let center_item = cx.new(|cx| {
12481 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12482 });
12483
12484 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12485 let top_pane_id = workspace.active_pane().entity_id();
12486 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12487 workspace.split_pane(
12488 workspace.active_pane().clone(),
12489 SplitDirection::Down,
12490 window,
12491 cx,
12492 );
12493 top_pane_id
12494 });
12495 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12496 let bottom_pane_id = workspace.active_pane().entity_id();
12497 workspace.add_item_to_active_pane(
12498 Box::new(bottom_item.clone()),
12499 None,
12500 false,
12501 window,
12502 cx,
12503 );
12504 workspace.split_pane(
12505 workspace.active_pane().clone(),
12506 SplitDirection::Up,
12507 window,
12508 cx,
12509 );
12510 bottom_pane_id
12511 });
12512 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12513 let left_pane_id = workspace.active_pane().entity_id();
12514 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12515 workspace.split_pane(
12516 workspace.active_pane().clone(),
12517 SplitDirection::Right,
12518 window,
12519 cx,
12520 );
12521 left_pane_id
12522 });
12523 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12524 let right_pane_id = workspace.active_pane().entity_id();
12525 workspace.add_item_to_active_pane(
12526 Box::new(right_item.clone()),
12527 None,
12528 false,
12529 window,
12530 cx,
12531 );
12532 workspace.split_pane(
12533 workspace.active_pane().clone(),
12534 SplitDirection::Left,
12535 window,
12536 cx,
12537 );
12538 right_pane_id
12539 });
12540 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12541 let center_pane_id = workspace.active_pane().entity_id();
12542 workspace.add_item_to_active_pane(
12543 Box::new(center_item.clone()),
12544 None,
12545 false,
12546 window,
12547 cx,
12548 );
12549 center_pane_id
12550 });
12551 cx.executor().run_until_parked();
12552
12553 workspace.update_in(cx, |workspace, window, cx| {
12554 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12555
12556 // Join into next from center pane into right
12557 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12558 });
12559
12560 workspace.update_in(cx, |workspace, window, cx| {
12561 let active_pane = workspace.active_pane();
12562 assert_eq!(right_pane_id, active_pane.entity_id());
12563 assert_eq!(2, active_pane.read(cx).items_len());
12564 let item_ids_in_pane =
12565 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12566 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12567 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12568
12569 // Join into next from right pane into bottom
12570 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12571 });
12572
12573 workspace.update_in(cx, |workspace, window, cx| {
12574 let active_pane = workspace.active_pane();
12575 assert_eq!(bottom_pane_id, active_pane.entity_id());
12576 assert_eq!(3, active_pane.read(cx).items_len());
12577 let item_ids_in_pane =
12578 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12579 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12580 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12581 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12582
12583 // Join into next from bottom pane into left
12584 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12585 });
12586
12587 workspace.update_in(cx, |workspace, window, cx| {
12588 let active_pane = workspace.active_pane();
12589 assert_eq!(left_pane_id, active_pane.entity_id());
12590 assert_eq!(4, active_pane.read(cx).items_len());
12591 let item_ids_in_pane =
12592 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12593 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12594 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12595 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12596 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12597
12598 // Join into next from left pane into top
12599 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12600 });
12601
12602 workspace.update_in(cx, |workspace, window, cx| {
12603 let active_pane = workspace.active_pane();
12604 assert_eq!(top_pane_id, active_pane.entity_id());
12605 assert_eq!(5, active_pane.read(cx).items_len());
12606 let item_ids_in_pane =
12607 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12608 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12609 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12610 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12611 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12612 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12613
12614 // Single pane left: no-op
12615 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12616 });
12617
12618 workspace.update(cx, |workspace, _cx| {
12619 let active_pane = workspace.active_pane();
12620 assert_eq!(top_pane_id, active_pane.entity_id());
12621 });
12622 }
12623
12624 fn add_an_item_to_active_pane(
12625 cx: &mut VisualTestContext,
12626 workspace: &Entity<Workspace>,
12627 item_id: u64,
12628 ) -> Entity<TestItem> {
12629 let item = cx.new(|cx| {
12630 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12631 item_id,
12632 "item{item_id}.txt",
12633 cx,
12634 )])
12635 });
12636 workspace.update_in(cx, |workspace, window, cx| {
12637 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12638 });
12639 item
12640 }
12641
12642 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12643 workspace.update_in(cx, |workspace, window, cx| {
12644 workspace.split_pane(
12645 workspace.active_pane().clone(),
12646 SplitDirection::Right,
12647 window,
12648 cx,
12649 )
12650 })
12651 }
12652
12653 #[gpui::test]
12654 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12655 init_test(cx);
12656 let fs = FakeFs::new(cx.executor());
12657 let project = Project::test(fs, None, cx).await;
12658 let (workspace, cx) =
12659 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12660
12661 add_an_item_to_active_pane(cx, &workspace, 1);
12662 split_pane(cx, &workspace);
12663 add_an_item_to_active_pane(cx, &workspace, 2);
12664 split_pane(cx, &workspace); // empty pane
12665 split_pane(cx, &workspace);
12666 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12667
12668 cx.executor().run_until_parked();
12669
12670 workspace.update(cx, |workspace, cx| {
12671 let num_panes = workspace.panes().len();
12672 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12673 let active_item = workspace
12674 .active_pane()
12675 .read(cx)
12676 .active_item()
12677 .expect("item is in focus");
12678
12679 assert_eq!(num_panes, 4);
12680 assert_eq!(num_items_in_current_pane, 1);
12681 assert_eq!(active_item.item_id(), last_item.item_id());
12682 });
12683
12684 workspace.update_in(cx, |workspace, window, cx| {
12685 workspace.join_all_panes(window, cx);
12686 });
12687
12688 workspace.update(cx, |workspace, cx| {
12689 let num_panes = workspace.panes().len();
12690 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12691 let active_item = workspace
12692 .active_pane()
12693 .read(cx)
12694 .active_item()
12695 .expect("item is in focus");
12696
12697 assert_eq!(num_panes, 1);
12698 assert_eq!(num_items_in_current_pane, 3);
12699 assert_eq!(active_item.item_id(), last_item.item_id());
12700 });
12701 }
12702
12703 #[gpui::test]
12704 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12705 init_test(cx);
12706 let fs = FakeFs::new(cx.executor());
12707
12708 let project = Project::test(fs, [], cx).await;
12709 let (multi_workspace, cx) =
12710 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12711 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12712
12713 workspace.update(cx, |workspace, _cx| {
12714 workspace.bounds.size.width = px(800.);
12715 });
12716
12717 workspace.update_in(cx, |workspace, window, cx| {
12718 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12719 workspace.add_panel(panel, window, cx);
12720 workspace.toggle_dock(DockPosition::Right, window, cx);
12721 });
12722
12723 let (panel, resized_width, ratio_basis_width) =
12724 workspace.update_in(cx, |workspace, window, cx| {
12725 let item = cx.new(|cx| {
12726 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12727 });
12728 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12729
12730 let dock = workspace.right_dock().read(cx);
12731 let workspace_width = workspace.bounds.size.width;
12732 let initial_width = workspace
12733 .dock_size(&dock, window, cx)
12734 .expect("flexible dock should have an initial width");
12735
12736 assert_eq!(initial_width, workspace_width / 2.);
12737
12738 workspace.resize_right_dock(px(300.), window, cx);
12739
12740 let dock = workspace.right_dock().read(cx);
12741 let resized_width = workspace
12742 .dock_size(&dock, window, cx)
12743 .expect("flexible dock should keep its resized width");
12744
12745 assert_eq!(resized_width, px(300.));
12746
12747 let panel = workspace
12748 .right_dock()
12749 .read(cx)
12750 .visible_panel()
12751 .expect("flexible dock should have a visible panel")
12752 .panel_id();
12753
12754 (panel, resized_width, workspace_width)
12755 });
12756
12757 workspace.update_in(cx, |workspace, window, cx| {
12758 workspace.toggle_dock(DockPosition::Right, window, cx);
12759 workspace.toggle_dock(DockPosition::Right, window, cx);
12760
12761 let dock = workspace.right_dock().read(cx);
12762 let reopened_width = workspace
12763 .dock_size(&dock, window, cx)
12764 .expect("flexible dock should restore when reopened");
12765
12766 assert_eq!(reopened_width, resized_width);
12767
12768 let right_dock = workspace.right_dock().read(cx);
12769 let flexible_panel = right_dock
12770 .visible_panel()
12771 .expect("flexible dock should still have a visible panel");
12772 assert_eq!(flexible_panel.panel_id(), panel);
12773 assert_eq!(
12774 right_dock
12775 .stored_panel_size_state(flexible_panel.as_ref())
12776 .and_then(|size_state| size_state.flex),
12777 Some(
12778 resized_width.to_f64() as f32
12779 / (workspace.bounds.size.width - resized_width).to_f64() as f32
12780 )
12781 );
12782 });
12783
12784 workspace.update_in(cx, |workspace, window, cx| {
12785 workspace.split_pane(
12786 workspace.active_pane().clone(),
12787 SplitDirection::Right,
12788 window,
12789 cx,
12790 );
12791
12792 let dock = workspace.right_dock().read(cx);
12793 let split_width = workspace
12794 .dock_size(&dock, window, cx)
12795 .expect("flexible dock should keep its user-resized proportion");
12796
12797 assert_eq!(split_width, px(300.));
12798
12799 workspace.bounds.size.width = px(1600.);
12800
12801 let dock = workspace.right_dock().read(cx);
12802 let resized_window_width = workspace
12803 .dock_size(&dock, window, cx)
12804 .expect("flexible dock should preserve proportional size on window resize");
12805
12806 assert_eq!(
12807 resized_window_width,
12808 workspace.bounds.size.width
12809 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12810 );
12811 });
12812 }
12813
12814 #[gpui::test]
12815 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12816 init_test(cx);
12817 let fs = FakeFs::new(cx.executor());
12818
12819 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12820 {
12821 let project = Project::test(fs.clone(), [], cx).await;
12822 let (multi_workspace, cx) =
12823 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12824 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12825
12826 workspace.update(cx, |workspace, _cx| {
12827 workspace.set_random_database_id();
12828 workspace.bounds.size.width = px(800.);
12829 });
12830
12831 let panel = workspace.update_in(cx, |workspace, window, cx| {
12832 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12833 workspace.add_panel(panel.clone(), window, cx);
12834 workspace.toggle_dock(DockPosition::Left, window, cx);
12835 panel
12836 });
12837
12838 workspace.update_in(cx, |workspace, window, cx| {
12839 workspace.resize_left_dock(px(350.), window, cx);
12840 });
12841
12842 cx.run_until_parked();
12843
12844 let persisted = workspace.read_with(cx, |workspace, cx| {
12845 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12846 });
12847 assert_eq!(
12848 persisted.and_then(|s| s.size),
12849 Some(px(350.)),
12850 "fixed-width panel size should be persisted to KVP"
12851 );
12852
12853 // Remove the panel and re-add a fresh instance with the same key.
12854 // The new instance should have its size state restored from KVP.
12855 workspace.update_in(cx, |workspace, window, cx| {
12856 workspace.remove_panel(&panel, window, cx);
12857 });
12858
12859 workspace.update_in(cx, |workspace, window, cx| {
12860 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12861 workspace.add_panel(new_panel, window, cx);
12862
12863 let left_dock = workspace.left_dock().read(cx);
12864 let size_state = left_dock
12865 .panel::<TestPanel>()
12866 .and_then(|p| left_dock.stored_panel_size_state(&p));
12867 assert_eq!(
12868 size_state.and_then(|s| s.size),
12869 Some(px(350.)),
12870 "re-added fixed-width panel should restore persisted size from KVP"
12871 );
12872 });
12873 }
12874
12875 // Flexible panel: both pixel size and ratio are persisted and restored.
12876 {
12877 let project = Project::test(fs.clone(), [], cx).await;
12878 let (multi_workspace, cx) =
12879 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12880 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12881
12882 workspace.update(cx, |workspace, _cx| {
12883 workspace.set_random_database_id();
12884 workspace.bounds.size.width = px(800.);
12885 });
12886
12887 let panel = workspace.update_in(cx, |workspace, window, cx| {
12888 let item = cx.new(|cx| {
12889 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12890 });
12891 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12892
12893 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12894 workspace.add_panel(panel.clone(), window, cx);
12895 workspace.toggle_dock(DockPosition::Right, window, cx);
12896 panel
12897 });
12898
12899 workspace.update_in(cx, |workspace, window, cx| {
12900 workspace.resize_right_dock(px(300.), window, cx);
12901 });
12902
12903 cx.run_until_parked();
12904
12905 let persisted = workspace
12906 .read_with(cx, |workspace, cx| {
12907 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12908 })
12909 .expect("flexible panel state should be persisted to KVP");
12910 assert_eq!(
12911 persisted.size, None,
12912 "flexible panel should not persist a redundant pixel size"
12913 );
12914 let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12915
12916 // Remove the panel and re-add: both size and ratio should be restored.
12917 workspace.update_in(cx, |workspace, window, cx| {
12918 workspace.remove_panel(&panel, window, cx);
12919 });
12920
12921 workspace.update_in(cx, |workspace, window, cx| {
12922 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12923 workspace.add_panel(new_panel, window, cx);
12924
12925 let right_dock = workspace.right_dock().read(cx);
12926 let size_state = right_dock
12927 .panel::<TestPanel>()
12928 .and_then(|p| right_dock.stored_panel_size_state(&p))
12929 .expect("re-added flexible panel should have restored size state from KVP");
12930 assert_eq!(
12931 size_state.size, None,
12932 "re-added flexible panel should not have a persisted pixel size"
12933 );
12934 assert_eq!(
12935 size_state.flex,
12936 Some(original_ratio),
12937 "re-added flexible panel should restore persisted flex"
12938 );
12939 });
12940 }
12941 }
12942
12943 #[gpui::test]
12944 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12945 init_test(cx);
12946 let fs = FakeFs::new(cx.executor());
12947
12948 let project = Project::test(fs, [], cx).await;
12949 let (multi_workspace, cx) =
12950 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12951 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12952
12953 workspace.update(cx, |workspace, _cx| {
12954 workspace.bounds.size.width = px(900.);
12955 });
12956
12957 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12958 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12959 // and the center pane each take half the workspace width.
12960 workspace.update_in(cx, |workspace, window, cx| {
12961 let item = cx.new(|cx| {
12962 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12963 });
12964 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12965
12966 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12967 workspace.add_panel(panel, window, cx);
12968 workspace.toggle_dock(DockPosition::Left, window, cx);
12969
12970 let left_dock = workspace.left_dock().read(cx);
12971 let left_width = workspace
12972 .dock_size(&left_dock, window, cx)
12973 .expect("left dock should have an active panel");
12974
12975 assert_eq!(
12976 left_width,
12977 workspace.bounds.size.width / 2.,
12978 "flexible left panel should split evenly with the center pane"
12979 );
12980 });
12981
12982 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12983 // change horizontal width fractions, so the flexible panel stays at the same
12984 // width as each half of the split.
12985 workspace.update_in(cx, |workspace, window, cx| {
12986 workspace.split_pane(
12987 workspace.active_pane().clone(),
12988 SplitDirection::Down,
12989 window,
12990 cx,
12991 );
12992
12993 let left_dock = workspace.left_dock().read(cx);
12994 let left_width = workspace
12995 .dock_size(&left_dock, window, cx)
12996 .expect("left dock should still have an active panel after vertical split");
12997
12998 assert_eq!(
12999 left_width,
13000 workspace.bounds.size.width / 2.,
13001 "flexible left panel width should match each vertically-split pane"
13002 );
13003 });
13004
13005 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
13006 // size reduces the available width, so the flexible left panel and the center
13007 // panes all shrink proportionally to accommodate it.
13008 workspace.update_in(cx, |workspace, window, cx| {
13009 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
13010 workspace.add_panel(panel, window, cx);
13011 workspace.toggle_dock(DockPosition::Right, window, cx);
13012
13013 let right_dock = workspace.right_dock().read(cx);
13014 let right_width = workspace
13015 .dock_size(&right_dock, window, cx)
13016 .expect("right dock should have an active panel");
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
13023 let available_width = workspace.bounds.size.width - right_width;
13024 assert_eq!(
13025 left_width,
13026 available_width / 2.,
13027 "flexible left panel should shrink proportionally as the right dock takes space"
13028 );
13029 });
13030
13031 // Step 4: Toggle the right dock's panel to flexible. Now both docks use
13032 // flex sizing and the workspace width is divided among left-flex, center
13033 // (implicit flex 1.0), and right-flex.
13034 workspace.update_in(cx, |workspace, window, cx| {
13035 let right_dock = workspace.right_dock().clone();
13036 let right_panel = right_dock
13037 .read(cx)
13038 .visible_panel()
13039 .expect("right dock should have a visible panel")
13040 .clone();
13041 workspace.toggle_dock_panel_flexible_size(
13042 &right_dock,
13043 right_panel.as_ref(),
13044 window,
13045 cx,
13046 );
13047
13048 let right_dock = right_dock.read(cx);
13049 let right_panel = right_dock
13050 .visible_panel()
13051 .expect("right dock should still have a visible panel");
13052 assert!(
13053 right_panel.has_flexible_size(window, cx),
13054 "right panel should now be flexible"
13055 );
13056
13057 let right_size_state = right_dock
13058 .stored_panel_size_state(right_panel.as_ref())
13059 .expect("right panel should have a stored size state after toggling");
13060 let right_flex = right_size_state
13061 .flex
13062 .expect("right panel should have a flex value after toggling");
13063
13064 let left_dock = workspace.left_dock().read(cx);
13065 let left_width = workspace
13066 .dock_size(&left_dock, window, cx)
13067 .expect("left dock should still have an active panel");
13068 let right_width = workspace
13069 .dock_size(&right_dock, window, cx)
13070 .expect("right dock should still have an active panel");
13071
13072 let left_flex = workspace
13073 .default_dock_flex(DockPosition::Left)
13074 .expect("left dock should have a default flex");
13075
13076 let total_flex = left_flex + 1.0 + right_flex;
13077 let expected_left = left_flex / total_flex * workspace.bounds.size.width;
13078 let expected_right = right_flex / total_flex * workspace.bounds.size.width;
13079 assert_eq!(
13080 left_width, expected_left,
13081 "flexible left panel should share workspace width via flex ratios"
13082 );
13083 assert_eq!(
13084 right_width, expected_right,
13085 "flexible right panel should share workspace width via flex ratios"
13086 );
13087 });
13088 }
13089
13090 struct TestModal(FocusHandle);
13091
13092 impl TestModal {
13093 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
13094 Self(cx.focus_handle())
13095 }
13096 }
13097
13098 impl EventEmitter<DismissEvent> for TestModal {}
13099
13100 impl Focusable for TestModal {
13101 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13102 self.0.clone()
13103 }
13104 }
13105
13106 impl ModalView for TestModal {}
13107
13108 impl Render for TestModal {
13109 fn render(
13110 &mut self,
13111 _window: &mut Window,
13112 _cx: &mut Context<TestModal>,
13113 ) -> impl IntoElement {
13114 div().track_focus(&self.0)
13115 }
13116 }
13117
13118 #[gpui::test]
13119 async fn test_panels(cx: &mut gpui::TestAppContext) {
13120 init_test(cx);
13121 let fs = FakeFs::new(cx.executor());
13122
13123 let project = Project::test(fs, [], cx).await;
13124 let (multi_workspace, cx) =
13125 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13126 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13127
13128 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
13129 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
13130 workspace.add_panel(panel_1.clone(), window, cx);
13131 workspace.toggle_dock(DockPosition::Left, window, cx);
13132 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
13133 workspace.add_panel(panel_2.clone(), window, cx);
13134 workspace.toggle_dock(DockPosition::Right, window, cx);
13135
13136 let left_dock = workspace.left_dock();
13137 assert_eq!(
13138 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13139 panel_1.panel_id()
13140 );
13141 assert_eq!(
13142 workspace.dock_size(&left_dock.read(cx), window, cx),
13143 Some(px(300.))
13144 );
13145
13146 workspace.resize_left_dock(px(1337.), window, cx);
13147 assert_eq!(
13148 workspace
13149 .right_dock()
13150 .read(cx)
13151 .visible_panel()
13152 .unwrap()
13153 .panel_id(),
13154 panel_2.panel_id(),
13155 );
13156
13157 (panel_1, panel_2)
13158 });
13159
13160 // Move panel_1 to the right
13161 panel_1.update_in(cx, |panel_1, window, cx| {
13162 panel_1.set_position(DockPosition::Right, window, cx)
13163 });
13164
13165 workspace.update_in(cx, |workspace, window, cx| {
13166 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
13167 // Since it was the only panel on the left, the left dock should now be closed.
13168 assert!(!workspace.left_dock().read(cx).is_open());
13169 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
13170 let right_dock = workspace.right_dock();
13171 assert_eq!(
13172 right_dock.read(cx).visible_panel().unwrap().panel_id(),
13173 panel_1.panel_id()
13174 );
13175 assert_eq!(
13176 right_dock
13177 .read(cx)
13178 .active_panel_size()
13179 .unwrap()
13180 .size
13181 .unwrap(),
13182 px(1337.)
13183 );
13184
13185 // Now we move panel_2 to the left
13186 panel_2.set_position(DockPosition::Left, window, cx);
13187 });
13188
13189 workspace.update(cx, |workspace, cx| {
13190 // Since panel_2 was not visible on the right, we don't open the left dock.
13191 assert!(!workspace.left_dock().read(cx).is_open());
13192 // And the right dock is unaffected in its displaying of panel_1
13193 assert!(workspace.right_dock().read(cx).is_open());
13194 assert_eq!(
13195 workspace
13196 .right_dock()
13197 .read(cx)
13198 .visible_panel()
13199 .unwrap()
13200 .panel_id(),
13201 panel_1.panel_id(),
13202 );
13203 });
13204
13205 // Move panel_1 back to the left
13206 panel_1.update_in(cx, |panel_1, window, cx| {
13207 panel_1.set_position(DockPosition::Left, window, cx)
13208 });
13209
13210 workspace.update_in(cx, |workspace, window, cx| {
13211 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
13212 let left_dock = workspace.left_dock();
13213 assert!(left_dock.read(cx).is_open());
13214 assert_eq!(
13215 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13216 panel_1.panel_id()
13217 );
13218 assert_eq!(
13219 workspace.dock_size(&left_dock.read(cx), window, cx),
13220 Some(px(1337.))
13221 );
13222 // And the right dock should be closed as it no longer has any panels.
13223 assert!(!workspace.right_dock().read(cx).is_open());
13224
13225 // Now we move panel_1 to the bottom
13226 panel_1.set_position(DockPosition::Bottom, window, cx);
13227 });
13228
13229 workspace.update_in(cx, |workspace, window, cx| {
13230 // Since panel_1 was visible on the left, we close the left dock.
13231 assert!(!workspace.left_dock().read(cx).is_open());
13232 // The bottom dock is sized based on the panel's default size,
13233 // since the panel orientation changed from vertical to horizontal.
13234 let bottom_dock = workspace.bottom_dock();
13235 assert_eq!(
13236 workspace.dock_size(&bottom_dock.read(cx), window, cx),
13237 Some(px(300.))
13238 );
13239 // Close bottom dock and move panel_1 back to the left.
13240 bottom_dock.update(cx, |bottom_dock, cx| {
13241 bottom_dock.set_open(false, window, cx)
13242 });
13243 panel_1.set_position(DockPosition::Left, window, cx);
13244 });
13245
13246 // Emit activated event on panel 1
13247 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
13248
13249 // Now the left dock is open and panel_1 is active and focused.
13250 workspace.update_in(cx, |workspace, window, cx| {
13251 let left_dock = workspace.left_dock();
13252 assert!(left_dock.read(cx).is_open());
13253 assert_eq!(
13254 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13255 panel_1.panel_id(),
13256 );
13257 assert!(panel_1.focus_handle(cx).is_focused(window));
13258 });
13259
13260 // Emit closed event on panel 2, which is not active
13261 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13262
13263 // Wo don't close the left dock, because panel_2 wasn't the active panel
13264 workspace.update(cx, |workspace, cx| {
13265 let left_dock = workspace.left_dock();
13266 assert!(left_dock.read(cx).is_open());
13267 assert_eq!(
13268 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13269 panel_1.panel_id(),
13270 );
13271 });
13272
13273 // Emitting a ZoomIn event shows the panel as zoomed.
13274 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13275 workspace.read_with(cx, |workspace, _| {
13276 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13277 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13278 });
13279
13280 // Move panel to another dock while it is zoomed
13281 panel_1.update_in(cx, |panel, window, cx| {
13282 panel.set_position(DockPosition::Right, window, cx)
13283 });
13284 workspace.read_with(cx, |workspace, _| {
13285 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13286
13287 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13288 });
13289
13290 // This is a helper for getting a:
13291 // - valid focus on an element,
13292 // - that isn't a part of the panes and panels system of the Workspace,
13293 // - and doesn't trigger the 'on_focus_lost' API.
13294 let focus_other_view = {
13295 let workspace = workspace.clone();
13296 move |cx: &mut VisualTestContext| {
13297 workspace.update_in(cx, |workspace, window, cx| {
13298 if workspace.active_modal::<TestModal>(cx).is_some() {
13299 workspace.toggle_modal(window, cx, TestModal::new);
13300 workspace.toggle_modal(window, cx, TestModal::new);
13301 } else {
13302 workspace.toggle_modal(window, cx, TestModal::new);
13303 }
13304 })
13305 }
13306 };
13307
13308 // If focus is transferred to another view that's not a panel or another pane, we still show
13309 // the panel as zoomed.
13310 focus_other_view(cx);
13311 workspace.read_with(cx, |workspace, _| {
13312 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13313 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13314 });
13315
13316 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13317 workspace.update_in(cx, |_workspace, window, cx| {
13318 cx.focus_self(window);
13319 });
13320 workspace.read_with(cx, |workspace, _| {
13321 assert_eq!(workspace.zoomed, None);
13322 assert_eq!(workspace.zoomed_position, None);
13323 });
13324
13325 // If focus is transferred again to another view that's not a panel or a pane, we won't
13326 // show the panel as zoomed because it wasn't zoomed before.
13327 focus_other_view(cx);
13328 workspace.read_with(cx, |workspace, _| {
13329 assert_eq!(workspace.zoomed, None);
13330 assert_eq!(workspace.zoomed_position, None);
13331 });
13332
13333 // When the panel is activated, it is zoomed again.
13334 cx.dispatch_action(ToggleRightDock);
13335 workspace.read_with(cx, |workspace, _| {
13336 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13337 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13338 });
13339
13340 // Emitting a ZoomOut event unzooms the panel.
13341 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13342 workspace.read_with(cx, |workspace, _| {
13343 assert_eq!(workspace.zoomed, None);
13344 assert_eq!(workspace.zoomed_position, None);
13345 });
13346
13347 // Emit closed event on panel 1, which is active
13348 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13349
13350 // Now the left dock is closed, because panel_1 was the active panel
13351 workspace.update(cx, |workspace, cx| {
13352 let right_dock = workspace.right_dock();
13353 assert!(!right_dock.read(cx).is_open());
13354 });
13355 }
13356
13357 #[gpui::test]
13358 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13359 init_test(cx);
13360
13361 let fs = FakeFs::new(cx.background_executor.clone());
13362 let project = Project::test(fs, [], cx).await;
13363 let (workspace, cx) =
13364 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13365 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13366
13367 let dirty_regular_buffer = cx.new(|cx| {
13368 TestItem::new(cx)
13369 .with_dirty(true)
13370 .with_label("1.txt")
13371 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13372 });
13373 let dirty_regular_buffer_2 = cx.new(|cx| {
13374 TestItem::new(cx)
13375 .with_dirty(true)
13376 .with_label("2.txt")
13377 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13378 });
13379 let dirty_multi_buffer_with_both = cx.new(|cx| {
13380 TestItem::new(cx)
13381 .with_dirty(true)
13382 .with_buffer_kind(ItemBufferKind::Multibuffer)
13383 .with_label("Fake Project Search")
13384 .with_project_items(&[
13385 dirty_regular_buffer.read(cx).project_items[0].clone(),
13386 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13387 ])
13388 });
13389 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13390 workspace.update_in(cx, |workspace, window, cx| {
13391 workspace.add_item(
13392 pane.clone(),
13393 Box::new(dirty_regular_buffer.clone()),
13394 None,
13395 false,
13396 false,
13397 window,
13398 cx,
13399 );
13400 workspace.add_item(
13401 pane.clone(),
13402 Box::new(dirty_regular_buffer_2.clone()),
13403 None,
13404 false,
13405 false,
13406 window,
13407 cx,
13408 );
13409 workspace.add_item(
13410 pane.clone(),
13411 Box::new(dirty_multi_buffer_with_both.clone()),
13412 None,
13413 false,
13414 false,
13415 window,
13416 cx,
13417 );
13418 });
13419
13420 pane.update_in(cx, |pane, window, cx| {
13421 pane.activate_item(2, true, true, window, cx);
13422 assert_eq!(
13423 pane.active_item().unwrap().item_id(),
13424 multi_buffer_with_both_files_id,
13425 "Should select the multi buffer in the pane"
13426 );
13427 });
13428 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13429 pane.close_other_items(
13430 &CloseOtherItems {
13431 save_intent: Some(SaveIntent::Save),
13432 close_pinned: true,
13433 },
13434 None,
13435 window,
13436 cx,
13437 )
13438 });
13439 cx.background_executor.run_until_parked();
13440 assert!(!cx.has_pending_prompt());
13441 close_all_but_multi_buffer_task
13442 .await
13443 .expect("Closing all buffers but the multi buffer failed");
13444 pane.update(cx, |pane, cx| {
13445 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13446 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13447 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13448 assert_eq!(pane.items_len(), 1);
13449 assert_eq!(
13450 pane.active_item().unwrap().item_id(),
13451 multi_buffer_with_both_files_id,
13452 "Should have only the multi buffer left in the pane"
13453 );
13454 assert!(
13455 dirty_multi_buffer_with_both.read(cx).is_dirty,
13456 "The multi buffer containing the unsaved buffer should still be dirty"
13457 );
13458 });
13459
13460 dirty_regular_buffer.update(cx, |buffer, cx| {
13461 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13462 });
13463
13464 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13465 pane.close_active_item(
13466 &CloseActiveItem {
13467 save_intent: Some(SaveIntent::Close),
13468 close_pinned: false,
13469 },
13470 window,
13471 cx,
13472 )
13473 });
13474 cx.background_executor.run_until_parked();
13475 assert!(
13476 cx.has_pending_prompt(),
13477 "Dirty multi buffer should prompt a save dialog"
13478 );
13479 cx.simulate_prompt_answer("Save");
13480 cx.background_executor.run_until_parked();
13481 close_multi_buffer_task
13482 .await
13483 .expect("Closing the multi buffer failed");
13484 pane.update(cx, |pane, cx| {
13485 assert_eq!(
13486 dirty_multi_buffer_with_both.read(cx).save_count,
13487 1,
13488 "Multi buffer item should get be saved"
13489 );
13490 // Test impl does not save inner items, so we do not assert them
13491 assert_eq!(
13492 pane.items_len(),
13493 0,
13494 "No more items should be left in the pane"
13495 );
13496 assert!(pane.active_item().is_none());
13497 });
13498 }
13499
13500 #[gpui::test]
13501 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13502 cx: &mut TestAppContext,
13503 ) {
13504 init_test(cx);
13505
13506 let fs = FakeFs::new(cx.background_executor.clone());
13507 let project = Project::test(fs, [], cx).await;
13508 let (workspace, cx) =
13509 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13510 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13511
13512 let dirty_regular_buffer = cx.new(|cx| {
13513 TestItem::new(cx)
13514 .with_dirty(true)
13515 .with_label("1.txt")
13516 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13517 });
13518 let dirty_regular_buffer_2 = cx.new(|cx| {
13519 TestItem::new(cx)
13520 .with_dirty(true)
13521 .with_label("2.txt")
13522 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13523 });
13524 let clear_regular_buffer = cx.new(|cx| {
13525 TestItem::new(cx)
13526 .with_label("3.txt")
13527 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13528 });
13529
13530 let dirty_multi_buffer_with_both = cx.new(|cx| {
13531 TestItem::new(cx)
13532 .with_dirty(true)
13533 .with_buffer_kind(ItemBufferKind::Multibuffer)
13534 .with_label("Fake Project Search")
13535 .with_project_items(&[
13536 dirty_regular_buffer.read(cx).project_items[0].clone(),
13537 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13538 clear_regular_buffer.read(cx).project_items[0].clone(),
13539 ])
13540 });
13541 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13542 workspace.update_in(cx, |workspace, window, cx| {
13543 workspace.add_item(
13544 pane.clone(),
13545 Box::new(dirty_regular_buffer.clone()),
13546 None,
13547 false,
13548 false,
13549 window,
13550 cx,
13551 );
13552 workspace.add_item(
13553 pane.clone(),
13554 Box::new(dirty_multi_buffer_with_both.clone()),
13555 None,
13556 false,
13557 false,
13558 window,
13559 cx,
13560 );
13561 });
13562
13563 pane.update_in(cx, |pane, window, cx| {
13564 pane.activate_item(1, true, true, window, cx);
13565 assert_eq!(
13566 pane.active_item().unwrap().item_id(),
13567 multi_buffer_with_both_files_id,
13568 "Should select the multi buffer in the pane"
13569 );
13570 });
13571 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13572 pane.close_active_item(
13573 &CloseActiveItem {
13574 save_intent: None,
13575 close_pinned: false,
13576 },
13577 window,
13578 cx,
13579 )
13580 });
13581 cx.background_executor.run_until_parked();
13582 assert!(
13583 cx.has_pending_prompt(),
13584 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13585 );
13586 }
13587
13588 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13589 /// closed when they are deleted from disk.
13590 #[gpui::test]
13591 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13592 init_test(cx);
13593
13594 // Enable the close_on_disk_deletion setting
13595 cx.update_global(|store: &mut SettingsStore, cx| {
13596 store.update_user_settings(cx, |settings| {
13597 settings.workspace.close_on_file_delete = Some(true);
13598 });
13599 });
13600
13601 let fs = FakeFs::new(cx.background_executor.clone());
13602 let project = Project::test(fs, [], cx).await;
13603 let (workspace, cx) =
13604 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13605 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13606
13607 // Create a test item that simulates a file
13608 let item = cx.new(|cx| {
13609 TestItem::new(cx)
13610 .with_label("test.txt")
13611 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13612 });
13613
13614 // Add item to workspace
13615 workspace.update_in(cx, |workspace, window, cx| {
13616 workspace.add_item(
13617 pane.clone(),
13618 Box::new(item.clone()),
13619 None,
13620 false,
13621 false,
13622 window,
13623 cx,
13624 );
13625 });
13626
13627 // Verify the item is in the pane
13628 pane.read_with(cx, |pane, _| {
13629 assert_eq!(pane.items().count(), 1);
13630 });
13631
13632 // Simulate file deletion by setting the item's deleted state
13633 item.update(cx, |item, _| {
13634 item.set_has_deleted_file(true);
13635 });
13636
13637 // Emit UpdateTab event to trigger the close behavior
13638 cx.run_until_parked();
13639 item.update(cx, |_, cx| {
13640 cx.emit(ItemEvent::UpdateTab);
13641 });
13642
13643 // Allow the close operation to complete
13644 cx.run_until_parked();
13645
13646 // Verify the item was automatically closed
13647 pane.read_with(cx, |pane, _| {
13648 assert_eq!(
13649 pane.items().count(),
13650 0,
13651 "Item should be automatically closed when file is deleted"
13652 );
13653 });
13654 }
13655
13656 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13657 /// open with a strikethrough when they are deleted from disk.
13658 #[gpui::test]
13659 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13660 init_test(cx);
13661
13662 // Ensure close_on_disk_deletion is disabled (default)
13663 cx.update_global(|store: &mut SettingsStore, cx| {
13664 store.update_user_settings(cx, |settings| {
13665 settings.workspace.close_on_file_delete = Some(false);
13666 });
13667 });
13668
13669 let fs = FakeFs::new(cx.background_executor.clone());
13670 let project = Project::test(fs, [], cx).await;
13671 let (workspace, cx) =
13672 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13673 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13674
13675 // Create a test item that simulates a file
13676 let item = cx.new(|cx| {
13677 TestItem::new(cx)
13678 .with_label("test.txt")
13679 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13680 });
13681
13682 // Add item to workspace
13683 workspace.update_in(cx, |workspace, window, cx| {
13684 workspace.add_item(
13685 pane.clone(),
13686 Box::new(item.clone()),
13687 None,
13688 false,
13689 false,
13690 window,
13691 cx,
13692 );
13693 });
13694
13695 // Verify the item is in the pane
13696 pane.read_with(cx, |pane, _| {
13697 assert_eq!(pane.items().count(), 1);
13698 });
13699
13700 // Simulate file deletion
13701 item.update(cx, |item, _| {
13702 item.set_has_deleted_file(true);
13703 });
13704
13705 // Emit UpdateTab event
13706 cx.run_until_parked();
13707 item.update(cx, |_, cx| {
13708 cx.emit(ItemEvent::UpdateTab);
13709 });
13710
13711 // Allow any potential close operation to complete
13712 cx.run_until_parked();
13713
13714 // Verify the item remains open (with strikethrough)
13715 pane.read_with(cx, |pane, _| {
13716 assert_eq!(
13717 pane.items().count(),
13718 1,
13719 "Item should remain open when close_on_disk_deletion is disabled"
13720 );
13721 });
13722
13723 // Verify the item shows as deleted
13724 item.read_with(cx, |item, _| {
13725 assert!(
13726 item.has_deleted_file,
13727 "Item should be marked as having deleted file"
13728 );
13729 });
13730 }
13731
13732 /// Tests that dirty files are not automatically closed when deleted from disk,
13733 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13734 /// unsaved changes without being prompted.
13735 #[gpui::test]
13736 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13737 init_test(cx);
13738
13739 // Enable the close_on_file_delete setting
13740 cx.update_global(|store: &mut SettingsStore, cx| {
13741 store.update_user_settings(cx, |settings| {
13742 settings.workspace.close_on_file_delete = Some(true);
13743 });
13744 });
13745
13746 let fs = FakeFs::new(cx.background_executor.clone());
13747 let project = Project::test(fs, [], cx).await;
13748 let (workspace, cx) =
13749 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13750 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13751
13752 // Create a dirty test item
13753 let item = cx.new(|cx| {
13754 TestItem::new(cx)
13755 .with_dirty(true)
13756 .with_label("test.txt")
13757 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13758 });
13759
13760 // Add item to workspace
13761 workspace.update_in(cx, |workspace, window, cx| {
13762 workspace.add_item(
13763 pane.clone(),
13764 Box::new(item.clone()),
13765 None,
13766 false,
13767 false,
13768 window,
13769 cx,
13770 );
13771 });
13772
13773 // Simulate file deletion
13774 item.update(cx, |item, _| {
13775 item.set_has_deleted_file(true);
13776 });
13777
13778 // Emit UpdateTab event to trigger the close behavior
13779 cx.run_until_parked();
13780 item.update(cx, |_, cx| {
13781 cx.emit(ItemEvent::UpdateTab);
13782 });
13783
13784 // Allow any potential close operation to complete
13785 cx.run_until_parked();
13786
13787 // Verify the item remains open (dirty files are not auto-closed)
13788 pane.read_with(cx, |pane, _| {
13789 assert_eq!(
13790 pane.items().count(),
13791 1,
13792 "Dirty items should not be automatically closed even when file is deleted"
13793 );
13794 });
13795
13796 // Verify the item is marked as deleted and still dirty
13797 item.read_with(cx, |item, _| {
13798 assert!(
13799 item.has_deleted_file,
13800 "Item should be marked as having deleted file"
13801 );
13802 assert!(item.is_dirty, "Item should still be dirty");
13803 });
13804 }
13805
13806 /// Tests that navigation history is cleaned up when files are auto-closed
13807 /// due to deletion from disk.
13808 #[gpui::test]
13809 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13810 init_test(cx);
13811
13812 // Enable the close_on_file_delete setting
13813 cx.update_global(|store: &mut SettingsStore, cx| {
13814 store.update_user_settings(cx, |settings| {
13815 settings.workspace.close_on_file_delete = Some(true);
13816 });
13817 });
13818
13819 let fs = FakeFs::new(cx.background_executor.clone());
13820 let project = Project::test(fs, [], cx).await;
13821 let (workspace, cx) =
13822 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13823 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13824
13825 // Create test items
13826 let item1 = cx.new(|cx| {
13827 TestItem::new(cx)
13828 .with_label("test1.txt")
13829 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13830 });
13831 let item1_id = item1.item_id();
13832
13833 let item2 = cx.new(|cx| {
13834 TestItem::new(cx)
13835 .with_label("test2.txt")
13836 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13837 });
13838
13839 // Add items to workspace
13840 workspace.update_in(cx, |workspace, window, cx| {
13841 workspace.add_item(
13842 pane.clone(),
13843 Box::new(item1.clone()),
13844 None,
13845 false,
13846 false,
13847 window,
13848 cx,
13849 );
13850 workspace.add_item(
13851 pane.clone(),
13852 Box::new(item2.clone()),
13853 None,
13854 false,
13855 false,
13856 window,
13857 cx,
13858 );
13859 });
13860
13861 // Activate item1 to ensure it gets navigation entries
13862 pane.update_in(cx, |pane, window, cx| {
13863 pane.activate_item(0, true, true, window, cx);
13864 });
13865
13866 // Switch to item2 and back to create navigation history
13867 pane.update_in(cx, |pane, window, cx| {
13868 pane.activate_item(1, true, true, window, cx);
13869 });
13870 cx.run_until_parked();
13871
13872 pane.update_in(cx, |pane, window, cx| {
13873 pane.activate_item(0, true, true, window, cx);
13874 });
13875 cx.run_until_parked();
13876
13877 // Simulate file deletion for item1
13878 item1.update(cx, |item, _| {
13879 item.set_has_deleted_file(true);
13880 });
13881
13882 // Emit UpdateTab event to trigger the close behavior
13883 item1.update(cx, |_, cx| {
13884 cx.emit(ItemEvent::UpdateTab);
13885 });
13886 cx.run_until_parked();
13887
13888 // Verify item1 was closed
13889 pane.read_with(cx, |pane, _| {
13890 assert_eq!(
13891 pane.items().count(),
13892 1,
13893 "Should have 1 item remaining after auto-close"
13894 );
13895 });
13896
13897 // Check navigation history after close
13898 let has_item = pane.read_with(cx, |pane, cx| {
13899 let mut has_item = false;
13900 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13901 if entry.item.id() == item1_id {
13902 has_item = true;
13903 }
13904 });
13905 has_item
13906 });
13907
13908 assert!(
13909 !has_item,
13910 "Navigation history should not contain closed item entries"
13911 );
13912 }
13913
13914 #[gpui::test]
13915 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13916 cx: &mut TestAppContext,
13917 ) {
13918 init_test(cx);
13919
13920 let fs = FakeFs::new(cx.background_executor.clone());
13921 let project = Project::test(fs, [], cx).await;
13922 let (workspace, cx) =
13923 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13924 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13925
13926 let dirty_regular_buffer = cx.new(|cx| {
13927 TestItem::new(cx)
13928 .with_dirty(true)
13929 .with_label("1.txt")
13930 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13931 });
13932 let dirty_regular_buffer_2 = cx.new(|cx| {
13933 TestItem::new(cx)
13934 .with_dirty(true)
13935 .with_label("2.txt")
13936 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13937 });
13938 let clear_regular_buffer = cx.new(|cx| {
13939 TestItem::new(cx)
13940 .with_label("3.txt")
13941 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13942 });
13943
13944 let dirty_multi_buffer = cx.new(|cx| {
13945 TestItem::new(cx)
13946 .with_dirty(true)
13947 .with_buffer_kind(ItemBufferKind::Multibuffer)
13948 .with_label("Fake Project Search")
13949 .with_project_items(&[
13950 dirty_regular_buffer.read(cx).project_items[0].clone(),
13951 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13952 clear_regular_buffer.read(cx).project_items[0].clone(),
13953 ])
13954 });
13955 workspace.update_in(cx, |workspace, window, cx| {
13956 workspace.add_item(
13957 pane.clone(),
13958 Box::new(dirty_regular_buffer.clone()),
13959 None,
13960 false,
13961 false,
13962 window,
13963 cx,
13964 );
13965 workspace.add_item(
13966 pane.clone(),
13967 Box::new(dirty_regular_buffer_2.clone()),
13968 None,
13969 false,
13970 false,
13971 window,
13972 cx,
13973 );
13974 workspace.add_item(
13975 pane.clone(),
13976 Box::new(dirty_multi_buffer.clone()),
13977 None,
13978 false,
13979 false,
13980 window,
13981 cx,
13982 );
13983 });
13984
13985 pane.update_in(cx, |pane, window, cx| {
13986 pane.activate_item(2, true, true, window, cx);
13987 assert_eq!(
13988 pane.active_item().unwrap().item_id(),
13989 dirty_multi_buffer.item_id(),
13990 "Should select the multi buffer in the pane"
13991 );
13992 });
13993 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13994 pane.close_active_item(
13995 &CloseActiveItem {
13996 save_intent: None,
13997 close_pinned: false,
13998 },
13999 window,
14000 cx,
14001 )
14002 });
14003 cx.background_executor.run_until_parked();
14004 assert!(
14005 !cx.has_pending_prompt(),
14006 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
14007 );
14008 close_multi_buffer_task
14009 .await
14010 .expect("Closing multi buffer failed");
14011 pane.update(cx, |pane, cx| {
14012 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
14013 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
14014 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
14015 assert_eq!(
14016 pane.items()
14017 .map(|item| item.item_id())
14018 .sorted()
14019 .collect::<Vec<_>>(),
14020 vec![
14021 dirty_regular_buffer.item_id(),
14022 dirty_regular_buffer_2.item_id(),
14023 ],
14024 "Should have no multi buffer left in the pane"
14025 );
14026 assert!(dirty_regular_buffer.read(cx).is_dirty);
14027 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
14028 });
14029 }
14030
14031 #[gpui::test]
14032 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
14033 init_test(cx);
14034 let fs = FakeFs::new(cx.executor());
14035 let project = Project::test(fs, [], cx).await;
14036 let (multi_workspace, cx) =
14037 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14038 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14039
14040 // Add a new panel to the right dock, opening the dock and setting the
14041 // focus to the new panel.
14042 let panel = workspace.update_in(cx, |workspace, window, cx| {
14043 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14044 workspace.add_panel(panel.clone(), window, cx);
14045
14046 workspace
14047 .right_dock()
14048 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14049
14050 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14051
14052 panel
14053 });
14054
14055 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14056 // panel to the next valid position which, in this case, is the left
14057 // dock.
14058 cx.dispatch_action(MoveFocusedPanelToNextPosition);
14059 workspace.update(cx, |workspace, cx| {
14060 assert!(workspace.left_dock().read(cx).is_open());
14061 assert_eq!(panel.read(cx).position, DockPosition::Left);
14062 });
14063
14064 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
14065 // panel to the next valid position which, in this case, is the bottom
14066 // dock.
14067 cx.dispatch_action(MoveFocusedPanelToNextPosition);
14068 workspace.update(cx, |workspace, cx| {
14069 assert!(workspace.bottom_dock().read(cx).is_open());
14070 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
14071 });
14072
14073 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
14074 // around moving the panel to its initial position, the right dock.
14075 cx.dispatch_action(MoveFocusedPanelToNextPosition);
14076 workspace.update(cx, |workspace, cx| {
14077 assert!(workspace.right_dock().read(cx).is_open());
14078 assert_eq!(panel.read(cx).position, DockPosition::Right);
14079 });
14080
14081 // Remove focus from the panel, ensuring that, if the panel is not
14082 // focused, the `MoveFocusedPanelToNextPosition` action does not update
14083 // the panel's position, so the panel is still in the right dock.
14084 workspace.update_in(cx, |workspace, window, cx| {
14085 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14086 });
14087
14088 cx.dispatch_action(MoveFocusedPanelToNextPosition);
14089 workspace.update(cx, |workspace, cx| {
14090 assert!(workspace.right_dock().read(cx).is_open());
14091 assert_eq!(panel.read(cx).position, DockPosition::Right);
14092 });
14093 }
14094
14095 #[gpui::test]
14096 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
14097 init_test(cx);
14098
14099 let fs = FakeFs::new(cx.executor());
14100 let project = Project::test(fs, [], cx).await;
14101 let (workspace, cx) =
14102 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14103
14104 let item_1 = cx.new(|cx| {
14105 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14106 });
14107 workspace.update_in(cx, |workspace, window, cx| {
14108 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14109 workspace.move_item_to_pane_in_direction(
14110 &MoveItemToPaneInDirection {
14111 direction: SplitDirection::Right,
14112 focus: true,
14113 clone: false,
14114 },
14115 window,
14116 cx,
14117 );
14118 workspace.move_item_to_pane_at_index(
14119 &MoveItemToPane {
14120 destination: 3,
14121 focus: true,
14122 clone: false,
14123 },
14124 window,
14125 cx,
14126 );
14127
14128 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
14129 assert_eq!(
14130 pane_items_paths(&workspace.active_pane, cx),
14131 vec!["first.txt".to_string()],
14132 "Single item was not moved anywhere"
14133 );
14134 });
14135
14136 let item_2 = cx.new(|cx| {
14137 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
14138 });
14139 workspace.update_in(cx, |workspace, window, cx| {
14140 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
14141 assert_eq!(
14142 pane_items_paths(&workspace.panes[0], cx),
14143 vec!["first.txt".to_string(), "second.txt".to_string()],
14144 );
14145 workspace.move_item_to_pane_in_direction(
14146 &MoveItemToPaneInDirection {
14147 direction: SplitDirection::Right,
14148 focus: true,
14149 clone: false,
14150 },
14151 window,
14152 cx,
14153 );
14154
14155 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
14156 assert_eq!(
14157 pane_items_paths(&workspace.panes[0], cx),
14158 vec!["first.txt".to_string()],
14159 "After moving, one item should be left in the original pane"
14160 );
14161 assert_eq!(
14162 pane_items_paths(&workspace.panes[1], cx),
14163 vec!["second.txt".to_string()],
14164 "New item should have been moved to the new pane"
14165 );
14166 });
14167
14168 let item_3 = cx.new(|cx| {
14169 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
14170 });
14171 workspace.update_in(cx, |workspace, window, cx| {
14172 let original_pane = workspace.panes[0].clone();
14173 workspace.set_active_pane(&original_pane, window, cx);
14174 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
14175 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
14176 assert_eq!(
14177 pane_items_paths(&workspace.active_pane, cx),
14178 vec!["first.txt".to_string(), "third.txt".to_string()],
14179 "New pane should be ready to move one item out"
14180 );
14181
14182 workspace.move_item_to_pane_at_index(
14183 &MoveItemToPane {
14184 destination: 3,
14185 focus: true,
14186 clone: false,
14187 },
14188 window,
14189 cx,
14190 );
14191 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
14192 assert_eq!(
14193 pane_items_paths(&workspace.active_pane, cx),
14194 vec!["first.txt".to_string()],
14195 "After moving, one item should be left in the original pane"
14196 );
14197 assert_eq!(
14198 pane_items_paths(&workspace.panes[1], cx),
14199 vec!["second.txt".to_string()],
14200 "Previously created pane should be unchanged"
14201 );
14202 assert_eq!(
14203 pane_items_paths(&workspace.panes[2], cx),
14204 vec!["third.txt".to_string()],
14205 "New item should have been moved to the new pane"
14206 );
14207 });
14208 }
14209
14210 #[gpui::test]
14211 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
14212 init_test(cx);
14213
14214 let fs = FakeFs::new(cx.executor());
14215 let project = Project::test(fs, [], cx).await;
14216 let (workspace, cx) =
14217 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14218
14219 let item_1 = cx.new(|cx| {
14220 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14221 });
14222 workspace.update_in(cx, |workspace, window, cx| {
14223 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14224 workspace.move_item_to_pane_in_direction(
14225 &MoveItemToPaneInDirection {
14226 direction: SplitDirection::Right,
14227 focus: true,
14228 clone: true,
14229 },
14230 window,
14231 cx,
14232 );
14233 });
14234 cx.run_until_parked();
14235 workspace.update_in(cx, |workspace, window, cx| {
14236 workspace.move_item_to_pane_at_index(
14237 &MoveItemToPane {
14238 destination: 3,
14239 focus: true,
14240 clone: true,
14241 },
14242 window,
14243 cx,
14244 );
14245 });
14246 cx.run_until_parked();
14247
14248 workspace.update(cx, |workspace, cx| {
14249 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
14250 for pane in workspace.panes() {
14251 assert_eq!(
14252 pane_items_paths(pane, cx),
14253 vec!["first.txt".to_string()],
14254 "Single item exists in all panes"
14255 );
14256 }
14257 });
14258
14259 // verify that the active pane has been updated after waiting for the
14260 // pane focus event to fire and resolve
14261 workspace.read_with(cx, |workspace, _app| {
14262 assert_eq!(
14263 workspace.active_pane(),
14264 &workspace.panes[2],
14265 "The third pane should be the active one: {:?}",
14266 workspace.panes
14267 );
14268 })
14269 }
14270
14271 #[gpui::test]
14272 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
14273 init_test(cx);
14274
14275 let fs = FakeFs::new(cx.executor());
14276 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14277
14278 let project = Project::test(fs, ["root".as_ref()], cx).await;
14279 let (workspace, cx) =
14280 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14281
14282 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14283 // Add item to pane A with project path
14284 let item_a = cx.new(|cx| {
14285 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14286 });
14287 workspace.update_in(cx, |workspace, window, cx| {
14288 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14289 });
14290
14291 // Split to create pane B
14292 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14293 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14294 });
14295
14296 // Add item with SAME project path to pane B, and pin it
14297 let item_b = cx.new(|cx| {
14298 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14299 });
14300 pane_b.update_in(cx, |pane, window, cx| {
14301 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14302 pane.set_pinned_count(1);
14303 });
14304
14305 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14306 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14307
14308 // close_pinned: false should only close the unpinned copy
14309 workspace.update_in(cx, |workspace, window, cx| {
14310 workspace.close_item_in_all_panes(
14311 &CloseItemInAllPanes {
14312 save_intent: Some(SaveIntent::Close),
14313 close_pinned: false,
14314 },
14315 window,
14316 cx,
14317 )
14318 });
14319 cx.executor().run_until_parked();
14320
14321 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14322 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14323 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14324 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14325
14326 // Split again, seeing as closing the previous item also closed its
14327 // pane, so only pane remains, which does not allow us to properly test
14328 // that both items close when `close_pinned: true`.
14329 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14330 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14331 });
14332
14333 // Add an item with the same project path to pane C so that
14334 // close_item_in_all_panes can determine what to close across all panes
14335 // (it reads the active item from the active pane, and split_pane
14336 // creates an empty pane).
14337 let item_c = cx.new(|cx| {
14338 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14339 });
14340 pane_c.update_in(cx, |pane, window, cx| {
14341 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14342 });
14343
14344 // close_pinned: true should close the pinned copy too
14345 workspace.update_in(cx, |workspace, window, cx| {
14346 let panes_count = workspace.panes().len();
14347 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14348
14349 workspace.close_item_in_all_panes(
14350 &CloseItemInAllPanes {
14351 save_intent: Some(SaveIntent::Close),
14352 close_pinned: true,
14353 },
14354 window,
14355 cx,
14356 )
14357 });
14358 cx.executor().run_until_parked();
14359
14360 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14361 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14362 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14363 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14364 }
14365
14366 mod register_project_item_tests {
14367
14368 use super::*;
14369
14370 // View
14371 struct TestPngItemView {
14372 focus_handle: FocusHandle,
14373 }
14374 // Model
14375 struct TestPngItem {}
14376
14377 impl project::ProjectItem for TestPngItem {
14378 fn try_open(
14379 _project: &Entity<Project>,
14380 path: &ProjectPath,
14381 cx: &mut App,
14382 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14383 if path.path.extension().unwrap() == "png" {
14384 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14385 } else {
14386 None
14387 }
14388 }
14389
14390 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14391 None
14392 }
14393
14394 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14395 None
14396 }
14397
14398 fn is_dirty(&self) -> bool {
14399 false
14400 }
14401 }
14402
14403 impl Item for TestPngItemView {
14404 type Event = ();
14405 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14406 "".into()
14407 }
14408 }
14409 impl EventEmitter<()> for TestPngItemView {}
14410 impl Focusable for TestPngItemView {
14411 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14412 self.focus_handle.clone()
14413 }
14414 }
14415
14416 impl Render for TestPngItemView {
14417 fn render(
14418 &mut self,
14419 _window: &mut Window,
14420 _cx: &mut Context<Self>,
14421 ) -> impl IntoElement {
14422 Empty
14423 }
14424 }
14425
14426 impl ProjectItem for TestPngItemView {
14427 type Item = TestPngItem;
14428
14429 fn for_project_item(
14430 _project: Entity<Project>,
14431 _pane: Option<&Pane>,
14432 _item: Entity<Self::Item>,
14433 _: &mut Window,
14434 cx: &mut Context<Self>,
14435 ) -> Self
14436 where
14437 Self: Sized,
14438 {
14439 Self {
14440 focus_handle: cx.focus_handle(),
14441 }
14442 }
14443 }
14444
14445 // View
14446 struct TestIpynbItemView {
14447 focus_handle: FocusHandle,
14448 }
14449 // Model
14450 struct TestIpynbItem {}
14451
14452 impl project::ProjectItem for TestIpynbItem {
14453 fn try_open(
14454 _project: &Entity<Project>,
14455 path: &ProjectPath,
14456 cx: &mut App,
14457 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14458 if path.path.extension().unwrap() == "ipynb" {
14459 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14460 } else {
14461 None
14462 }
14463 }
14464
14465 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14466 None
14467 }
14468
14469 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14470 None
14471 }
14472
14473 fn is_dirty(&self) -> bool {
14474 false
14475 }
14476 }
14477
14478 impl Item for TestIpynbItemView {
14479 type Event = ();
14480 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14481 "".into()
14482 }
14483 }
14484 impl EventEmitter<()> for TestIpynbItemView {}
14485 impl Focusable for TestIpynbItemView {
14486 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14487 self.focus_handle.clone()
14488 }
14489 }
14490
14491 impl Render for TestIpynbItemView {
14492 fn render(
14493 &mut self,
14494 _window: &mut Window,
14495 _cx: &mut Context<Self>,
14496 ) -> impl IntoElement {
14497 Empty
14498 }
14499 }
14500
14501 impl ProjectItem for TestIpynbItemView {
14502 type Item = TestIpynbItem;
14503
14504 fn for_project_item(
14505 _project: Entity<Project>,
14506 _pane: Option<&Pane>,
14507 _item: Entity<Self::Item>,
14508 _: &mut Window,
14509 cx: &mut Context<Self>,
14510 ) -> Self
14511 where
14512 Self: Sized,
14513 {
14514 Self {
14515 focus_handle: cx.focus_handle(),
14516 }
14517 }
14518 }
14519
14520 struct TestAlternatePngItemView {
14521 focus_handle: FocusHandle,
14522 }
14523
14524 impl Item for TestAlternatePngItemView {
14525 type Event = ();
14526 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14527 "".into()
14528 }
14529 }
14530
14531 impl EventEmitter<()> for TestAlternatePngItemView {}
14532 impl Focusable for TestAlternatePngItemView {
14533 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14534 self.focus_handle.clone()
14535 }
14536 }
14537
14538 impl Render for TestAlternatePngItemView {
14539 fn render(
14540 &mut self,
14541 _window: &mut Window,
14542 _cx: &mut Context<Self>,
14543 ) -> impl IntoElement {
14544 Empty
14545 }
14546 }
14547
14548 impl ProjectItem for TestAlternatePngItemView {
14549 type Item = TestPngItem;
14550
14551 fn for_project_item(
14552 _project: Entity<Project>,
14553 _pane: Option<&Pane>,
14554 _item: Entity<Self::Item>,
14555 _: &mut Window,
14556 cx: &mut Context<Self>,
14557 ) -> Self
14558 where
14559 Self: Sized,
14560 {
14561 Self {
14562 focus_handle: cx.focus_handle(),
14563 }
14564 }
14565 }
14566
14567 #[gpui::test]
14568 async fn test_register_project_item(cx: &mut TestAppContext) {
14569 init_test(cx);
14570
14571 cx.update(|cx| {
14572 register_project_item::<TestPngItemView>(cx);
14573 register_project_item::<TestIpynbItemView>(cx);
14574 });
14575
14576 let fs = FakeFs::new(cx.executor());
14577 fs.insert_tree(
14578 "/root1",
14579 json!({
14580 "one.png": "BINARYDATAHERE",
14581 "two.ipynb": "{ totally a notebook }",
14582 "three.txt": "editing text, sure why not?"
14583 }),
14584 )
14585 .await;
14586
14587 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14588 let (workspace, cx) =
14589 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14590
14591 let worktree_id = project.update(cx, |project, cx| {
14592 project.worktrees(cx).next().unwrap().read(cx).id()
14593 });
14594
14595 let handle = workspace
14596 .update_in(cx, |workspace, window, cx| {
14597 let project_path = (worktree_id, rel_path("one.png"));
14598 workspace.open_path(project_path, None, true, window, cx)
14599 })
14600 .await
14601 .unwrap();
14602
14603 // Now we can check if the handle we got back errored or not
14604 assert_eq!(
14605 handle.to_any_view().entity_type(),
14606 TypeId::of::<TestPngItemView>()
14607 );
14608
14609 let handle = workspace
14610 .update_in(cx, |workspace, window, cx| {
14611 let project_path = (worktree_id, rel_path("two.ipynb"));
14612 workspace.open_path(project_path, None, true, window, cx)
14613 })
14614 .await
14615 .unwrap();
14616
14617 assert_eq!(
14618 handle.to_any_view().entity_type(),
14619 TypeId::of::<TestIpynbItemView>()
14620 );
14621
14622 let handle = workspace
14623 .update_in(cx, |workspace, window, cx| {
14624 let project_path = (worktree_id, rel_path("three.txt"));
14625 workspace.open_path(project_path, None, true, window, cx)
14626 })
14627 .await;
14628 assert!(handle.is_err());
14629 }
14630
14631 #[gpui::test]
14632 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14633 init_test(cx);
14634
14635 cx.update(|cx| {
14636 register_project_item::<TestPngItemView>(cx);
14637 register_project_item::<TestAlternatePngItemView>(cx);
14638 });
14639
14640 let fs = FakeFs::new(cx.executor());
14641 fs.insert_tree(
14642 "/root1",
14643 json!({
14644 "one.png": "BINARYDATAHERE",
14645 "two.ipynb": "{ totally a notebook }",
14646 "three.txt": "editing text, sure why not?"
14647 }),
14648 )
14649 .await;
14650 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14651 let (workspace, cx) =
14652 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14653 let worktree_id = project.update(cx, |project, cx| {
14654 project.worktrees(cx).next().unwrap().read(cx).id()
14655 });
14656
14657 let handle = workspace
14658 .update_in(cx, |workspace, window, cx| {
14659 let project_path = (worktree_id, rel_path("one.png"));
14660 workspace.open_path(project_path, None, true, window, cx)
14661 })
14662 .await
14663 .unwrap();
14664
14665 // This _must_ be the second item registered
14666 assert_eq!(
14667 handle.to_any_view().entity_type(),
14668 TypeId::of::<TestAlternatePngItemView>()
14669 );
14670
14671 let handle = workspace
14672 .update_in(cx, |workspace, window, cx| {
14673 let project_path = (worktree_id, rel_path("three.txt"));
14674 workspace.open_path(project_path, None, true, window, cx)
14675 })
14676 .await;
14677 assert!(handle.is_err());
14678 }
14679 }
14680
14681 #[gpui::test]
14682 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14683 init_test(cx);
14684
14685 let fs = FakeFs::new(cx.executor());
14686 let project = Project::test(fs, [], cx).await;
14687 let (workspace, _cx) =
14688 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14689
14690 // Test with status bar shown (default)
14691 workspace.read_with(cx, |workspace, cx| {
14692 let visible = workspace.status_bar_visible(cx);
14693 assert!(visible, "Status bar should be visible by default");
14694 });
14695
14696 // Test with status bar hidden
14697 cx.update_global(|store: &mut SettingsStore, cx| {
14698 store.update_user_settings(cx, |settings| {
14699 settings.status_bar.get_or_insert_default().show = Some(false);
14700 });
14701 });
14702
14703 workspace.read_with(cx, |workspace, cx| {
14704 let visible = workspace.status_bar_visible(cx);
14705 assert!(!visible, "Status bar should be hidden when show is false");
14706 });
14707
14708 // Test with status bar shown explicitly
14709 cx.update_global(|store: &mut SettingsStore, cx| {
14710 store.update_user_settings(cx, |settings| {
14711 settings.status_bar.get_or_insert_default().show = Some(true);
14712 });
14713 });
14714
14715 workspace.read_with(cx, |workspace, cx| {
14716 let visible = workspace.status_bar_visible(cx);
14717 assert!(visible, "Status bar should be visible when show is true");
14718 });
14719 }
14720
14721 #[gpui::test]
14722 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14723 init_test(cx);
14724
14725 let fs = FakeFs::new(cx.executor());
14726 let project = Project::test(fs, [], cx).await;
14727 let (multi_workspace, cx) =
14728 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14729 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14730 let panel = workspace.update_in(cx, |workspace, window, cx| {
14731 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14732 workspace.add_panel(panel.clone(), window, cx);
14733
14734 workspace
14735 .right_dock()
14736 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14737
14738 panel
14739 });
14740
14741 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14742 let item_a = cx.new(TestItem::new);
14743 let item_b = cx.new(TestItem::new);
14744 let item_a_id = item_a.entity_id();
14745 let item_b_id = item_b.entity_id();
14746
14747 pane.update_in(cx, |pane, window, cx| {
14748 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14749 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14750 });
14751
14752 pane.read_with(cx, |pane, _| {
14753 assert_eq!(pane.items_len(), 2);
14754 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14755 });
14756
14757 workspace.update_in(cx, |workspace, window, cx| {
14758 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14759 });
14760
14761 workspace.update_in(cx, |_, window, cx| {
14762 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14763 });
14764
14765 // Assert that the `pane::CloseActiveItem` action is handled at the
14766 // workspace level when one of the dock panels is focused and, in that
14767 // case, the center pane's active item is closed but the focus is not
14768 // moved.
14769 cx.dispatch_action(pane::CloseActiveItem::default());
14770 cx.run_until_parked();
14771
14772 pane.read_with(cx, |pane, _| {
14773 assert_eq!(pane.items_len(), 1);
14774 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14775 });
14776
14777 workspace.update_in(cx, |workspace, window, cx| {
14778 assert!(workspace.right_dock().read(cx).is_open());
14779 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14780 });
14781 }
14782
14783 #[gpui::test]
14784 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14785 init_test(cx);
14786 let fs = FakeFs::new(cx.executor());
14787
14788 let project_a = Project::test(fs.clone(), [], cx).await;
14789 let project_b = Project::test(fs, [], cx).await;
14790
14791 let multi_workspace_handle =
14792 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14793 cx.run_until_parked();
14794
14795 multi_workspace_handle
14796 .update(cx, |mw, _window, cx| {
14797 mw.open_sidebar(cx);
14798 })
14799 .unwrap();
14800
14801 let workspace_a = multi_workspace_handle
14802 .read_with(cx, |mw, _| mw.workspace().clone())
14803 .unwrap();
14804
14805 let _workspace_b = multi_workspace_handle
14806 .update(cx, |mw, window, cx| {
14807 mw.test_add_workspace(project_b, window, cx)
14808 })
14809 .unwrap();
14810
14811 // Switch to workspace A
14812 multi_workspace_handle
14813 .update(cx, |mw, window, cx| {
14814 let workspace = mw.workspaces().next().unwrap().clone();
14815 mw.activate(workspace, window, cx);
14816 })
14817 .unwrap();
14818
14819 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14820
14821 // Add a panel to workspace A's right dock and open the dock
14822 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14823 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14824 workspace.add_panel(panel.clone(), window, cx);
14825 workspace
14826 .right_dock()
14827 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14828 panel
14829 });
14830
14831 // Focus the panel through the workspace (matching existing test pattern)
14832 workspace_a.update_in(cx, |workspace, window, cx| {
14833 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14834 });
14835
14836 // Zoom the panel
14837 panel.update_in(cx, |panel, window, cx| {
14838 panel.set_zoomed(true, window, cx);
14839 });
14840
14841 // Verify the panel is zoomed and the dock is open
14842 workspace_a.update_in(cx, |workspace, window, cx| {
14843 assert!(
14844 workspace.right_dock().read(cx).is_open(),
14845 "dock should be open before switch"
14846 );
14847 assert!(
14848 panel.is_zoomed(window, cx),
14849 "panel should be zoomed before switch"
14850 );
14851 assert!(
14852 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14853 "panel should be focused before switch"
14854 );
14855 });
14856
14857 // Switch to workspace B
14858 multi_workspace_handle
14859 .update(cx, |mw, window, cx| {
14860 let workspace = mw.workspaces().nth(1).unwrap().clone();
14861 mw.activate(workspace, window, cx);
14862 })
14863 .unwrap();
14864 cx.run_until_parked();
14865
14866 // Switch back to workspace A
14867 multi_workspace_handle
14868 .update(cx, |mw, window, cx| {
14869 let workspace = mw.workspaces().next().unwrap().clone();
14870 mw.activate(workspace, window, cx);
14871 })
14872 .unwrap();
14873 cx.run_until_parked();
14874
14875 // Verify the panel is still zoomed and the dock is still open
14876 workspace_a.update_in(cx, |workspace, window, cx| {
14877 assert!(
14878 workspace.right_dock().read(cx).is_open(),
14879 "dock should still be open after switching back"
14880 );
14881 assert!(
14882 panel.is_zoomed(window, cx),
14883 "panel should still be zoomed after switching back"
14884 );
14885 });
14886 }
14887
14888 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14889 pane.read(cx)
14890 .items()
14891 .flat_map(|item| {
14892 item.project_paths(cx)
14893 .into_iter()
14894 .map(|path| path.path.display(PathStyle::local()).into_owned())
14895 })
14896 .collect()
14897 }
14898
14899 pub fn init_test(cx: &mut TestAppContext) {
14900 cx.update(|cx| {
14901 let settings_store = SettingsStore::test(cx);
14902 cx.set_global(settings_store);
14903 cx.set_global(db::AppDatabase::test_new());
14904 theme_settings::init(theme::LoadThemes::JustBase, cx);
14905 });
14906 }
14907
14908 #[gpui::test]
14909 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14910 use settings::{ThemeName, ThemeSelection};
14911 use theme::SystemAppearance;
14912 use zed_actions::theme::ToggleMode;
14913
14914 init_test(cx);
14915
14916 let fs = FakeFs::new(cx.executor());
14917 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14918
14919 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14920 .await;
14921
14922 // Build a test project and workspace view so the test can invoke
14923 // the workspace action handler the same way the UI would.
14924 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14925 let (workspace, cx) =
14926 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14927
14928 // Seed the settings file with a plain static light theme so the
14929 // first toggle always starts from a known persisted state.
14930 workspace.update_in(cx, |_workspace, _window, cx| {
14931 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14932 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14933 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14934 });
14935 });
14936 cx.executor().advance_clock(Duration::from_millis(200));
14937 cx.run_until_parked();
14938
14939 // Confirm the initial persisted settings contain the static theme
14940 // we just wrote before any toggling happens.
14941 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14942 assert!(settings_text.contains(r#""theme": "One Light""#));
14943
14944 // Toggle once. This should migrate the persisted theme settings
14945 // into light/dark slots and enable system mode.
14946 workspace.update_in(cx, |workspace, window, cx| {
14947 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14948 });
14949 cx.executor().advance_clock(Duration::from_millis(200));
14950 cx.run_until_parked();
14951
14952 // 1. Static -> Dynamic
14953 // this assertion checks theme changed from static to dynamic.
14954 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14955 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14956 assert_eq!(
14957 parsed["theme"],
14958 serde_json::json!({
14959 "mode": "system",
14960 "light": "One Light",
14961 "dark": "One Dark"
14962 })
14963 );
14964
14965 // 2. Toggle again, suppose it will change the mode to light
14966 workspace.update_in(cx, |workspace, window, cx| {
14967 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14968 });
14969 cx.executor().advance_clock(Duration::from_millis(200));
14970 cx.run_until_parked();
14971
14972 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14973 assert!(settings_text.contains(r#""mode": "light""#));
14974 }
14975
14976 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14977 let item = TestProjectItem::new(id, path, cx);
14978 item.update(cx, |item, _| {
14979 item.is_dirty = true;
14980 });
14981 item
14982 }
14983
14984 #[gpui::test]
14985 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14986 cx: &mut gpui::TestAppContext,
14987 ) {
14988 init_test(cx);
14989 let fs = FakeFs::new(cx.executor());
14990
14991 let project = Project::test(fs, [], cx).await;
14992 let (workspace, cx) =
14993 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14994
14995 let panel = workspace.update_in(cx, |workspace, window, cx| {
14996 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14997 workspace.add_panel(panel.clone(), window, cx);
14998 workspace
14999 .right_dock()
15000 .update(cx, |dock, cx| dock.set_open(true, window, cx));
15001 panel
15002 });
15003
15004 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
15005 pane.update_in(cx, |pane, window, cx| {
15006 let item = cx.new(TestItem::new);
15007 pane.add_item(Box::new(item), true, true, None, window, cx);
15008 });
15009
15010 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
15011 // mirrors the real-world flow and avoids side effects from directly
15012 // focusing the panel while the center pane is active.
15013 workspace.update_in(cx, |workspace, window, cx| {
15014 workspace.toggle_panel_focus::<TestPanel>(window, cx);
15015 });
15016
15017 panel.update_in(cx, |panel, window, cx| {
15018 panel.set_zoomed(true, window, cx);
15019 });
15020
15021 workspace.update_in(cx, |workspace, window, cx| {
15022 assert!(workspace.right_dock().read(cx).is_open());
15023 assert!(panel.is_zoomed(window, cx));
15024 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
15025 });
15026
15027 // Simulate a spurious pane::Event::Focus on the center pane while the
15028 // panel still has focus. This mirrors what happens during macOS window
15029 // activation: the center pane fires a focus event even though actual
15030 // focus remains on the dock panel.
15031 pane.update_in(cx, |_, _, cx| {
15032 cx.emit(pane::Event::Focus);
15033 });
15034
15035 // The dock must remain open because the panel had focus at the time the
15036 // event was processed. Before the fix, dock_to_preserve was None for
15037 // panels that don't implement pane(), causing the dock to close.
15038 workspace.update_in(cx, |workspace, window, cx| {
15039 assert!(
15040 workspace.right_dock().read(cx).is_open(),
15041 "Dock should stay open when its zoomed panel (without pane()) still has focus"
15042 );
15043 assert!(panel.is_zoomed(window, cx));
15044 });
15045 }
15046
15047 #[gpui::test]
15048 async fn test_panels_stay_open_after_position_change_and_settings_update(
15049 cx: &mut gpui::TestAppContext,
15050 ) {
15051 init_test(cx);
15052 let fs = FakeFs::new(cx.executor());
15053 let project = Project::test(fs, [], cx).await;
15054 let (workspace, cx) =
15055 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
15056
15057 // Add two panels to the left dock and open it.
15058 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
15059 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
15060 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
15061 workspace.add_panel(panel_a.clone(), window, cx);
15062 workspace.add_panel(panel_b.clone(), window, cx);
15063 workspace.left_dock().update(cx, |dock, cx| {
15064 dock.set_open(true, window, cx);
15065 dock.activate_panel(0, window, cx);
15066 });
15067 (panel_a, panel_b)
15068 });
15069
15070 workspace.update_in(cx, |workspace, _, cx| {
15071 assert!(workspace.left_dock().read(cx).is_open());
15072 });
15073
15074 // Simulate a feature flag changing default dock positions: both panels
15075 // move from Left to Right.
15076 workspace.update_in(cx, |_workspace, _window, cx| {
15077 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
15078 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
15079 cx.update_global::<SettingsStore, _>(|_, _| {});
15080 });
15081
15082 // Both panels should now be in the right dock.
15083 workspace.update_in(cx, |workspace, _, cx| {
15084 let right_dock = workspace.right_dock().read(cx);
15085 assert_eq!(right_dock.panels_len(), 2);
15086 });
15087
15088 // Open the right dock and activate panel_b (simulating the user
15089 // opening the panel after it moved).
15090 workspace.update_in(cx, |workspace, window, cx| {
15091 workspace.right_dock().update(cx, |dock, cx| {
15092 dock.set_open(true, window, cx);
15093 dock.activate_panel(1, window, cx);
15094 });
15095 });
15096
15097 // Now trigger another SettingsStore change
15098 workspace.update_in(cx, |_workspace, _window, cx| {
15099 cx.update_global::<SettingsStore, _>(|_, _| {});
15100 });
15101
15102 workspace.update_in(cx, |workspace, _, cx| {
15103 assert!(
15104 workspace.right_dock().read(cx).is_open(),
15105 "Right dock should still be open after a settings change"
15106 );
15107 assert_eq!(
15108 workspace.right_dock().read(cx).panels_len(),
15109 2,
15110 "Both panels should still be in the right dock"
15111 );
15112 });
15113 }
15114}