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, MoveWorkspaceToNewWindow,
35 MultiWorkspace, MultiWorkspaceEvent, NewThread, NextProjectGroup, NextThread,
36 PreviousProjectGroup, PreviousThread, ShowFewerThreads, ShowMoreThreads, Sidebar, SidebarEvent,
37 SidebarHandle, SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar,
38 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 SerializedWorkspaceLocation, SessionWorkspace,
91 },
92 read_serialized_multi_workspaces, resolve_worktree_workspaces,
93};
94use postage::stream::Stream;
95use project::{
96 DirectoryLister, Project, ProjectEntryId, ProjectGroupKey, ProjectPath, ResolvedPath, Worktree,
97 WorktreeId, 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 active_worktree_override: Option<WorktreeId>,
1330 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1331 active_pane: Entity<Pane>,
1332 last_active_center_pane: Option<WeakEntity<Pane>>,
1333 last_active_view_id: Option<proto::ViewId>,
1334 status_bar: Entity<StatusBar>,
1335 pub(crate) modal_layer: Entity<ModalLayer>,
1336 toast_layer: Entity<ToastLayer>,
1337 titlebar_item: Option<AnyView>,
1338 notifications: Notifications,
1339 suppressed_notifications: HashSet<NotificationId>,
1340 project: Entity<Project>,
1341 follower_states: HashMap<CollaboratorId, FollowerState>,
1342 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1343 window_edited: bool,
1344 last_window_title: Option<String>,
1345 dirty_items: HashMap<EntityId, Subscription>,
1346 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1347 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1348 database_id: Option<WorkspaceId>,
1349 app_state: Arc<AppState>,
1350 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1351 _subscriptions: Vec<Subscription>,
1352 _apply_leader_updates: Task<Result<()>>,
1353 _observe_current_user: Task<Result<()>>,
1354 _schedule_serialize_workspace: Option<Task<()>>,
1355 _serialize_workspace_task: Option<Task<()>>,
1356 _schedule_serialize_ssh_paths: Option<Task<()>>,
1357 pane_history_timestamp: Arc<AtomicUsize>,
1358 bounds: Bounds<Pixels>,
1359 pub centered_layout: bool,
1360 bounds_save_task_queued: Option<Task<()>>,
1361 on_prompt_for_new_path: Option<PromptForNewPath>,
1362 on_prompt_for_open_path: Option<PromptForOpenPath>,
1363 terminal_provider: Option<Box<dyn TerminalProvider>>,
1364 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1365 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1366 _items_serializer: Task<Result<()>>,
1367 session_id: Option<String>,
1368 scheduled_tasks: Vec<Task<()>>,
1369 last_open_dock_positions: Vec<DockPosition>,
1370 removing: bool,
1371 open_in_dev_container: bool,
1372 _dev_container_task: Option<Task<Result<()>>>,
1373 _panels_task: Option<Task<Result<()>>>,
1374 sidebar_focus_handle: Option<FocusHandle>,
1375 multi_workspace: Option<WeakEntity<MultiWorkspace>>,
1376}
1377
1378impl EventEmitter<Event> for Workspace {}
1379
1380#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1381pub struct ViewId {
1382 pub creator: CollaboratorId,
1383 pub id: u64,
1384}
1385
1386pub struct FollowerState {
1387 center_pane: Entity<Pane>,
1388 dock_pane: Option<Entity<Pane>>,
1389 active_view_id: Option<ViewId>,
1390 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1391}
1392
1393struct FollowerView {
1394 view: Box<dyn FollowableItemHandle>,
1395 location: Option<proto::PanelId>,
1396}
1397
1398#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1399pub enum OpenMode {
1400 /// Open the workspace in a new window.
1401 NewWindow,
1402 /// Add to the window's multi workspace without activating it (used during deserialization).
1403 Add,
1404 /// Add to the window's multi workspace and activate it.
1405 #[default]
1406 Activate,
1407}
1408
1409impl Workspace {
1410 pub fn new(
1411 workspace_id: Option<WorkspaceId>,
1412 project: Entity<Project>,
1413 app_state: Arc<AppState>,
1414 window: &mut Window,
1415 cx: &mut Context<Self>,
1416 ) -> Self {
1417 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1418 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1419 if let TrustedWorktreesEvent::Trusted(..) = e {
1420 // Do not persist auto trusted worktrees
1421 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1422 worktrees_store.update(cx, |worktrees_store, cx| {
1423 worktrees_store.schedule_serialization(
1424 cx,
1425 |new_trusted_worktrees, cx| {
1426 let timeout =
1427 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1428 let db = WorkspaceDb::global(cx);
1429 cx.background_spawn(async move {
1430 timeout.await;
1431 db.save_trusted_worktrees(new_trusted_worktrees)
1432 .await
1433 .log_err();
1434 })
1435 },
1436 )
1437 });
1438 }
1439 }
1440 })
1441 .detach();
1442
1443 cx.observe_global::<SettingsStore>(|_, cx| {
1444 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1445 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1446 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1447 trusted_worktrees.auto_trust_all(cx);
1448 })
1449 }
1450 }
1451 })
1452 .detach();
1453 }
1454
1455 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1456 match event {
1457 project::Event::RemoteIdChanged(_) => {
1458 this.update_window_title(window, cx);
1459 }
1460
1461 project::Event::CollaboratorLeft(peer_id) => {
1462 this.collaborator_left(*peer_id, window, cx);
1463 }
1464
1465 &project::Event::WorktreeRemoved(_) => {
1466 this.update_window_title(window, cx);
1467 this.serialize_workspace(window, cx);
1468 this.update_history(cx);
1469 }
1470
1471 &project::Event::WorktreeAdded(id) => {
1472 this.update_window_title(window, cx);
1473 if this
1474 .project()
1475 .read(cx)
1476 .worktree_for_id(id, cx)
1477 .is_some_and(|wt| wt.read(cx).is_visible())
1478 {
1479 this.serialize_workspace(window, cx);
1480 this.update_history(cx);
1481 }
1482 }
1483 project::Event::WorktreeUpdatedEntries(..) => {
1484 this.update_window_title(window, cx);
1485 this.serialize_workspace(window, cx);
1486 }
1487
1488 project::Event::DisconnectedFromHost => {
1489 this.update_window_edited(window, cx);
1490 let leaders_to_unfollow =
1491 this.follower_states.keys().copied().collect::<Vec<_>>();
1492 for leader_id in leaders_to_unfollow {
1493 this.unfollow(leader_id, window, cx);
1494 }
1495 }
1496
1497 project::Event::DisconnectedFromRemote {
1498 server_not_running: _,
1499 } => {
1500 this.update_window_edited(window, cx);
1501 }
1502
1503 project::Event::Closed => {
1504 window.remove_window();
1505 }
1506
1507 project::Event::DeletedEntry(_, entry_id) => {
1508 for pane in this.panes.iter() {
1509 pane.update(cx, |pane, cx| {
1510 pane.handle_deleted_project_item(*entry_id, window, cx)
1511 });
1512 }
1513 }
1514
1515 project::Event::Toast {
1516 notification_id,
1517 message,
1518 link,
1519 } => this.show_notification(
1520 NotificationId::named(notification_id.clone()),
1521 cx,
1522 |cx| {
1523 let mut notification = MessageNotification::new(message.clone(), cx);
1524 if let Some(link) = link {
1525 notification = notification
1526 .more_info_message(link.label)
1527 .more_info_url(link.url);
1528 }
1529
1530 cx.new(|_| notification)
1531 },
1532 ),
1533
1534 project::Event::HideToast { notification_id } => {
1535 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1536 }
1537
1538 project::Event::LanguageServerPrompt(request) => {
1539 struct LanguageServerPrompt;
1540
1541 this.show_notification(
1542 NotificationId::composite::<LanguageServerPrompt>(request.id),
1543 cx,
1544 |cx| {
1545 cx.new(|cx| {
1546 notifications::LanguageServerPrompt::new(request.clone(), cx)
1547 })
1548 },
1549 );
1550 }
1551
1552 project::Event::AgentLocationChanged => {
1553 this.handle_agent_location_changed(window, cx)
1554 }
1555
1556 _ => {}
1557 }
1558 cx.notify()
1559 })
1560 .detach();
1561
1562 cx.subscribe_in(
1563 &project.read(cx).breakpoint_store(),
1564 window,
1565 |workspace, _, event, window, cx| match event {
1566 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1567 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1568 workspace.serialize_workspace(window, cx);
1569 }
1570 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1571 },
1572 )
1573 .detach();
1574 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1575 cx.subscribe_in(
1576 &toolchain_store,
1577 window,
1578 |workspace, _, event, window, cx| match event {
1579 ToolchainStoreEvent::CustomToolchainsModified => {
1580 workspace.serialize_workspace(window, cx);
1581 }
1582 _ => {}
1583 },
1584 )
1585 .detach();
1586 }
1587
1588 cx.on_focus_lost(window, |this, window, cx| {
1589 let focus_handle = this.focus_handle(cx);
1590 window.focus(&focus_handle, cx);
1591 })
1592 .detach();
1593
1594 let weak_handle = cx.entity().downgrade();
1595 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1596
1597 let center_pane = cx.new(|cx| {
1598 let mut center_pane = Pane::new(
1599 weak_handle.clone(),
1600 project.clone(),
1601 pane_history_timestamp.clone(),
1602 None,
1603 NewFile.boxed_clone(),
1604 true,
1605 window,
1606 cx,
1607 );
1608 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1609 center_pane.set_should_display_welcome_page(true);
1610 center_pane
1611 });
1612 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1613 .detach();
1614
1615 window.focus(¢er_pane.focus_handle(cx), cx);
1616
1617 cx.emit(Event::PaneAdded(center_pane.clone()));
1618
1619 let any_window_handle = window.window_handle();
1620 app_state.workspace_store.update(cx, |store, _| {
1621 store
1622 .workspaces
1623 .insert((any_window_handle, weak_handle.clone()));
1624 });
1625
1626 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1627 let mut connection_status = app_state.client.status();
1628 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1629 current_user.next().await;
1630 connection_status.next().await;
1631 let mut stream =
1632 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1633
1634 while stream.recv().await.is_some() {
1635 this.update(cx, |_, cx| cx.notify())?;
1636 }
1637 anyhow::Ok(())
1638 });
1639
1640 // All leader updates are enqueued and then processed in a single task, so
1641 // that each asynchronous operation can be run in order.
1642 let (leader_updates_tx, mut leader_updates_rx) =
1643 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1644 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1645 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1646 Self::process_leader_update(&this, leader_id, update, cx)
1647 .await
1648 .log_err();
1649 }
1650
1651 Ok(())
1652 });
1653
1654 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1655 let modal_layer = cx.new(|_| ModalLayer::new());
1656 let toast_layer = cx.new(|_| ToastLayer::new());
1657 cx.subscribe(
1658 &modal_layer,
1659 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1660 cx.emit(Event::ModalOpened);
1661 },
1662 )
1663 .detach();
1664
1665 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1666 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1667 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1668 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1669 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1670 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1671 let multi_workspace = window
1672 .root::<MultiWorkspace>()
1673 .flatten()
1674 .map(|mw| mw.downgrade());
1675 let status_bar = cx.new(|cx| {
1676 let mut status_bar =
1677 StatusBar::new(¢er_pane.clone(), multi_workspace.clone(), window, cx);
1678 status_bar.add_left_item(left_dock_buttons, window, cx);
1679 status_bar.add_right_item(right_dock_buttons, window, cx);
1680 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1681 status_bar
1682 });
1683
1684 let session_id = app_state.session.read(cx).id().to_owned();
1685
1686 let mut active_call = None;
1687 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1688 let subscriptions =
1689 vec![
1690 call.0
1691 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1692 ];
1693 active_call = Some((call, subscriptions));
1694 }
1695
1696 let (serializable_items_tx, serializable_items_rx) =
1697 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1698 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1699 Self::serialize_items(&this, serializable_items_rx, cx).await
1700 });
1701
1702 let subscriptions = vec![
1703 cx.observe_window_activation(window, Self::on_window_activation_changed),
1704 cx.observe_window_bounds(window, move |this, window, cx| {
1705 if this.bounds_save_task_queued.is_some() {
1706 return;
1707 }
1708 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1709 cx.background_executor()
1710 .timer(Duration::from_millis(100))
1711 .await;
1712 this.update_in(cx, |this, window, cx| {
1713 this.save_window_bounds(window, cx).detach();
1714 this.bounds_save_task_queued.take();
1715 })
1716 .ok();
1717 }));
1718 cx.notify();
1719 }),
1720 cx.observe_window_appearance(window, |_, window, cx| {
1721 let window_appearance = window.appearance();
1722
1723 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1724
1725 theme_settings::reload_theme(cx);
1726 theme_settings::reload_icon_theme(cx);
1727 }),
1728 cx.on_release({
1729 let weak_handle = weak_handle.clone();
1730 move |this, cx| {
1731 this.app_state.workspace_store.update(cx, move |store, _| {
1732 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1733 })
1734 }
1735 }),
1736 ];
1737
1738 cx.defer_in(window, move |this, window, cx| {
1739 this.update_window_title(window, cx);
1740 this.show_initial_notifications(cx);
1741 });
1742
1743 let mut center = PaneGroup::new(center_pane.clone());
1744 center.set_is_center(true);
1745 center.mark_positions(cx);
1746
1747 Workspace {
1748 weak_self: weak_handle.clone(),
1749 zoomed: None,
1750 zoomed_position: None,
1751 previous_dock_drag_coordinates: None,
1752 center,
1753 panes: vec![center_pane.clone()],
1754 panes_by_item: Default::default(),
1755 active_pane: center_pane.clone(),
1756 last_active_center_pane: Some(center_pane.downgrade()),
1757 last_active_view_id: None,
1758 status_bar,
1759 modal_layer,
1760 toast_layer,
1761 titlebar_item: None,
1762 active_worktree_override: None,
1763 notifications: Notifications::default(),
1764 suppressed_notifications: HashSet::default(),
1765 left_dock,
1766 bottom_dock,
1767 right_dock,
1768 _panels_task: None,
1769 project: project.clone(),
1770 follower_states: Default::default(),
1771 last_leaders_by_pane: Default::default(),
1772 dispatching_keystrokes: Default::default(),
1773 window_edited: false,
1774 last_window_title: None,
1775 dirty_items: Default::default(),
1776 active_call,
1777 database_id: workspace_id,
1778 app_state,
1779 _observe_current_user,
1780 _apply_leader_updates,
1781 _schedule_serialize_workspace: None,
1782 _serialize_workspace_task: None,
1783 _schedule_serialize_ssh_paths: None,
1784 leader_updates_tx,
1785 _subscriptions: subscriptions,
1786 pane_history_timestamp,
1787 workspace_actions: Default::default(),
1788 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1789 bounds: Default::default(),
1790 centered_layout: false,
1791 bounds_save_task_queued: None,
1792 on_prompt_for_new_path: None,
1793 on_prompt_for_open_path: None,
1794 terminal_provider: None,
1795 debugger_provider: None,
1796 serializable_items_tx,
1797 _items_serializer,
1798 session_id: Some(session_id),
1799
1800 scheduled_tasks: Vec::new(),
1801 last_open_dock_positions: Vec::new(),
1802 removing: false,
1803 sidebar_focus_handle: None,
1804 multi_workspace,
1805 open_in_dev_container: false,
1806 _dev_container_task: None,
1807 }
1808 }
1809
1810 pub fn new_local(
1811 abs_paths: Vec<PathBuf>,
1812 app_state: Arc<AppState>,
1813 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1814 env: Option<HashMap<String, String>>,
1815 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1816 open_mode: OpenMode,
1817 cx: &mut App,
1818 ) -> Task<anyhow::Result<OpenResult>> {
1819 let project_handle = Project::local(
1820 app_state.client.clone(),
1821 app_state.node_runtime.clone(),
1822 app_state.user_store.clone(),
1823 app_state.languages.clone(),
1824 app_state.fs.clone(),
1825 env,
1826 Default::default(),
1827 cx,
1828 );
1829
1830 let db = WorkspaceDb::global(cx);
1831 let kvp = db::kvp::KeyValueStore::global(cx);
1832 cx.spawn(async move |cx| {
1833 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1834 for path in abs_paths.into_iter() {
1835 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1836 paths_to_open.push(canonical)
1837 } else {
1838 paths_to_open.push(path)
1839 }
1840 }
1841
1842 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1843
1844 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1845 paths_to_open = paths.ordered_paths().cloned().collect();
1846 if !paths.is_lexicographically_ordered() {
1847 project_handle.update(cx, |project, cx| {
1848 project.set_worktrees_reordered(true, cx);
1849 });
1850 }
1851 }
1852
1853 // Get project paths for all of the abs_paths
1854 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1855 Vec::with_capacity(paths_to_open.len());
1856
1857 for path in paths_to_open.into_iter() {
1858 if let Some((_, project_entry)) = cx
1859 .update(|cx| {
1860 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1861 })
1862 .await
1863 .log_err()
1864 {
1865 project_paths.push((path, Some(project_entry)));
1866 } else {
1867 project_paths.push((path, None));
1868 }
1869 }
1870
1871 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1872 serialized_workspace.id
1873 } else {
1874 db.next_id().await.unwrap_or_else(|_| Default::default())
1875 };
1876
1877 let toolchains = db.toolchains(workspace_id).await?;
1878
1879 for (toolchain, worktree_path, path) in toolchains {
1880 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1881 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1882 this.find_worktree(&worktree_path, cx)
1883 .and_then(|(worktree, rel_path)| {
1884 if rel_path.is_empty() {
1885 Some(worktree.read(cx).id())
1886 } else {
1887 None
1888 }
1889 })
1890 }) else {
1891 // We did not find a worktree with a given path, but that's whatever.
1892 continue;
1893 };
1894 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1895 continue;
1896 }
1897
1898 project_handle
1899 .update(cx, |this, cx| {
1900 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1901 })
1902 .await;
1903 }
1904 if let Some(workspace) = serialized_workspace.as_ref() {
1905 project_handle.update(cx, |this, cx| {
1906 for (scope, toolchains) in &workspace.user_toolchains {
1907 for toolchain in toolchains {
1908 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1909 }
1910 }
1911 });
1912 }
1913
1914 let window_to_replace = match open_mode {
1915 OpenMode::NewWindow => None,
1916 _ => requesting_window,
1917 };
1918
1919 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1920 if let Some(window) = window_to_replace {
1921 let centered_layout = serialized_workspace
1922 .as_ref()
1923 .map(|w| w.centered_layout)
1924 .unwrap_or(false);
1925
1926 let workspace = window.update(cx, |multi_workspace, window, cx| {
1927 let workspace = cx.new(|cx| {
1928 let mut workspace = Workspace::new(
1929 Some(workspace_id),
1930 project_handle.clone(),
1931 app_state.clone(),
1932 window,
1933 cx,
1934 );
1935
1936 workspace.centered_layout = centered_layout;
1937
1938 // Call init callback to add items before window renders
1939 if let Some(init) = init {
1940 init(&mut workspace, window, cx);
1941 }
1942
1943 workspace
1944 });
1945 match open_mode {
1946 OpenMode::Activate => {
1947 multi_workspace.activate(workspace.clone(), window, cx);
1948 }
1949 OpenMode::Add => {
1950 multi_workspace.add(workspace.clone(), &*window, cx);
1951 }
1952 OpenMode::NewWindow => {
1953 unreachable!()
1954 }
1955 }
1956 workspace
1957 })?;
1958 (window, workspace)
1959 } else {
1960 let window_bounds_override = window_bounds_env_override();
1961
1962 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1963 (Some(WindowBounds::Windowed(bounds)), None)
1964 } else if let Some(workspace) = serialized_workspace.as_ref()
1965 && let Some(display) = workspace.display
1966 && let Some(bounds) = workspace.window_bounds.as_ref()
1967 {
1968 // Reopening an existing workspace - restore its saved bounds
1969 (Some(bounds.0), Some(display))
1970 } else if let Some((display, bounds)) =
1971 persistence::read_default_window_bounds(&kvp)
1972 {
1973 // New or empty workspace - use the last known window bounds
1974 (Some(bounds), Some(display))
1975 } else {
1976 // New window - let GPUI's default_bounds() handle cascading
1977 (None, None)
1978 };
1979
1980 // Use the serialized workspace to construct the new window
1981 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1982 options.window_bounds = window_bounds;
1983 let centered_layout = serialized_workspace
1984 .as_ref()
1985 .map(|w| w.centered_layout)
1986 .unwrap_or(false);
1987 let window = cx.open_window(options, {
1988 let app_state = app_state.clone();
1989 let project_handle = project_handle.clone();
1990 move |window, cx| {
1991 let workspace = cx.new(|cx| {
1992 let mut workspace = Workspace::new(
1993 Some(workspace_id),
1994 project_handle,
1995 app_state,
1996 window,
1997 cx,
1998 );
1999 workspace.centered_layout = centered_layout;
2000
2001 // Call init callback to add items before window renders
2002 if let Some(init) = init {
2003 init(&mut workspace, window, cx);
2004 }
2005
2006 workspace
2007 });
2008 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
2009 }
2010 })?;
2011 let workspace =
2012 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
2013 multi_workspace.workspace().clone()
2014 })?;
2015 (window, workspace)
2016 };
2017
2018 notify_if_database_failed(window, cx);
2019 // Check if this is an empty workspace (no paths to open)
2020 // An empty workspace is one where project_paths is empty
2021 let is_empty_workspace = project_paths.is_empty();
2022 // Check if serialized workspace has paths before it's moved
2023 let serialized_workspace_has_paths = serialized_workspace
2024 .as_ref()
2025 .map(|ws| !ws.paths.is_empty())
2026 .unwrap_or(false);
2027
2028 let opened_items = window
2029 .update(cx, |_, window, cx| {
2030 workspace.update(cx, |_workspace: &mut Workspace, cx| {
2031 open_items(serialized_workspace, project_paths, window, cx)
2032 })
2033 })?
2034 .await
2035 .unwrap_or_default();
2036
2037 // Restore default dock state for empty workspaces
2038 // Only restore if:
2039 // 1. This is an empty workspace (no paths), AND
2040 // 2. The serialized workspace either doesn't exist or has no paths
2041 if is_empty_workspace && !serialized_workspace_has_paths {
2042 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
2043 window
2044 .update(cx, |_, window, cx| {
2045 workspace.update(cx, |workspace, cx| {
2046 for (dock, serialized_dock) in [
2047 (&workspace.right_dock, &default_docks.right),
2048 (&workspace.left_dock, &default_docks.left),
2049 (&workspace.bottom_dock, &default_docks.bottom),
2050 ] {
2051 dock.update(cx, |dock, cx| {
2052 dock.serialized_dock = Some(serialized_dock.clone());
2053 dock.restore_state(window, cx);
2054 });
2055 }
2056 cx.notify();
2057 });
2058 })
2059 .log_err();
2060 }
2061 }
2062
2063 window
2064 .update(cx, |_, _window, cx| {
2065 workspace.update(cx, |this: &mut Workspace, cx| {
2066 this.update_history(cx);
2067 });
2068 })
2069 .log_err();
2070 Ok(OpenResult {
2071 window,
2072 workspace,
2073 opened_items,
2074 })
2075 })
2076 }
2077
2078 pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
2079 self.project.read(cx).project_group_key(cx)
2080 }
2081
2082 pub fn weak_handle(&self) -> WeakEntity<Self> {
2083 self.weak_self.clone()
2084 }
2085
2086 pub fn left_dock(&self) -> &Entity<Dock> {
2087 &self.left_dock
2088 }
2089
2090 pub fn bottom_dock(&self) -> &Entity<Dock> {
2091 &self.bottom_dock
2092 }
2093
2094 pub fn set_bottom_dock_layout(
2095 &mut self,
2096 layout: BottomDockLayout,
2097 window: &mut Window,
2098 cx: &mut Context<Self>,
2099 ) {
2100 let fs = self.project().read(cx).fs();
2101 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2102 content.workspace.bottom_dock_layout = Some(layout);
2103 });
2104
2105 cx.notify();
2106 self.serialize_workspace(window, cx);
2107 }
2108
2109 pub fn right_dock(&self) -> &Entity<Dock> {
2110 &self.right_dock
2111 }
2112
2113 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2114 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2115 }
2116
2117 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2118 let left_dock = self.left_dock.read(cx);
2119 let left_visible = left_dock.is_open();
2120 let left_active_panel = left_dock
2121 .active_panel()
2122 .map(|panel| panel.persistent_name().to_string());
2123 // `zoomed_position` is kept in sync with individual panel zoom state
2124 // by the dock code in `Dock::new` and `Dock::add_panel`.
2125 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2126
2127 let right_dock = self.right_dock.read(cx);
2128 let right_visible = right_dock.is_open();
2129 let right_active_panel = right_dock
2130 .active_panel()
2131 .map(|panel| panel.persistent_name().to_string());
2132 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2133
2134 let bottom_dock = self.bottom_dock.read(cx);
2135 let bottom_visible = bottom_dock.is_open();
2136 let bottom_active_panel = bottom_dock
2137 .active_panel()
2138 .map(|panel| panel.persistent_name().to_string());
2139 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2140
2141 DockStructure {
2142 left: DockData {
2143 visible: left_visible,
2144 active_panel: left_active_panel,
2145 zoom: left_dock_zoom,
2146 },
2147 right: DockData {
2148 visible: right_visible,
2149 active_panel: right_active_panel,
2150 zoom: right_dock_zoom,
2151 },
2152 bottom: DockData {
2153 visible: bottom_visible,
2154 active_panel: bottom_active_panel,
2155 zoom: bottom_dock_zoom,
2156 },
2157 }
2158 }
2159
2160 pub fn set_dock_structure(
2161 &self,
2162 docks: DockStructure,
2163 window: &mut Window,
2164 cx: &mut Context<Self>,
2165 ) {
2166 for (dock, data) in [
2167 (&self.left_dock, docks.left),
2168 (&self.bottom_dock, docks.bottom),
2169 (&self.right_dock, docks.right),
2170 ] {
2171 dock.update(cx, |dock, cx| {
2172 dock.serialized_dock = Some(data);
2173 dock.restore_state(window, cx);
2174 });
2175 }
2176 }
2177
2178 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2179 self.items(cx)
2180 .filter_map(|item| {
2181 let project_path = item.project_path(cx)?;
2182 self.project.read(cx).absolute_path(&project_path, cx)
2183 })
2184 .collect()
2185 }
2186
2187 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2188 match position {
2189 DockPosition::Left => &self.left_dock,
2190 DockPosition::Bottom => &self.bottom_dock,
2191 DockPosition::Right => &self.right_dock,
2192 }
2193 }
2194
2195 pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
2196 self.all_docks().into_iter().find_map(|dock| {
2197 let dock = dock.read(cx);
2198 dock.has_agent_panel(cx).then_some(dock.position())
2199 })
2200 }
2201
2202 pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
2203 self.all_docks().into_iter().find_map(|dock| {
2204 let dock = dock.read(cx);
2205 let panel = dock.panel::<T>()?;
2206 dock.stored_panel_size_state(&panel)
2207 })
2208 }
2209
2210 pub fn persisted_panel_size_state(
2211 &self,
2212 panel_key: &'static str,
2213 cx: &App,
2214 ) -> Option<dock::PanelSizeState> {
2215 dock::Dock::load_persisted_size_state(self, panel_key, cx)
2216 }
2217
2218 pub fn persist_panel_size_state(
2219 &self,
2220 panel_key: &str,
2221 size_state: dock::PanelSizeState,
2222 cx: &mut App,
2223 ) {
2224 let Some(workspace_id) = self
2225 .database_id()
2226 .map(|id| i64::from(id).to_string())
2227 .or(self.session_id())
2228 else {
2229 return;
2230 };
2231
2232 let kvp = db::kvp::KeyValueStore::global(cx);
2233 let panel_key = panel_key.to_string();
2234 cx.background_spawn(async move {
2235 let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
2236 scope
2237 .write(
2238 format!("{workspace_id}:{panel_key}"),
2239 serde_json::to_string(&size_state)?,
2240 )
2241 .await
2242 })
2243 .detach_and_log_err(cx);
2244 }
2245
2246 pub fn set_panel_size_state<T: Panel>(
2247 &mut self,
2248 size_state: dock::PanelSizeState,
2249 window: &mut Window,
2250 cx: &mut Context<Self>,
2251 ) -> bool {
2252 let Some(panel) = self.panel::<T>(cx) else {
2253 return false;
2254 };
2255
2256 let dock = self.dock_at_position(panel.position(window, cx));
2257 let did_set = dock.update(cx, |dock, cx| {
2258 dock.set_panel_size_state(&panel, size_state, cx)
2259 });
2260
2261 if did_set {
2262 self.persist_panel_size_state(T::panel_key(), size_state, cx);
2263 }
2264
2265 did_set
2266 }
2267
2268 pub fn toggle_dock_panel_flexible_size(
2269 &self,
2270 dock: &Entity<Dock>,
2271 panel: &dyn PanelHandle,
2272 window: &mut Window,
2273 cx: &mut App,
2274 ) {
2275 let position = dock.read(cx).position();
2276 let current_size = self.dock_size(&dock.read(cx), window, cx);
2277 let current_flex =
2278 current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
2279 dock.update(cx, |dock, cx| {
2280 dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
2281 });
2282 }
2283
2284 fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
2285 let panel = dock.active_panel()?;
2286 let size_state = dock
2287 .stored_panel_size_state(panel.as_ref())
2288 .unwrap_or_default();
2289 let position = dock.position();
2290
2291 let use_flex = panel.has_flexible_size(window, cx);
2292
2293 if position.axis() == Axis::Horizontal
2294 && use_flex
2295 && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
2296 {
2297 let workspace_width = self.bounds.size.width;
2298 if workspace_width <= Pixels::ZERO {
2299 return None;
2300 }
2301 let flex = flex.max(0.001);
2302 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2303 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2304 // Both docks are flex items sharing the full workspace width.
2305 let total_flex = flex + 1.0 + opposite_flex;
2306 return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
2307 } else {
2308 // Opposite dock is fixed-width; flex items share (W - fixed).
2309 let opposite_fixed = opposite
2310 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2311 .unwrap_or_default();
2312 let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
2313 return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
2314 }
2315 }
2316
2317 Some(
2318 size_state
2319 .size
2320 .unwrap_or_else(|| panel.default_size(window, cx)),
2321 )
2322 }
2323
2324 pub fn dock_flex_for_size(
2325 &self,
2326 position: DockPosition,
2327 size: Pixels,
2328 window: &Window,
2329 cx: &App,
2330 ) -> Option<f32> {
2331 if position.axis() != Axis::Horizontal {
2332 return None;
2333 }
2334
2335 let workspace_width = self.bounds.size.width;
2336 if workspace_width <= Pixels::ZERO {
2337 return None;
2338 }
2339
2340 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2341 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2342 let size = size.clamp(px(0.), workspace_width - px(1.));
2343 Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
2344 } else {
2345 let opposite_width = opposite
2346 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2347 .unwrap_or_default();
2348 let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
2349 let remaining = (available - size).max(px(1.));
2350 Some((size / remaining).max(0.0))
2351 }
2352 }
2353
2354 fn opposite_dock_panel_and_size_state(
2355 &self,
2356 position: DockPosition,
2357 window: &Window,
2358 cx: &App,
2359 ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
2360 let opposite_position = match position {
2361 DockPosition::Left => DockPosition::Right,
2362 DockPosition::Right => DockPosition::Left,
2363 DockPosition::Bottom => return None,
2364 };
2365
2366 let opposite_dock = self.dock_at_position(opposite_position).read(cx);
2367 let panel = opposite_dock.visible_panel()?;
2368 let mut size_state = opposite_dock
2369 .stored_panel_size_state(panel.as_ref())
2370 .unwrap_or_default();
2371 if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
2372 size_state.flex = self.default_dock_flex(opposite_position);
2373 }
2374 Some((panel.clone(), size_state))
2375 }
2376
2377 pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
2378 if position.axis() != Axis::Horizontal {
2379 return None;
2380 }
2381
2382 let pane = self.last_active_center_pane.clone()?.upgrade()?;
2383 Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
2384 }
2385
2386 pub fn is_edited(&self) -> bool {
2387 self.window_edited
2388 }
2389
2390 pub fn add_panel<T: Panel>(
2391 &mut self,
2392 panel: Entity<T>,
2393 window: &mut Window,
2394 cx: &mut Context<Self>,
2395 ) {
2396 let focus_handle = panel.panel_focus_handle(cx);
2397 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2398 .detach();
2399
2400 let dock_position = panel.position(window, cx);
2401 let dock = self.dock_at_position(dock_position);
2402 let any_panel = panel.to_any();
2403 let persisted_size_state =
2404 self.persisted_panel_size_state(T::panel_key(), cx)
2405 .or_else(|| {
2406 load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
2407 let state = dock::PanelSizeState {
2408 size: Some(size),
2409 flex: None,
2410 };
2411 self.persist_panel_size_state(T::panel_key(), state, cx);
2412 state
2413 })
2414 });
2415
2416 dock.update(cx, |dock, cx| {
2417 let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
2418 if let Some(size_state) = persisted_size_state {
2419 dock.set_panel_size_state(&panel, size_state, cx);
2420 }
2421 index
2422 });
2423
2424 cx.emit(Event::PanelAdded(any_panel));
2425 }
2426
2427 pub fn remove_panel<T: Panel>(
2428 &mut self,
2429 panel: &Entity<T>,
2430 window: &mut Window,
2431 cx: &mut Context<Self>,
2432 ) {
2433 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2434 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2435 }
2436 }
2437
2438 pub fn status_bar(&self) -> &Entity<StatusBar> {
2439 &self.status_bar
2440 }
2441
2442 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2443 self.sidebar_focus_handle = handle;
2444 }
2445
2446 pub fn status_bar_visible(&self, cx: &App) -> bool {
2447 StatusBarSettings::get_global(cx).show
2448 }
2449
2450 pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
2451 self.multi_workspace.as_ref()
2452 }
2453
2454 pub fn set_multi_workspace(
2455 &mut self,
2456 multi_workspace: WeakEntity<MultiWorkspace>,
2457 cx: &mut App,
2458 ) {
2459 self.status_bar.update(cx, |status_bar, cx| {
2460 status_bar.set_multi_workspace(multi_workspace.clone(), cx);
2461 });
2462 self.multi_workspace = Some(multi_workspace);
2463 }
2464
2465 pub fn app_state(&self) -> &Arc<AppState> {
2466 &self.app_state
2467 }
2468
2469 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2470 self._panels_task = Some(task);
2471 }
2472
2473 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2474 self._panels_task.take()
2475 }
2476
2477 pub fn user_store(&self) -> &Entity<UserStore> {
2478 &self.app_state.user_store
2479 }
2480
2481 pub fn project(&self) -> &Entity<Project> {
2482 &self.project
2483 }
2484
2485 pub fn path_style(&self, cx: &App) -> PathStyle {
2486 self.project.read(cx).path_style(cx)
2487 }
2488
2489 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2490 let mut history: HashMap<EntityId, usize> = HashMap::default();
2491
2492 for pane_handle in &self.panes {
2493 let pane = pane_handle.read(cx);
2494
2495 for entry in pane.activation_history() {
2496 history.insert(
2497 entry.entity_id,
2498 history
2499 .get(&entry.entity_id)
2500 .cloned()
2501 .unwrap_or(0)
2502 .max(entry.timestamp),
2503 );
2504 }
2505 }
2506
2507 history
2508 }
2509
2510 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2511 let mut recent_item: Option<Entity<T>> = None;
2512 let mut recent_timestamp = 0;
2513 for pane_handle in &self.panes {
2514 let pane = pane_handle.read(cx);
2515 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2516 pane.items().map(|item| (item.item_id(), item)).collect();
2517 for entry in pane.activation_history() {
2518 if entry.timestamp > recent_timestamp
2519 && let Some(&item) = item_map.get(&entry.entity_id)
2520 && let Some(typed_item) = item.act_as::<T>(cx)
2521 {
2522 recent_timestamp = entry.timestamp;
2523 recent_item = Some(typed_item);
2524 }
2525 }
2526 }
2527 recent_item
2528 }
2529
2530 pub fn recent_navigation_history_iter(
2531 &self,
2532 cx: &App,
2533 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2534 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2535 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2536
2537 for pane in &self.panes {
2538 let pane = pane.read(cx);
2539
2540 pane.nav_history()
2541 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2542 if let Some(fs_path) = &fs_path {
2543 abs_paths_opened
2544 .entry(fs_path.clone())
2545 .or_default()
2546 .insert(project_path.clone());
2547 }
2548 let timestamp = entry.timestamp;
2549 match history.entry(project_path) {
2550 hash_map::Entry::Occupied(mut entry) => {
2551 let (_, old_timestamp) = entry.get();
2552 if ×tamp > old_timestamp {
2553 entry.insert((fs_path, timestamp));
2554 }
2555 }
2556 hash_map::Entry::Vacant(entry) => {
2557 entry.insert((fs_path, timestamp));
2558 }
2559 }
2560 });
2561
2562 if let Some(item) = pane.active_item()
2563 && let Some(project_path) = item.project_path(cx)
2564 {
2565 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2566
2567 if let Some(fs_path) = &fs_path {
2568 abs_paths_opened
2569 .entry(fs_path.clone())
2570 .or_default()
2571 .insert(project_path.clone());
2572 }
2573
2574 history.insert(project_path, (fs_path, std::usize::MAX));
2575 }
2576 }
2577
2578 history
2579 .into_iter()
2580 .sorted_by_key(|(_, (_, order))| *order)
2581 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2582 .rev()
2583 .filter(move |(history_path, abs_path)| {
2584 let latest_project_path_opened = abs_path
2585 .as_ref()
2586 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2587 .and_then(|project_paths| {
2588 project_paths
2589 .iter()
2590 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2591 });
2592
2593 latest_project_path_opened.is_none_or(|path| path == history_path)
2594 })
2595 }
2596
2597 pub fn recent_navigation_history(
2598 &self,
2599 limit: Option<usize>,
2600 cx: &App,
2601 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2602 self.recent_navigation_history_iter(cx)
2603 .take(limit.unwrap_or(usize::MAX))
2604 .collect()
2605 }
2606
2607 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2608 for pane in &self.panes {
2609 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2610 }
2611 }
2612
2613 fn navigate_history(
2614 &mut self,
2615 pane: WeakEntity<Pane>,
2616 mode: NavigationMode,
2617 window: &mut Window,
2618 cx: &mut Context<Workspace>,
2619 ) -> Task<Result<()>> {
2620 self.navigate_history_impl(
2621 pane,
2622 mode,
2623 window,
2624 &mut |history, cx| history.pop(mode, cx),
2625 cx,
2626 )
2627 }
2628
2629 fn navigate_tag_history(
2630 &mut self,
2631 pane: WeakEntity<Pane>,
2632 mode: TagNavigationMode,
2633 window: &mut Window,
2634 cx: &mut Context<Workspace>,
2635 ) -> Task<Result<()>> {
2636 self.navigate_history_impl(
2637 pane,
2638 NavigationMode::Normal,
2639 window,
2640 &mut |history, _cx| history.pop_tag(mode),
2641 cx,
2642 )
2643 }
2644
2645 fn navigate_history_impl(
2646 &mut self,
2647 pane: WeakEntity<Pane>,
2648 mode: NavigationMode,
2649 window: &mut Window,
2650 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2651 cx: &mut Context<Workspace>,
2652 ) -> Task<Result<()>> {
2653 let to_load = if let Some(pane) = pane.upgrade() {
2654 pane.update(cx, |pane, cx| {
2655 window.focus(&pane.focus_handle(cx), cx);
2656 loop {
2657 // Retrieve the weak item handle from the history.
2658 let entry = cb(pane.nav_history_mut(), cx)?;
2659
2660 // If the item is still present in this pane, then activate it.
2661 if let Some(index) = entry
2662 .item
2663 .upgrade()
2664 .and_then(|v| pane.index_for_item(v.as_ref()))
2665 {
2666 let prev_active_item_index = pane.active_item_index();
2667 pane.nav_history_mut().set_mode(mode);
2668 pane.activate_item(index, true, true, window, cx);
2669 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2670
2671 let mut navigated = prev_active_item_index != pane.active_item_index();
2672 if let Some(data) = entry.data {
2673 navigated |= pane.active_item()?.navigate(data, window, cx);
2674 }
2675
2676 if navigated {
2677 break None;
2678 }
2679 } else {
2680 // If the item is no longer present in this pane, then retrieve its
2681 // path info in order to reopen it.
2682 break pane
2683 .nav_history()
2684 .path_for_item(entry.item.id())
2685 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2686 }
2687 }
2688 })
2689 } else {
2690 None
2691 };
2692
2693 if let Some((project_path, abs_path, entry)) = to_load {
2694 // If the item was no longer present, then load it again from its previous path, first try the local path
2695 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2696
2697 cx.spawn_in(window, async move |workspace, cx| {
2698 let open_by_project_path = open_by_project_path.await;
2699 let mut navigated = false;
2700 match open_by_project_path
2701 .with_context(|| format!("Navigating to {project_path:?}"))
2702 {
2703 Ok((project_entry_id, build_item)) => {
2704 let prev_active_item_id = pane.update(cx, |pane, _| {
2705 pane.nav_history_mut().set_mode(mode);
2706 pane.active_item().map(|p| p.item_id())
2707 })?;
2708
2709 pane.update_in(cx, |pane, window, cx| {
2710 let item = pane.open_item(
2711 project_entry_id,
2712 project_path,
2713 true,
2714 entry.is_preview,
2715 true,
2716 None,
2717 window, cx,
2718 build_item,
2719 );
2720 navigated |= Some(item.item_id()) != prev_active_item_id;
2721 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2722 if let Some(data) = entry.data {
2723 navigated |= item.navigate(data, window, cx);
2724 }
2725 })?;
2726 }
2727 Err(open_by_project_path_e) => {
2728 // Fall back to opening by abs path, in case an external file was opened and closed,
2729 // and its worktree is now dropped
2730 if let Some(abs_path) = abs_path {
2731 let prev_active_item_id = pane.update(cx, |pane, _| {
2732 pane.nav_history_mut().set_mode(mode);
2733 pane.active_item().map(|p| p.item_id())
2734 })?;
2735 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2736 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2737 })?;
2738 match open_by_abs_path
2739 .await
2740 .with_context(|| format!("Navigating to {abs_path:?}"))
2741 {
2742 Ok(item) => {
2743 pane.update_in(cx, |pane, window, cx| {
2744 navigated |= Some(item.item_id()) != prev_active_item_id;
2745 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2746 if let Some(data) = entry.data {
2747 navigated |= item.navigate(data, window, cx);
2748 }
2749 })?;
2750 }
2751 Err(open_by_abs_path_e) => {
2752 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2753 }
2754 }
2755 }
2756 }
2757 }
2758
2759 if !navigated {
2760 workspace
2761 .update_in(cx, |workspace, window, cx| {
2762 Self::navigate_history(workspace, pane, mode, window, cx)
2763 })?
2764 .await?;
2765 }
2766
2767 Ok(())
2768 })
2769 } else {
2770 Task::ready(Ok(()))
2771 }
2772 }
2773
2774 pub fn go_back(
2775 &mut self,
2776 pane: WeakEntity<Pane>,
2777 window: &mut Window,
2778 cx: &mut Context<Workspace>,
2779 ) -> Task<Result<()>> {
2780 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2781 }
2782
2783 pub fn go_forward(
2784 &mut self,
2785 pane: WeakEntity<Pane>,
2786 window: &mut Window,
2787 cx: &mut Context<Workspace>,
2788 ) -> Task<Result<()>> {
2789 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2790 }
2791
2792 pub fn reopen_closed_item(
2793 &mut self,
2794 window: &mut Window,
2795 cx: &mut Context<Workspace>,
2796 ) -> Task<Result<()>> {
2797 self.navigate_history(
2798 self.active_pane().downgrade(),
2799 NavigationMode::ReopeningClosedItem,
2800 window,
2801 cx,
2802 )
2803 }
2804
2805 pub fn client(&self) -> &Arc<Client> {
2806 &self.app_state.client
2807 }
2808
2809 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2810 self.titlebar_item = Some(item);
2811 cx.notify();
2812 }
2813
2814 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2815 self.on_prompt_for_new_path = Some(prompt)
2816 }
2817
2818 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2819 self.on_prompt_for_open_path = Some(prompt)
2820 }
2821
2822 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2823 self.terminal_provider = Some(Box::new(provider));
2824 }
2825
2826 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2827 self.debugger_provider = Some(Arc::new(provider));
2828 }
2829
2830 pub fn set_open_in_dev_container(&mut self, value: bool) {
2831 self.open_in_dev_container = value;
2832 }
2833
2834 pub fn open_in_dev_container(&self) -> bool {
2835 self.open_in_dev_container
2836 }
2837
2838 pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
2839 self._dev_container_task = Some(task);
2840 }
2841
2842 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2843 self.debugger_provider.clone()
2844 }
2845
2846 pub fn prompt_for_open_path(
2847 &mut self,
2848 path_prompt_options: PathPromptOptions,
2849 lister: DirectoryLister,
2850 window: &mut Window,
2851 cx: &mut Context<Self>,
2852 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2853 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2854 let prompt = self.on_prompt_for_open_path.take().unwrap();
2855 let rx = prompt(self, lister, window, cx);
2856 self.on_prompt_for_open_path = Some(prompt);
2857 rx
2858 } else {
2859 let (tx, rx) = oneshot::channel();
2860 let abs_path = cx.prompt_for_paths(path_prompt_options);
2861
2862 cx.spawn_in(window, async move |workspace, cx| {
2863 let Ok(result) = abs_path.await else {
2864 return Ok(());
2865 };
2866
2867 match result {
2868 Ok(result) => {
2869 tx.send(result).ok();
2870 }
2871 Err(err) => {
2872 let rx = workspace.update_in(cx, |workspace, window, cx| {
2873 workspace.show_portal_error(err.to_string(), cx);
2874 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2875 let rx = prompt(workspace, lister, window, cx);
2876 workspace.on_prompt_for_open_path = Some(prompt);
2877 rx
2878 })?;
2879 if let Ok(path) = rx.await {
2880 tx.send(path).ok();
2881 }
2882 }
2883 };
2884 anyhow::Ok(())
2885 })
2886 .detach();
2887
2888 rx
2889 }
2890 }
2891
2892 pub fn prompt_for_new_path(
2893 &mut self,
2894 lister: DirectoryLister,
2895 suggested_name: Option<String>,
2896 window: &mut Window,
2897 cx: &mut Context<Self>,
2898 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2899 if self.project.read(cx).is_via_collab()
2900 || self.project.read(cx).is_via_remote_server()
2901 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2902 {
2903 let prompt = self.on_prompt_for_new_path.take().unwrap();
2904 let rx = prompt(self, lister, suggested_name, window, cx);
2905 self.on_prompt_for_new_path = Some(prompt);
2906 return rx;
2907 }
2908
2909 let (tx, rx) = oneshot::channel();
2910 cx.spawn_in(window, async move |workspace, cx| {
2911 let abs_path = workspace.update(cx, |workspace, cx| {
2912 let relative_to = workspace
2913 .most_recent_active_path(cx)
2914 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2915 .or_else(|| {
2916 let project = workspace.project.read(cx);
2917 project.visible_worktrees(cx).find_map(|worktree| {
2918 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2919 })
2920 })
2921 .or_else(std::env::home_dir)
2922 .unwrap_or_else(|| PathBuf::from(""));
2923 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2924 })?;
2925 let abs_path = match abs_path.await? {
2926 Ok(path) => path,
2927 Err(err) => {
2928 let rx = workspace.update_in(cx, |workspace, window, cx| {
2929 workspace.show_portal_error(err.to_string(), cx);
2930
2931 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2932 let rx = prompt(workspace, lister, suggested_name, window, cx);
2933 workspace.on_prompt_for_new_path = Some(prompt);
2934 rx
2935 })?;
2936 if let Ok(path) = rx.await {
2937 tx.send(path).ok();
2938 }
2939 return anyhow::Ok(());
2940 }
2941 };
2942
2943 tx.send(abs_path.map(|path| vec![path])).ok();
2944 anyhow::Ok(())
2945 })
2946 .detach();
2947
2948 rx
2949 }
2950
2951 pub fn titlebar_item(&self) -> Option<AnyView> {
2952 self.titlebar_item.clone()
2953 }
2954
2955 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2956 /// When set, git-related operations should use this worktree instead of deriving
2957 /// the active worktree from the focused file.
2958 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2959 self.active_worktree_override
2960 }
2961
2962 pub fn set_active_worktree_override(
2963 &mut self,
2964 worktree_id: Option<WorktreeId>,
2965 cx: &mut Context<Self>,
2966 ) {
2967 self.active_worktree_override = worktree_id;
2968 cx.notify();
2969 }
2970
2971 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2972 self.active_worktree_override = None;
2973 cx.notify();
2974 }
2975
2976 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2977 ///
2978 /// If the given workspace has a local project, then it will be passed
2979 /// to the callback. Otherwise, a new empty window will be created.
2980 pub fn with_local_workspace<T, F>(
2981 &mut self,
2982 window: &mut Window,
2983 cx: &mut Context<Self>,
2984 callback: F,
2985 ) -> Task<Result<T>>
2986 where
2987 T: 'static,
2988 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2989 {
2990 if self.project.read(cx).is_local() {
2991 Task::ready(Ok(callback(self, window, cx)))
2992 } else {
2993 let env = self.project.read(cx).cli_environment(cx);
2994 let task = Self::new_local(
2995 Vec::new(),
2996 self.app_state.clone(),
2997 None,
2998 env,
2999 None,
3000 OpenMode::Activate,
3001 cx,
3002 );
3003 cx.spawn_in(window, async move |_vh, cx| {
3004 let OpenResult {
3005 window: multi_workspace_window,
3006 ..
3007 } = task.await?;
3008 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3009 let workspace = multi_workspace.workspace().clone();
3010 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3011 })
3012 })
3013 }
3014 }
3015
3016 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
3017 ///
3018 /// If the given workspace has a local project, then it will be passed
3019 /// to the callback. Otherwise, a new empty window will be created.
3020 pub fn with_local_or_wsl_workspace<T, F>(
3021 &mut self,
3022 window: &mut Window,
3023 cx: &mut Context<Self>,
3024 callback: F,
3025 ) -> Task<Result<T>>
3026 where
3027 T: 'static,
3028 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
3029 {
3030 let project = self.project.read(cx);
3031 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
3032 Task::ready(Ok(callback(self, window, cx)))
3033 } else {
3034 let env = self.project.read(cx).cli_environment(cx);
3035 let task = Self::new_local(
3036 Vec::new(),
3037 self.app_state.clone(),
3038 None,
3039 env,
3040 None,
3041 OpenMode::Activate,
3042 cx,
3043 );
3044 cx.spawn_in(window, async move |_vh, cx| {
3045 let OpenResult {
3046 window: multi_workspace_window,
3047 ..
3048 } = task.await?;
3049 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3050 let workspace = multi_workspace.workspace().clone();
3051 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3052 })
3053 })
3054 }
3055 }
3056
3057 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3058 self.project.read(cx).worktrees(cx)
3059 }
3060
3061 pub fn visible_worktrees<'a>(
3062 &self,
3063 cx: &'a App,
3064 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3065 self.project.read(cx).visible_worktrees(cx)
3066 }
3067
3068 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
3069 let futures = self
3070 .worktrees(cx)
3071 .filter_map(|worktree| worktree.read(cx).as_local())
3072 .map(|worktree| worktree.scan_complete())
3073 .collect::<Vec<_>>();
3074 async move {
3075 for future in futures {
3076 future.await;
3077 }
3078 }
3079 }
3080
3081 pub fn close_global(cx: &mut App) {
3082 cx.defer(|cx| {
3083 cx.windows().iter().find(|window| {
3084 window
3085 .update(cx, |_, window, _| {
3086 if window.is_window_active() {
3087 //This can only get called when the window's project connection has been lost
3088 //so we don't need to prompt the user for anything and instead just close the window
3089 window.remove_window();
3090 true
3091 } else {
3092 false
3093 }
3094 })
3095 .unwrap_or(false)
3096 });
3097 });
3098 }
3099
3100 pub fn move_focused_panel_to_next_position(
3101 &mut self,
3102 _: &MoveFocusedPanelToNextPosition,
3103 window: &mut Window,
3104 cx: &mut Context<Self>,
3105 ) {
3106 let docks = self.all_docks();
3107 let active_dock = docks
3108 .into_iter()
3109 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3110
3111 if let Some(dock) = active_dock {
3112 dock.update(cx, |dock, cx| {
3113 let active_panel = dock
3114 .active_panel()
3115 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
3116
3117 if let Some(panel) = active_panel {
3118 panel.move_to_next_position(window, cx);
3119 }
3120 })
3121 }
3122 }
3123
3124 pub fn prepare_to_close(
3125 &mut self,
3126 close_intent: CloseIntent,
3127 window: &mut Window,
3128 cx: &mut Context<Self>,
3129 ) -> Task<Result<bool>> {
3130 let active_call = self.active_global_call();
3131
3132 cx.spawn_in(window, async move |this, cx| {
3133 this.update(cx, |this, _| {
3134 if close_intent == CloseIntent::CloseWindow {
3135 this.removing = true;
3136 }
3137 })?;
3138
3139 let workspace_count = cx.update(|_window, cx| {
3140 cx.windows()
3141 .iter()
3142 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
3143 .count()
3144 })?;
3145
3146 #[cfg(target_os = "macos")]
3147 let save_last_workspace = false;
3148
3149 // On Linux and Windows, closing the last window should restore the last workspace.
3150 #[cfg(not(target_os = "macos"))]
3151 let save_last_workspace = {
3152 let remaining_workspaces = cx.update(|_window, cx| {
3153 cx.windows()
3154 .iter()
3155 .filter_map(|window| window.downcast::<MultiWorkspace>())
3156 .filter_map(|multi_workspace| {
3157 multi_workspace
3158 .update(cx, |multi_workspace, _, cx| {
3159 multi_workspace.workspace().read(cx).removing
3160 })
3161 .ok()
3162 })
3163 .filter(|removing| !removing)
3164 .count()
3165 })?;
3166
3167 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
3168 };
3169
3170 if let Some(active_call) = active_call
3171 && workspace_count == 1
3172 && cx
3173 .update(|_window, cx| active_call.0.is_in_room(cx))
3174 .unwrap_or(false)
3175 {
3176 if close_intent == CloseIntent::CloseWindow {
3177 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
3178 let answer = cx.update(|window, cx| {
3179 window.prompt(
3180 PromptLevel::Warning,
3181 "Do you want to leave the current call?",
3182 None,
3183 &["Close window and hang up", "Cancel"],
3184 cx,
3185 )
3186 })?;
3187
3188 if answer.await.log_err() == Some(1) {
3189 return anyhow::Ok(false);
3190 } else {
3191 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
3192 task.await.log_err();
3193 }
3194 }
3195 }
3196 if close_intent == CloseIntent::ReplaceWindow {
3197 _ = cx.update(|_window, cx| {
3198 let multi_workspace = cx
3199 .windows()
3200 .iter()
3201 .filter_map(|window| window.downcast::<MultiWorkspace>())
3202 .next()
3203 .unwrap();
3204 let project = multi_workspace
3205 .read(cx)?
3206 .workspace()
3207 .read(cx)
3208 .project
3209 .clone();
3210 if project.read(cx).is_shared() {
3211 active_call.0.unshare_project(project, cx)?;
3212 }
3213 Ok::<_, anyhow::Error>(())
3214 });
3215 }
3216 }
3217
3218 let save_result = this
3219 .update_in(cx, |this, window, cx| {
3220 this.save_all_internal(SaveIntent::Close, window, cx)
3221 })?
3222 .await;
3223
3224 // If we're not quitting, but closing, we remove the workspace from
3225 // the current session.
3226 if close_intent != CloseIntent::Quit
3227 && !save_last_workspace
3228 && save_result.as_ref().is_ok_and(|&res| res)
3229 {
3230 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
3231 .await;
3232 }
3233
3234 save_result
3235 })
3236 }
3237
3238 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
3239 self.save_all_internal(
3240 action.save_intent.unwrap_or(SaveIntent::SaveAll),
3241 window,
3242 cx,
3243 )
3244 .detach_and_log_err(cx);
3245 }
3246
3247 fn send_keystrokes(
3248 &mut self,
3249 action: &SendKeystrokes,
3250 window: &mut Window,
3251 cx: &mut Context<Self>,
3252 ) {
3253 let keystrokes: Vec<Keystroke> = action
3254 .0
3255 .split(' ')
3256 .flat_map(|k| Keystroke::parse(k).log_err())
3257 .map(|k| {
3258 cx.keyboard_mapper()
3259 .map_key_equivalent(k, false)
3260 .inner()
3261 .clone()
3262 })
3263 .collect();
3264 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
3265 }
3266
3267 pub fn send_keystrokes_impl(
3268 &mut self,
3269 keystrokes: Vec<Keystroke>,
3270 window: &mut Window,
3271 cx: &mut Context<Self>,
3272 ) -> Shared<Task<()>> {
3273 let mut state = self.dispatching_keystrokes.borrow_mut();
3274 if !state.dispatched.insert(keystrokes.clone()) {
3275 cx.propagate();
3276 return state.task.clone().unwrap();
3277 }
3278
3279 state.queue.extend(keystrokes);
3280
3281 let keystrokes = self.dispatching_keystrokes.clone();
3282 if state.task.is_none() {
3283 state.task = Some(
3284 window
3285 .spawn(cx, async move |cx| {
3286 // limit to 100 keystrokes to avoid infinite recursion.
3287 for _ in 0..100 {
3288 let keystroke = {
3289 let mut state = keystrokes.borrow_mut();
3290 let Some(keystroke) = state.queue.pop_front() else {
3291 state.dispatched.clear();
3292 state.task.take();
3293 return;
3294 };
3295 keystroke
3296 };
3297 cx.update(|window, cx| {
3298 let focused = window.focused(cx);
3299 window.dispatch_keystroke(keystroke.clone(), cx);
3300 if window.focused(cx) != focused {
3301 // dispatch_keystroke may cause the focus to change.
3302 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3303 // And we need that to happen before the next keystroke to keep vim mode happy...
3304 // (Note that the tests always do this implicitly, so you must manually test with something like:
3305 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3306 // )
3307 window.draw(cx).clear();
3308 }
3309 })
3310 .ok();
3311
3312 // Yield between synthetic keystrokes so deferred focus and
3313 // other effects can settle before dispatching the next key.
3314 yield_now().await;
3315 }
3316
3317 *keystrokes.borrow_mut() = Default::default();
3318 log::error!("over 100 keystrokes passed to send_keystrokes");
3319 })
3320 .shared(),
3321 );
3322 }
3323 state.task.clone().unwrap()
3324 }
3325
3326 fn save_all_internal(
3327 &mut self,
3328 mut save_intent: SaveIntent,
3329 window: &mut Window,
3330 cx: &mut Context<Self>,
3331 ) -> Task<Result<bool>> {
3332 if self.project.read(cx).is_disconnected(cx) {
3333 return Task::ready(Ok(true));
3334 }
3335 let dirty_items = self
3336 .panes
3337 .iter()
3338 .flat_map(|pane| {
3339 pane.read(cx).items().filter_map(|item| {
3340 if item.is_dirty(cx) {
3341 item.tab_content_text(0, cx);
3342 Some((pane.downgrade(), item.boxed_clone()))
3343 } else {
3344 None
3345 }
3346 })
3347 })
3348 .collect::<Vec<_>>();
3349
3350 let project = self.project.clone();
3351 cx.spawn_in(window, async move |workspace, cx| {
3352 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3353 let (serialize_tasks, remaining_dirty_items) =
3354 workspace.update_in(cx, |workspace, window, cx| {
3355 let mut remaining_dirty_items = Vec::new();
3356 let mut serialize_tasks = Vec::new();
3357 for (pane, item) in dirty_items {
3358 if let Some(task) = item
3359 .to_serializable_item_handle(cx)
3360 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3361 {
3362 serialize_tasks.push(task);
3363 } else {
3364 remaining_dirty_items.push((pane, item));
3365 }
3366 }
3367 (serialize_tasks, remaining_dirty_items)
3368 })?;
3369
3370 futures::future::try_join_all(serialize_tasks).await?;
3371
3372 if !remaining_dirty_items.is_empty() {
3373 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3374 }
3375
3376 if remaining_dirty_items.len() > 1 {
3377 let answer = workspace.update_in(cx, |_, window, cx| {
3378 let detail = Pane::file_names_for_prompt(
3379 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3380 cx,
3381 );
3382 window.prompt(
3383 PromptLevel::Warning,
3384 "Do you want to save all changes in the following files?",
3385 Some(&detail),
3386 &["Save all", "Discard all", "Cancel"],
3387 cx,
3388 )
3389 })?;
3390 match answer.await.log_err() {
3391 Some(0) => save_intent = SaveIntent::SaveAll,
3392 Some(1) => save_intent = SaveIntent::Skip,
3393 Some(2) => return Ok(false),
3394 _ => {}
3395 }
3396 }
3397
3398 remaining_dirty_items
3399 } else {
3400 dirty_items
3401 };
3402
3403 for (pane, item) in dirty_items {
3404 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3405 (
3406 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3407 item.project_entry_ids(cx),
3408 )
3409 })?;
3410 if (singleton || !project_entry_ids.is_empty())
3411 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3412 {
3413 return Ok(false);
3414 }
3415 }
3416 Ok(true)
3417 })
3418 }
3419
3420 pub fn open_workspace_for_paths(
3421 &mut self,
3422 // replace_current_window: bool,
3423 mut open_mode: OpenMode,
3424 paths: Vec<PathBuf>,
3425 window: &mut Window,
3426 cx: &mut Context<Self>,
3427 ) -> Task<Result<Entity<Workspace>>> {
3428 let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
3429 let is_remote = self.project.read(cx).is_via_collab();
3430 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3431 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3432
3433 let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
3434 if workspace_is_empty {
3435 open_mode = OpenMode::Activate;
3436 }
3437
3438 let app_state = self.app_state.clone();
3439
3440 cx.spawn(async move |_, cx| {
3441 let OpenResult { workspace, .. } = cx
3442 .update(|cx| {
3443 open_paths(
3444 &paths,
3445 app_state,
3446 OpenOptions {
3447 requesting_window,
3448 open_mode,
3449 ..Default::default()
3450 },
3451 cx,
3452 )
3453 })
3454 .await?;
3455 Ok(workspace)
3456 })
3457 }
3458
3459 #[allow(clippy::type_complexity)]
3460 pub fn open_paths(
3461 &mut self,
3462 mut abs_paths: Vec<PathBuf>,
3463 options: OpenOptions,
3464 pane: Option<WeakEntity<Pane>>,
3465 window: &mut Window,
3466 cx: &mut Context<Self>,
3467 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3468 let fs = self.app_state.fs.clone();
3469
3470 let caller_ordered_abs_paths = abs_paths.clone();
3471
3472 // Sort the paths to ensure we add worktrees for parents before their children.
3473 abs_paths.sort_unstable();
3474 cx.spawn_in(window, async move |this, cx| {
3475 let mut tasks = Vec::with_capacity(abs_paths.len());
3476
3477 for abs_path in &abs_paths {
3478 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3479 OpenVisible::All => Some(true),
3480 OpenVisible::None => Some(false),
3481 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3482 Some(Some(metadata)) => Some(!metadata.is_dir),
3483 Some(None) => Some(true),
3484 None => None,
3485 },
3486 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3487 Some(Some(metadata)) => Some(metadata.is_dir),
3488 Some(None) => Some(false),
3489 None => None,
3490 },
3491 };
3492 let project_path = match visible {
3493 Some(visible) => match this
3494 .update(cx, |this, cx| {
3495 Workspace::project_path_for_path(
3496 this.project.clone(),
3497 abs_path,
3498 visible,
3499 cx,
3500 )
3501 })
3502 .log_err()
3503 {
3504 Some(project_path) => project_path.await.log_err(),
3505 None => None,
3506 },
3507 None => None,
3508 };
3509
3510 let this = this.clone();
3511 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3512 let fs = fs.clone();
3513 let pane = pane.clone();
3514 let task = cx.spawn(async move |cx| {
3515 let (_worktree, project_path) = project_path?;
3516 if fs.is_dir(&abs_path).await {
3517 // Opening a directory should not race to update the active entry.
3518 // We'll select/reveal a deterministic final entry after all paths finish opening.
3519 None
3520 } else {
3521 Some(
3522 this.update_in(cx, |this, window, cx| {
3523 this.open_path(
3524 project_path,
3525 pane,
3526 options.focus.unwrap_or(true),
3527 window,
3528 cx,
3529 )
3530 })
3531 .ok()?
3532 .await,
3533 )
3534 }
3535 });
3536 tasks.push(task);
3537 }
3538
3539 let results = futures::future::join_all(tasks).await;
3540
3541 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3542 let mut winner: Option<(PathBuf, bool)> = None;
3543 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3544 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3545 if !metadata.is_dir {
3546 winner = Some((abs_path, false));
3547 break;
3548 }
3549 if winner.is_none() {
3550 winner = Some((abs_path, true));
3551 }
3552 } else if winner.is_none() {
3553 winner = Some((abs_path, false));
3554 }
3555 }
3556
3557 // Compute the winner entry id on the foreground thread and emit once, after all
3558 // paths finish opening. This avoids races between concurrently-opening paths
3559 // (directories in particular) and makes the resulting project panel selection
3560 // deterministic.
3561 if let Some((winner_abs_path, winner_is_dir)) = winner {
3562 'emit_winner: {
3563 let winner_abs_path: Arc<Path> =
3564 SanitizedPath::new(&winner_abs_path).as_path().into();
3565
3566 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3567 OpenVisible::All => true,
3568 OpenVisible::None => false,
3569 OpenVisible::OnlyFiles => !winner_is_dir,
3570 OpenVisible::OnlyDirectories => winner_is_dir,
3571 };
3572
3573 let Some(worktree_task) = this
3574 .update(cx, |workspace, cx| {
3575 workspace.project.update(cx, |project, cx| {
3576 project.find_or_create_worktree(
3577 winner_abs_path.as_ref(),
3578 visible,
3579 cx,
3580 )
3581 })
3582 })
3583 .ok()
3584 else {
3585 break 'emit_winner;
3586 };
3587
3588 let Ok((worktree, _)) = worktree_task.await else {
3589 break 'emit_winner;
3590 };
3591
3592 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3593 let worktree = worktree.read(cx);
3594 let worktree_abs_path = worktree.abs_path();
3595 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3596 worktree.root_entry()
3597 } else {
3598 winner_abs_path
3599 .strip_prefix(worktree_abs_path.as_ref())
3600 .ok()
3601 .and_then(|relative_path| {
3602 let relative_path =
3603 RelPath::new(relative_path, PathStyle::local())
3604 .log_err()?;
3605 worktree.entry_for_path(&relative_path)
3606 })
3607 }?;
3608 Some(entry.id)
3609 }) else {
3610 break 'emit_winner;
3611 };
3612
3613 this.update(cx, |workspace, cx| {
3614 workspace.project.update(cx, |_, cx| {
3615 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3616 });
3617 })
3618 .ok();
3619 }
3620 }
3621
3622 results
3623 })
3624 }
3625
3626 pub fn open_resolved_path(
3627 &mut self,
3628 path: ResolvedPath,
3629 window: &mut Window,
3630 cx: &mut Context<Self>,
3631 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3632 match path {
3633 ResolvedPath::ProjectPath { project_path, .. } => {
3634 self.open_path(project_path, None, true, window, cx)
3635 }
3636 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3637 PathBuf::from(path),
3638 OpenOptions {
3639 visible: Some(OpenVisible::None),
3640 ..Default::default()
3641 },
3642 window,
3643 cx,
3644 ),
3645 }
3646 }
3647
3648 pub fn absolute_path_of_worktree(
3649 &self,
3650 worktree_id: WorktreeId,
3651 cx: &mut Context<Self>,
3652 ) -> Option<PathBuf> {
3653 self.project
3654 .read(cx)
3655 .worktree_for_id(worktree_id, cx)
3656 // TODO: use `abs_path` or `root_dir`
3657 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3658 }
3659
3660 pub fn add_folder_to_project(
3661 &mut self,
3662 _: &AddFolderToProject,
3663 window: &mut Window,
3664 cx: &mut Context<Self>,
3665 ) {
3666 let project = self.project.read(cx);
3667 if project.is_via_collab() {
3668 self.show_error(
3669 &anyhow!("You cannot add folders to someone else's project"),
3670 cx,
3671 );
3672 return;
3673 }
3674 let paths = self.prompt_for_open_path(
3675 PathPromptOptions {
3676 files: false,
3677 directories: true,
3678 multiple: true,
3679 prompt: None,
3680 },
3681 DirectoryLister::Project(self.project.clone()),
3682 window,
3683 cx,
3684 );
3685 cx.spawn_in(window, async move |this, cx| {
3686 if let Some(paths) = paths.await.log_err().flatten() {
3687 let results = this
3688 .update_in(cx, |this, window, cx| {
3689 this.open_paths(
3690 paths,
3691 OpenOptions {
3692 visible: Some(OpenVisible::All),
3693 ..Default::default()
3694 },
3695 None,
3696 window,
3697 cx,
3698 )
3699 })?
3700 .await;
3701 for result in results.into_iter().flatten() {
3702 result.log_err();
3703 }
3704 }
3705 anyhow::Ok(())
3706 })
3707 .detach_and_log_err(cx);
3708 }
3709
3710 pub fn project_path_for_path(
3711 project: Entity<Project>,
3712 abs_path: &Path,
3713 visible: bool,
3714 cx: &mut App,
3715 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3716 let entry = project.update(cx, |project, cx| {
3717 project.find_or_create_worktree(abs_path, visible, cx)
3718 });
3719 cx.spawn(async move |cx| {
3720 let (worktree, path) = entry.await?;
3721 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3722 Ok((worktree, ProjectPath { worktree_id, path }))
3723 })
3724 }
3725
3726 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3727 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3728 }
3729
3730 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3731 self.items_of_type(cx).max_by_key(|item| item.item_id())
3732 }
3733
3734 pub fn items_of_type<'a, T: Item>(
3735 &'a self,
3736 cx: &'a App,
3737 ) -> impl 'a + Iterator<Item = Entity<T>> {
3738 self.panes
3739 .iter()
3740 .flat_map(|pane| pane.read(cx).items_of_type())
3741 }
3742
3743 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3744 self.active_pane().read(cx).active_item()
3745 }
3746
3747 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3748 let item = self.active_item(cx)?;
3749 item.to_any_view().downcast::<I>().ok()
3750 }
3751
3752 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3753 self.active_item(cx).and_then(|item| item.project_path(cx))
3754 }
3755
3756 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3757 self.recent_navigation_history_iter(cx)
3758 .filter_map(|(path, abs_path)| {
3759 let worktree = self
3760 .project
3761 .read(cx)
3762 .worktree_for_id(path.worktree_id, cx)?;
3763 if worktree.read(cx).is_visible() {
3764 abs_path
3765 } else {
3766 None
3767 }
3768 })
3769 .next()
3770 }
3771
3772 pub fn save_active_item(
3773 &mut self,
3774 save_intent: SaveIntent,
3775 window: &mut Window,
3776 cx: &mut App,
3777 ) -> Task<Result<()>> {
3778 let project = self.project.clone();
3779 let pane = self.active_pane();
3780 let item = pane.read(cx).active_item();
3781 let pane = pane.downgrade();
3782
3783 window.spawn(cx, async move |cx| {
3784 if let Some(item) = item {
3785 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3786 .await
3787 .map(|_| ())
3788 } else {
3789 Ok(())
3790 }
3791 })
3792 }
3793
3794 pub fn close_inactive_items_and_panes(
3795 &mut self,
3796 action: &CloseInactiveTabsAndPanes,
3797 window: &mut Window,
3798 cx: &mut Context<Self>,
3799 ) {
3800 if let Some(task) = self.close_all_internal(
3801 true,
3802 action.save_intent.unwrap_or(SaveIntent::Close),
3803 window,
3804 cx,
3805 ) {
3806 task.detach_and_log_err(cx)
3807 }
3808 }
3809
3810 pub fn close_all_items_and_panes(
3811 &mut self,
3812 action: &CloseAllItemsAndPanes,
3813 window: &mut Window,
3814 cx: &mut Context<Self>,
3815 ) {
3816 if let Some(task) = self.close_all_internal(
3817 false,
3818 action.save_intent.unwrap_or(SaveIntent::Close),
3819 window,
3820 cx,
3821 ) {
3822 task.detach_and_log_err(cx)
3823 }
3824 }
3825
3826 /// Closes the active item across all panes.
3827 pub fn close_item_in_all_panes(
3828 &mut self,
3829 action: &CloseItemInAllPanes,
3830 window: &mut Window,
3831 cx: &mut Context<Self>,
3832 ) {
3833 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3834 return;
3835 };
3836
3837 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3838 let close_pinned = action.close_pinned;
3839
3840 if let Some(project_path) = active_item.project_path(cx) {
3841 self.close_items_with_project_path(
3842 &project_path,
3843 save_intent,
3844 close_pinned,
3845 window,
3846 cx,
3847 );
3848 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3849 let item_id = active_item.item_id();
3850 self.active_pane().update(cx, |pane, cx| {
3851 pane.close_item_by_id(item_id, save_intent, window, cx)
3852 .detach_and_log_err(cx);
3853 });
3854 }
3855 }
3856
3857 /// Closes all items with the given project path across all panes.
3858 pub fn close_items_with_project_path(
3859 &mut self,
3860 project_path: &ProjectPath,
3861 save_intent: SaveIntent,
3862 close_pinned: bool,
3863 window: &mut Window,
3864 cx: &mut Context<Self>,
3865 ) {
3866 let panes = self.panes().to_vec();
3867 for pane in panes {
3868 pane.update(cx, |pane, cx| {
3869 pane.close_items_for_project_path(
3870 project_path,
3871 save_intent,
3872 close_pinned,
3873 window,
3874 cx,
3875 )
3876 .detach_and_log_err(cx);
3877 });
3878 }
3879 }
3880
3881 fn close_all_internal(
3882 &mut self,
3883 retain_active_pane: bool,
3884 save_intent: SaveIntent,
3885 window: &mut Window,
3886 cx: &mut Context<Self>,
3887 ) -> Option<Task<Result<()>>> {
3888 let current_pane = self.active_pane();
3889
3890 let mut tasks = Vec::new();
3891
3892 if retain_active_pane {
3893 let current_pane_close = current_pane.update(cx, |pane, cx| {
3894 pane.close_other_items(
3895 &CloseOtherItems {
3896 save_intent: None,
3897 close_pinned: false,
3898 },
3899 None,
3900 window,
3901 cx,
3902 )
3903 });
3904
3905 tasks.push(current_pane_close);
3906 }
3907
3908 for pane in self.panes() {
3909 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3910 continue;
3911 }
3912
3913 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3914 pane.close_all_items(
3915 &CloseAllItems {
3916 save_intent: Some(save_intent),
3917 close_pinned: false,
3918 },
3919 window,
3920 cx,
3921 )
3922 });
3923
3924 tasks.push(close_pane_items)
3925 }
3926
3927 if tasks.is_empty() {
3928 None
3929 } else {
3930 Some(cx.spawn_in(window, async move |_, _| {
3931 for task in tasks {
3932 task.await?
3933 }
3934 Ok(())
3935 }))
3936 }
3937 }
3938
3939 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3940 self.dock_at_position(position).read(cx).is_open()
3941 }
3942
3943 pub fn toggle_dock(
3944 &mut self,
3945 dock_side: DockPosition,
3946 window: &mut Window,
3947 cx: &mut Context<Self>,
3948 ) {
3949 let mut focus_center = false;
3950 let mut reveal_dock = false;
3951
3952 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3953 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3954
3955 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3956 telemetry::event!(
3957 "Panel Button Clicked",
3958 name = panel.persistent_name(),
3959 toggle_state = !was_visible
3960 );
3961 }
3962 if was_visible {
3963 self.save_open_dock_positions(cx);
3964 }
3965
3966 let dock = self.dock_at_position(dock_side);
3967 dock.update(cx, |dock, cx| {
3968 dock.set_open(!was_visible, window, cx);
3969
3970 if dock.active_panel().is_none() {
3971 let Some(panel_ix) = dock
3972 .first_enabled_panel_idx(cx)
3973 .log_with_level(log::Level::Info)
3974 else {
3975 return;
3976 };
3977 dock.activate_panel(panel_ix, window, cx);
3978 }
3979
3980 if let Some(active_panel) = dock.active_panel() {
3981 if was_visible {
3982 if active_panel
3983 .panel_focus_handle(cx)
3984 .contains_focused(window, cx)
3985 {
3986 focus_center = true;
3987 }
3988 } else {
3989 let focus_handle = &active_panel.panel_focus_handle(cx);
3990 window.focus(focus_handle, cx);
3991 reveal_dock = true;
3992 }
3993 }
3994 });
3995
3996 if reveal_dock {
3997 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3998 }
3999
4000 if focus_center {
4001 self.active_pane
4002 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4003 }
4004
4005 cx.notify();
4006 self.serialize_workspace(window, cx);
4007 }
4008
4009 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
4010 self.all_docks().into_iter().find(|&dock| {
4011 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
4012 })
4013 }
4014
4015 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
4016 if let Some(dock) = self.active_dock(window, cx).cloned() {
4017 self.save_open_dock_positions(cx);
4018 dock.update(cx, |dock, cx| {
4019 dock.set_open(false, window, cx);
4020 });
4021 return true;
4022 }
4023 false
4024 }
4025
4026 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4027 self.save_open_dock_positions(cx);
4028 for dock in self.all_docks() {
4029 dock.update(cx, |dock, cx| {
4030 dock.set_open(false, window, cx);
4031 });
4032 }
4033
4034 cx.focus_self(window);
4035 cx.notify();
4036 self.serialize_workspace(window, cx);
4037 }
4038
4039 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
4040 self.all_docks()
4041 .into_iter()
4042 .filter_map(|dock| {
4043 let dock_ref = dock.read(cx);
4044 if dock_ref.is_open() {
4045 Some(dock_ref.position())
4046 } else {
4047 None
4048 }
4049 })
4050 .collect()
4051 }
4052
4053 /// Saves the positions of currently open docks.
4054 ///
4055 /// Updates `last_open_dock_positions` with positions of all currently open
4056 /// docks, to later be restored by the 'Toggle All Docks' action.
4057 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
4058 let open_dock_positions = self.get_open_dock_positions(cx);
4059 if !open_dock_positions.is_empty() {
4060 self.last_open_dock_positions = open_dock_positions;
4061 }
4062 }
4063
4064 /// Toggles all docks between open and closed states.
4065 ///
4066 /// If any docks are open, closes all and remembers their positions. If all
4067 /// docks are closed, restores the last remembered dock configuration.
4068 fn toggle_all_docks(
4069 &mut self,
4070 _: &ToggleAllDocks,
4071 window: &mut Window,
4072 cx: &mut Context<Self>,
4073 ) {
4074 let open_dock_positions = self.get_open_dock_positions(cx);
4075
4076 if !open_dock_positions.is_empty() {
4077 self.close_all_docks(window, cx);
4078 } else if !self.last_open_dock_positions.is_empty() {
4079 self.restore_last_open_docks(window, cx);
4080 }
4081 }
4082
4083 /// Reopens docks from the most recently remembered configuration.
4084 ///
4085 /// Opens all docks whose positions are stored in `last_open_dock_positions`
4086 /// and clears the stored positions.
4087 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4088 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
4089
4090 for position in positions_to_open {
4091 let dock = self.dock_at_position(position);
4092 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
4093 }
4094
4095 cx.focus_self(window);
4096 cx.notify();
4097 self.serialize_workspace(window, cx);
4098 }
4099
4100 /// Transfer focus to the panel of the given type.
4101 pub fn focus_panel<T: Panel>(
4102 &mut self,
4103 window: &mut Window,
4104 cx: &mut Context<Self>,
4105 ) -> Option<Entity<T>> {
4106 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
4107 panel.to_any().downcast().ok()
4108 }
4109
4110 /// Focus the panel of the given type if it isn't already focused. If it is
4111 /// already focused, then transfer focus back to the workspace center.
4112 /// When the `close_panel_on_toggle` setting is enabled, also closes the
4113 /// panel when transferring focus back to the center.
4114 pub fn toggle_panel_focus<T: Panel>(
4115 &mut self,
4116 window: &mut Window,
4117 cx: &mut Context<Self>,
4118 ) -> bool {
4119 let mut did_focus_panel = false;
4120 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
4121 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
4122 did_focus_panel
4123 });
4124
4125 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
4126 self.close_panel::<T>(window, cx);
4127 }
4128
4129 telemetry::event!(
4130 "Panel Button Clicked",
4131 name = T::persistent_name(),
4132 toggle_state = did_focus_panel
4133 );
4134
4135 did_focus_panel
4136 }
4137
4138 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4139 if let Some(item) = self.active_item(cx) {
4140 item.item_focus_handle(cx).focus(window, cx);
4141 } else {
4142 log::error!("Could not find a focus target when switching focus to the center panes",);
4143 }
4144 }
4145
4146 pub fn activate_panel_for_proto_id(
4147 &mut self,
4148 panel_id: PanelId,
4149 window: &mut Window,
4150 cx: &mut Context<Self>,
4151 ) -> Option<Arc<dyn PanelHandle>> {
4152 let mut panel = None;
4153 for dock in self.all_docks() {
4154 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
4155 panel = dock.update(cx, |dock, cx| {
4156 dock.activate_panel(panel_index, window, cx);
4157 dock.set_open(true, window, cx);
4158 dock.active_panel().cloned()
4159 });
4160 break;
4161 }
4162 }
4163
4164 if panel.is_some() {
4165 cx.notify();
4166 self.serialize_workspace(window, cx);
4167 }
4168
4169 panel
4170 }
4171
4172 /// Focus or unfocus the given panel type, depending on the given callback.
4173 fn focus_or_unfocus_panel<T: Panel>(
4174 &mut self,
4175 window: &mut Window,
4176 cx: &mut Context<Self>,
4177 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
4178 ) -> Option<Arc<dyn PanelHandle>> {
4179 let mut result_panel = None;
4180 let mut serialize = false;
4181 for dock in self.all_docks() {
4182 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4183 let mut focus_center = false;
4184 let panel = dock.update(cx, |dock, cx| {
4185 dock.activate_panel(panel_index, window, cx);
4186
4187 let panel = dock.active_panel().cloned();
4188 if let Some(panel) = panel.as_ref() {
4189 if should_focus(&**panel, window, cx) {
4190 dock.set_open(true, window, cx);
4191 panel.panel_focus_handle(cx).focus(window, cx);
4192 } else {
4193 focus_center = true;
4194 }
4195 }
4196 panel
4197 });
4198
4199 if focus_center {
4200 self.active_pane
4201 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4202 }
4203
4204 result_panel = panel;
4205 serialize = true;
4206 break;
4207 }
4208 }
4209
4210 if serialize {
4211 self.serialize_workspace(window, cx);
4212 }
4213
4214 cx.notify();
4215 result_panel
4216 }
4217
4218 /// Open the panel of the given type
4219 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4220 for dock in self.all_docks() {
4221 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4222 dock.update(cx, |dock, cx| {
4223 dock.activate_panel(panel_index, window, cx);
4224 dock.set_open(true, window, cx);
4225 });
4226 }
4227 }
4228 }
4229
4230 /// Open the panel of the given type, dismissing any zoomed items that
4231 /// would obscure it (e.g. a zoomed terminal).
4232 pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4233 let dock_position = self.all_docks().iter().find_map(|dock| {
4234 let dock = dock.read(cx);
4235 dock.panel_index_for_type::<T>().map(|_| dock.position())
4236 });
4237 self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
4238 self.open_panel::<T>(window, cx);
4239 }
4240
4241 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4242 for dock in self.all_docks().iter() {
4243 dock.update(cx, |dock, cx| {
4244 if dock.panel::<T>().is_some() {
4245 dock.set_open(false, window, cx)
4246 }
4247 })
4248 }
4249 }
4250
4251 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4252 self.all_docks()
4253 .iter()
4254 .find_map(|dock| dock.read(cx).panel::<T>())
4255 }
4256
4257 fn dismiss_zoomed_items_to_reveal(
4258 &mut self,
4259 dock_to_reveal: Option<DockPosition>,
4260 window: &mut Window,
4261 cx: &mut Context<Self>,
4262 ) {
4263 // If a center pane is zoomed, unzoom it.
4264 for pane in &self.panes {
4265 if pane != &self.active_pane || dock_to_reveal.is_some() {
4266 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4267 }
4268 }
4269
4270 // If another dock is zoomed, hide it.
4271 let mut focus_center = false;
4272 for dock in self.all_docks() {
4273 dock.update(cx, |dock, cx| {
4274 if Some(dock.position()) != dock_to_reveal
4275 && let Some(panel) = dock.active_panel()
4276 && panel.is_zoomed(window, cx)
4277 {
4278 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4279 dock.set_open(false, window, cx);
4280 }
4281 });
4282 }
4283
4284 if focus_center {
4285 self.active_pane
4286 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4287 }
4288
4289 if self.zoomed_position != dock_to_reveal {
4290 self.zoomed = None;
4291 self.zoomed_position = None;
4292 cx.emit(Event::ZoomChanged);
4293 }
4294
4295 cx.notify();
4296 }
4297
4298 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4299 let pane = cx.new(|cx| {
4300 let mut pane = Pane::new(
4301 self.weak_handle(),
4302 self.project.clone(),
4303 self.pane_history_timestamp.clone(),
4304 None,
4305 NewFile.boxed_clone(),
4306 true,
4307 window,
4308 cx,
4309 );
4310 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4311 pane
4312 });
4313 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4314 .detach();
4315 self.panes.push(pane.clone());
4316
4317 window.focus(&pane.focus_handle(cx), cx);
4318
4319 cx.emit(Event::PaneAdded(pane.clone()));
4320 pane
4321 }
4322
4323 pub fn add_item_to_center(
4324 &mut self,
4325 item: Box<dyn ItemHandle>,
4326 window: &mut Window,
4327 cx: &mut Context<Self>,
4328 ) -> bool {
4329 if let Some(center_pane) = self.last_active_center_pane.clone() {
4330 if let Some(center_pane) = center_pane.upgrade() {
4331 center_pane.update(cx, |pane, cx| {
4332 pane.add_item(item, true, true, None, window, cx)
4333 });
4334 true
4335 } else {
4336 false
4337 }
4338 } else {
4339 false
4340 }
4341 }
4342
4343 pub fn add_item_to_active_pane(
4344 &mut self,
4345 item: Box<dyn ItemHandle>,
4346 destination_index: Option<usize>,
4347 focus_item: bool,
4348 window: &mut Window,
4349 cx: &mut App,
4350 ) {
4351 self.add_item(
4352 self.active_pane.clone(),
4353 item,
4354 destination_index,
4355 false,
4356 focus_item,
4357 window,
4358 cx,
4359 )
4360 }
4361
4362 pub fn add_item(
4363 &mut self,
4364 pane: Entity<Pane>,
4365 item: Box<dyn ItemHandle>,
4366 destination_index: Option<usize>,
4367 activate_pane: bool,
4368 focus_item: bool,
4369 window: &mut Window,
4370 cx: &mut App,
4371 ) {
4372 pane.update(cx, |pane, cx| {
4373 pane.add_item(
4374 item,
4375 activate_pane,
4376 focus_item,
4377 destination_index,
4378 window,
4379 cx,
4380 )
4381 });
4382 }
4383
4384 pub fn split_item(
4385 &mut self,
4386 split_direction: SplitDirection,
4387 item: Box<dyn ItemHandle>,
4388 window: &mut Window,
4389 cx: &mut Context<Self>,
4390 ) {
4391 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4392 self.add_item(new_pane, item, None, true, true, window, cx);
4393 }
4394
4395 pub fn open_abs_path(
4396 &mut self,
4397 abs_path: PathBuf,
4398 options: OpenOptions,
4399 window: &mut Window,
4400 cx: &mut Context<Self>,
4401 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4402 cx.spawn_in(window, async move |workspace, cx| {
4403 let open_paths_task_result = workspace
4404 .update_in(cx, |workspace, window, cx| {
4405 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4406 })
4407 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4408 .await;
4409 anyhow::ensure!(
4410 open_paths_task_result.len() == 1,
4411 "open abs path {abs_path:?} task returned incorrect number of results"
4412 );
4413 match open_paths_task_result
4414 .into_iter()
4415 .next()
4416 .expect("ensured single task result")
4417 {
4418 Some(open_result) => {
4419 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4420 }
4421 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4422 }
4423 })
4424 }
4425
4426 pub fn split_abs_path(
4427 &mut self,
4428 abs_path: PathBuf,
4429 visible: bool,
4430 window: &mut Window,
4431 cx: &mut Context<Self>,
4432 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4433 let project_path_task =
4434 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4435 cx.spawn_in(window, async move |this, cx| {
4436 let (_, path) = project_path_task.await?;
4437 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4438 .await
4439 })
4440 }
4441
4442 pub fn open_path(
4443 &mut self,
4444 path: impl Into<ProjectPath>,
4445 pane: Option<WeakEntity<Pane>>,
4446 focus_item: bool,
4447 window: &mut Window,
4448 cx: &mut App,
4449 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4450 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4451 }
4452
4453 pub fn open_path_preview(
4454 &mut self,
4455 path: impl Into<ProjectPath>,
4456 pane: Option<WeakEntity<Pane>>,
4457 focus_item: bool,
4458 allow_preview: bool,
4459 activate: bool,
4460 window: &mut Window,
4461 cx: &mut App,
4462 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4463 let pane = pane.unwrap_or_else(|| {
4464 self.last_active_center_pane.clone().unwrap_or_else(|| {
4465 self.panes
4466 .first()
4467 .expect("There must be an active pane")
4468 .downgrade()
4469 })
4470 });
4471
4472 let project_path = path.into();
4473 let task = self.load_path(project_path.clone(), window, cx);
4474 window.spawn(cx, async move |cx| {
4475 let (project_entry_id, build_item) = task.await?;
4476
4477 pane.update_in(cx, |pane, window, cx| {
4478 pane.open_item(
4479 project_entry_id,
4480 project_path,
4481 focus_item,
4482 allow_preview,
4483 activate,
4484 None,
4485 window,
4486 cx,
4487 build_item,
4488 )
4489 })
4490 })
4491 }
4492
4493 pub fn split_path(
4494 &mut self,
4495 path: impl Into<ProjectPath>,
4496 window: &mut Window,
4497 cx: &mut Context<Self>,
4498 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4499 self.split_path_preview(path, false, None, window, cx)
4500 }
4501
4502 pub fn split_path_preview(
4503 &mut self,
4504 path: impl Into<ProjectPath>,
4505 allow_preview: bool,
4506 split_direction: Option<SplitDirection>,
4507 window: &mut Window,
4508 cx: &mut Context<Self>,
4509 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4510 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4511 self.panes
4512 .first()
4513 .expect("There must be an active pane")
4514 .downgrade()
4515 });
4516
4517 if let Member::Pane(center_pane) = &self.center.root
4518 && center_pane.read(cx).items_len() == 0
4519 {
4520 return self.open_path(path, Some(pane), true, window, cx);
4521 }
4522
4523 let project_path = path.into();
4524 let task = self.load_path(project_path.clone(), window, cx);
4525 cx.spawn_in(window, async move |this, cx| {
4526 let (project_entry_id, build_item) = task.await?;
4527 this.update_in(cx, move |this, window, cx| -> Option<_> {
4528 let pane = pane.upgrade()?;
4529 let new_pane = this.split_pane(
4530 pane,
4531 split_direction.unwrap_or(SplitDirection::Right),
4532 window,
4533 cx,
4534 );
4535 new_pane.update(cx, |new_pane, cx| {
4536 Some(new_pane.open_item(
4537 project_entry_id,
4538 project_path,
4539 true,
4540 allow_preview,
4541 true,
4542 None,
4543 window,
4544 cx,
4545 build_item,
4546 ))
4547 })
4548 })
4549 .map(|option| option.context("pane was dropped"))?
4550 })
4551 }
4552
4553 fn load_path(
4554 &mut self,
4555 path: ProjectPath,
4556 window: &mut Window,
4557 cx: &mut App,
4558 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4559 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4560 registry.open_path(self.project(), &path, window, cx)
4561 }
4562
4563 pub fn find_project_item<T>(
4564 &self,
4565 pane: &Entity<Pane>,
4566 project_item: &Entity<T::Item>,
4567 cx: &App,
4568 ) -> Option<Entity<T>>
4569 where
4570 T: ProjectItem,
4571 {
4572 use project::ProjectItem as _;
4573 let project_item = project_item.read(cx);
4574 let entry_id = project_item.entry_id(cx);
4575 let project_path = project_item.project_path(cx);
4576
4577 let mut item = None;
4578 if let Some(entry_id) = entry_id {
4579 item = pane.read(cx).item_for_entry(entry_id, cx);
4580 }
4581 if item.is_none()
4582 && let Some(project_path) = project_path
4583 {
4584 item = pane.read(cx).item_for_path(project_path, cx);
4585 }
4586
4587 item.and_then(|item| item.downcast::<T>())
4588 }
4589
4590 pub fn is_project_item_open<T>(
4591 &self,
4592 pane: &Entity<Pane>,
4593 project_item: &Entity<T::Item>,
4594 cx: &App,
4595 ) -> bool
4596 where
4597 T: ProjectItem,
4598 {
4599 self.find_project_item::<T>(pane, project_item, cx)
4600 .is_some()
4601 }
4602
4603 pub fn open_project_item<T>(
4604 &mut self,
4605 pane: Entity<Pane>,
4606 project_item: Entity<T::Item>,
4607 activate_pane: bool,
4608 focus_item: bool,
4609 keep_old_preview: bool,
4610 allow_new_preview: bool,
4611 window: &mut Window,
4612 cx: &mut Context<Self>,
4613 ) -> Entity<T>
4614 where
4615 T: ProjectItem,
4616 {
4617 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4618
4619 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4620 if !keep_old_preview
4621 && let Some(old_id) = old_item_id
4622 && old_id != item.item_id()
4623 {
4624 // switching to a different item, so unpreview old active item
4625 pane.update(cx, |pane, _| {
4626 pane.unpreview_item_if_preview(old_id);
4627 });
4628 }
4629
4630 self.activate_item(&item, activate_pane, focus_item, window, cx);
4631 if !allow_new_preview {
4632 pane.update(cx, |pane, _| {
4633 pane.unpreview_item_if_preview(item.item_id());
4634 });
4635 }
4636 return item;
4637 }
4638
4639 let item = pane.update(cx, |pane, cx| {
4640 cx.new(|cx| {
4641 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4642 })
4643 });
4644 let mut destination_index = None;
4645 pane.update(cx, |pane, cx| {
4646 if !keep_old_preview && let Some(old_id) = old_item_id {
4647 pane.unpreview_item_if_preview(old_id);
4648 }
4649 if allow_new_preview {
4650 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4651 }
4652 });
4653
4654 self.add_item(
4655 pane,
4656 Box::new(item.clone()),
4657 destination_index,
4658 activate_pane,
4659 focus_item,
4660 window,
4661 cx,
4662 );
4663 item
4664 }
4665
4666 pub fn open_shared_screen(
4667 &mut self,
4668 peer_id: PeerId,
4669 window: &mut Window,
4670 cx: &mut Context<Self>,
4671 ) {
4672 if let Some(shared_screen) =
4673 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4674 {
4675 self.active_pane.update(cx, |pane, cx| {
4676 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4677 });
4678 }
4679 }
4680
4681 pub fn activate_item(
4682 &mut self,
4683 item: &dyn ItemHandle,
4684 activate_pane: bool,
4685 focus_item: bool,
4686 window: &mut Window,
4687 cx: &mut App,
4688 ) -> bool {
4689 let result = self.panes.iter().find_map(|pane| {
4690 pane.read(cx)
4691 .index_for_item(item)
4692 .map(|ix| (pane.clone(), ix))
4693 });
4694 if let Some((pane, ix)) = result {
4695 pane.update(cx, |pane, cx| {
4696 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4697 });
4698 true
4699 } else {
4700 false
4701 }
4702 }
4703
4704 fn activate_pane_at_index(
4705 &mut self,
4706 action: &ActivatePane,
4707 window: &mut Window,
4708 cx: &mut Context<Self>,
4709 ) {
4710 let panes = self.center.panes();
4711 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4712 window.focus(&pane.focus_handle(cx), cx);
4713 } else {
4714 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4715 .detach();
4716 }
4717 }
4718
4719 fn move_item_to_pane_at_index(
4720 &mut self,
4721 action: &MoveItemToPane,
4722 window: &mut Window,
4723 cx: &mut Context<Self>,
4724 ) {
4725 let panes = self.center.panes();
4726 let destination = match panes.get(action.destination) {
4727 Some(&destination) => destination.clone(),
4728 None => {
4729 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4730 return;
4731 }
4732 let direction = SplitDirection::Right;
4733 let split_off_pane = self
4734 .find_pane_in_direction(direction, cx)
4735 .unwrap_or_else(|| self.active_pane.clone());
4736 let new_pane = self.add_pane(window, cx);
4737 self.center.split(&split_off_pane, &new_pane, direction, cx);
4738 new_pane
4739 }
4740 };
4741
4742 if action.clone {
4743 if self
4744 .active_pane
4745 .read(cx)
4746 .active_item()
4747 .is_some_and(|item| item.can_split(cx))
4748 {
4749 clone_active_item(
4750 self.database_id(),
4751 &self.active_pane,
4752 &destination,
4753 action.focus,
4754 window,
4755 cx,
4756 );
4757 return;
4758 }
4759 }
4760 move_active_item(
4761 &self.active_pane,
4762 &destination,
4763 action.focus,
4764 true,
4765 window,
4766 cx,
4767 )
4768 }
4769
4770 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4771 let panes = self.center.panes();
4772 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4773 let next_ix = (ix + 1) % panes.len();
4774 let next_pane = panes[next_ix].clone();
4775 window.focus(&next_pane.focus_handle(cx), cx);
4776 }
4777 }
4778
4779 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4780 let panes = self.center.panes();
4781 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4782 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4783 let prev_pane = panes[prev_ix].clone();
4784 window.focus(&prev_pane.focus_handle(cx), cx);
4785 }
4786 }
4787
4788 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4789 let last_pane = self.center.last_pane();
4790 window.focus(&last_pane.focus_handle(cx), cx);
4791 }
4792
4793 pub fn activate_pane_in_direction(
4794 &mut self,
4795 direction: SplitDirection,
4796 window: &mut Window,
4797 cx: &mut App,
4798 ) {
4799 use ActivateInDirectionTarget as Target;
4800 enum Origin {
4801 Sidebar,
4802 LeftDock,
4803 RightDock,
4804 BottomDock,
4805 Center,
4806 }
4807
4808 let origin: Origin = if self
4809 .sidebar_focus_handle
4810 .as_ref()
4811 .is_some_and(|h| h.contains_focused(window, cx))
4812 {
4813 Origin::Sidebar
4814 } else {
4815 [
4816 (&self.left_dock, Origin::LeftDock),
4817 (&self.right_dock, Origin::RightDock),
4818 (&self.bottom_dock, Origin::BottomDock),
4819 ]
4820 .into_iter()
4821 .find_map(|(dock, origin)| {
4822 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4823 Some(origin)
4824 } else {
4825 None
4826 }
4827 })
4828 .unwrap_or(Origin::Center)
4829 };
4830
4831 let get_last_active_pane = || {
4832 let pane = self
4833 .last_active_center_pane
4834 .clone()
4835 .unwrap_or_else(|| {
4836 self.panes
4837 .first()
4838 .expect("There must be an active pane")
4839 .downgrade()
4840 })
4841 .upgrade()?;
4842 (pane.read(cx).items_len() != 0).then_some(pane)
4843 };
4844
4845 let try_dock =
4846 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4847
4848 let sidebar_target = self
4849 .sidebar_focus_handle
4850 .as_ref()
4851 .map(|h| Target::Sidebar(h.clone()));
4852
4853 let sidebar_on_right = self
4854 .multi_workspace
4855 .as_ref()
4856 .and_then(|mw| mw.upgrade())
4857 .map_or(false, |mw| {
4858 mw.read(cx).sidebar_side(cx) == SidebarSide::Right
4859 });
4860
4861 let away_from_sidebar = if sidebar_on_right {
4862 SplitDirection::Left
4863 } else {
4864 SplitDirection::Right
4865 };
4866
4867 let (near_dock, far_dock) = if sidebar_on_right {
4868 (&self.right_dock, &self.left_dock)
4869 } else {
4870 (&self.left_dock, &self.right_dock)
4871 };
4872
4873 let target = match (origin, direction) {
4874 (Origin::Sidebar, dir) if dir == away_from_sidebar => try_dock(near_dock)
4875 .or_else(|| get_last_active_pane().map(Target::Pane))
4876 .or_else(|| try_dock(&self.bottom_dock))
4877 .or_else(|| try_dock(far_dock)),
4878
4879 (Origin::Sidebar, _) => None,
4880
4881 // We're in the center, so we first try to go to a different pane,
4882 // otherwise try to go to a dock.
4883 (Origin::Center, direction) => {
4884 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4885 Some(Target::Pane(pane))
4886 } else {
4887 match direction {
4888 SplitDirection::Up => None,
4889 SplitDirection::Down => try_dock(&self.bottom_dock),
4890 SplitDirection::Left => {
4891 let dock_target = try_dock(&self.left_dock);
4892 if sidebar_on_right {
4893 dock_target
4894 } else {
4895 dock_target.or(sidebar_target)
4896 }
4897 }
4898 SplitDirection::Right => {
4899 let dock_target = try_dock(&self.right_dock);
4900 if sidebar_on_right {
4901 dock_target.or(sidebar_target)
4902 } else {
4903 dock_target
4904 }
4905 }
4906 }
4907 }
4908 }
4909
4910 (Origin::LeftDock, SplitDirection::Right) => {
4911 if let Some(last_active_pane) = get_last_active_pane() {
4912 Some(Target::Pane(last_active_pane))
4913 } else {
4914 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4915 }
4916 }
4917
4918 (Origin::LeftDock, SplitDirection::Left) => {
4919 if sidebar_on_right {
4920 None
4921 } else {
4922 sidebar_target
4923 }
4924 }
4925
4926 (Origin::LeftDock, SplitDirection::Down)
4927 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4928
4929 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4930 (Origin::BottomDock, SplitDirection::Left) => {
4931 let dock_target = try_dock(&self.left_dock);
4932 if sidebar_on_right {
4933 dock_target
4934 } else {
4935 dock_target.or(sidebar_target)
4936 }
4937 }
4938 (Origin::BottomDock, SplitDirection::Right) => {
4939 let dock_target = try_dock(&self.right_dock);
4940 if sidebar_on_right {
4941 dock_target.or(sidebar_target)
4942 } else {
4943 dock_target
4944 }
4945 }
4946
4947 (Origin::RightDock, SplitDirection::Left) => {
4948 if let Some(last_active_pane) = get_last_active_pane() {
4949 Some(Target::Pane(last_active_pane))
4950 } else {
4951 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
4952 }
4953 }
4954
4955 (Origin::RightDock, SplitDirection::Right) => {
4956 if sidebar_on_right {
4957 sidebar_target
4958 } else {
4959 None
4960 }
4961 }
4962
4963 _ => None,
4964 };
4965
4966 match target {
4967 Some(ActivateInDirectionTarget::Pane(pane)) => {
4968 let pane = pane.read(cx);
4969 if let Some(item) = pane.active_item() {
4970 item.item_focus_handle(cx).focus(window, cx);
4971 } else {
4972 log::error!(
4973 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4974 );
4975 }
4976 }
4977 Some(ActivateInDirectionTarget::Dock(dock)) => {
4978 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4979 window.defer(cx, move |window, cx| {
4980 let dock = dock.read(cx);
4981 if let Some(panel) = dock.active_panel() {
4982 panel.panel_focus_handle(cx).focus(window, cx);
4983 } else {
4984 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4985 }
4986 })
4987 }
4988 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4989 focus_handle.focus(window, cx);
4990 }
4991 None => {}
4992 }
4993 }
4994
4995 pub fn move_item_to_pane_in_direction(
4996 &mut self,
4997 action: &MoveItemToPaneInDirection,
4998 window: &mut Window,
4999 cx: &mut Context<Self>,
5000 ) {
5001 let destination = match self.find_pane_in_direction(action.direction, cx) {
5002 Some(destination) => destination,
5003 None => {
5004 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
5005 return;
5006 }
5007 let new_pane = self.add_pane(window, cx);
5008 self.center
5009 .split(&self.active_pane, &new_pane, action.direction, cx);
5010 new_pane
5011 }
5012 };
5013
5014 if action.clone {
5015 if self
5016 .active_pane
5017 .read(cx)
5018 .active_item()
5019 .is_some_and(|item| item.can_split(cx))
5020 {
5021 clone_active_item(
5022 self.database_id(),
5023 &self.active_pane,
5024 &destination,
5025 action.focus,
5026 window,
5027 cx,
5028 );
5029 return;
5030 }
5031 }
5032 move_active_item(
5033 &self.active_pane,
5034 &destination,
5035 action.focus,
5036 true,
5037 window,
5038 cx,
5039 );
5040 }
5041
5042 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
5043 self.center.bounding_box_for_pane(pane)
5044 }
5045
5046 pub fn find_pane_in_direction(
5047 &mut self,
5048 direction: SplitDirection,
5049 cx: &App,
5050 ) -> Option<Entity<Pane>> {
5051 self.center
5052 .find_pane_in_direction(&self.active_pane, direction, cx)
5053 .cloned()
5054 }
5055
5056 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
5057 if let Some(to) = self.find_pane_in_direction(direction, cx) {
5058 self.center.swap(&self.active_pane, &to, cx);
5059 cx.notify();
5060 }
5061 }
5062
5063 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
5064 if self
5065 .center
5066 .move_to_border(&self.active_pane, direction, cx)
5067 .unwrap()
5068 {
5069 cx.notify();
5070 }
5071 }
5072
5073 pub fn resize_pane(
5074 &mut self,
5075 axis: gpui::Axis,
5076 amount: Pixels,
5077 window: &mut Window,
5078 cx: &mut Context<Self>,
5079 ) {
5080 let docks = self.all_docks();
5081 let active_dock = docks
5082 .into_iter()
5083 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
5084
5085 if let Some(dock_entity) = active_dock {
5086 let dock = dock_entity.read(cx);
5087 let Some(panel_size) = self.dock_size(&dock, window, cx) else {
5088 return;
5089 };
5090 match dock.position() {
5091 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
5092 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
5093 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
5094 }
5095 } else {
5096 self.center
5097 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
5098 }
5099 cx.notify();
5100 }
5101
5102 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
5103 self.center.reset_pane_sizes(cx);
5104 cx.notify();
5105 }
5106
5107 fn handle_pane_focused(
5108 &mut self,
5109 pane: Entity<Pane>,
5110 window: &mut Window,
5111 cx: &mut Context<Self>,
5112 ) {
5113 // This is explicitly hoisted out of the following check for pane identity as
5114 // terminal panel panes are not registered as a center panes.
5115 self.status_bar.update(cx, |status_bar, cx| {
5116 status_bar.set_active_pane(&pane, window, cx);
5117 });
5118 if self.active_pane != pane {
5119 self.set_active_pane(&pane, window, cx);
5120 }
5121
5122 if self.last_active_center_pane.is_none() {
5123 self.last_active_center_pane = Some(pane.downgrade());
5124 }
5125
5126 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
5127 // This prevents the dock from closing when focus events fire during window activation.
5128 // We also preserve any dock whose active panel itself has focus — this covers
5129 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
5130 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
5131 let dock_read = dock.read(cx);
5132 if let Some(panel) = dock_read.active_panel() {
5133 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
5134 || panel.panel_focus_handle(cx).contains_focused(window, cx)
5135 {
5136 return Some(dock_read.position());
5137 }
5138 }
5139 None
5140 });
5141
5142 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
5143 if pane.read(cx).is_zoomed() {
5144 self.zoomed = Some(pane.downgrade().into());
5145 } else {
5146 self.zoomed = None;
5147 }
5148 self.zoomed_position = None;
5149 cx.emit(Event::ZoomChanged);
5150 self.update_active_view_for_followers(window, cx);
5151 pane.update(cx, |pane, _| {
5152 pane.track_alternate_file_items();
5153 });
5154
5155 cx.notify();
5156 }
5157
5158 fn set_active_pane(
5159 &mut self,
5160 pane: &Entity<Pane>,
5161 window: &mut Window,
5162 cx: &mut Context<Self>,
5163 ) {
5164 self.active_pane = pane.clone();
5165 self.active_item_path_changed(true, window, cx);
5166 self.last_active_center_pane = Some(pane.downgrade());
5167 }
5168
5169 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5170 self.update_active_view_for_followers(window, cx);
5171 }
5172
5173 fn handle_pane_event(
5174 &mut self,
5175 pane: &Entity<Pane>,
5176 event: &pane::Event,
5177 window: &mut Window,
5178 cx: &mut Context<Self>,
5179 ) {
5180 let mut serialize_workspace = true;
5181 match event {
5182 pane::Event::AddItem { item } => {
5183 item.added_to_pane(self, pane.clone(), window, cx);
5184 cx.emit(Event::ItemAdded {
5185 item: item.boxed_clone(),
5186 });
5187 }
5188 pane::Event::Split { direction, mode } => {
5189 match mode {
5190 SplitMode::ClonePane => {
5191 self.split_and_clone(pane.clone(), *direction, window, cx)
5192 .detach();
5193 }
5194 SplitMode::EmptyPane => {
5195 self.split_pane(pane.clone(), *direction, window, cx);
5196 }
5197 SplitMode::MovePane => {
5198 self.split_and_move(pane.clone(), *direction, window, cx);
5199 }
5200 };
5201 }
5202 pane::Event::JoinIntoNext => {
5203 self.join_pane_into_next(pane.clone(), window, cx);
5204 }
5205 pane::Event::JoinAll => {
5206 self.join_all_panes(window, cx);
5207 }
5208 pane::Event::Remove { focus_on_pane } => {
5209 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5210 }
5211 pane::Event::ActivateItem {
5212 local,
5213 focus_changed,
5214 } => {
5215 window.invalidate_character_coordinates();
5216
5217 pane.update(cx, |pane, _| {
5218 pane.track_alternate_file_items();
5219 });
5220 if *local {
5221 self.unfollow_in_pane(pane, window, cx);
5222 }
5223 serialize_workspace = *focus_changed || pane != self.active_pane();
5224 if pane == self.active_pane() {
5225 self.active_item_path_changed(*focus_changed, window, cx);
5226 self.update_active_view_for_followers(window, cx);
5227 } else if *local {
5228 self.set_active_pane(pane, window, cx);
5229 }
5230 }
5231 pane::Event::UserSavedItem { item, save_intent } => {
5232 cx.emit(Event::UserSavedItem {
5233 pane: pane.downgrade(),
5234 item: item.boxed_clone(),
5235 save_intent: *save_intent,
5236 });
5237 serialize_workspace = false;
5238 }
5239 pane::Event::ChangeItemTitle => {
5240 if *pane == self.active_pane {
5241 self.active_item_path_changed(false, window, cx);
5242 }
5243 serialize_workspace = false;
5244 }
5245 pane::Event::RemovedItem { item } => {
5246 cx.emit(Event::ActiveItemChanged);
5247 self.update_window_edited(window, cx);
5248 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5249 && entry.get().entity_id() == pane.entity_id()
5250 {
5251 entry.remove();
5252 }
5253 cx.emit(Event::ItemRemoved {
5254 item_id: item.item_id(),
5255 });
5256 }
5257 pane::Event::Focus => {
5258 window.invalidate_character_coordinates();
5259 self.handle_pane_focused(pane.clone(), window, cx);
5260 }
5261 pane::Event::ZoomIn => {
5262 if *pane == self.active_pane {
5263 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5264 if pane.read(cx).has_focus(window, cx) {
5265 self.zoomed = Some(pane.downgrade().into());
5266 self.zoomed_position = None;
5267 cx.emit(Event::ZoomChanged);
5268 }
5269 cx.notify();
5270 }
5271 }
5272 pane::Event::ZoomOut => {
5273 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5274 if self.zoomed_position.is_none() {
5275 self.zoomed = None;
5276 cx.emit(Event::ZoomChanged);
5277 }
5278 cx.notify();
5279 }
5280 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5281 }
5282
5283 if serialize_workspace {
5284 self.serialize_workspace(window, cx);
5285 }
5286 }
5287
5288 pub fn unfollow_in_pane(
5289 &mut self,
5290 pane: &Entity<Pane>,
5291 window: &mut Window,
5292 cx: &mut Context<Workspace>,
5293 ) -> Option<CollaboratorId> {
5294 let leader_id = self.leader_for_pane(pane)?;
5295 self.unfollow(leader_id, window, cx);
5296 Some(leader_id)
5297 }
5298
5299 pub fn split_pane(
5300 &mut self,
5301 pane_to_split: Entity<Pane>,
5302 split_direction: SplitDirection,
5303 window: &mut Window,
5304 cx: &mut Context<Self>,
5305 ) -> Entity<Pane> {
5306 let new_pane = self.add_pane(window, cx);
5307 self.center
5308 .split(&pane_to_split, &new_pane, split_direction, cx);
5309 cx.notify();
5310 new_pane
5311 }
5312
5313 pub fn split_and_move(
5314 &mut self,
5315 pane: Entity<Pane>,
5316 direction: SplitDirection,
5317 window: &mut Window,
5318 cx: &mut Context<Self>,
5319 ) {
5320 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5321 return;
5322 };
5323 let new_pane = self.add_pane(window, cx);
5324 new_pane.update(cx, |pane, cx| {
5325 pane.add_item(item, true, true, None, window, cx)
5326 });
5327 self.center.split(&pane, &new_pane, direction, cx);
5328 cx.notify();
5329 }
5330
5331 pub fn split_and_clone(
5332 &mut self,
5333 pane: Entity<Pane>,
5334 direction: SplitDirection,
5335 window: &mut Window,
5336 cx: &mut Context<Self>,
5337 ) -> Task<Option<Entity<Pane>>> {
5338 let Some(item) = pane.read(cx).active_item() else {
5339 return Task::ready(None);
5340 };
5341 if !item.can_split(cx) {
5342 return Task::ready(None);
5343 }
5344 let task = item.clone_on_split(self.database_id(), window, cx);
5345 cx.spawn_in(window, async move |this, cx| {
5346 if let Some(clone) = task.await {
5347 this.update_in(cx, |this, window, cx| {
5348 let new_pane = this.add_pane(window, cx);
5349 let nav_history = pane.read(cx).fork_nav_history();
5350 new_pane.update(cx, |pane, cx| {
5351 pane.set_nav_history(nav_history, cx);
5352 pane.add_item(clone, true, true, None, window, cx)
5353 });
5354 this.center.split(&pane, &new_pane, direction, cx);
5355 cx.notify();
5356 new_pane
5357 })
5358 .ok()
5359 } else {
5360 None
5361 }
5362 })
5363 }
5364
5365 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5366 let active_item = self.active_pane.read(cx).active_item();
5367 for pane in &self.panes {
5368 join_pane_into_active(&self.active_pane, pane, window, cx);
5369 }
5370 if let Some(active_item) = active_item {
5371 self.activate_item(active_item.as_ref(), true, true, window, cx);
5372 }
5373 cx.notify();
5374 }
5375
5376 pub fn join_pane_into_next(
5377 &mut self,
5378 pane: Entity<Pane>,
5379 window: &mut Window,
5380 cx: &mut Context<Self>,
5381 ) {
5382 let next_pane = self
5383 .find_pane_in_direction(SplitDirection::Right, cx)
5384 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5385 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5386 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5387 let Some(next_pane) = next_pane else {
5388 return;
5389 };
5390 move_all_items(&pane, &next_pane, window, cx);
5391 cx.notify();
5392 }
5393
5394 fn remove_pane(
5395 &mut self,
5396 pane: Entity<Pane>,
5397 focus_on: Option<Entity<Pane>>,
5398 window: &mut Window,
5399 cx: &mut Context<Self>,
5400 ) {
5401 if self.center.remove(&pane, cx).unwrap() {
5402 self.force_remove_pane(&pane, &focus_on, window, cx);
5403 self.unfollow_in_pane(&pane, window, cx);
5404 self.last_leaders_by_pane.remove(&pane.downgrade());
5405 for removed_item in pane.read(cx).items() {
5406 self.panes_by_item.remove(&removed_item.item_id());
5407 }
5408
5409 cx.notify();
5410 } else {
5411 self.active_item_path_changed(true, window, cx);
5412 }
5413 cx.emit(Event::PaneRemoved);
5414 }
5415
5416 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5417 &mut self.panes
5418 }
5419
5420 pub fn panes(&self) -> &[Entity<Pane>] {
5421 &self.panes
5422 }
5423
5424 pub fn active_pane(&self) -> &Entity<Pane> {
5425 &self.active_pane
5426 }
5427
5428 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5429 for dock in self.all_docks() {
5430 if dock.focus_handle(cx).contains_focused(window, cx)
5431 && let Some(pane) = dock
5432 .read(cx)
5433 .active_panel()
5434 .and_then(|panel| panel.pane(cx))
5435 {
5436 return pane;
5437 }
5438 }
5439 self.active_pane().clone()
5440 }
5441
5442 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5443 self.find_pane_in_direction(SplitDirection::Right, cx)
5444 .unwrap_or_else(|| {
5445 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5446 })
5447 }
5448
5449 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5450 self.pane_for_item_id(handle.item_id())
5451 }
5452
5453 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5454 let weak_pane = self.panes_by_item.get(&item_id)?;
5455 weak_pane.upgrade()
5456 }
5457
5458 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5459 self.panes
5460 .iter()
5461 .find(|pane| pane.entity_id() == entity_id)
5462 .cloned()
5463 }
5464
5465 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5466 self.follower_states.retain(|leader_id, state| {
5467 if *leader_id == CollaboratorId::PeerId(peer_id) {
5468 for item in state.items_by_leader_view_id.values() {
5469 item.view.set_leader_id(None, window, cx);
5470 }
5471 false
5472 } else {
5473 true
5474 }
5475 });
5476 cx.notify();
5477 }
5478
5479 pub fn start_following(
5480 &mut self,
5481 leader_id: impl Into<CollaboratorId>,
5482 window: &mut Window,
5483 cx: &mut Context<Self>,
5484 ) -> Option<Task<Result<()>>> {
5485 let leader_id = leader_id.into();
5486 let pane = self.active_pane().clone();
5487
5488 self.last_leaders_by_pane
5489 .insert(pane.downgrade(), leader_id);
5490 self.unfollow(leader_id, window, cx);
5491 self.unfollow_in_pane(&pane, window, cx);
5492 self.follower_states.insert(
5493 leader_id,
5494 FollowerState {
5495 center_pane: pane.clone(),
5496 dock_pane: None,
5497 active_view_id: None,
5498 items_by_leader_view_id: Default::default(),
5499 },
5500 );
5501 cx.notify();
5502
5503 match leader_id {
5504 CollaboratorId::PeerId(leader_peer_id) => {
5505 let room_id = self.active_call()?.room_id(cx)?;
5506 let project_id = self.project.read(cx).remote_id();
5507 let request = self.app_state.client.request(proto::Follow {
5508 room_id,
5509 project_id,
5510 leader_id: Some(leader_peer_id),
5511 });
5512
5513 Some(cx.spawn_in(window, async move |this, cx| {
5514 let response = request.await?;
5515 this.update(cx, |this, _| {
5516 let state = this
5517 .follower_states
5518 .get_mut(&leader_id)
5519 .context("following interrupted")?;
5520 state.active_view_id = response
5521 .active_view
5522 .as_ref()
5523 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5524 anyhow::Ok(())
5525 })??;
5526 if let Some(view) = response.active_view {
5527 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5528 }
5529 this.update_in(cx, |this, window, cx| {
5530 this.leader_updated(leader_id, window, cx)
5531 })?;
5532 Ok(())
5533 }))
5534 }
5535 CollaboratorId::Agent => {
5536 self.leader_updated(leader_id, window, cx)?;
5537 Some(Task::ready(Ok(())))
5538 }
5539 }
5540 }
5541
5542 pub fn follow_next_collaborator(
5543 &mut self,
5544 _: &FollowNextCollaborator,
5545 window: &mut Window,
5546 cx: &mut Context<Self>,
5547 ) {
5548 let collaborators = self.project.read(cx).collaborators();
5549 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5550 let mut collaborators = collaborators.keys().copied();
5551 for peer_id in collaborators.by_ref() {
5552 if CollaboratorId::PeerId(peer_id) == leader_id {
5553 break;
5554 }
5555 }
5556 collaborators.next().map(CollaboratorId::PeerId)
5557 } else if let Some(last_leader_id) =
5558 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5559 {
5560 match last_leader_id {
5561 CollaboratorId::PeerId(peer_id) => {
5562 if collaborators.contains_key(peer_id) {
5563 Some(*last_leader_id)
5564 } else {
5565 None
5566 }
5567 }
5568 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5569 }
5570 } else {
5571 None
5572 };
5573
5574 let pane = self.active_pane.clone();
5575 let Some(leader_id) = next_leader_id.or_else(|| {
5576 Some(CollaboratorId::PeerId(
5577 collaborators.keys().copied().next()?,
5578 ))
5579 }) else {
5580 return;
5581 };
5582 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5583 return;
5584 }
5585 if let Some(task) = self.start_following(leader_id, window, cx) {
5586 task.detach_and_log_err(cx)
5587 }
5588 }
5589
5590 pub fn follow(
5591 &mut self,
5592 leader_id: impl Into<CollaboratorId>,
5593 window: &mut Window,
5594 cx: &mut Context<Self>,
5595 ) {
5596 let leader_id = leader_id.into();
5597
5598 if let CollaboratorId::PeerId(peer_id) = leader_id {
5599 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5600 return;
5601 };
5602 let Some(remote_participant) =
5603 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5604 else {
5605 return;
5606 };
5607
5608 let project = self.project.read(cx);
5609
5610 let other_project_id = match remote_participant.location {
5611 ParticipantLocation::External => None,
5612 ParticipantLocation::UnsharedProject => None,
5613 ParticipantLocation::SharedProject { project_id } => {
5614 if Some(project_id) == project.remote_id() {
5615 None
5616 } else {
5617 Some(project_id)
5618 }
5619 }
5620 };
5621
5622 // if they are active in another project, follow there.
5623 if let Some(project_id) = other_project_id {
5624 let app_state = self.app_state.clone();
5625 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5626 .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
5627 Some(format!("{error:#}"))
5628 });
5629 }
5630 }
5631
5632 // if you're already following, find the right pane and focus it.
5633 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5634 window.focus(&follower_state.pane().focus_handle(cx), cx);
5635
5636 return;
5637 }
5638
5639 // Otherwise, follow.
5640 if let Some(task) = self.start_following(leader_id, window, cx) {
5641 task.detach_and_log_err(cx)
5642 }
5643 }
5644
5645 pub fn unfollow(
5646 &mut self,
5647 leader_id: impl Into<CollaboratorId>,
5648 window: &mut Window,
5649 cx: &mut Context<Self>,
5650 ) -> Option<()> {
5651 cx.notify();
5652
5653 let leader_id = leader_id.into();
5654 let state = self.follower_states.remove(&leader_id)?;
5655 for (_, item) in state.items_by_leader_view_id {
5656 item.view.set_leader_id(None, window, cx);
5657 }
5658
5659 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5660 let project_id = self.project.read(cx).remote_id();
5661 let room_id = self.active_call()?.room_id(cx)?;
5662 self.app_state
5663 .client
5664 .send(proto::Unfollow {
5665 room_id,
5666 project_id,
5667 leader_id: Some(leader_peer_id),
5668 })
5669 .log_err();
5670 }
5671
5672 Some(())
5673 }
5674
5675 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5676 self.follower_states.contains_key(&id.into())
5677 }
5678
5679 fn active_item_path_changed(
5680 &mut self,
5681 focus_changed: bool,
5682 window: &mut Window,
5683 cx: &mut Context<Self>,
5684 ) {
5685 cx.emit(Event::ActiveItemChanged);
5686 let active_entry = self.active_project_path(cx);
5687 self.project.update(cx, |project, cx| {
5688 project.set_active_path(active_entry.clone(), cx)
5689 });
5690
5691 if focus_changed && let Some(project_path) = &active_entry {
5692 let git_store_entity = self.project.read(cx).git_store().clone();
5693 git_store_entity.update(cx, |git_store, cx| {
5694 git_store.set_active_repo_for_path(project_path, cx);
5695 });
5696 }
5697
5698 self.update_window_title(window, cx);
5699 }
5700
5701 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5702 let project = self.project().read(cx);
5703 let mut title = String::new();
5704
5705 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5706 let name = {
5707 let settings_location = SettingsLocation {
5708 worktree_id: worktree.read(cx).id(),
5709 path: RelPath::empty(),
5710 };
5711
5712 let settings = WorktreeSettings::get(Some(settings_location), cx);
5713 match &settings.project_name {
5714 Some(name) => name.as_str(),
5715 None => worktree.read(cx).root_name_str(),
5716 }
5717 };
5718 if i > 0 {
5719 title.push_str(", ");
5720 }
5721 title.push_str(name);
5722 }
5723
5724 if title.is_empty() {
5725 title = "empty project".to_string();
5726 }
5727
5728 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5729 let filename = path.path.file_name().or_else(|| {
5730 Some(
5731 project
5732 .worktree_for_id(path.worktree_id, cx)?
5733 .read(cx)
5734 .root_name_str(),
5735 )
5736 });
5737
5738 if let Some(filename) = filename {
5739 title.push_str(" — ");
5740 title.push_str(filename.as_ref());
5741 }
5742 }
5743
5744 if project.is_via_collab() {
5745 title.push_str(" ↙");
5746 } else if project.is_shared() {
5747 title.push_str(" ↗");
5748 }
5749
5750 if let Some(last_title) = self.last_window_title.as_ref()
5751 && &title == last_title
5752 {
5753 return;
5754 }
5755 window.set_window_title(&title);
5756 SystemWindowTabController::update_tab_title(
5757 cx,
5758 window.window_handle().window_id(),
5759 SharedString::from(&title),
5760 );
5761 self.last_window_title = Some(title);
5762 }
5763
5764 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5765 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5766 if is_edited != self.window_edited {
5767 self.window_edited = is_edited;
5768 window.set_window_edited(self.window_edited)
5769 }
5770 }
5771
5772 fn update_item_dirty_state(
5773 &mut self,
5774 item: &dyn ItemHandle,
5775 window: &mut Window,
5776 cx: &mut App,
5777 ) {
5778 let is_dirty = item.is_dirty(cx);
5779 let item_id = item.item_id();
5780 let was_dirty = self.dirty_items.contains_key(&item_id);
5781 if is_dirty == was_dirty {
5782 return;
5783 }
5784 if was_dirty {
5785 self.dirty_items.remove(&item_id);
5786 self.update_window_edited(window, cx);
5787 return;
5788 }
5789
5790 let workspace = self.weak_handle();
5791 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5792 return;
5793 };
5794 let on_release_callback = Box::new(move |cx: &mut App| {
5795 window_handle
5796 .update(cx, |_, window, cx| {
5797 workspace
5798 .update(cx, |workspace, cx| {
5799 workspace.dirty_items.remove(&item_id);
5800 workspace.update_window_edited(window, cx)
5801 })
5802 .ok();
5803 })
5804 .ok();
5805 });
5806
5807 let s = item.on_release(cx, on_release_callback);
5808 self.dirty_items.insert(item_id, s);
5809 self.update_window_edited(window, cx);
5810 }
5811
5812 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5813 if self.notifications.is_empty() {
5814 None
5815 } else {
5816 Some(
5817 div()
5818 .absolute()
5819 .right_3()
5820 .bottom_3()
5821 .w_112()
5822 .h_full()
5823 .flex()
5824 .flex_col()
5825 .justify_end()
5826 .gap_2()
5827 .children(
5828 self.notifications
5829 .iter()
5830 .map(|(_, notification)| notification.clone().into_any()),
5831 ),
5832 )
5833 }
5834 }
5835
5836 // RPC handlers
5837
5838 fn active_view_for_follower(
5839 &self,
5840 follower_project_id: Option<u64>,
5841 window: &mut Window,
5842 cx: &mut Context<Self>,
5843 ) -> Option<proto::View> {
5844 let (item, panel_id) = self.active_item_for_followers(window, cx);
5845 let item = item?;
5846 let leader_id = self
5847 .pane_for(&*item)
5848 .and_then(|pane| self.leader_for_pane(&pane));
5849 let leader_peer_id = match leader_id {
5850 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5851 Some(CollaboratorId::Agent) | None => None,
5852 };
5853
5854 let item_handle = item.to_followable_item_handle(cx)?;
5855 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5856 let variant = item_handle.to_state_proto(window, cx)?;
5857
5858 if item_handle.is_project_item(window, cx)
5859 && (follower_project_id.is_none()
5860 || follower_project_id != self.project.read(cx).remote_id())
5861 {
5862 return None;
5863 }
5864
5865 Some(proto::View {
5866 id: id.to_proto(),
5867 leader_id: leader_peer_id,
5868 variant: Some(variant),
5869 panel_id: panel_id.map(|id| id as i32),
5870 })
5871 }
5872
5873 fn handle_follow(
5874 &mut self,
5875 follower_project_id: Option<u64>,
5876 window: &mut Window,
5877 cx: &mut Context<Self>,
5878 ) -> proto::FollowResponse {
5879 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5880
5881 cx.notify();
5882 proto::FollowResponse {
5883 views: active_view.iter().cloned().collect(),
5884 active_view,
5885 }
5886 }
5887
5888 fn handle_update_followers(
5889 &mut self,
5890 leader_id: PeerId,
5891 message: proto::UpdateFollowers,
5892 _window: &mut Window,
5893 _cx: &mut Context<Self>,
5894 ) {
5895 self.leader_updates_tx
5896 .unbounded_send((leader_id, message))
5897 .ok();
5898 }
5899
5900 async fn process_leader_update(
5901 this: &WeakEntity<Self>,
5902 leader_id: PeerId,
5903 update: proto::UpdateFollowers,
5904 cx: &mut AsyncWindowContext,
5905 ) -> Result<()> {
5906 match update.variant.context("invalid update")? {
5907 proto::update_followers::Variant::CreateView(view) => {
5908 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5909 let should_add_view = this.update(cx, |this, _| {
5910 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5911 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5912 } else {
5913 anyhow::Ok(false)
5914 }
5915 })??;
5916
5917 if should_add_view {
5918 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5919 }
5920 }
5921 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5922 let should_add_view = this.update(cx, |this, _| {
5923 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5924 state.active_view_id = update_active_view
5925 .view
5926 .as_ref()
5927 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5928
5929 if state.active_view_id.is_some_and(|view_id| {
5930 !state.items_by_leader_view_id.contains_key(&view_id)
5931 }) {
5932 anyhow::Ok(true)
5933 } else {
5934 anyhow::Ok(false)
5935 }
5936 } else {
5937 anyhow::Ok(false)
5938 }
5939 })??;
5940
5941 if should_add_view && let Some(view) = update_active_view.view {
5942 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5943 }
5944 }
5945 proto::update_followers::Variant::UpdateView(update_view) => {
5946 let variant = update_view.variant.context("missing update view variant")?;
5947 let id = update_view.id.context("missing update view id")?;
5948 let mut tasks = Vec::new();
5949 this.update_in(cx, |this, window, cx| {
5950 let project = this.project.clone();
5951 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5952 let view_id = ViewId::from_proto(id.clone())?;
5953 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5954 tasks.push(item.view.apply_update_proto(
5955 &project,
5956 variant.clone(),
5957 window,
5958 cx,
5959 ));
5960 }
5961 }
5962 anyhow::Ok(())
5963 })??;
5964 try_join_all(tasks).await.log_err();
5965 }
5966 }
5967 this.update_in(cx, |this, window, cx| {
5968 this.leader_updated(leader_id, window, cx)
5969 })?;
5970 Ok(())
5971 }
5972
5973 async fn add_view_from_leader(
5974 this: WeakEntity<Self>,
5975 leader_id: PeerId,
5976 view: &proto::View,
5977 cx: &mut AsyncWindowContext,
5978 ) -> Result<()> {
5979 let this = this.upgrade().context("workspace dropped")?;
5980
5981 let Some(id) = view.id.clone() else {
5982 anyhow::bail!("no id for view");
5983 };
5984 let id = ViewId::from_proto(id)?;
5985 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5986
5987 let pane = this.update(cx, |this, _cx| {
5988 let state = this
5989 .follower_states
5990 .get(&leader_id.into())
5991 .context("stopped following")?;
5992 anyhow::Ok(state.pane().clone())
5993 })?;
5994 let existing_item = pane.update_in(cx, |pane, window, cx| {
5995 let client = this.read(cx).client().clone();
5996 pane.items().find_map(|item| {
5997 let item = item.to_followable_item_handle(cx)?;
5998 if item.remote_id(&client, window, cx) == Some(id) {
5999 Some(item)
6000 } else {
6001 None
6002 }
6003 })
6004 })?;
6005 let item = if let Some(existing_item) = existing_item {
6006 existing_item
6007 } else {
6008 let variant = view.variant.clone();
6009 anyhow::ensure!(variant.is_some(), "missing view variant");
6010
6011 let task = cx.update(|window, cx| {
6012 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
6013 })?;
6014
6015 let Some(task) = task else {
6016 anyhow::bail!(
6017 "failed to construct view from leader (maybe from a different version of zed?)"
6018 );
6019 };
6020
6021 let mut new_item = task.await?;
6022 pane.update_in(cx, |pane, window, cx| {
6023 let mut item_to_remove = None;
6024 for (ix, item) in pane.items().enumerate() {
6025 if let Some(item) = item.to_followable_item_handle(cx) {
6026 match new_item.dedup(item.as_ref(), window, cx) {
6027 Some(item::Dedup::KeepExisting) => {
6028 new_item =
6029 item.boxed_clone().to_followable_item_handle(cx).unwrap();
6030 break;
6031 }
6032 Some(item::Dedup::ReplaceExisting) => {
6033 item_to_remove = Some((ix, item.item_id()));
6034 break;
6035 }
6036 None => {}
6037 }
6038 }
6039 }
6040
6041 if let Some((ix, id)) = item_to_remove {
6042 pane.remove_item(id, false, false, window, cx);
6043 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
6044 }
6045 })?;
6046
6047 new_item
6048 };
6049
6050 this.update_in(cx, |this, window, cx| {
6051 let state = this.follower_states.get_mut(&leader_id.into())?;
6052 item.set_leader_id(Some(leader_id.into()), window, cx);
6053 state.items_by_leader_view_id.insert(
6054 id,
6055 FollowerView {
6056 view: item,
6057 location: panel_id,
6058 },
6059 );
6060
6061 Some(())
6062 })
6063 .context("no follower state")?;
6064
6065 Ok(())
6066 }
6067
6068 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6069 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
6070 return;
6071 };
6072
6073 if let Some(agent_location) = self.project.read(cx).agent_location() {
6074 let buffer_entity_id = agent_location.buffer.entity_id();
6075 let view_id = ViewId {
6076 creator: CollaboratorId::Agent,
6077 id: buffer_entity_id.as_u64(),
6078 };
6079 follower_state.active_view_id = Some(view_id);
6080
6081 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
6082 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
6083 hash_map::Entry::Vacant(entry) => {
6084 let existing_view =
6085 follower_state
6086 .center_pane
6087 .read(cx)
6088 .items()
6089 .find_map(|item| {
6090 let item = item.to_followable_item_handle(cx)?;
6091 if item.buffer_kind(cx) == ItemBufferKind::Singleton
6092 && item.project_item_model_ids(cx).as_slice()
6093 == [buffer_entity_id]
6094 {
6095 Some(item)
6096 } else {
6097 None
6098 }
6099 });
6100 let view = existing_view.or_else(|| {
6101 agent_location.buffer.upgrade().and_then(|buffer| {
6102 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
6103 registry.build_item(buffer, self.project.clone(), None, window, cx)
6104 })?
6105 .to_followable_item_handle(cx)
6106 })
6107 });
6108
6109 view.map(|view| {
6110 entry.insert(FollowerView {
6111 view,
6112 location: None,
6113 })
6114 })
6115 }
6116 };
6117
6118 if let Some(item) = item {
6119 item.view
6120 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
6121 item.view
6122 .update_agent_location(agent_location.position, window, cx);
6123 }
6124 } else {
6125 follower_state.active_view_id = None;
6126 }
6127
6128 self.leader_updated(CollaboratorId::Agent, window, cx);
6129 }
6130
6131 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
6132 let mut is_project_item = true;
6133 let mut update = proto::UpdateActiveView::default();
6134 if window.is_window_active() {
6135 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
6136
6137 if let Some(item) = active_item
6138 && item.item_focus_handle(cx).contains_focused(window, cx)
6139 {
6140 let leader_id = self
6141 .pane_for(&*item)
6142 .and_then(|pane| self.leader_for_pane(&pane));
6143 let leader_peer_id = match leader_id {
6144 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
6145 Some(CollaboratorId::Agent) | None => None,
6146 };
6147
6148 if let Some(item) = item.to_followable_item_handle(cx) {
6149 let id = item
6150 .remote_id(&self.app_state.client, window, cx)
6151 .map(|id| id.to_proto());
6152
6153 if let Some(id) = id
6154 && let Some(variant) = item.to_state_proto(window, cx)
6155 {
6156 let view = Some(proto::View {
6157 id,
6158 leader_id: leader_peer_id,
6159 variant: Some(variant),
6160 panel_id: panel_id.map(|id| id as i32),
6161 });
6162
6163 is_project_item = item.is_project_item(window, cx);
6164 update = proto::UpdateActiveView { view };
6165 };
6166 }
6167 }
6168 }
6169
6170 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
6171 if active_view_id != self.last_active_view_id.as_ref() {
6172 self.last_active_view_id = active_view_id.cloned();
6173 self.update_followers(
6174 is_project_item,
6175 proto::update_followers::Variant::UpdateActiveView(update),
6176 window,
6177 cx,
6178 );
6179 }
6180 }
6181
6182 fn active_item_for_followers(
6183 &self,
6184 window: &mut Window,
6185 cx: &mut App,
6186 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
6187 let mut active_item = None;
6188 let mut panel_id = None;
6189 for dock in self.all_docks() {
6190 if dock.focus_handle(cx).contains_focused(window, cx)
6191 && let Some(panel) = dock.read(cx).active_panel()
6192 && let Some(pane) = panel.pane(cx)
6193 && let Some(item) = pane.read(cx).active_item()
6194 {
6195 active_item = Some(item);
6196 panel_id = panel.remote_id();
6197 break;
6198 }
6199 }
6200
6201 if active_item.is_none() {
6202 active_item = self.active_pane().read(cx).active_item();
6203 }
6204 (active_item, panel_id)
6205 }
6206
6207 fn update_followers(
6208 &self,
6209 project_only: bool,
6210 update: proto::update_followers::Variant,
6211 _: &mut Window,
6212 cx: &mut App,
6213 ) -> Option<()> {
6214 // If this update only applies to for followers in the current project,
6215 // then skip it unless this project is shared. If it applies to all
6216 // followers, regardless of project, then set `project_id` to none,
6217 // indicating that it goes to all followers.
6218 let project_id = if project_only {
6219 Some(self.project.read(cx).remote_id()?)
6220 } else {
6221 None
6222 };
6223 self.app_state().workspace_store.update(cx, |store, cx| {
6224 store.update_followers(project_id, update, cx)
6225 })
6226 }
6227
6228 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6229 self.follower_states.iter().find_map(|(leader_id, state)| {
6230 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6231 Some(*leader_id)
6232 } else {
6233 None
6234 }
6235 })
6236 }
6237
6238 fn leader_updated(
6239 &mut self,
6240 leader_id: impl Into<CollaboratorId>,
6241 window: &mut Window,
6242 cx: &mut Context<Self>,
6243 ) -> Option<Box<dyn ItemHandle>> {
6244 cx.notify();
6245
6246 let leader_id = leader_id.into();
6247 let (panel_id, item) = match leader_id {
6248 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6249 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6250 };
6251
6252 let state = self.follower_states.get(&leader_id)?;
6253 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6254 let pane;
6255 if let Some(panel_id) = panel_id {
6256 pane = self
6257 .activate_panel_for_proto_id(panel_id, window, cx)?
6258 .pane(cx)?;
6259 let state = self.follower_states.get_mut(&leader_id)?;
6260 state.dock_pane = Some(pane.clone());
6261 } else {
6262 pane = state.center_pane.clone();
6263 let state = self.follower_states.get_mut(&leader_id)?;
6264 if let Some(dock_pane) = state.dock_pane.take() {
6265 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6266 }
6267 }
6268
6269 pane.update(cx, |pane, cx| {
6270 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6271 if let Some(index) = pane.index_for_item(item.as_ref()) {
6272 pane.activate_item(index, false, false, window, cx);
6273 } else {
6274 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6275 }
6276
6277 if focus_active_item {
6278 pane.focus_active_item(window, cx)
6279 }
6280 });
6281
6282 Some(item)
6283 }
6284
6285 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6286 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6287 let active_view_id = state.active_view_id?;
6288 Some(
6289 state
6290 .items_by_leader_view_id
6291 .get(&active_view_id)?
6292 .view
6293 .boxed_clone(),
6294 )
6295 }
6296
6297 fn active_item_for_peer(
6298 &self,
6299 peer_id: PeerId,
6300 window: &mut Window,
6301 cx: &mut Context<Self>,
6302 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6303 let call = self.active_call()?;
6304 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6305 let leader_in_this_app;
6306 let leader_in_this_project;
6307 match participant.location {
6308 ParticipantLocation::SharedProject { project_id } => {
6309 leader_in_this_app = true;
6310 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6311 }
6312 ParticipantLocation::UnsharedProject => {
6313 leader_in_this_app = true;
6314 leader_in_this_project = false;
6315 }
6316 ParticipantLocation::External => {
6317 leader_in_this_app = false;
6318 leader_in_this_project = false;
6319 }
6320 };
6321 let state = self.follower_states.get(&peer_id.into())?;
6322 let mut item_to_activate = None;
6323 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6324 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6325 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6326 {
6327 item_to_activate = Some((item.location, item.view.boxed_clone()));
6328 }
6329 } else if let Some(shared_screen) =
6330 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6331 {
6332 item_to_activate = Some((None, Box::new(shared_screen)));
6333 }
6334 item_to_activate
6335 }
6336
6337 fn shared_screen_for_peer(
6338 &self,
6339 peer_id: PeerId,
6340 pane: &Entity<Pane>,
6341 window: &mut Window,
6342 cx: &mut App,
6343 ) -> Option<Entity<SharedScreen>> {
6344 self.active_call()?
6345 .create_shared_screen(peer_id, pane, window, cx)
6346 }
6347
6348 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6349 if window.is_window_active() {
6350 self.update_active_view_for_followers(window, cx);
6351
6352 if let Some(database_id) = self.database_id {
6353 let db = WorkspaceDb::global(cx);
6354 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6355 .detach();
6356 }
6357 } else {
6358 for pane in &self.panes {
6359 pane.update(cx, |pane, cx| {
6360 if let Some(item) = pane.active_item() {
6361 item.workspace_deactivated(window, cx);
6362 }
6363 for item in pane.items() {
6364 if matches!(
6365 item.workspace_settings(cx).autosave,
6366 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6367 ) {
6368 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6369 .detach_and_log_err(cx);
6370 }
6371 }
6372 });
6373 }
6374 }
6375 }
6376
6377 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6378 self.active_call.as_ref().map(|(call, _)| &*call.0)
6379 }
6380
6381 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6382 self.active_call.as_ref().map(|(call, _)| call.clone())
6383 }
6384
6385 fn on_active_call_event(
6386 &mut self,
6387 event: &ActiveCallEvent,
6388 window: &mut Window,
6389 cx: &mut Context<Self>,
6390 ) {
6391 match event {
6392 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6393 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6394 self.leader_updated(participant_id, window, cx);
6395 }
6396 }
6397 }
6398
6399 pub fn database_id(&self) -> Option<WorkspaceId> {
6400 self.database_id
6401 }
6402
6403 #[cfg(any(test, feature = "test-support"))]
6404 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6405 self.database_id = Some(id);
6406 }
6407
6408 pub fn session_id(&self) -> Option<String> {
6409 self.session_id.clone()
6410 }
6411
6412 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6413 let Some(display) = window.display(cx) else {
6414 return Task::ready(());
6415 };
6416 let Ok(display_uuid) = display.uuid() else {
6417 return Task::ready(());
6418 };
6419
6420 let window_bounds = window.inner_window_bounds();
6421 let database_id = self.database_id;
6422 let has_paths = !self.root_paths(cx).is_empty();
6423 let db = WorkspaceDb::global(cx);
6424 let kvp = db::kvp::KeyValueStore::global(cx);
6425
6426 cx.background_executor().spawn(async move {
6427 if !has_paths {
6428 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6429 .await
6430 .log_err();
6431 }
6432 if let Some(database_id) = database_id {
6433 db.set_window_open_status(
6434 database_id,
6435 SerializedWindowBounds(window_bounds),
6436 display_uuid,
6437 )
6438 .await
6439 .log_err();
6440 } else {
6441 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6442 .await
6443 .log_err();
6444 }
6445 })
6446 }
6447
6448 /// Bypass the 200ms serialization throttle and write workspace state to
6449 /// the DB immediately. Returns a task the caller can await to ensure the
6450 /// write completes. Used by the quit handler so the most recent state
6451 /// isn't lost to a pending throttle timer when the process exits.
6452 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6453 self._schedule_serialize_workspace.take();
6454 self._serialize_workspace_task.take();
6455 self.bounds_save_task_queued.take();
6456
6457 let bounds_task = self.save_window_bounds(window, cx);
6458 let serialize_task = self.serialize_workspace_internal(window, cx);
6459 cx.spawn(async move |_| {
6460 bounds_task.await;
6461 serialize_task.await;
6462 })
6463 }
6464
6465 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6466 let project = self.project().read(cx);
6467 project
6468 .visible_worktrees(cx)
6469 .map(|worktree| worktree.read(cx).abs_path())
6470 .collect::<Vec<_>>()
6471 }
6472
6473 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6474 match member {
6475 Member::Axis(PaneAxis { members, .. }) => {
6476 for child in members.iter() {
6477 self.remove_panes(child.clone(), window, cx)
6478 }
6479 }
6480 Member::Pane(pane) => {
6481 self.force_remove_pane(&pane, &None, window, cx);
6482 }
6483 }
6484 }
6485
6486 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6487 self.session_id.take();
6488 self.serialize_workspace_internal(window, cx)
6489 }
6490
6491 fn force_remove_pane(
6492 &mut self,
6493 pane: &Entity<Pane>,
6494 focus_on: &Option<Entity<Pane>>,
6495 window: &mut Window,
6496 cx: &mut Context<Workspace>,
6497 ) {
6498 self.panes.retain(|p| p != pane);
6499 if let Some(focus_on) = focus_on {
6500 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6501 } else if self.active_pane() == pane {
6502 self.panes
6503 .last()
6504 .unwrap()
6505 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6506 }
6507 if self.last_active_center_pane == Some(pane.downgrade()) {
6508 self.last_active_center_pane = None;
6509 }
6510 cx.notify();
6511 }
6512
6513 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6514 if self._schedule_serialize_workspace.is_none() {
6515 self._schedule_serialize_workspace =
6516 Some(cx.spawn_in(window, async move |this, cx| {
6517 cx.background_executor()
6518 .timer(SERIALIZATION_THROTTLE_TIME)
6519 .await;
6520 this.update_in(cx, |this, window, cx| {
6521 this._serialize_workspace_task =
6522 Some(this.serialize_workspace_internal(window, cx));
6523 this._schedule_serialize_workspace.take();
6524 })
6525 .log_err();
6526 }));
6527 }
6528 }
6529
6530 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6531 let Some(database_id) = self.database_id() else {
6532 return Task::ready(());
6533 };
6534
6535 fn serialize_pane_handle(
6536 pane_handle: &Entity<Pane>,
6537 window: &mut Window,
6538 cx: &mut App,
6539 ) -> SerializedPane {
6540 let (items, active, pinned_count) = {
6541 let pane = pane_handle.read(cx);
6542 let active_item_id = pane.active_item().map(|item| item.item_id());
6543 (
6544 pane.items()
6545 .filter_map(|handle| {
6546 let handle = handle.to_serializable_item_handle(cx)?;
6547
6548 Some(SerializedItem {
6549 kind: Arc::from(handle.serialized_item_kind()),
6550 item_id: handle.item_id().as_u64(),
6551 active: Some(handle.item_id()) == active_item_id,
6552 preview: pane.is_active_preview_item(handle.item_id()),
6553 })
6554 })
6555 .collect::<Vec<_>>(),
6556 pane.has_focus(window, cx),
6557 pane.pinned_count(),
6558 )
6559 };
6560
6561 SerializedPane::new(items, active, pinned_count)
6562 }
6563
6564 fn build_serialized_pane_group(
6565 pane_group: &Member,
6566 window: &mut Window,
6567 cx: &mut App,
6568 ) -> SerializedPaneGroup {
6569 match pane_group {
6570 Member::Axis(PaneAxis {
6571 axis,
6572 members,
6573 flexes,
6574 bounding_boxes: _,
6575 }) => SerializedPaneGroup::Group {
6576 axis: SerializedAxis(*axis),
6577 children: members
6578 .iter()
6579 .map(|member| build_serialized_pane_group(member, window, cx))
6580 .collect::<Vec<_>>(),
6581 flexes: Some(flexes.lock().clone()),
6582 },
6583 Member::Pane(pane_handle) => {
6584 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6585 }
6586 }
6587 }
6588
6589 fn build_serialized_docks(
6590 this: &Workspace,
6591 window: &mut Window,
6592 cx: &mut App,
6593 ) -> DockStructure {
6594 this.capture_dock_state(window, cx)
6595 }
6596
6597 match self.workspace_location(cx) {
6598 WorkspaceLocation::Location(location, paths) => {
6599 let breakpoints = self.project.update(cx, |project, cx| {
6600 project
6601 .breakpoint_store()
6602 .read(cx)
6603 .all_source_breakpoints(cx)
6604 });
6605 let user_toolchains = self
6606 .project
6607 .read(cx)
6608 .user_toolchains(cx)
6609 .unwrap_or_default();
6610
6611 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6612 let docks = build_serialized_docks(self, window, cx);
6613 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6614
6615 let serialized_workspace = SerializedWorkspace {
6616 id: database_id,
6617 location,
6618 paths,
6619 center_group,
6620 window_bounds,
6621 display: Default::default(),
6622 docks,
6623 centered_layout: self.centered_layout,
6624 session_id: self.session_id.clone(),
6625 breakpoints,
6626 window_id: Some(window.window_handle().window_id().as_u64()),
6627 user_toolchains,
6628 };
6629
6630 let db = WorkspaceDb::global(cx);
6631 window.spawn(cx, async move |_| {
6632 db.save_workspace(serialized_workspace).await;
6633 })
6634 }
6635 WorkspaceLocation::DetachFromSession => {
6636 let window_bounds = SerializedWindowBounds(window.window_bounds());
6637 let display = window.display(cx).and_then(|d| d.uuid().ok());
6638 // Save dock state for empty local workspaces
6639 let docks = build_serialized_docks(self, window, cx);
6640 let db = WorkspaceDb::global(cx);
6641 let kvp = db::kvp::KeyValueStore::global(cx);
6642 window.spawn(cx, async move |_| {
6643 db.set_window_open_status(
6644 database_id,
6645 window_bounds,
6646 display.unwrap_or_default(),
6647 )
6648 .await
6649 .log_err();
6650 db.set_session_id(database_id, None).await.log_err();
6651 persistence::write_default_dock_state(&kvp, docks)
6652 .await
6653 .log_err();
6654 })
6655 }
6656 WorkspaceLocation::None => {
6657 // Save dock state for empty non-local workspaces
6658 let docks = build_serialized_docks(self, window, cx);
6659 let kvp = db::kvp::KeyValueStore::global(cx);
6660 window.spawn(cx, async move |_| {
6661 persistence::write_default_dock_state(&kvp, docks)
6662 .await
6663 .log_err();
6664 })
6665 }
6666 }
6667 }
6668
6669 fn has_any_items_open(&self, cx: &App) -> bool {
6670 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6671 }
6672
6673 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6674 let paths = PathList::new(&self.root_paths(cx));
6675 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6676 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6677 } else if self.project.read(cx).is_local() {
6678 if !paths.is_empty() || self.has_any_items_open(cx) {
6679 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6680 } else {
6681 WorkspaceLocation::DetachFromSession
6682 }
6683 } else {
6684 WorkspaceLocation::None
6685 }
6686 }
6687
6688 fn update_history(&self, cx: &mut App) {
6689 let Some(id) = self.database_id() else {
6690 return;
6691 };
6692 if !self.project.read(cx).is_local() {
6693 return;
6694 }
6695 if let Some(manager) = HistoryManager::global(cx) {
6696 let paths = PathList::new(&self.root_paths(cx));
6697 manager.update(cx, |this, cx| {
6698 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6699 });
6700 }
6701 }
6702
6703 async fn serialize_items(
6704 this: &WeakEntity<Self>,
6705 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6706 cx: &mut AsyncWindowContext,
6707 ) -> Result<()> {
6708 const CHUNK_SIZE: usize = 200;
6709
6710 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6711
6712 while let Some(items_received) = serializable_items.next().await {
6713 let unique_items =
6714 items_received
6715 .into_iter()
6716 .fold(HashMap::default(), |mut acc, item| {
6717 acc.entry(item.item_id()).or_insert(item);
6718 acc
6719 });
6720
6721 // We use into_iter() here so that the references to the items are moved into
6722 // the tasks and not kept alive while we're sleeping.
6723 for (_, item) in unique_items.into_iter() {
6724 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6725 item.serialize(workspace, false, window, cx)
6726 }) {
6727 cx.background_spawn(async move { task.await.log_err() })
6728 .detach();
6729 }
6730 }
6731
6732 cx.background_executor()
6733 .timer(SERIALIZATION_THROTTLE_TIME)
6734 .await;
6735 }
6736
6737 Ok(())
6738 }
6739
6740 pub(crate) fn enqueue_item_serialization(
6741 &mut self,
6742 item: Box<dyn SerializableItemHandle>,
6743 ) -> Result<()> {
6744 self.serializable_items_tx
6745 .unbounded_send(item)
6746 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6747 }
6748
6749 pub(crate) fn load_workspace(
6750 serialized_workspace: SerializedWorkspace,
6751 paths_to_open: Vec<Option<ProjectPath>>,
6752 window: &mut Window,
6753 cx: &mut Context<Workspace>,
6754 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6755 cx.spawn_in(window, async move |workspace, cx| {
6756 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6757
6758 let mut center_group = None;
6759 let mut center_items = None;
6760
6761 // Traverse the splits tree and add to things
6762 if let Some((group, active_pane, items)) = serialized_workspace
6763 .center_group
6764 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6765 .await
6766 {
6767 center_items = Some(items);
6768 center_group = Some((group, active_pane))
6769 }
6770
6771 let mut items_by_project_path = HashMap::default();
6772 let mut item_ids_by_kind = HashMap::default();
6773 let mut all_deserialized_items = Vec::default();
6774 cx.update(|_, cx| {
6775 for item in center_items.unwrap_or_default().into_iter().flatten() {
6776 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6777 item_ids_by_kind
6778 .entry(serializable_item_handle.serialized_item_kind())
6779 .or_insert(Vec::new())
6780 .push(item.item_id().as_u64() as ItemId);
6781 }
6782
6783 if let Some(project_path) = item.project_path(cx) {
6784 items_by_project_path.insert(project_path, item.clone());
6785 }
6786 all_deserialized_items.push(item);
6787 }
6788 })?;
6789
6790 let opened_items = paths_to_open
6791 .into_iter()
6792 .map(|path_to_open| {
6793 path_to_open
6794 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6795 })
6796 .collect::<Vec<_>>();
6797
6798 // Remove old panes from workspace panes list
6799 workspace.update_in(cx, |workspace, window, cx| {
6800 if let Some((center_group, active_pane)) = center_group {
6801 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6802
6803 // Swap workspace center group
6804 workspace.center = PaneGroup::with_root(center_group);
6805 workspace.center.set_is_center(true);
6806 workspace.center.mark_positions(cx);
6807
6808 if let Some(active_pane) = active_pane {
6809 workspace.set_active_pane(&active_pane, window, cx);
6810 cx.focus_self(window);
6811 } else {
6812 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6813 }
6814 }
6815
6816 let docks = serialized_workspace.docks;
6817
6818 for (dock, serialized_dock) in [
6819 (&mut workspace.right_dock, docks.right),
6820 (&mut workspace.left_dock, docks.left),
6821 (&mut workspace.bottom_dock, docks.bottom),
6822 ]
6823 .iter_mut()
6824 {
6825 dock.update(cx, |dock, cx| {
6826 dock.serialized_dock = Some(serialized_dock.clone());
6827 dock.restore_state(window, cx);
6828 });
6829 }
6830
6831 cx.notify();
6832 })?;
6833
6834 let _ = project
6835 .update(cx, |project, cx| {
6836 project
6837 .breakpoint_store()
6838 .update(cx, |breakpoint_store, cx| {
6839 breakpoint_store
6840 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6841 })
6842 })
6843 .await;
6844
6845 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6846 // after loading the items, we might have different items and in order to avoid
6847 // the database filling up, we delete items that haven't been loaded now.
6848 //
6849 // The items that have been loaded, have been saved after they've been added to the workspace.
6850 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6851 item_ids_by_kind
6852 .into_iter()
6853 .map(|(item_kind, loaded_items)| {
6854 SerializableItemRegistry::cleanup(
6855 item_kind,
6856 serialized_workspace.id,
6857 loaded_items,
6858 window,
6859 cx,
6860 )
6861 .log_err()
6862 })
6863 .collect::<Vec<_>>()
6864 })?;
6865
6866 futures::future::join_all(clean_up_tasks).await;
6867
6868 workspace
6869 .update_in(cx, |workspace, window, cx| {
6870 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6871 workspace.serialize_workspace_internal(window, cx).detach();
6872
6873 // Ensure that we mark the window as edited if we did load dirty items
6874 workspace.update_window_edited(window, cx);
6875 })
6876 .ok();
6877
6878 Ok(opened_items)
6879 })
6880 }
6881
6882 pub fn key_context(&self, cx: &App) -> KeyContext {
6883 let mut context = KeyContext::new_with_defaults();
6884 context.add("Workspace");
6885 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6886 if let Some(status) = self
6887 .debugger_provider
6888 .as_ref()
6889 .and_then(|provider| provider.active_thread_state(cx))
6890 {
6891 match status {
6892 ThreadStatus::Running | ThreadStatus::Stepping => {
6893 context.add("debugger_running");
6894 }
6895 ThreadStatus::Stopped => context.add("debugger_stopped"),
6896 ThreadStatus::Exited | ThreadStatus::Ended => {}
6897 }
6898 }
6899
6900 if self.left_dock.read(cx).is_open() {
6901 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6902 context.set("left_dock", active_panel.panel_key());
6903 }
6904 }
6905
6906 if self.right_dock.read(cx).is_open() {
6907 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6908 context.set("right_dock", active_panel.panel_key());
6909 }
6910 }
6911
6912 if self.bottom_dock.read(cx).is_open() {
6913 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6914 context.set("bottom_dock", active_panel.panel_key());
6915 }
6916 }
6917
6918 context
6919 }
6920
6921 /// Multiworkspace uses this to add workspace action handling to itself
6922 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6923 self.add_workspace_actions_listeners(div, window, cx)
6924 .on_action(cx.listener(
6925 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6926 for action in &action_sequence.0 {
6927 window.dispatch_action(action.boxed_clone(), cx);
6928 }
6929 },
6930 ))
6931 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6932 .on_action(cx.listener(Self::close_all_items_and_panes))
6933 .on_action(cx.listener(Self::close_item_in_all_panes))
6934 .on_action(cx.listener(Self::save_all))
6935 .on_action(cx.listener(Self::send_keystrokes))
6936 .on_action(cx.listener(Self::add_folder_to_project))
6937 .on_action(cx.listener(Self::follow_next_collaborator))
6938 .on_action(cx.listener(Self::activate_pane_at_index))
6939 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6940 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6941 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6942 .on_action(cx.listener(Self::toggle_theme_mode))
6943 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6944 let pane = workspace.active_pane().clone();
6945 workspace.unfollow_in_pane(&pane, window, cx);
6946 }))
6947 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6948 workspace
6949 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6950 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6951 }))
6952 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6953 workspace
6954 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6955 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6956 }))
6957 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6958 workspace
6959 .save_active_item(SaveIntent::SaveAs, window, cx)
6960 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6961 }))
6962 .on_action(
6963 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6964 workspace.activate_previous_pane(window, cx)
6965 }),
6966 )
6967 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6968 workspace.activate_next_pane(window, cx)
6969 }))
6970 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6971 workspace.activate_last_pane(window, cx)
6972 }))
6973 .on_action(
6974 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6975 workspace.activate_next_window(cx)
6976 }),
6977 )
6978 .on_action(
6979 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6980 workspace.activate_previous_window(cx)
6981 }),
6982 )
6983 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6984 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6985 }))
6986 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6987 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6988 }))
6989 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6990 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6991 }))
6992 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6993 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6994 }))
6995 .on_action(cx.listener(
6996 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6997 workspace.move_item_to_pane_in_direction(action, window, cx)
6998 },
6999 ))
7000 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
7001 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
7002 }))
7003 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
7004 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
7005 }))
7006 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
7007 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
7008 }))
7009 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
7010 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
7011 }))
7012 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
7013 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
7014 SplitDirection::Down,
7015 SplitDirection::Up,
7016 SplitDirection::Right,
7017 SplitDirection::Left,
7018 ];
7019 for dir in DIRECTION_PRIORITY {
7020 if workspace.find_pane_in_direction(dir, cx).is_some() {
7021 workspace.swap_pane_in_direction(dir, cx);
7022 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
7023 break;
7024 }
7025 }
7026 }))
7027 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
7028 workspace.move_pane_to_border(SplitDirection::Left, cx)
7029 }))
7030 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
7031 workspace.move_pane_to_border(SplitDirection::Right, cx)
7032 }))
7033 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
7034 workspace.move_pane_to_border(SplitDirection::Up, cx)
7035 }))
7036 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
7037 workspace.move_pane_to_border(SplitDirection::Down, cx)
7038 }))
7039 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
7040 this.toggle_dock(DockPosition::Left, window, cx);
7041 }))
7042 .on_action(cx.listener(
7043 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
7044 workspace.toggle_dock(DockPosition::Right, window, cx);
7045 },
7046 ))
7047 .on_action(cx.listener(
7048 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
7049 workspace.toggle_dock(DockPosition::Bottom, window, cx);
7050 },
7051 ))
7052 .on_action(cx.listener(
7053 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
7054 if !workspace.close_active_dock(window, cx) {
7055 cx.propagate();
7056 }
7057 },
7058 ))
7059 .on_action(
7060 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
7061 workspace.close_all_docks(window, cx);
7062 }),
7063 )
7064 .on_action(cx.listener(Self::toggle_all_docks))
7065 .on_action(cx.listener(
7066 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
7067 workspace.clear_all_notifications(cx);
7068 },
7069 ))
7070 .on_action(cx.listener(
7071 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
7072 workspace.clear_navigation_history(window, cx);
7073 },
7074 ))
7075 .on_action(cx.listener(
7076 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
7077 if let Some((notification_id, _)) = workspace.notifications.pop() {
7078 workspace.suppress_notification(¬ification_id, cx);
7079 }
7080 },
7081 ))
7082 .on_action(cx.listener(
7083 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
7084 workspace.show_worktree_trust_security_modal(true, window, cx);
7085 },
7086 ))
7087 .on_action(
7088 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
7089 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
7090 trusted_worktrees.update(cx, |trusted_worktrees, _| {
7091 trusted_worktrees.clear_trusted_paths()
7092 });
7093 let db = WorkspaceDb::global(cx);
7094 cx.spawn(async move |_, cx| {
7095 if db.clear_trusted_worktrees().await.log_err().is_some() {
7096 cx.update(|cx| reload(cx));
7097 }
7098 })
7099 .detach();
7100 }
7101 }),
7102 )
7103 .on_action(cx.listener(
7104 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
7105 workspace.reopen_closed_item(window, cx).detach();
7106 },
7107 ))
7108 .on_action(cx.listener(
7109 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
7110 for dock in workspace.all_docks() {
7111 if dock.focus_handle(cx).contains_focused(window, cx) {
7112 let panel = dock.read(cx).active_panel().cloned();
7113 if let Some(panel) = panel {
7114 dock.update(cx, |dock, cx| {
7115 dock.set_panel_size_state(
7116 panel.as_ref(),
7117 dock::PanelSizeState::default(),
7118 cx,
7119 );
7120 });
7121 }
7122 return;
7123 }
7124 }
7125 },
7126 ))
7127 .on_action(cx.listener(
7128 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
7129 for dock in workspace.all_docks() {
7130 let panel = dock.read(cx).visible_panel().cloned();
7131 if let Some(panel) = panel {
7132 dock.update(cx, |dock, cx| {
7133 dock.set_panel_size_state(
7134 panel.as_ref(),
7135 dock::PanelSizeState::default(),
7136 cx,
7137 );
7138 });
7139 }
7140 }
7141 },
7142 ))
7143 .on_action(cx.listener(
7144 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
7145 adjust_active_dock_size_by_px(
7146 px_with_ui_font_fallback(act.px, cx),
7147 workspace,
7148 window,
7149 cx,
7150 );
7151 },
7152 ))
7153 .on_action(cx.listener(
7154 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
7155 adjust_active_dock_size_by_px(
7156 px_with_ui_font_fallback(act.px, cx) * -1.,
7157 workspace,
7158 window,
7159 cx,
7160 );
7161 },
7162 ))
7163 .on_action(cx.listener(
7164 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
7165 adjust_open_docks_size_by_px(
7166 px_with_ui_font_fallback(act.px, cx),
7167 workspace,
7168 window,
7169 cx,
7170 );
7171 },
7172 ))
7173 .on_action(cx.listener(
7174 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
7175 adjust_open_docks_size_by_px(
7176 px_with_ui_font_fallback(act.px, cx) * -1.,
7177 workspace,
7178 window,
7179 cx,
7180 );
7181 },
7182 ))
7183 .on_action(cx.listener(Workspace::toggle_centered_layout))
7184 .on_action(cx.listener(
7185 |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
7186 if let Some(active_dock) = workspace.active_dock(window, cx) {
7187 let dock = active_dock.read(cx);
7188 if let Some(active_panel) = dock.active_panel() {
7189 if active_panel.pane(cx).is_none() {
7190 let mut recent_pane: Option<Entity<Pane>> = None;
7191 let mut recent_timestamp = 0;
7192 for pane_handle in workspace.panes() {
7193 let pane = pane_handle.read(cx);
7194 for entry in pane.activation_history() {
7195 if entry.timestamp > recent_timestamp {
7196 recent_timestamp = entry.timestamp;
7197 recent_pane = Some(pane_handle.clone());
7198 }
7199 }
7200 }
7201
7202 if let Some(pane) = recent_pane {
7203 let wrap_around = action.wrap_around;
7204 pane.update(cx, |pane, cx| {
7205 let current_index = pane.active_item_index();
7206 let items_len = pane.items_len();
7207 if items_len > 0 {
7208 let next_index = if current_index + 1 < items_len {
7209 current_index + 1
7210 } else if wrap_around {
7211 0
7212 } else {
7213 return;
7214 };
7215 pane.activate_item(
7216 next_index, false, false, window, cx,
7217 );
7218 }
7219 });
7220 return;
7221 }
7222 }
7223 }
7224 }
7225 cx.propagate();
7226 },
7227 ))
7228 .on_action(cx.listener(
7229 |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
7230 if let Some(active_dock) = workspace.active_dock(window, cx) {
7231 let dock = active_dock.read(cx);
7232 if let Some(active_panel) = dock.active_panel() {
7233 if active_panel.pane(cx).is_none() {
7234 let mut recent_pane: Option<Entity<Pane>> = None;
7235 let mut recent_timestamp = 0;
7236 for pane_handle in workspace.panes() {
7237 let pane = pane_handle.read(cx);
7238 for entry in pane.activation_history() {
7239 if entry.timestamp > recent_timestamp {
7240 recent_timestamp = entry.timestamp;
7241 recent_pane = Some(pane_handle.clone());
7242 }
7243 }
7244 }
7245
7246 if let Some(pane) = recent_pane {
7247 let wrap_around = action.wrap_around;
7248 pane.update(cx, |pane, cx| {
7249 let current_index = pane.active_item_index();
7250 let items_len = pane.items_len();
7251 if items_len > 0 {
7252 let prev_index = if current_index > 0 {
7253 current_index - 1
7254 } else if wrap_around {
7255 items_len.saturating_sub(1)
7256 } else {
7257 return;
7258 };
7259 pane.activate_item(
7260 prev_index, false, false, window, cx,
7261 );
7262 }
7263 });
7264 return;
7265 }
7266 }
7267 }
7268 }
7269 cx.propagate();
7270 },
7271 ))
7272 .on_action(cx.listener(
7273 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7274 if let Some(active_dock) = workspace.active_dock(window, cx) {
7275 let dock = active_dock.read(cx);
7276 if let Some(active_panel) = dock.active_panel() {
7277 if active_panel.pane(cx).is_none() {
7278 let active_pane = workspace.active_pane().clone();
7279 active_pane.update(cx, |pane, cx| {
7280 pane.close_active_item(action, window, cx)
7281 .detach_and_log_err(cx);
7282 });
7283 return;
7284 }
7285 }
7286 }
7287 cx.propagate();
7288 },
7289 ))
7290 .on_action(
7291 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7292 let pane = workspace.active_pane().clone();
7293 if let Some(item) = pane.read(cx).active_item() {
7294 item.toggle_read_only(window, cx);
7295 }
7296 }),
7297 )
7298 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7299 workspace.focus_center_pane(window, cx);
7300 }))
7301 .on_action(cx.listener(Workspace::cancel))
7302 }
7303
7304 #[cfg(any(test, feature = "test-support"))]
7305 pub fn set_random_database_id(&mut self) {
7306 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7307 }
7308
7309 #[cfg(any(test, feature = "test-support"))]
7310 pub(crate) fn test_new(
7311 project: Entity<Project>,
7312 window: &mut Window,
7313 cx: &mut Context<Self>,
7314 ) -> Self {
7315 use node_runtime::NodeRuntime;
7316 use session::Session;
7317
7318 let client = project.read(cx).client();
7319 let user_store = project.read(cx).user_store();
7320 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7321 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7322 window.activate_window();
7323 let app_state = Arc::new(AppState {
7324 languages: project.read(cx).languages().clone(),
7325 workspace_store,
7326 client,
7327 user_store,
7328 fs: project.read(cx).fs().clone(),
7329 build_window_options: |_, _| Default::default(),
7330 node_runtime: NodeRuntime::unavailable(),
7331 session,
7332 });
7333 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7334 workspace
7335 .active_pane
7336 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7337 workspace
7338 }
7339
7340 pub fn register_action<A: Action>(
7341 &mut self,
7342 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7343 ) -> &mut Self {
7344 let callback = Arc::new(callback);
7345
7346 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7347 let callback = callback.clone();
7348 div.on_action(cx.listener(move |workspace, event, window, cx| {
7349 (callback)(workspace, event, window, cx)
7350 }))
7351 }));
7352 self
7353 }
7354 pub fn register_action_renderer(
7355 &mut self,
7356 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7357 ) -> &mut Self {
7358 self.workspace_actions.push(Box::new(callback));
7359 self
7360 }
7361
7362 fn add_workspace_actions_listeners(
7363 &self,
7364 mut div: Div,
7365 window: &mut Window,
7366 cx: &mut Context<Self>,
7367 ) -> Div {
7368 for action in self.workspace_actions.iter() {
7369 div = (action)(div, self, window, cx)
7370 }
7371 div
7372 }
7373
7374 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7375 self.modal_layer.read(cx).has_active_modal()
7376 }
7377
7378 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7379 self.modal_layer
7380 .read(cx)
7381 .is_active_modal_command_palette(cx)
7382 }
7383
7384 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7385 self.modal_layer.read(cx).active_modal()
7386 }
7387
7388 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7389 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7390 /// If no modal is active, the new modal will be shown.
7391 ///
7392 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7393 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7394 /// will not be shown.
7395 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7396 where
7397 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7398 {
7399 self.modal_layer.update(cx, |modal_layer, cx| {
7400 modal_layer.toggle_modal(window, cx, build)
7401 })
7402 }
7403
7404 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7405 self.modal_layer
7406 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7407 }
7408
7409 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7410 self.toast_layer
7411 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7412 }
7413
7414 pub fn toggle_centered_layout(
7415 &mut self,
7416 _: &ToggleCenteredLayout,
7417 _: &mut Window,
7418 cx: &mut Context<Self>,
7419 ) {
7420 self.centered_layout = !self.centered_layout;
7421 if let Some(database_id) = self.database_id() {
7422 let db = WorkspaceDb::global(cx);
7423 let centered_layout = self.centered_layout;
7424 cx.background_spawn(async move {
7425 db.set_centered_layout(database_id, centered_layout).await
7426 })
7427 .detach_and_log_err(cx);
7428 }
7429 cx.notify();
7430 }
7431
7432 fn adjust_padding(padding: Option<f32>) -> f32 {
7433 padding
7434 .unwrap_or(CenteredPaddingSettings::default().0)
7435 .clamp(
7436 CenteredPaddingSettings::MIN_PADDING,
7437 CenteredPaddingSettings::MAX_PADDING,
7438 )
7439 }
7440
7441 fn render_dock(
7442 &self,
7443 position: DockPosition,
7444 dock: &Entity<Dock>,
7445 window: &mut Window,
7446 cx: &mut App,
7447 ) -> Option<Div> {
7448 if self.zoomed_position == Some(position) {
7449 return None;
7450 }
7451
7452 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7453 let pane = panel.pane(cx)?;
7454 let follower_states = &self.follower_states;
7455 leader_border_for_pane(follower_states, &pane, window, cx)
7456 });
7457
7458 let mut container = div()
7459 .flex()
7460 .overflow_hidden()
7461 .flex_none()
7462 .child(dock.clone())
7463 .children(leader_border);
7464
7465 // Apply sizing only when the dock is open. When closed the dock is still
7466 // included in the element tree so its focus handle remains mounted — without
7467 // this, toggle_panel_focus cannot focus the panel when the dock is closed.
7468 let dock = dock.read(cx);
7469 if let Some(panel) = dock.visible_panel() {
7470 let size_state = dock.stored_panel_size_state(panel.as_ref());
7471 if position.axis() == Axis::Horizontal {
7472 let use_flexible = panel.has_flexible_size(window, cx);
7473 let flex_grow = if use_flexible {
7474 size_state
7475 .and_then(|state| state.flex)
7476 .or_else(|| self.default_dock_flex(position))
7477 } else {
7478 None
7479 };
7480 if let Some(grow) = flex_grow {
7481 let grow = grow.max(0.001);
7482 let style = container.style();
7483 style.flex_grow = Some(grow);
7484 style.flex_shrink = Some(1.0);
7485 style.flex_basis = Some(relative(0.).into());
7486 } else {
7487 let size = size_state
7488 .and_then(|state| state.size)
7489 .unwrap_or_else(|| panel.default_size(window, cx));
7490 container = container.w(size);
7491 }
7492 } else {
7493 let size = size_state
7494 .and_then(|state| state.size)
7495 .unwrap_or_else(|| panel.default_size(window, cx));
7496 container = container.h(size);
7497 }
7498 }
7499
7500 Some(container)
7501 }
7502
7503 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7504 window
7505 .root::<MultiWorkspace>()
7506 .flatten()
7507 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7508 }
7509
7510 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7511 self.zoomed.as_ref()
7512 }
7513
7514 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7515 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7516 return;
7517 };
7518 let windows = cx.windows();
7519 let next_window =
7520 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7521 || {
7522 windows
7523 .iter()
7524 .cycle()
7525 .skip_while(|window| window.window_id() != current_window_id)
7526 .nth(1)
7527 },
7528 );
7529
7530 if let Some(window) = next_window {
7531 window
7532 .update(cx, |_, window, _| window.activate_window())
7533 .ok();
7534 }
7535 }
7536
7537 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7538 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7539 return;
7540 };
7541 let windows = cx.windows();
7542 let prev_window =
7543 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7544 || {
7545 windows
7546 .iter()
7547 .rev()
7548 .cycle()
7549 .skip_while(|window| window.window_id() != current_window_id)
7550 .nth(1)
7551 },
7552 );
7553
7554 if let Some(window) = prev_window {
7555 window
7556 .update(cx, |_, window, _| window.activate_window())
7557 .ok();
7558 }
7559 }
7560
7561 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7562 if cx.stop_active_drag(window) {
7563 } else if let Some((notification_id, _)) = self.notifications.pop() {
7564 dismiss_app_notification(¬ification_id, cx);
7565 } else {
7566 cx.propagate();
7567 }
7568 }
7569
7570 fn resize_dock(
7571 &mut self,
7572 dock_pos: DockPosition,
7573 new_size: Pixels,
7574 window: &mut Window,
7575 cx: &mut Context<Self>,
7576 ) {
7577 match dock_pos {
7578 DockPosition::Left => self.resize_left_dock(new_size, window, cx),
7579 DockPosition::Right => self.resize_right_dock(new_size, window, cx),
7580 DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
7581 }
7582 }
7583
7584 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7585 let workspace_width = self.bounds.size.width;
7586 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7587
7588 self.right_dock.read_with(cx, |right_dock, cx| {
7589 let right_dock_size = right_dock
7590 .stored_active_panel_size(window, cx)
7591 .unwrap_or(Pixels::ZERO);
7592 if right_dock_size + size > workspace_width {
7593 size = workspace_width - right_dock_size
7594 }
7595 });
7596
7597 let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
7598 self.left_dock.update(cx, |left_dock, cx| {
7599 if WorkspaceSettings::get_global(cx)
7600 .resize_all_panels_in_dock
7601 .contains(&DockPosition::Left)
7602 {
7603 left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7604 } else {
7605 left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7606 }
7607 });
7608 }
7609
7610 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7611 let workspace_width = self.bounds.size.width;
7612 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7613 self.left_dock.read_with(cx, |left_dock, cx| {
7614 let left_dock_size = left_dock
7615 .stored_active_panel_size(window, cx)
7616 .unwrap_or(Pixels::ZERO);
7617 if left_dock_size + size > workspace_width {
7618 size = workspace_width - left_dock_size
7619 }
7620 });
7621 let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
7622 self.right_dock.update(cx, |right_dock, cx| {
7623 if WorkspaceSettings::get_global(cx)
7624 .resize_all_panels_in_dock
7625 .contains(&DockPosition::Right)
7626 {
7627 right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7628 } else {
7629 right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7630 }
7631 });
7632 }
7633
7634 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7635 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7636 self.bottom_dock.update(cx, |bottom_dock, cx| {
7637 if WorkspaceSettings::get_global(cx)
7638 .resize_all_panels_in_dock
7639 .contains(&DockPosition::Bottom)
7640 {
7641 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7642 } else {
7643 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7644 }
7645 });
7646 }
7647
7648 fn toggle_edit_predictions_all_files(
7649 &mut self,
7650 _: &ToggleEditPrediction,
7651 _window: &mut Window,
7652 cx: &mut Context<Self>,
7653 ) {
7654 let fs = self.project().read(cx).fs().clone();
7655 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7656 update_settings_file(fs, cx, move |file, _| {
7657 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7658 });
7659 }
7660
7661 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7662 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7663 let next_mode = match current_mode {
7664 Some(theme_settings::ThemeAppearanceMode::Light) => {
7665 theme_settings::ThemeAppearanceMode::Dark
7666 }
7667 Some(theme_settings::ThemeAppearanceMode::Dark) => {
7668 theme_settings::ThemeAppearanceMode::Light
7669 }
7670 Some(theme_settings::ThemeAppearanceMode::System) | None => {
7671 match cx.theme().appearance() {
7672 theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
7673 theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
7674 }
7675 }
7676 };
7677
7678 let fs = self.project().read(cx).fs().clone();
7679 settings::update_settings_file(fs, cx, move |settings, _cx| {
7680 theme_settings::set_mode(settings, next_mode);
7681 });
7682 }
7683
7684 pub fn show_worktree_trust_security_modal(
7685 &mut self,
7686 toggle: bool,
7687 window: &mut Window,
7688 cx: &mut Context<Self>,
7689 ) {
7690 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7691 if toggle {
7692 security_modal.update(cx, |security_modal, cx| {
7693 security_modal.dismiss(cx);
7694 })
7695 } else {
7696 security_modal.update(cx, |security_modal, cx| {
7697 security_modal.refresh_restricted_paths(cx);
7698 });
7699 }
7700 } else {
7701 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7702 .map(|trusted_worktrees| {
7703 trusted_worktrees
7704 .read(cx)
7705 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7706 })
7707 .unwrap_or(false);
7708 if has_restricted_worktrees {
7709 let project = self.project().read(cx);
7710 let remote_host = project
7711 .remote_connection_options(cx)
7712 .map(RemoteHostLocation::from);
7713 let worktree_store = project.worktree_store().downgrade();
7714 self.toggle_modal(window, cx, |_, cx| {
7715 SecurityModal::new(worktree_store, remote_host, cx)
7716 });
7717 }
7718 }
7719 }
7720}
7721
7722pub trait AnyActiveCall {
7723 fn entity(&self) -> AnyEntity;
7724 fn is_in_room(&self, _: &App) -> bool;
7725 fn room_id(&self, _: &App) -> Option<u64>;
7726 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7727 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7728 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7729 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7730 fn is_sharing_project(&self, _: &App) -> bool;
7731 fn has_remote_participants(&self, _: &App) -> bool;
7732 fn local_participant_is_guest(&self, _: &App) -> bool;
7733 fn client(&self, _: &App) -> Arc<Client>;
7734 fn share_on_join(&self, _: &App) -> bool;
7735 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7736 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7737 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7738 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7739 fn join_project(
7740 &self,
7741 _: u64,
7742 _: Arc<LanguageRegistry>,
7743 _: Arc<dyn Fs>,
7744 _: &mut App,
7745 ) -> Task<Result<Entity<Project>>>;
7746 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7747 fn subscribe(
7748 &self,
7749 _: &mut Window,
7750 _: &mut Context<Workspace>,
7751 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7752 ) -> Subscription;
7753 fn create_shared_screen(
7754 &self,
7755 _: PeerId,
7756 _: &Entity<Pane>,
7757 _: &mut Window,
7758 _: &mut App,
7759 ) -> Option<Entity<SharedScreen>>;
7760}
7761
7762#[derive(Clone)]
7763pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7764impl Global for GlobalAnyActiveCall {}
7765
7766impl GlobalAnyActiveCall {
7767 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7768 cx.try_global()
7769 }
7770
7771 pub(crate) fn global(cx: &App) -> &Self {
7772 cx.global()
7773 }
7774}
7775
7776/// Workspace-local view of a remote participant's location.
7777#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7778pub enum ParticipantLocation {
7779 SharedProject { project_id: u64 },
7780 UnsharedProject,
7781 External,
7782}
7783
7784impl ParticipantLocation {
7785 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7786 match location
7787 .and_then(|l| l.variant)
7788 .context("participant location was not provided")?
7789 {
7790 proto::participant_location::Variant::SharedProject(project) => {
7791 Ok(Self::SharedProject {
7792 project_id: project.id,
7793 })
7794 }
7795 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7796 proto::participant_location::Variant::External(_) => Ok(Self::External),
7797 }
7798 }
7799}
7800/// Workspace-local view of a remote collaborator's state.
7801/// This is the subset of `call::RemoteParticipant` that workspace needs.
7802#[derive(Clone)]
7803pub struct RemoteCollaborator {
7804 pub user: Arc<User>,
7805 pub peer_id: PeerId,
7806 pub location: ParticipantLocation,
7807 pub participant_index: ParticipantIndex,
7808}
7809
7810pub enum ActiveCallEvent {
7811 ParticipantLocationChanged { participant_id: PeerId },
7812 RemoteVideoTracksChanged { participant_id: PeerId },
7813}
7814
7815fn leader_border_for_pane(
7816 follower_states: &HashMap<CollaboratorId, FollowerState>,
7817 pane: &Entity<Pane>,
7818 _: &Window,
7819 cx: &App,
7820) -> Option<Div> {
7821 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7822 if state.pane() == pane {
7823 Some((*leader_id, state))
7824 } else {
7825 None
7826 }
7827 })?;
7828
7829 let mut leader_color = match leader_id {
7830 CollaboratorId::PeerId(leader_peer_id) => {
7831 let leader = GlobalAnyActiveCall::try_global(cx)?
7832 .0
7833 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7834
7835 cx.theme()
7836 .players()
7837 .color_for_participant(leader.participant_index.0)
7838 .cursor
7839 }
7840 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7841 };
7842 leader_color.fade_out(0.3);
7843 Some(
7844 div()
7845 .absolute()
7846 .size_full()
7847 .left_0()
7848 .top_0()
7849 .border_2()
7850 .border_color(leader_color),
7851 )
7852}
7853
7854fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7855 ZED_WINDOW_POSITION
7856 .zip(*ZED_WINDOW_SIZE)
7857 .map(|(position, size)| Bounds {
7858 origin: position,
7859 size,
7860 })
7861}
7862
7863fn open_items(
7864 serialized_workspace: Option<SerializedWorkspace>,
7865 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7866 window: &mut Window,
7867 cx: &mut Context<Workspace>,
7868) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7869 let restored_items = serialized_workspace.map(|serialized_workspace| {
7870 Workspace::load_workspace(
7871 serialized_workspace,
7872 project_paths_to_open
7873 .iter()
7874 .map(|(_, project_path)| project_path)
7875 .cloned()
7876 .collect(),
7877 window,
7878 cx,
7879 )
7880 });
7881
7882 cx.spawn_in(window, async move |workspace, cx| {
7883 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7884
7885 if let Some(restored_items) = restored_items {
7886 let restored_items = restored_items.await?;
7887
7888 let restored_project_paths = restored_items
7889 .iter()
7890 .filter_map(|item| {
7891 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7892 .ok()
7893 .flatten()
7894 })
7895 .collect::<HashSet<_>>();
7896
7897 for restored_item in restored_items {
7898 opened_items.push(restored_item.map(Ok));
7899 }
7900
7901 project_paths_to_open
7902 .iter_mut()
7903 .for_each(|(_, project_path)| {
7904 if let Some(project_path_to_open) = project_path
7905 && restored_project_paths.contains(project_path_to_open)
7906 {
7907 *project_path = None;
7908 }
7909 });
7910 } else {
7911 for _ in 0..project_paths_to_open.len() {
7912 opened_items.push(None);
7913 }
7914 }
7915 assert!(opened_items.len() == project_paths_to_open.len());
7916
7917 let tasks =
7918 project_paths_to_open
7919 .into_iter()
7920 .enumerate()
7921 .map(|(ix, (abs_path, project_path))| {
7922 let workspace = workspace.clone();
7923 cx.spawn(async move |cx| {
7924 let file_project_path = project_path?;
7925 let abs_path_task = workspace.update(cx, |workspace, cx| {
7926 workspace.project().update(cx, |project, cx| {
7927 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7928 })
7929 });
7930
7931 // We only want to open file paths here. If one of the items
7932 // here is a directory, it was already opened further above
7933 // with a `find_or_create_worktree`.
7934 if let Ok(task) = abs_path_task
7935 && task.await.is_none_or(|p| p.is_file())
7936 {
7937 return Some((
7938 ix,
7939 workspace
7940 .update_in(cx, |workspace, window, cx| {
7941 workspace.open_path(
7942 file_project_path,
7943 None,
7944 true,
7945 window,
7946 cx,
7947 )
7948 })
7949 .log_err()?
7950 .await,
7951 ));
7952 }
7953 None
7954 })
7955 });
7956
7957 let tasks = tasks.collect::<Vec<_>>();
7958
7959 let tasks = futures::future::join_all(tasks);
7960 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7961 opened_items[ix] = Some(path_open_result);
7962 }
7963
7964 Ok(opened_items)
7965 })
7966}
7967
7968#[derive(Clone)]
7969enum ActivateInDirectionTarget {
7970 Pane(Entity<Pane>),
7971 Dock(Entity<Dock>),
7972 Sidebar(FocusHandle),
7973}
7974
7975fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7976 window
7977 .update(cx, |multi_workspace, _, cx| {
7978 let workspace = multi_workspace.workspace().clone();
7979 workspace.update(cx, |workspace, cx| {
7980 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7981 struct DatabaseFailedNotification;
7982
7983 workspace.show_notification(
7984 NotificationId::unique::<DatabaseFailedNotification>(),
7985 cx,
7986 |cx| {
7987 cx.new(|cx| {
7988 MessageNotification::new("Failed to load the database file.", cx)
7989 .primary_message("File an Issue")
7990 .primary_icon(IconName::Plus)
7991 .primary_on_click(|window, cx| {
7992 window.dispatch_action(Box::new(FileBugReport), cx)
7993 })
7994 })
7995 },
7996 );
7997 }
7998 });
7999 })
8000 .log_err();
8001}
8002
8003fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
8004 if val == 0 {
8005 ThemeSettings::get_global(cx).ui_font_size(cx)
8006 } else {
8007 px(val as f32)
8008 }
8009}
8010
8011fn adjust_active_dock_size_by_px(
8012 px: Pixels,
8013 workspace: &mut Workspace,
8014 window: &mut Window,
8015 cx: &mut Context<Workspace>,
8016) {
8017 let Some(active_dock) = workspace
8018 .all_docks()
8019 .into_iter()
8020 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
8021 else {
8022 return;
8023 };
8024 let dock = active_dock.read(cx);
8025 let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
8026 return;
8027 };
8028 workspace.resize_dock(dock.position(), panel_size + px, window, cx);
8029}
8030
8031fn adjust_open_docks_size_by_px(
8032 px: Pixels,
8033 workspace: &mut Workspace,
8034 window: &mut Window,
8035 cx: &mut Context<Workspace>,
8036) {
8037 let docks = workspace
8038 .all_docks()
8039 .into_iter()
8040 .filter_map(|dock_entity| {
8041 let dock = dock_entity.read(cx);
8042 if dock.is_open() {
8043 let dock_pos = dock.position();
8044 let panel_size = workspace.dock_size(&dock, window, cx)?;
8045 Some((dock_pos, panel_size + px))
8046 } else {
8047 None
8048 }
8049 })
8050 .collect::<Vec<_>>();
8051
8052 for (position, new_size) in docks {
8053 workspace.resize_dock(position, new_size, window, cx);
8054 }
8055}
8056
8057impl Focusable for Workspace {
8058 fn focus_handle(&self, cx: &App) -> FocusHandle {
8059 self.active_pane.focus_handle(cx)
8060 }
8061}
8062
8063#[derive(Clone)]
8064struct DraggedDock(DockPosition);
8065
8066impl Render for DraggedDock {
8067 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8068 gpui::Empty
8069 }
8070}
8071
8072impl Render for Workspace {
8073 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8074 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
8075 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
8076 log::info!("Rendered first frame");
8077 }
8078
8079 let centered_layout = self.centered_layout
8080 && self.center.panes().len() == 1
8081 && self.active_item(cx).is_some();
8082 let render_padding = |size| {
8083 (size > 0.0).then(|| {
8084 div()
8085 .h_full()
8086 .w(relative(size))
8087 .bg(cx.theme().colors().editor_background)
8088 .border_color(cx.theme().colors().pane_group_border)
8089 })
8090 };
8091 let paddings = if centered_layout {
8092 let settings = WorkspaceSettings::get_global(cx).centered_layout;
8093 (
8094 render_padding(Self::adjust_padding(
8095 settings.left_padding.map(|padding| padding.0),
8096 )),
8097 render_padding(Self::adjust_padding(
8098 settings.right_padding.map(|padding| padding.0),
8099 )),
8100 )
8101 } else {
8102 (None, None)
8103 };
8104 let ui_font = theme_settings::setup_ui_font(window, cx);
8105
8106 let theme = cx.theme().clone();
8107 let colors = theme.colors();
8108 let notification_entities = self
8109 .notifications
8110 .iter()
8111 .map(|(_, notification)| notification.entity_id())
8112 .collect::<Vec<_>>();
8113 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
8114
8115 div()
8116 .relative()
8117 .size_full()
8118 .flex()
8119 .flex_col()
8120 .font(ui_font)
8121 .gap_0()
8122 .justify_start()
8123 .items_start()
8124 .text_color(colors.text)
8125 .overflow_hidden()
8126 .children(self.titlebar_item.clone())
8127 .on_modifiers_changed(move |_, _, cx| {
8128 for &id in ¬ification_entities {
8129 cx.notify(id);
8130 }
8131 })
8132 .child(
8133 div()
8134 .size_full()
8135 .relative()
8136 .flex_1()
8137 .flex()
8138 .flex_col()
8139 .child(
8140 div()
8141 .id("workspace")
8142 .bg(colors.background)
8143 .relative()
8144 .flex_1()
8145 .w_full()
8146 .flex()
8147 .flex_col()
8148 .overflow_hidden()
8149 .border_t_1()
8150 .border_b_1()
8151 .border_color(colors.border)
8152 .child({
8153 let this = cx.entity();
8154 canvas(
8155 move |bounds, window, cx| {
8156 this.update(cx, |this, cx| {
8157 let bounds_changed = this.bounds != bounds;
8158 this.bounds = bounds;
8159
8160 if bounds_changed {
8161 this.left_dock.update(cx, |dock, cx| {
8162 dock.clamp_panel_size(
8163 bounds.size.width,
8164 window,
8165 cx,
8166 )
8167 });
8168
8169 this.right_dock.update(cx, |dock, cx| {
8170 dock.clamp_panel_size(
8171 bounds.size.width,
8172 window,
8173 cx,
8174 )
8175 });
8176
8177 this.bottom_dock.update(cx, |dock, cx| {
8178 dock.clamp_panel_size(
8179 bounds.size.height,
8180 window,
8181 cx,
8182 )
8183 });
8184 }
8185 })
8186 },
8187 |_, _, _, _| {},
8188 )
8189 .absolute()
8190 .size_full()
8191 })
8192 .when(self.zoomed.is_none(), |this| {
8193 this.on_drag_move(cx.listener(
8194 move |workspace,
8195 e: &DragMoveEvent<DraggedDock>,
8196 window,
8197 cx| {
8198 if workspace.previous_dock_drag_coordinates
8199 != Some(e.event.position)
8200 {
8201 workspace.previous_dock_drag_coordinates =
8202 Some(e.event.position);
8203
8204 match e.drag(cx).0 {
8205 DockPosition::Left => {
8206 workspace.resize_left_dock(
8207 e.event.position.x
8208 - workspace.bounds.left(),
8209 window,
8210 cx,
8211 );
8212 }
8213 DockPosition::Right => {
8214 workspace.resize_right_dock(
8215 workspace.bounds.right()
8216 - e.event.position.x,
8217 window,
8218 cx,
8219 );
8220 }
8221 DockPosition::Bottom => {
8222 workspace.resize_bottom_dock(
8223 workspace.bounds.bottom()
8224 - e.event.position.y,
8225 window,
8226 cx,
8227 );
8228 }
8229 };
8230 workspace.serialize_workspace(window, cx);
8231 }
8232 },
8233 ))
8234
8235 })
8236 .child({
8237 match bottom_dock_layout {
8238 BottomDockLayout::Full => div()
8239 .flex()
8240 .flex_col()
8241 .h_full()
8242 .child(
8243 div()
8244 .flex()
8245 .flex_row()
8246 .flex_1()
8247 .overflow_hidden()
8248 .children(self.render_dock(
8249 DockPosition::Left,
8250 &self.left_dock,
8251 window,
8252 cx,
8253 ))
8254
8255 .child(
8256 div()
8257 .flex()
8258 .flex_col()
8259 .flex_1()
8260 .overflow_hidden()
8261 .child(
8262 h_flex()
8263 .flex_1()
8264 .when_some(
8265 paddings.0,
8266 |this, p| {
8267 this.child(
8268 p.border_r_1(),
8269 )
8270 },
8271 )
8272 .child(self.center.render(
8273 self.zoomed.as_ref(),
8274 &PaneRenderContext {
8275 follower_states:
8276 &self.follower_states,
8277 active_call: self.active_call(),
8278 active_pane: &self.active_pane,
8279 app_state: &self.app_state,
8280 project: &self.project,
8281 workspace: &self.weak_self,
8282 },
8283 window,
8284 cx,
8285 ))
8286 .when_some(
8287 paddings.1,
8288 |this, p| {
8289 this.child(
8290 p.border_l_1(),
8291 )
8292 },
8293 ),
8294 ),
8295 )
8296
8297 .children(self.render_dock(
8298 DockPosition::Right,
8299 &self.right_dock,
8300 window,
8301 cx,
8302 )),
8303 )
8304 .child(div().w_full().children(self.render_dock(
8305 DockPosition::Bottom,
8306 &self.bottom_dock,
8307 window,
8308 cx
8309 ))),
8310
8311 BottomDockLayout::LeftAligned => div()
8312 .flex()
8313 .flex_row()
8314 .h_full()
8315 .child(
8316 div()
8317 .flex()
8318 .flex_col()
8319 .flex_1()
8320 .h_full()
8321 .child(
8322 div()
8323 .flex()
8324 .flex_row()
8325 .flex_1()
8326 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8327
8328 .child(
8329 div()
8330 .flex()
8331 .flex_col()
8332 .flex_1()
8333 .overflow_hidden()
8334 .child(
8335 h_flex()
8336 .flex_1()
8337 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8338 .child(self.center.render(
8339 self.zoomed.as_ref(),
8340 &PaneRenderContext {
8341 follower_states:
8342 &self.follower_states,
8343 active_call: self.active_call(),
8344 active_pane: &self.active_pane,
8345 app_state: &self.app_state,
8346 project: &self.project,
8347 workspace: &self.weak_self,
8348 },
8349 window,
8350 cx,
8351 ))
8352 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8353 )
8354 )
8355
8356 )
8357 .child(
8358 div()
8359 .w_full()
8360 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8361 ),
8362 )
8363 .children(self.render_dock(
8364 DockPosition::Right,
8365 &self.right_dock,
8366 window,
8367 cx,
8368 )),
8369 BottomDockLayout::RightAligned => div()
8370 .flex()
8371 .flex_row()
8372 .h_full()
8373 .children(self.render_dock(
8374 DockPosition::Left,
8375 &self.left_dock,
8376 window,
8377 cx,
8378 ))
8379
8380 .child(
8381 div()
8382 .flex()
8383 .flex_col()
8384 .flex_1()
8385 .h_full()
8386 .child(
8387 div()
8388 .flex()
8389 .flex_row()
8390 .flex_1()
8391 .child(
8392 div()
8393 .flex()
8394 .flex_col()
8395 .flex_1()
8396 .overflow_hidden()
8397 .child(
8398 h_flex()
8399 .flex_1()
8400 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8401 .child(self.center.render(
8402 self.zoomed.as_ref(),
8403 &PaneRenderContext {
8404 follower_states:
8405 &self.follower_states,
8406 active_call: self.active_call(),
8407 active_pane: &self.active_pane,
8408 app_state: &self.app_state,
8409 project: &self.project,
8410 workspace: &self.weak_self,
8411 },
8412 window,
8413 cx,
8414 ))
8415 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8416 )
8417 )
8418
8419 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8420 )
8421 .child(
8422 div()
8423 .w_full()
8424 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8425 ),
8426 ),
8427 BottomDockLayout::Contained => div()
8428 .flex()
8429 .flex_row()
8430 .h_full()
8431 .children(self.render_dock(
8432 DockPosition::Left,
8433 &self.left_dock,
8434 window,
8435 cx,
8436 ))
8437
8438 .child(
8439 div()
8440 .flex()
8441 .flex_col()
8442 .flex_1()
8443 .overflow_hidden()
8444 .child(
8445 h_flex()
8446 .flex_1()
8447 .when_some(paddings.0, |this, p| {
8448 this.child(p.border_r_1())
8449 })
8450 .child(self.center.render(
8451 self.zoomed.as_ref(),
8452 &PaneRenderContext {
8453 follower_states:
8454 &self.follower_states,
8455 active_call: self.active_call(),
8456 active_pane: &self.active_pane,
8457 app_state: &self.app_state,
8458 project: &self.project,
8459 workspace: &self.weak_self,
8460 },
8461 window,
8462 cx,
8463 ))
8464 .when_some(paddings.1, |this, p| {
8465 this.child(p.border_l_1())
8466 }),
8467 )
8468 .children(self.render_dock(
8469 DockPosition::Bottom,
8470 &self.bottom_dock,
8471 window,
8472 cx,
8473 )),
8474 )
8475
8476 .children(self.render_dock(
8477 DockPosition::Right,
8478 &self.right_dock,
8479 window,
8480 cx,
8481 )),
8482 }
8483 })
8484 .children(self.zoomed.as_ref().and_then(|view| {
8485 let zoomed_view = view.upgrade()?;
8486 let div = div()
8487 .occlude()
8488 .absolute()
8489 .overflow_hidden()
8490 .border_color(colors.border)
8491 .bg(colors.background)
8492 .child(zoomed_view)
8493 .inset_0()
8494 .shadow_lg();
8495
8496 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8497 return Some(div);
8498 }
8499
8500 Some(match self.zoomed_position {
8501 Some(DockPosition::Left) => div.right_2().border_r_1(),
8502 Some(DockPosition::Right) => div.left_2().border_l_1(),
8503 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8504 None => {
8505 div.top_2().bottom_2().left_2().right_2().border_1()
8506 }
8507 })
8508 }))
8509 .children(self.render_notifications(window, cx)),
8510 )
8511 .when(self.status_bar_visible(cx), |parent| {
8512 parent.child(self.status_bar.clone())
8513 })
8514 .child(self.toast_layer.clone()),
8515 )
8516 }
8517}
8518
8519impl WorkspaceStore {
8520 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8521 Self {
8522 workspaces: Default::default(),
8523 _subscriptions: vec![
8524 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8525 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8526 ],
8527 client,
8528 }
8529 }
8530
8531 pub fn update_followers(
8532 &self,
8533 project_id: Option<u64>,
8534 update: proto::update_followers::Variant,
8535 cx: &App,
8536 ) -> Option<()> {
8537 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8538 let room_id = active_call.0.room_id(cx)?;
8539 self.client
8540 .send(proto::UpdateFollowers {
8541 room_id,
8542 project_id,
8543 variant: Some(update),
8544 })
8545 .log_err()
8546 }
8547
8548 pub async fn handle_follow(
8549 this: Entity<Self>,
8550 envelope: TypedEnvelope<proto::Follow>,
8551 mut cx: AsyncApp,
8552 ) -> Result<proto::FollowResponse> {
8553 this.update(&mut cx, |this, cx| {
8554 let follower = Follower {
8555 project_id: envelope.payload.project_id,
8556 peer_id: envelope.original_sender_id()?,
8557 };
8558
8559 let mut response = proto::FollowResponse::default();
8560
8561 this.workspaces.retain(|(window_handle, weak_workspace)| {
8562 let Some(workspace) = weak_workspace.upgrade() else {
8563 return false;
8564 };
8565 window_handle
8566 .update(cx, |_, window, cx| {
8567 workspace.update(cx, |workspace, cx| {
8568 let handler_response =
8569 workspace.handle_follow(follower.project_id, window, cx);
8570 if let Some(active_view) = handler_response.active_view
8571 && workspace.project.read(cx).remote_id() == follower.project_id
8572 {
8573 response.active_view = Some(active_view)
8574 }
8575 });
8576 })
8577 .is_ok()
8578 });
8579
8580 Ok(response)
8581 })
8582 }
8583
8584 async fn handle_update_followers(
8585 this: Entity<Self>,
8586 envelope: TypedEnvelope<proto::UpdateFollowers>,
8587 mut cx: AsyncApp,
8588 ) -> Result<()> {
8589 let leader_id = envelope.original_sender_id()?;
8590 let update = envelope.payload;
8591
8592 this.update(&mut cx, |this, cx| {
8593 this.workspaces.retain(|(window_handle, weak_workspace)| {
8594 let Some(workspace) = weak_workspace.upgrade() else {
8595 return false;
8596 };
8597 window_handle
8598 .update(cx, |_, window, cx| {
8599 workspace.update(cx, |workspace, cx| {
8600 let project_id = workspace.project.read(cx).remote_id();
8601 if update.project_id != project_id && update.project_id.is_some() {
8602 return;
8603 }
8604 workspace.handle_update_followers(
8605 leader_id,
8606 update.clone(),
8607 window,
8608 cx,
8609 );
8610 });
8611 })
8612 .is_ok()
8613 });
8614 Ok(())
8615 })
8616 }
8617
8618 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8619 self.workspaces.iter().map(|(_, weak)| weak)
8620 }
8621
8622 pub fn workspaces_with_windows(
8623 &self,
8624 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8625 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8626 }
8627}
8628
8629impl ViewId {
8630 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8631 Ok(Self {
8632 creator: message
8633 .creator
8634 .map(CollaboratorId::PeerId)
8635 .context("creator is missing")?,
8636 id: message.id,
8637 })
8638 }
8639
8640 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8641 if let CollaboratorId::PeerId(peer_id) = self.creator {
8642 Some(proto::ViewId {
8643 creator: Some(peer_id),
8644 id: self.id,
8645 })
8646 } else {
8647 None
8648 }
8649 }
8650}
8651
8652impl FollowerState {
8653 fn pane(&self) -> &Entity<Pane> {
8654 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8655 }
8656}
8657
8658pub trait WorkspaceHandle {
8659 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8660}
8661
8662impl WorkspaceHandle for Entity<Workspace> {
8663 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8664 self.read(cx)
8665 .worktrees(cx)
8666 .flat_map(|worktree| {
8667 let worktree_id = worktree.read(cx).id();
8668 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8669 worktree_id,
8670 path: f.path.clone(),
8671 })
8672 })
8673 .collect::<Vec<_>>()
8674 }
8675}
8676
8677pub async fn last_opened_workspace_location(
8678 db: &WorkspaceDb,
8679 fs: &dyn fs::Fs,
8680) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8681 db.last_workspace(fs)
8682 .await
8683 .log_err()
8684 .flatten()
8685 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8686}
8687
8688pub async fn last_session_workspace_locations(
8689 db: &WorkspaceDb,
8690 last_session_id: &str,
8691 last_session_window_stack: Option<Vec<WindowId>>,
8692 fs: &dyn fs::Fs,
8693) -> Option<Vec<SessionWorkspace>> {
8694 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8695 .await
8696 .log_err()
8697}
8698
8699pub async fn restore_multiworkspace(
8700 multi_workspace: SerializedMultiWorkspace,
8701 app_state: Arc<AppState>,
8702 cx: &mut AsyncApp,
8703) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8704 let SerializedMultiWorkspace {
8705 active_workspace,
8706 state,
8707 } = multi_workspace;
8708 let MultiWorkspaceState {
8709 sidebar_open,
8710 project_group_keys,
8711 sidebar_state,
8712 ..
8713 } = state;
8714
8715 let window_handle = if active_workspace.paths.is_empty() {
8716 cx.update(|cx| {
8717 open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx)
8718 })
8719 .await?
8720 } else {
8721 let OpenResult { window, .. } = cx
8722 .update(|cx| {
8723 Workspace::new_local(
8724 active_workspace.paths.paths().to_vec(),
8725 app_state.clone(),
8726 None,
8727 None,
8728 None,
8729 OpenMode::Activate,
8730 cx,
8731 )
8732 })
8733 .await?;
8734 window
8735 };
8736
8737 if !project_group_keys.is_empty() {
8738 let restored_keys: Vec<ProjectGroupKey> =
8739 project_group_keys.into_iter().map(Into::into).collect();
8740 window_handle
8741 .update(cx, |multi_workspace, _window, _cx| {
8742 multi_workspace.restore_project_group_keys(restored_keys);
8743 })
8744 .ok();
8745 }
8746
8747 if sidebar_open {
8748 window_handle
8749 .update(cx, |multi_workspace, _, cx| {
8750 multi_workspace.open_sidebar(cx);
8751 })
8752 .ok();
8753 }
8754
8755 if let Some(sidebar_state) = sidebar_state {
8756 window_handle
8757 .update(cx, |multi_workspace, window, cx| {
8758 if let Some(sidebar) = multi_workspace.sidebar() {
8759 sidebar.restore_serialized_state(&sidebar_state, window, cx);
8760 }
8761 multi_workspace.serialize(cx);
8762 })
8763 .ok();
8764 }
8765
8766 window_handle
8767 .update(cx, |_, window, _cx| {
8768 window.activate_window();
8769 })
8770 .ok();
8771
8772 Ok(window_handle)
8773}
8774
8775actions!(
8776 collab,
8777 [
8778 /// Opens the channel notes for the current call.
8779 ///
8780 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8781 /// channel in the collab panel.
8782 ///
8783 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8784 /// can be copied via "Copy link to section" in the context menu of the channel notes
8785 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8786 OpenChannelNotes,
8787 /// Mutes your microphone.
8788 Mute,
8789 /// Deafens yourself (mute both microphone and speakers).
8790 Deafen,
8791 /// Leaves the current call.
8792 LeaveCall,
8793 /// Shares the current project with collaborators.
8794 ShareProject,
8795 /// Shares your screen with collaborators.
8796 ScreenShare,
8797 /// Copies the current room name and session id for debugging purposes.
8798 CopyRoomId,
8799 ]
8800);
8801
8802/// Opens the channel notes for a specific channel by its ID.
8803#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8804#[action(namespace = collab)]
8805#[serde(deny_unknown_fields)]
8806pub struct OpenChannelNotesById {
8807 pub channel_id: u64,
8808}
8809
8810actions!(
8811 zed,
8812 [
8813 /// Opens the Zed log file.
8814 OpenLog,
8815 /// Reveals the Zed log file in the system file manager.
8816 RevealLogInFileManager
8817 ]
8818);
8819
8820async fn join_channel_internal(
8821 channel_id: ChannelId,
8822 app_state: &Arc<AppState>,
8823 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8824 requesting_workspace: Option<WeakEntity<Workspace>>,
8825 active_call: &dyn AnyActiveCall,
8826 cx: &mut AsyncApp,
8827) -> Result<bool> {
8828 let (should_prompt, already_in_channel) = cx.update(|cx| {
8829 if !active_call.is_in_room(cx) {
8830 return (false, false);
8831 }
8832
8833 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8834 let should_prompt = active_call.is_sharing_project(cx)
8835 && active_call.has_remote_participants(cx)
8836 && !already_in_channel;
8837 (should_prompt, already_in_channel)
8838 });
8839
8840 if already_in_channel {
8841 let task = cx.update(|cx| {
8842 if let Some((project, host)) = active_call.most_active_project(cx) {
8843 Some(join_in_room_project(project, host, app_state.clone(), cx))
8844 } else {
8845 None
8846 }
8847 });
8848 if let Some(task) = task {
8849 task.await?;
8850 }
8851 return anyhow::Ok(true);
8852 }
8853
8854 if should_prompt {
8855 if let Some(multi_workspace) = requesting_window {
8856 let answer = multi_workspace
8857 .update(cx, |_, window, cx| {
8858 window.prompt(
8859 PromptLevel::Warning,
8860 "Do you want to switch channels?",
8861 Some("Leaving this call will unshare your current project."),
8862 &["Yes, Join Channel", "Cancel"],
8863 cx,
8864 )
8865 })?
8866 .await;
8867
8868 if answer == Ok(1) {
8869 return Ok(false);
8870 }
8871 } else {
8872 return Ok(false);
8873 }
8874 }
8875
8876 let client = cx.update(|cx| active_call.client(cx));
8877
8878 let mut client_status = client.status();
8879
8880 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8881 'outer: loop {
8882 let Some(status) = client_status.recv().await else {
8883 anyhow::bail!("error connecting");
8884 };
8885
8886 match status {
8887 Status::Connecting
8888 | Status::Authenticating
8889 | Status::Authenticated
8890 | Status::Reconnecting
8891 | Status::Reauthenticating
8892 | Status::Reauthenticated => continue,
8893 Status::Connected { .. } => break 'outer,
8894 Status::SignedOut | Status::AuthenticationError => {
8895 return Err(ErrorCode::SignedOut.into());
8896 }
8897 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8898 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8899 return Err(ErrorCode::Disconnected.into());
8900 }
8901 }
8902 }
8903
8904 let joined = cx
8905 .update(|cx| active_call.join_channel(channel_id, cx))
8906 .await?;
8907
8908 if !joined {
8909 return anyhow::Ok(true);
8910 }
8911
8912 cx.update(|cx| active_call.room_update_completed(cx)).await;
8913
8914 let task = cx.update(|cx| {
8915 if let Some((project, host)) = active_call.most_active_project(cx) {
8916 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8917 }
8918
8919 // If you are the first to join a channel, see if you should share your project.
8920 if !active_call.has_remote_participants(cx)
8921 && !active_call.local_participant_is_guest(cx)
8922 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8923 {
8924 let project = workspace.update(cx, |workspace, cx| {
8925 let project = workspace.project.read(cx);
8926
8927 if !active_call.share_on_join(cx) {
8928 return None;
8929 }
8930
8931 if (project.is_local() || project.is_via_remote_server())
8932 && project.visible_worktrees(cx).any(|tree| {
8933 tree.read(cx)
8934 .root_entry()
8935 .is_some_and(|entry| entry.is_dir())
8936 })
8937 {
8938 Some(workspace.project.clone())
8939 } else {
8940 None
8941 }
8942 });
8943 if let Some(project) = project {
8944 let share_task = active_call.share_project(project, cx);
8945 return Some(cx.spawn(async move |_cx| -> Result<()> {
8946 share_task.await?;
8947 Ok(())
8948 }));
8949 }
8950 }
8951
8952 None
8953 });
8954 if let Some(task) = task {
8955 task.await?;
8956 return anyhow::Ok(true);
8957 }
8958 anyhow::Ok(false)
8959}
8960
8961pub fn join_channel(
8962 channel_id: ChannelId,
8963 app_state: Arc<AppState>,
8964 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8965 requesting_workspace: Option<WeakEntity<Workspace>>,
8966 cx: &mut App,
8967) -> Task<Result<()>> {
8968 let active_call = GlobalAnyActiveCall::global(cx).clone();
8969 cx.spawn(async move |cx| {
8970 let result = join_channel_internal(
8971 channel_id,
8972 &app_state,
8973 requesting_window,
8974 requesting_workspace,
8975 &*active_call.0,
8976 cx,
8977 )
8978 .await;
8979
8980 // join channel succeeded, and opened a window
8981 if matches!(result, Ok(true)) {
8982 return anyhow::Ok(());
8983 }
8984
8985 // find an existing workspace to focus and show call controls
8986 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8987 if active_window.is_none() {
8988 // no open workspaces, make one to show the error in (blergh)
8989 let OpenResult {
8990 window: window_handle,
8991 ..
8992 } = cx
8993 .update(|cx| {
8994 Workspace::new_local(
8995 vec![],
8996 app_state.clone(),
8997 requesting_window,
8998 None,
8999 None,
9000 OpenMode::Activate,
9001 cx,
9002 )
9003 })
9004 .await?;
9005
9006 window_handle
9007 .update(cx, |_, window, _cx| {
9008 window.activate_window();
9009 })
9010 .ok();
9011
9012 if result.is_ok() {
9013 cx.update(|cx| {
9014 cx.dispatch_action(&OpenChannelNotes);
9015 });
9016 }
9017
9018 active_window = Some(window_handle);
9019 }
9020
9021 if let Err(err) = result {
9022 log::error!("failed to join channel: {}", err);
9023 if let Some(active_window) = active_window {
9024 active_window
9025 .update(cx, |_, window, cx| {
9026 let detail: SharedString = match err.error_code() {
9027 ErrorCode::SignedOut => "Please sign in to continue.".into(),
9028 ErrorCode::UpgradeRequired => concat!(
9029 "Your are running an unsupported version of Zed. ",
9030 "Please update to continue."
9031 )
9032 .into(),
9033 ErrorCode::NoSuchChannel => concat!(
9034 "No matching channel was found. ",
9035 "Please check the link and try again."
9036 )
9037 .into(),
9038 ErrorCode::Forbidden => concat!(
9039 "This channel is private, and you do not have access. ",
9040 "Please ask someone to add you and try again."
9041 )
9042 .into(),
9043 ErrorCode::Disconnected => {
9044 "Please check your internet connection and try again.".into()
9045 }
9046 _ => format!("{}\n\nPlease try again.", err).into(),
9047 };
9048 window.prompt(
9049 PromptLevel::Critical,
9050 "Failed to join channel",
9051 Some(&detail),
9052 &["Ok"],
9053 cx,
9054 )
9055 })?
9056 .await
9057 .ok();
9058 }
9059 }
9060
9061 // return ok, we showed the error to the user.
9062 anyhow::Ok(())
9063 })
9064}
9065
9066pub async fn get_any_active_multi_workspace(
9067 app_state: Arc<AppState>,
9068 mut cx: AsyncApp,
9069) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
9070 // find an existing workspace to focus and show call controls
9071 let active_window = activate_any_workspace_window(&mut cx);
9072 if active_window.is_none() {
9073 cx.update(|cx| {
9074 Workspace::new_local(
9075 vec![],
9076 app_state.clone(),
9077 None,
9078 None,
9079 None,
9080 OpenMode::Activate,
9081 cx,
9082 )
9083 })
9084 .await?;
9085 }
9086 activate_any_workspace_window(&mut cx).context("could not open zed")
9087}
9088
9089fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
9090 cx.update(|cx| {
9091 if let Some(workspace_window) = cx
9092 .active_window()
9093 .and_then(|window| window.downcast::<MultiWorkspace>())
9094 {
9095 return Some(workspace_window);
9096 }
9097
9098 for window in cx.windows() {
9099 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
9100 workspace_window
9101 .update(cx, |_, window, _| window.activate_window())
9102 .ok();
9103 return Some(workspace_window);
9104 }
9105 }
9106 None
9107 })
9108}
9109
9110pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
9111 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
9112}
9113
9114pub fn workspace_windows_for_location(
9115 serialized_location: &SerializedWorkspaceLocation,
9116 cx: &App,
9117) -> Vec<WindowHandle<MultiWorkspace>> {
9118 cx.windows()
9119 .into_iter()
9120 .filter_map(|window| window.downcast::<MultiWorkspace>())
9121 .filter(|multi_workspace| {
9122 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
9123 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
9124 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
9125 }
9126 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
9127 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
9128 a.distro_name == b.distro_name
9129 }
9130 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
9131 a.container_id == b.container_id
9132 }
9133 #[cfg(any(test, feature = "test-support"))]
9134 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
9135 a.id == b.id
9136 }
9137 _ => false,
9138 };
9139
9140 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
9141 multi_workspace.workspaces().any(|workspace| {
9142 match workspace.read(cx).workspace_location(cx) {
9143 WorkspaceLocation::Location(location, _) => {
9144 match (&location, serialized_location) {
9145 (
9146 SerializedWorkspaceLocation::Local,
9147 SerializedWorkspaceLocation::Local,
9148 ) => true,
9149 (
9150 SerializedWorkspaceLocation::Remote(a),
9151 SerializedWorkspaceLocation::Remote(b),
9152 ) => same_host(a, b),
9153 _ => false,
9154 }
9155 }
9156 _ => false,
9157 }
9158 })
9159 })
9160 })
9161 .collect()
9162}
9163
9164pub async fn find_existing_workspace(
9165 abs_paths: &[PathBuf],
9166 open_options: &OpenOptions,
9167 location: &SerializedWorkspaceLocation,
9168 cx: &mut AsyncApp,
9169) -> (
9170 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
9171 OpenVisible,
9172) {
9173 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9174 let mut open_visible = OpenVisible::All;
9175 let mut best_match = None;
9176
9177 if open_options.open_new_workspace != Some(true) {
9178 cx.update(|cx| {
9179 for window in workspace_windows_for_location(location, cx) {
9180 if let Ok(multi_workspace) = window.read(cx) {
9181 for workspace in multi_workspace.workspaces() {
9182 let project = workspace.read(cx).project.read(cx);
9183 let m = project.visibility_for_paths(
9184 abs_paths,
9185 open_options.open_new_workspace == None,
9186 cx,
9187 );
9188 if m > best_match {
9189 existing = Some((window, workspace.clone()));
9190 best_match = m;
9191 } else if best_match.is_none()
9192 && open_options.open_new_workspace == Some(false)
9193 {
9194 existing = Some((window, workspace.clone()))
9195 }
9196 }
9197 }
9198 }
9199 });
9200
9201 let all_paths_are_files = existing
9202 .as_ref()
9203 .and_then(|(_, target_workspace)| {
9204 cx.update(|cx| {
9205 let workspace = target_workspace.read(cx);
9206 let project = workspace.project.read(cx);
9207 let path_style = workspace.path_style(cx);
9208 Some(!abs_paths.iter().any(|path| {
9209 let path = util::paths::SanitizedPath::new(path);
9210 project.worktrees(cx).any(|worktree| {
9211 let worktree = worktree.read(cx);
9212 let abs_path = worktree.abs_path();
9213 path_style
9214 .strip_prefix(path.as_ref(), abs_path.as_ref())
9215 .and_then(|rel| worktree.entry_for_path(&rel))
9216 .is_some_and(|e| e.is_dir())
9217 })
9218 }))
9219 })
9220 })
9221 .unwrap_or(false);
9222
9223 if open_options.open_new_workspace.is_none()
9224 && existing.is_some()
9225 && open_options.wait
9226 && all_paths_are_files
9227 {
9228 cx.update(|cx| {
9229 let windows = workspace_windows_for_location(location, cx);
9230 let window = cx
9231 .active_window()
9232 .and_then(|window| window.downcast::<MultiWorkspace>())
9233 .filter(|window| windows.contains(window))
9234 .or_else(|| windows.into_iter().next());
9235 if let Some(window) = window {
9236 if let Ok(multi_workspace) = window.read(cx) {
9237 let active_workspace = multi_workspace.workspace().clone();
9238 existing = Some((window, active_workspace));
9239 open_visible = OpenVisible::None;
9240 }
9241 }
9242 });
9243 }
9244 }
9245 (existing, open_visible)
9246}
9247
9248#[derive(Default, Clone)]
9249pub struct OpenOptions {
9250 pub visible: Option<OpenVisible>,
9251 pub focus: Option<bool>,
9252 pub open_new_workspace: Option<bool>,
9253 pub wait: bool,
9254 pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
9255 pub open_mode: OpenMode,
9256 pub env: Option<HashMap<String, String>>,
9257 pub open_in_dev_container: bool,
9258}
9259
9260/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9261/// or [`Workspace::open_workspace_for_paths`].
9262pub struct OpenResult {
9263 pub window: WindowHandle<MultiWorkspace>,
9264 pub workspace: Entity<Workspace>,
9265 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9266}
9267
9268/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9269pub fn open_workspace_by_id(
9270 workspace_id: WorkspaceId,
9271 app_state: Arc<AppState>,
9272 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9273 cx: &mut App,
9274) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9275 let project_handle = Project::local(
9276 app_state.client.clone(),
9277 app_state.node_runtime.clone(),
9278 app_state.user_store.clone(),
9279 app_state.languages.clone(),
9280 app_state.fs.clone(),
9281 None,
9282 project::LocalProjectFlags {
9283 init_worktree_trust: true,
9284 ..project::LocalProjectFlags::default()
9285 },
9286 cx,
9287 );
9288
9289 let db = WorkspaceDb::global(cx);
9290 let kvp = db::kvp::KeyValueStore::global(cx);
9291 cx.spawn(async move |cx| {
9292 let serialized_workspace = db
9293 .workspace_for_id(workspace_id)
9294 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9295
9296 let centered_layout = serialized_workspace.centered_layout;
9297
9298 let (window, workspace) = if let Some(window) = requesting_window {
9299 let workspace = window.update(cx, |multi_workspace, window, cx| {
9300 let workspace = cx.new(|cx| {
9301 let mut workspace = Workspace::new(
9302 Some(workspace_id),
9303 project_handle.clone(),
9304 app_state.clone(),
9305 window,
9306 cx,
9307 );
9308 workspace.centered_layout = centered_layout;
9309 workspace
9310 });
9311 multi_workspace.add(workspace.clone(), &*window, cx);
9312 workspace
9313 })?;
9314 (window, workspace)
9315 } else {
9316 let window_bounds_override = window_bounds_env_override();
9317
9318 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9319 (Some(WindowBounds::Windowed(bounds)), None)
9320 } else if let Some(display) = serialized_workspace.display
9321 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9322 {
9323 (Some(bounds.0), Some(display))
9324 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9325 (Some(bounds), Some(display))
9326 } else {
9327 (None, None)
9328 };
9329
9330 let options = cx.update(|cx| {
9331 let mut options = (app_state.build_window_options)(display, cx);
9332 options.window_bounds = window_bounds;
9333 options
9334 });
9335
9336 let window = cx.open_window(options, {
9337 let app_state = app_state.clone();
9338 let project_handle = project_handle.clone();
9339 move |window, cx| {
9340 let workspace = cx.new(|cx| {
9341 let mut workspace = Workspace::new(
9342 Some(workspace_id),
9343 project_handle,
9344 app_state,
9345 window,
9346 cx,
9347 );
9348 workspace.centered_layout = centered_layout;
9349 workspace
9350 });
9351 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9352 }
9353 })?;
9354
9355 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9356 multi_workspace.workspace().clone()
9357 })?;
9358
9359 (window, workspace)
9360 };
9361
9362 notify_if_database_failed(window, cx);
9363
9364 // Restore items from the serialized workspace
9365 window
9366 .update(cx, |_, window, cx| {
9367 workspace.update(cx, |_workspace, cx| {
9368 open_items(Some(serialized_workspace), vec![], window, cx)
9369 })
9370 })?
9371 .await?;
9372
9373 window.update(cx, |_, window, cx| {
9374 workspace.update(cx, |workspace, cx| {
9375 workspace.serialize_workspace(window, cx);
9376 });
9377 })?;
9378
9379 Ok(window)
9380 })
9381}
9382
9383#[allow(clippy::type_complexity)]
9384pub fn open_paths(
9385 abs_paths: &[PathBuf],
9386 app_state: Arc<AppState>,
9387 mut open_options: OpenOptions,
9388 cx: &mut App,
9389) -> Task<anyhow::Result<OpenResult>> {
9390 let abs_paths = abs_paths.to_vec();
9391 #[cfg(target_os = "windows")]
9392 let wsl_path = abs_paths
9393 .iter()
9394 .find_map(|p| util::paths::WslPath::from_path(p));
9395
9396 cx.spawn(async move |cx| {
9397 let (mut existing, mut open_visible) = find_existing_workspace(
9398 &abs_paths,
9399 &open_options,
9400 &SerializedWorkspaceLocation::Local,
9401 cx,
9402 )
9403 .await;
9404
9405 // Fallback: if no workspace contains the paths and all paths are files,
9406 // prefer an existing local workspace window (active window first).
9407 if open_options.open_new_workspace.is_none() && existing.is_none() {
9408 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9409 let all_metadatas = futures::future::join_all(all_paths)
9410 .await
9411 .into_iter()
9412 .filter_map(|result| result.ok().flatten());
9413
9414 if all_metadatas.into_iter().all(|file| !file.is_dir) {
9415 cx.update(|cx| {
9416 let windows = workspace_windows_for_location(
9417 &SerializedWorkspaceLocation::Local,
9418 cx,
9419 );
9420 let window = cx
9421 .active_window()
9422 .and_then(|window| window.downcast::<MultiWorkspace>())
9423 .filter(|window| windows.contains(window))
9424 .or_else(|| windows.into_iter().next());
9425 if let Some(window) = window {
9426 if let Ok(multi_workspace) = window.read(cx) {
9427 let active_workspace = multi_workspace.workspace().clone();
9428 existing = Some((window, active_workspace));
9429 open_visible = OpenVisible::None;
9430 }
9431 }
9432 });
9433 }
9434 }
9435
9436 // Fallback for directories: when no flag is specified and no existing
9437 // workspace matched, add the directory as a new workspace in the
9438 // active window's MultiWorkspace (instead of opening a new window).
9439 if open_options.open_new_workspace.is_none() && existing.is_none() {
9440 let target_window = cx.update(|cx| {
9441 let windows = workspace_windows_for_location(
9442 &SerializedWorkspaceLocation::Local,
9443 cx,
9444 );
9445 let window = cx
9446 .active_window()
9447 .and_then(|window| window.downcast::<MultiWorkspace>())
9448 .filter(|window| windows.contains(window))
9449 .or_else(|| windows.into_iter().next());
9450 window.filter(|window| {
9451 window.read(cx).is_ok_and(|mw| mw.multi_workspace_enabled(cx))
9452 })
9453 });
9454
9455 if let Some(window) = target_window {
9456 open_options.requesting_window = Some(window);
9457 window
9458 .update(cx, |multi_workspace, _, cx| {
9459 multi_workspace.open_sidebar(cx);
9460 })
9461 .log_err();
9462 }
9463 }
9464
9465 let open_in_dev_container = open_options.open_in_dev_container;
9466
9467 let result = if let Some((existing, target_workspace)) = existing {
9468 let open_task = existing
9469 .update(cx, |multi_workspace, window, cx| {
9470 window.activate_window();
9471 multi_workspace.activate(target_workspace.clone(), window, cx);
9472 target_workspace.update(cx, |workspace, cx| {
9473 if open_in_dev_container {
9474 workspace.set_open_in_dev_container(true);
9475 }
9476 workspace.open_paths(
9477 abs_paths,
9478 OpenOptions {
9479 visible: Some(open_visible),
9480 ..Default::default()
9481 },
9482 None,
9483 window,
9484 cx,
9485 )
9486 })
9487 })?
9488 .await;
9489
9490 _ = existing.update(cx, |multi_workspace, _, cx| {
9491 let workspace = multi_workspace.workspace().clone();
9492 workspace.update(cx, |workspace, cx| {
9493 for item in open_task.iter().flatten() {
9494 if let Err(e) = item {
9495 workspace.show_error(&e, cx);
9496 }
9497 }
9498 });
9499 });
9500
9501 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9502 } else {
9503 let init = if open_in_dev_container {
9504 Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
9505 workspace.set_open_in_dev_container(true);
9506 }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
9507 } else {
9508 None
9509 };
9510 let result = cx
9511 .update(move |cx| {
9512 Workspace::new_local(
9513 abs_paths,
9514 app_state.clone(),
9515 open_options.requesting_window,
9516 open_options.env,
9517 init,
9518 open_options.open_mode,
9519 cx,
9520 )
9521 })
9522 .await;
9523
9524 if let Ok(ref result) = result {
9525 result.window
9526 .update(cx, |_, window, _cx| {
9527 window.activate_window();
9528 })
9529 .log_err();
9530 }
9531
9532 result
9533 };
9534
9535 #[cfg(target_os = "windows")]
9536 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9537 && let Ok(ref result) = result
9538 {
9539 result.window
9540 .update(cx, move |multi_workspace, _window, cx| {
9541 struct OpenInWsl;
9542 let workspace = multi_workspace.workspace().clone();
9543 workspace.update(cx, |workspace, cx| {
9544 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9545 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9546 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9547 cx.new(move |cx| {
9548 MessageNotification::new(msg, cx)
9549 .primary_message("Open in WSL")
9550 .primary_icon(IconName::FolderOpen)
9551 .primary_on_click(move |window, cx| {
9552 window.dispatch_action(Box::new(remote::OpenWslPath {
9553 distro: remote::WslConnectionOptions {
9554 distro_name: distro.clone(),
9555 user: None,
9556 },
9557 paths: vec![path.clone().into()],
9558 }), cx)
9559 })
9560 })
9561 });
9562 });
9563 })
9564 .unwrap();
9565 };
9566 result
9567 })
9568}
9569
9570pub fn open_new(
9571 open_options: OpenOptions,
9572 app_state: Arc<AppState>,
9573 cx: &mut App,
9574 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9575) -> Task<anyhow::Result<()>> {
9576 let addition = open_options.open_mode;
9577 let task = Workspace::new_local(
9578 Vec::new(),
9579 app_state,
9580 open_options.requesting_window,
9581 open_options.env,
9582 Some(Box::new(init)),
9583 addition,
9584 cx,
9585 );
9586 cx.spawn(async move |cx| {
9587 let OpenResult { window, .. } = task.await?;
9588 window
9589 .update(cx, |_, window, _cx| {
9590 window.activate_window();
9591 })
9592 .ok();
9593 Ok(())
9594 })
9595}
9596
9597pub fn create_and_open_local_file(
9598 path: &'static Path,
9599 window: &mut Window,
9600 cx: &mut Context<Workspace>,
9601 default_content: impl 'static + Send + FnOnce() -> Rope,
9602) -> Task<Result<Box<dyn ItemHandle>>> {
9603 cx.spawn_in(window, async move |workspace, cx| {
9604 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9605 if !fs.is_file(path).await {
9606 fs.create_file(path, Default::default()).await?;
9607 fs.save(path, &default_content(), Default::default())
9608 .await?;
9609 }
9610
9611 workspace
9612 .update_in(cx, |workspace, window, cx| {
9613 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9614 let path = workspace
9615 .project
9616 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9617 cx.spawn_in(window, async move |workspace, cx| {
9618 let path = path.await?;
9619
9620 let path = fs.canonicalize(&path).await.unwrap_or(path);
9621
9622 let mut items = workspace
9623 .update_in(cx, |workspace, window, cx| {
9624 workspace.open_paths(
9625 vec![path.to_path_buf()],
9626 OpenOptions {
9627 visible: Some(OpenVisible::None),
9628 ..Default::default()
9629 },
9630 None,
9631 window,
9632 cx,
9633 )
9634 })?
9635 .await;
9636 let item = items.pop().flatten();
9637 item.with_context(|| format!("path {path:?} is not a file"))?
9638 })
9639 })
9640 })?
9641 .await?
9642 .await
9643 })
9644}
9645
9646pub fn open_remote_project_with_new_connection(
9647 window: WindowHandle<MultiWorkspace>,
9648 remote_connection: Arc<dyn RemoteConnection>,
9649 cancel_rx: oneshot::Receiver<()>,
9650 delegate: Arc<dyn RemoteClientDelegate>,
9651 app_state: Arc<AppState>,
9652 paths: Vec<PathBuf>,
9653 cx: &mut App,
9654) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9655 cx.spawn(async move |cx| {
9656 let (workspace_id, serialized_workspace) =
9657 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9658 .await?;
9659
9660 let session = match cx
9661 .update(|cx| {
9662 remote::RemoteClient::new(
9663 ConnectionIdentifier::Workspace(workspace_id.0),
9664 remote_connection,
9665 cancel_rx,
9666 delegate,
9667 cx,
9668 )
9669 })
9670 .await?
9671 {
9672 Some(result) => result,
9673 None => return Ok(Vec::new()),
9674 };
9675
9676 let project = cx.update(|cx| {
9677 project::Project::remote(
9678 session,
9679 app_state.client.clone(),
9680 app_state.node_runtime.clone(),
9681 app_state.user_store.clone(),
9682 app_state.languages.clone(),
9683 app_state.fs.clone(),
9684 true,
9685 cx,
9686 )
9687 });
9688
9689 open_remote_project_inner(
9690 project,
9691 paths,
9692 workspace_id,
9693 serialized_workspace,
9694 app_state,
9695 window,
9696 cx,
9697 )
9698 .await
9699 })
9700}
9701
9702pub fn open_remote_project_with_existing_connection(
9703 connection_options: RemoteConnectionOptions,
9704 project: Entity<Project>,
9705 paths: Vec<PathBuf>,
9706 app_state: Arc<AppState>,
9707 window: WindowHandle<MultiWorkspace>,
9708 cx: &mut AsyncApp,
9709) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9710 cx.spawn(async move |cx| {
9711 let (workspace_id, serialized_workspace) =
9712 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9713
9714 open_remote_project_inner(
9715 project,
9716 paths,
9717 workspace_id,
9718 serialized_workspace,
9719 app_state,
9720 window,
9721 cx,
9722 )
9723 .await
9724 })
9725}
9726
9727async fn open_remote_project_inner(
9728 project: Entity<Project>,
9729 paths: Vec<PathBuf>,
9730 workspace_id: WorkspaceId,
9731 serialized_workspace: Option<SerializedWorkspace>,
9732 app_state: Arc<AppState>,
9733 window: WindowHandle<MultiWorkspace>,
9734 cx: &mut AsyncApp,
9735) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9736 let db = cx.update(|cx| WorkspaceDb::global(cx));
9737 let toolchains = db.toolchains(workspace_id).await?;
9738 for (toolchain, worktree_path, path) in toolchains {
9739 project
9740 .update(cx, |this, cx| {
9741 let Some(worktree_id) =
9742 this.find_worktree(&worktree_path, cx)
9743 .and_then(|(worktree, rel_path)| {
9744 if rel_path.is_empty() {
9745 Some(worktree.read(cx).id())
9746 } else {
9747 None
9748 }
9749 })
9750 else {
9751 return Task::ready(None);
9752 };
9753
9754 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9755 })
9756 .await;
9757 }
9758 let mut project_paths_to_open = vec![];
9759 let mut project_path_errors = vec![];
9760
9761 for path in paths {
9762 let result = cx
9763 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9764 .await;
9765 match result {
9766 Ok((_, project_path)) => {
9767 project_paths_to_open.push((path.clone(), Some(project_path)));
9768 }
9769 Err(error) => {
9770 project_path_errors.push(error);
9771 }
9772 };
9773 }
9774
9775 if project_paths_to_open.is_empty() {
9776 return Err(project_path_errors.pop().context("no paths given")?);
9777 }
9778
9779 let workspace = window.update(cx, |multi_workspace, window, cx| {
9780 telemetry::event!("SSH Project Opened");
9781
9782 let new_workspace = cx.new(|cx| {
9783 let mut workspace =
9784 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9785 workspace.update_history(cx);
9786
9787 if let Some(ref serialized) = serialized_workspace {
9788 workspace.centered_layout = serialized.centered_layout;
9789 }
9790
9791 workspace
9792 });
9793
9794 multi_workspace.activate(new_workspace.clone(), window, cx);
9795 new_workspace
9796 })?;
9797
9798 let items = window
9799 .update(cx, |_, window, cx| {
9800 window.activate_window();
9801 workspace.update(cx, |_workspace, cx| {
9802 open_items(serialized_workspace, project_paths_to_open, window, cx)
9803 })
9804 })?
9805 .await?;
9806
9807 workspace.update(cx, |workspace, cx| {
9808 for error in project_path_errors {
9809 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9810 if let Some(path) = error.error_tag("path") {
9811 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9812 }
9813 } else {
9814 workspace.show_error(&error, cx)
9815 }
9816 }
9817 });
9818
9819 Ok(items.into_iter().map(|item| item?.ok()).collect())
9820}
9821
9822fn deserialize_remote_project(
9823 connection_options: RemoteConnectionOptions,
9824 paths: Vec<PathBuf>,
9825 cx: &AsyncApp,
9826) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9827 let db = cx.update(|cx| WorkspaceDb::global(cx));
9828 cx.background_spawn(async move {
9829 let remote_connection_id = db
9830 .get_or_create_remote_connection(connection_options)
9831 .await?;
9832
9833 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9834
9835 let workspace_id = if let Some(workspace_id) =
9836 serialized_workspace.as_ref().map(|workspace| workspace.id)
9837 {
9838 workspace_id
9839 } else {
9840 db.next_id().await?
9841 };
9842
9843 Ok((workspace_id, serialized_workspace))
9844 })
9845}
9846
9847pub fn join_in_room_project(
9848 project_id: u64,
9849 follow_user_id: u64,
9850 app_state: Arc<AppState>,
9851 cx: &mut App,
9852) -> Task<Result<()>> {
9853 let windows = cx.windows();
9854 cx.spawn(async move |cx| {
9855 let existing_window_and_workspace: Option<(
9856 WindowHandle<MultiWorkspace>,
9857 Entity<Workspace>,
9858 )> = windows.into_iter().find_map(|window_handle| {
9859 window_handle
9860 .downcast::<MultiWorkspace>()
9861 .and_then(|window_handle| {
9862 window_handle
9863 .update(cx, |multi_workspace, _window, cx| {
9864 for workspace in multi_workspace.workspaces() {
9865 if workspace.read(cx).project().read(cx).remote_id()
9866 == Some(project_id)
9867 {
9868 return Some((window_handle, workspace.clone()));
9869 }
9870 }
9871 None
9872 })
9873 .unwrap_or(None)
9874 })
9875 });
9876
9877 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9878 existing_window_and_workspace
9879 {
9880 existing_window
9881 .update(cx, |multi_workspace, window, cx| {
9882 multi_workspace.activate(target_workspace, window, cx);
9883 })
9884 .ok();
9885 existing_window
9886 } else {
9887 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9888 let project = cx
9889 .update(|cx| {
9890 active_call.0.join_project(
9891 project_id,
9892 app_state.languages.clone(),
9893 app_state.fs.clone(),
9894 cx,
9895 )
9896 })
9897 .await?;
9898
9899 let window_bounds_override = window_bounds_env_override();
9900 cx.update(|cx| {
9901 let mut options = (app_state.build_window_options)(None, cx);
9902 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9903 cx.open_window(options, |window, cx| {
9904 let workspace = cx.new(|cx| {
9905 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9906 });
9907 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9908 })
9909 })?
9910 };
9911
9912 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9913 cx.activate(true);
9914 window.activate_window();
9915
9916 // We set the active workspace above, so this is the correct workspace.
9917 let workspace = multi_workspace.workspace().clone();
9918 workspace.update(cx, |workspace, cx| {
9919 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9920 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9921 .or_else(|| {
9922 // If we couldn't follow the given user, follow the host instead.
9923 let collaborator = workspace
9924 .project()
9925 .read(cx)
9926 .collaborators()
9927 .values()
9928 .find(|collaborator| collaborator.is_host)?;
9929 Some(collaborator.peer_id)
9930 });
9931
9932 if let Some(follow_peer_id) = follow_peer_id {
9933 workspace.follow(follow_peer_id, window, cx);
9934 }
9935 });
9936 })?;
9937
9938 anyhow::Ok(())
9939 })
9940}
9941
9942pub fn reload(cx: &mut App) {
9943 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9944 let mut workspace_windows = cx
9945 .windows()
9946 .into_iter()
9947 .filter_map(|window| window.downcast::<MultiWorkspace>())
9948 .collect::<Vec<_>>();
9949
9950 // If multiple windows have unsaved changes, and need a save prompt,
9951 // prompt in the active window before switching to a different window.
9952 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9953
9954 let mut prompt = None;
9955 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9956 prompt = window
9957 .update(cx, |_, window, cx| {
9958 window.prompt(
9959 PromptLevel::Info,
9960 "Are you sure you want to restart?",
9961 None,
9962 &["Restart", "Cancel"],
9963 cx,
9964 )
9965 })
9966 .ok();
9967 }
9968
9969 cx.spawn(async move |cx| {
9970 if let Some(prompt) = prompt {
9971 let answer = prompt.await?;
9972 if answer != 0 {
9973 return anyhow::Ok(());
9974 }
9975 }
9976
9977 // If the user cancels any save prompt, then keep the app open.
9978 for window in workspace_windows {
9979 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9980 let workspace = multi_workspace.workspace().clone();
9981 workspace.update(cx, |workspace, cx| {
9982 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9983 })
9984 }) && !should_close.await?
9985 {
9986 return anyhow::Ok(());
9987 }
9988 }
9989 cx.update(|cx| cx.restart());
9990 anyhow::Ok(())
9991 })
9992 .detach_and_log_err(cx);
9993}
9994
9995fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9996 let mut parts = value.split(',');
9997 let x: usize = parts.next()?.parse().ok()?;
9998 let y: usize = parts.next()?.parse().ok()?;
9999 Some(point(px(x as f32), px(y as f32)))
10000}
10001
10002fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
10003 let mut parts = value.split(',');
10004 let width: usize = parts.next()?.parse().ok()?;
10005 let height: usize = parts.next()?.parse().ok()?;
10006 Some(size(px(width as f32), px(height as f32)))
10007}
10008
10009/// Add client-side decorations (rounded corners, shadows, resize handling) when
10010/// appropriate.
10011///
10012/// The `border_radius_tiling` parameter allows overriding which corners get
10013/// rounded, independently of the actual window tiling state. This is used
10014/// specifically for the workspace switcher sidebar: when the sidebar is open,
10015/// we want square corners on the left (so the sidebar appears flush with the
10016/// window edge) but we still need the shadow padding for proper visual
10017/// appearance. Unlike actual window tiling, this only affects border radius -
10018/// not padding or shadows.
10019pub fn client_side_decorations(
10020 element: impl IntoElement,
10021 window: &mut Window,
10022 cx: &mut App,
10023 border_radius_tiling: Tiling,
10024) -> Stateful<Div> {
10025 const BORDER_SIZE: Pixels = px(1.0);
10026 let decorations = window.window_decorations();
10027 let tiling = match decorations {
10028 Decorations::Server => Tiling::default(),
10029 Decorations::Client { tiling } => tiling,
10030 };
10031
10032 match decorations {
10033 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
10034 Decorations::Server => window.set_client_inset(px(0.0)),
10035 }
10036
10037 struct GlobalResizeEdge(ResizeEdge);
10038 impl Global for GlobalResizeEdge {}
10039
10040 div()
10041 .id("window-backdrop")
10042 .bg(transparent_black())
10043 .map(|div| match decorations {
10044 Decorations::Server => div,
10045 Decorations::Client { .. } => div
10046 .when(
10047 !(tiling.top
10048 || tiling.right
10049 || border_radius_tiling.top
10050 || border_radius_tiling.right),
10051 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10052 )
10053 .when(
10054 !(tiling.top
10055 || tiling.left
10056 || border_radius_tiling.top
10057 || border_radius_tiling.left),
10058 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10059 )
10060 .when(
10061 !(tiling.bottom
10062 || tiling.right
10063 || border_radius_tiling.bottom
10064 || border_radius_tiling.right),
10065 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10066 )
10067 .when(
10068 !(tiling.bottom
10069 || tiling.left
10070 || border_radius_tiling.bottom
10071 || border_radius_tiling.left),
10072 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10073 )
10074 .when(!tiling.top, |div| {
10075 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10076 })
10077 .when(!tiling.bottom, |div| {
10078 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10079 })
10080 .when(!tiling.left, |div| {
10081 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10082 })
10083 .when(!tiling.right, |div| {
10084 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10085 })
10086 .on_mouse_move(move |e, window, cx| {
10087 let size = window.window_bounds().get_bounds().size;
10088 let pos = e.position;
10089
10090 let new_edge =
10091 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10092
10093 let edge = cx.try_global::<GlobalResizeEdge>();
10094 if new_edge != edge.map(|edge| edge.0) {
10095 window
10096 .window_handle()
10097 .update(cx, |workspace, _, cx| {
10098 cx.notify(workspace.entity_id());
10099 })
10100 .ok();
10101 }
10102 })
10103 .on_mouse_down(MouseButton::Left, move |e, window, _| {
10104 let size = window.window_bounds().get_bounds().size;
10105 let pos = e.position;
10106
10107 let edge = match resize_edge(
10108 pos,
10109 theme::CLIENT_SIDE_DECORATION_SHADOW,
10110 size,
10111 tiling,
10112 ) {
10113 Some(value) => value,
10114 None => return,
10115 };
10116
10117 window.start_window_resize(edge);
10118 }),
10119 })
10120 .size_full()
10121 .child(
10122 div()
10123 .cursor(CursorStyle::Arrow)
10124 .map(|div| match decorations {
10125 Decorations::Server => div,
10126 Decorations::Client { .. } => div
10127 .border_color(cx.theme().colors().border)
10128 .when(
10129 !(tiling.top
10130 || tiling.right
10131 || border_radius_tiling.top
10132 || border_radius_tiling.right),
10133 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10134 )
10135 .when(
10136 !(tiling.top
10137 || tiling.left
10138 || border_radius_tiling.top
10139 || border_radius_tiling.left),
10140 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10141 )
10142 .when(
10143 !(tiling.bottom
10144 || tiling.right
10145 || border_radius_tiling.bottom
10146 || border_radius_tiling.right),
10147 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10148 )
10149 .when(
10150 !(tiling.bottom
10151 || tiling.left
10152 || border_radius_tiling.bottom
10153 || border_radius_tiling.left),
10154 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10155 )
10156 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10157 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10158 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10159 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10160 .when(!tiling.is_tiled(), |div| {
10161 div.shadow(vec![gpui::BoxShadow {
10162 color: Hsla {
10163 h: 0.,
10164 s: 0.,
10165 l: 0.,
10166 a: 0.4,
10167 },
10168 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10169 spread_radius: px(0.),
10170 offset: point(px(0.0), px(0.0)),
10171 }])
10172 }),
10173 })
10174 .on_mouse_move(|_e, _, cx| {
10175 cx.stop_propagation();
10176 })
10177 .size_full()
10178 .child(element),
10179 )
10180 .map(|div| match decorations {
10181 Decorations::Server => div,
10182 Decorations::Client { tiling, .. } => div.child(
10183 canvas(
10184 |_bounds, window, _| {
10185 window.insert_hitbox(
10186 Bounds::new(
10187 point(px(0.0), px(0.0)),
10188 window.window_bounds().get_bounds().size,
10189 ),
10190 HitboxBehavior::Normal,
10191 )
10192 },
10193 move |_bounds, hitbox, window, cx| {
10194 let mouse = window.mouse_position();
10195 let size = window.window_bounds().get_bounds().size;
10196 let Some(edge) =
10197 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10198 else {
10199 return;
10200 };
10201 cx.set_global(GlobalResizeEdge(edge));
10202 window.set_cursor_style(
10203 match edge {
10204 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10205 ResizeEdge::Left | ResizeEdge::Right => {
10206 CursorStyle::ResizeLeftRight
10207 }
10208 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10209 CursorStyle::ResizeUpLeftDownRight
10210 }
10211 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10212 CursorStyle::ResizeUpRightDownLeft
10213 }
10214 },
10215 &hitbox,
10216 );
10217 },
10218 )
10219 .size_full()
10220 .absolute(),
10221 ),
10222 })
10223}
10224
10225fn resize_edge(
10226 pos: Point<Pixels>,
10227 shadow_size: Pixels,
10228 window_size: Size<Pixels>,
10229 tiling: Tiling,
10230) -> Option<ResizeEdge> {
10231 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10232 if bounds.contains(&pos) {
10233 return None;
10234 }
10235
10236 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10237 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10238 if !tiling.top && top_left_bounds.contains(&pos) {
10239 return Some(ResizeEdge::TopLeft);
10240 }
10241
10242 let top_right_bounds = Bounds::new(
10243 Point::new(window_size.width - corner_size.width, px(0.)),
10244 corner_size,
10245 );
10246 if !tiling.top && top_right_bounds.contains(&pos) {
10247 return Some(ResizeEdge::TopRight);
10248 }
10249
10250 let bottom_left_bounds = Bounds::new(
10251 Point::new(px(0.), window_size.height - corner_size.height),
10252 corner_size,
10253 );
10254 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10255 return Some(ResizeEdge::BottomLeft);
10256 }
10257
10258 let bottom_right_bounds = Bounds::new(
10259 Point::new(
10260 window_size.width - corner_size.width,
10261 window_size.height - corner_size.height,
10262 ),
10263 corner_size,
10264 );
10265 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10266 return Some(ResizeEdge::BottomRight);
10267 }
10268
10269 if !tiling.top && pos.y < shadow_size {
10270 Some(ResizeEdge::Top)
10271 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10272 Some(ResizeEdge::Bottom)
10273 } else if !tiling.left && pos.x < shadow_size {
10274 Some(ResizeEdge::Left)
10275 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10276 Some(ResizeEdge::Right)
10277 } else {
10278 None
10279 }
10280}
10281
10282fn join_pane_into_active(
10283 active_pane: &Entity<Pane>,
10284 pane: &Entity<Pane>,
10285 window: &mut Window,
10286 cx: &mut App,
10287) {
10288 if pane == active_pane {
10289 } else if pane.read(cx).items_len() == 0 {
10290 pane.update(cx, |_, cx| {
10291 cx.emit(pane::Event::Remove {
10292 focus_on_pane: None,
10293 });
10294 })
10295 } else {
10296 move_all_items(pane, active_pane, window, cx);
10297 }
10298}
10299
10300fn move_all_items(
10301 from_pane: &Entity<Pane>,
10302 to_pane: &Entity<Pane>,
10303 window: &mut Window,
10304 cx: &mut App,
10305) {
10306 let destination_is_different = from_pane != to_pane;
10307 let mut moved_items = 0;
10308 for (item_ix, item_handle) in from_pane
10309 .read(cx)
10310 .items()
10311 .enumerate()
10312 .map(|(ix, item)| (ix, item.clone()))
10313 .collect::<Vec<_>>()
10314 {
10315 let ix = item_ix - moved_items;
10316 if destination_is_different {
10317 // Close item from previous pane
10318 from_pane.update(cx, |source, cx| {
10319 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10320 });
10321 moved_items += 1;
10322 }
10323
10324 // This automatically removes duplicate items in the pane
10325 to_pane.update(cx, |destination, cx| {
10326 destination.add_item(item_handle, true, true, None, window, cx);
10327 window.focus(&destination.focus_handle(cx), cx)
10328 });
10329 }
10330}
10331
10332pub fn move_item(
10333 source: &Entity<Pane>,
10334 destination: &Entity<Pane>,
10335 item_id_to_move: EntityId,
10336 destination_index: usize,
10337 activate: bool,
10338 window: &mut Window,
10339 cx: &mut App,
10340) {
10341 let Some((item_ix, item_handle)) = source
10342 .read(cx)
10343 .items()
10344 .enumerate()
10345 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10346 .map(|(ix, item)| (ix, item.clone()))
10347 else {
10348 // Tab was closed during drag
10349 return;
10350 };
10351
10352 if source != destination {
10353 // Close item from previous pane
10354 source.update(cx, |source, cx| {
10355 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10356 });
10357 }
10358
10359 // This automatically removes duplicate items in the pane
10360 destination.update(cx, |destination, cx| {
10361 destination.add_item_inner(
10362 item_handle,
10363 activate,
10364 activate,
10365 activate,
10366 Some(destination_index),
10367 window,
10368 cx,
10369 );
10370 if activate {
10371 window.focus(&destination.focus_handle(cx), cx)
10372 }
10373 });
10374}
10375
10376pub fn move_active_item(
10377 source: &Entity<Pane>,
10378 destination: &Entity<Pane>,
10379 focus_destination: bool,
10380 close_if_empty: bool,
10381 window: &mut Window,
10382 cx: &mut App,
10383) {
10384 if source == destination {
10385 return;
10386 }
10387 let Some(active_item) = source.read(cx).active_item() else {
10388 return;
10389 };
10390 source.update(cx, |source_pane, cx| {
10391 let item_id = active_item.item_id();
10392 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10393 destination.update(cx, |target_pane, cx| {
10394 target_pane.add_item(
10395 active_item,
10396 focus_destination,
10397 focus_destination,
10398 Some(target_pane.items_len()),
10399 window,
10400 cx,
10401 );
10402 });
10403 });
10404}
10405
10406pub fn clone_active_item(
10407 workspace_id: Option<WorkspaceId>,
10408 source: &Entity<Pane>,
10409 destination: &Entity<Pane>,
10410 focus_destination: bool,
10411 window: &mut Window,
10412 cx: &mut App,
10413) {
10414 if source == destination {
10415 return;
10416 }
10417 let Some(active_item) = source.read(cx).active_item() else {
10418 return;
10419 };
10420 if !active_item.can_split(cx) {
10421 return;
10422 }
10423 let destination = destination.downgrade();
10424 let task = active_item.clone_on_split(workspace_id, window, cx);
10425 window
10426 .spawn(cx, async move |cx| {
10427 let Some(clone) = task.await else {
10428 return;
10429 };
10430 destination
10431 .update_in(cx, |target_pane, window, cx| {
10432 target_pane.add_item(
10433 clone,
10434 focus_destination,
10435 focus_destination,
10436 Some(target_pane.items_len()),
10437 window,
10438 cx,
10439 );
10440 })
10441 .log_err();
10442 })
10443 .detach();
10444}
10445
10446#[derive(Debug)]
10447pub struct WorkspacePosition {
10448 pub window_bounds: Option<WindowBounds>,
10449 pub display: Option<Uuid>,
10450 pub centered_layout: bool,
10451}
10452
10453pub fn remote_workspace_position_from_db(
10454 connection_options: RemoteConnectionOptions,
10455 paths_to_open: &[PathBuf],
10456 cx: &App,
10457) -> Task<Result<WorkspacePosition>> {
10458 let paths = paths_to_open.to_vec();
10459 let db = WorkspaceDb::global(cx);
10460 let kvp = db::kvp::KeyValueStore::global(cx);
10461
10462 cx.background_spawn(async move {
10463 let remote_connection_id = db
10464 .get_or_create_remote_connection(connection_options)
10465 .await
10466 .context("fetching serialized ssh project")?;
10467 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10468
10469 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10470 (Some(WindowBounds::Windowed(bounds)), None)
10471 } else {
10472 let restorable_bounds = serialized_workspace
10473 .as_ref()
10474 .and_then(|workspace| {
10475 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10476 })
10477 .or_else(|| persistence::read_default_window_bounds(&kvp));
10478
10479 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10480 (Some(serialized_bounds), Some(serialized_display))
10481 } else {
10482 (None, None)
10483 }
10484 };
10485
10486 let centered_layout = serialized_workspace
10487 .as_ref()
10488 .map(|w| w.centered_layout)
10489 .unwrap_or(false);
10490
10491 Ok(WorkspacePosition {
10492 window_bounds,
10493 display,
10494 centered_layout,
10495 })
10496 })
10497}
10498
10499pub fn with_active_or_new_workspace(
10500 cx: &mut App,
10501 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10502) {
10503 match cx
10504 .active_window()
10505 .and_then(|w| w.downcast::<MultiWorkspace>())
10506 {
10507 Some(multi_workspace) => {
10508 cx.defer(move |cx| {
10509 multi_workspace
10510 .update(cx, |multi_workspace, window, cx| {
10511 let workspace = multi_workspace.workspace().clone();
10512 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10513 })
10514 .log_err();
10515 });
10516 }
10517 None => {
10518 let app_state = AppState::global(cx);
10519 open_new(
10520 OpenOptions::default(),
10521 app_state,
10522 cx,
10523 move |workspace, window, cx| f(workspace, window, cx),
10524 )
10525 .detach_and_log_err(cx);
10526 }
10527 }
10528}
10529
10530/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10531/// key. This migration path only runs once per panel per workspace.
10532fn load_legacy_panel_size(
10533 panel_key: &str,
10534 dock_position: DockPosition,
10535 workspace: &Workspace,
10536 cx: &mut App,
10537) -> Option<Pixels> {
10538 #[derive(Deserialize)]
10539 struct LegacyPanelState {
10540 #[serde(default)]
10541 width: Option<Pixels>,
10542 #[serde(default)]
10543 height: Option<Pixels>,
10544 }
10545
10546 let workspace_id = workspace
10547 .database_id()
10548 .map(|id| i64::from(id).to_string())
10549 .or_else(|| workspace.session_id())?;
10550
10551 let legacy_key = match panel_key {
10552 "ProjectPanel" => {
10553 format!("{}-{:?}", "ProjectPanel", workspace_id)
10554 }
10555 "OutlinePanel" => {
10556 format!("{}-{:?}", "OutlinePanel", workspace_id)
10557 }
10558 "GitPanel" => {
10559 format!("{}-{:?}", "GitPanel", workspace_id)
10560 }
10561 "TerminalPanel" => {
10562 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10563 }
10564 _ => return None,
10565 };
10566
10567 let kvp = db::kvp::KeyValueStore::global(cx);
10568 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10569 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10570 let size = match dock_position {
10571 DockPosition::Bottom => state.height,
10572 DockPosition::Left | DockPosition::Right => state.width,
10573 }?;
10574
10575 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10576 .detach_and_log_err(cx);
10577
10578 Some(size)
10579}
10580
10581#[cfg(test)]
10582mod tests {
10583 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10584
10585 use super::*;
10586 use crate::{
10587 dock::{PanelEvent, test::TestPanel},
10588 item::{
10589 ItemBufferKind, ItemEvent,
10590 test::{TestItem, TestProjectItem},
10591 },
10592 };
10593 use fs::FakeFs;
10594 use gpui::{
10595 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10596 UpdateGlobal, VisualTestContext, px,
10597 };
10598 use project::{Project, ProjectEntryId};
10599 use serde_json::json;
10600 use settings::SettingsStore;
10601 use util::path;
10602 use util::rel_path::rel_path;
10603
10604 #[gpui::test]
10605 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10606 init_test(cx);
10607
10608 let fs = FakeFs::new(cx.executor());
10609 let project = Project::test(fs, [], cx).await;
10610 let (workspace, cx) =
10611 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10612
10613 // Adding an item with no ambiguity renders the tab without detail.
10614 let item1 = cx.new(|cx| {
10615 let mut item = TestItem::new(cx);
10616 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10617 item
10618 });
10619 workspace.update_in(cx, |workspace, window, cx| {
10620 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10621 });
10622 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10623
10624 // Adding an item that creates ambiguity increases the level of detail on
10625 // both tabs.
10626 let item2 = cx.new_window_entity(|_window, cx| {
10627 let mut item = TestItem::new(cx);
10628 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10629 item
10630 });
10631 workspace.update_in(cx, |workspace, window, cx| {
10632 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10633 });
10634 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10635 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10636
10637 // Adding an item that creates ambiguity increases the level of detail only
10638 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10639 // we stop at the highest detail available.
10640 let item3 = cx.new(|cx| {
10641 let mut item = TestItem::new(cx);
10642 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10643 item
10644 });
10645 workspace.update_in(cx, |workspace, window, cx| {
10646 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10647 });
10648 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10649 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10650 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10651 }
10652
10653 #[gpui::test]
10654 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10655 init_test(cx);
10656
10657 let fs = FakeFs::new(cx.executor());
10658 fs.insert_tree(
10659 "/root1",
10660 json!({
10661 "one.txt": "",
10662 "two.txt": "",
10663 }),
10664 )
10665 .await;
10666 fs.insert_tree(
10667 "/root2",
10668 json!({
10669 "three.txt": "",
10670 }),
10671 )
10672 .await;
10673
10674 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10675 let (workspace, cx) =
10676 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10677 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10678 let worktree_id = project.update(cx, |project, cx| {
10679 project.worktrees(cx).next().unwrap().read(cx).id()
10680 });
10681
10682 let item1 = cx.new(|cx| {
10683 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10684 });
10685 let item2 = cx.new(|cx| {
10686 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10687 });
10688
10689 // Add an item to an empty pane
10690 workspace.update_in(cx, |workspace, window, cx| {
10691 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10692 });
10693 project.update(cx, |project, cx| {
10694 assert_eq!(
10695 project.active_entry(),
10696 project
10697 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10698 .map(|e| e.id)
10699 );
10700 });
10701 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10702
10703 // Add a second item to a non-empty pane
10704 workspace.update_in(cx, |workspace, window, cx| {
10705 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10706 });
10707 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10708 project.update(cx, |project, cx| {
10709 assert_eq!(
10710 project.active_entry(),
10711 project
10712 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10713 .map(|e| e.id)
10714 );
10715 });
10716
10717 // Close the active item
10718 pane.update_in(cx, |pane, window, cx| {
10719 pane.close_active_item(&Default::default(), window, cx)
10720 })
10721 .await
10722 .unwrap();
10723 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10724 project.update(cx, |project, cx| {
10725 assert_eq!(
10726 project.active_entry(),
10727 project
10728 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10729 .map(|e| e.id)
10730 );
10731 });
10732
10733 // Add a project folder
10734 project
10735 .update(cx, |project, cx| {
10736 project.find_or_create_worktree("root2", true, cx)
10737 })
10738 .await
10739 .unwrap();
10740 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10741
10742 // Remove a project folder
10743 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10744 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10745 }
10746
10747 #[gpui::test]
10748 async fn test_close_window(cx: &mut TestAppContext) {
10749 init_test(cx);
10750
10751 let fs = FakeFs::new(cx.executor());
10752 fs.insert_tree("/root", json!({ "one": "" })).await;
10753
10754 let project = Project::test(fs, ["root".as_ref()], cx).await;
10755 let (workspace, cx) =
10756 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10757
10758 // When there are no dirty items, there's nothing to do.
10759 let item1 = cx.new(TestItem::new);
10760 workspace.update_in(cx, |w, window, cx| {
10761 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10762 });
10763 let task = workspace.update_in(cx, |w, window, cx| {
10764 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10765 });
10766 assert!(task.await.unwrap());
10767
10768 // When there are dirty untitled items, prompt to save each one. If the user
10769 // cancels any prompt, then abort.
10770 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10771 let item3 = cx.new(|cx| {
10772 TestItem::new(cx)
10773 .with_dirty(true)
10774 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10775 });
10776 workspace.update_in(cx, |w, window, cx| {
10777 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10778 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10779 });
10780 let task = workspace.update_in(cx, |w, window, cx| {
10781 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10782 });
10783 cx.executor().run_until_parked();
10784 cx.simulate_prompt_answer("Cancel"); // cancel save all
10785 cx.executor().run_until_parked();
10786 assert!(!cx.has_pending_prompt());
10787 assert!(!task.await.unwrap());
10788 }
10789
10790 #[gpui::test]
10791 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10792 init_test(cx);
10793
10794 let fs = FakeFs::new(cx.executor());
10795 fs.insert_tree("/root", json!({ "one": "" })).await;
10796
10797 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10798 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10799 let multi_workspace_handle =
10800 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10801 cx.run_until_parked();
10802
10803 multi_workspace_handle
10804 .update(cx, |mw, _window, cx| {
10805 mw.open_sidebar(cx);
10806 })
10807 .unwrap();
10808
10809 let workspace_a = multi_workspace_handle
10810 .read_with(cx, |mw, _| mw.workspace().clone())
10811 .unwrap();
10812
10813 let workspace_b = multi_workspace_handle
10814 .update(cx, |mw, window, cx| {
10815 mw.test_add_workspace(project_b, window, cx)
10816 })
10817 .unwrap();
10818
10819 // Activate workspace A
10820 multi_workspace_handle
10821 .update(cx, |mw, window, cx| {
10822 let workspace = mw.workspaces().next().unwrap().clone();
10823 mw.activate(workspace, window, cx);
10824 })
10825 .unwrap();
10826
10827 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10828
10829 // Workspace A has a clean item
10830 let item_a = cx.new(TestItem::new);
10831 workspace_a.update_in(cx, |w, window, cx| {
10832 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10833 });
10834
10835 // Workspace B has a dirty item
10836 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10837 workspace_b.update_in(cx, |w, window, cx| {
10838 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10839 });
10840
10841 // Verify workspace A is active
10842 multi_workspace_handle
10843 .read_with(cx, |mw, _| {
10844 assert_eq!(mw.workspace(), &workspace_a);
10845 })
10846 .unwrap();
10847
10848 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10849 multi_workspace_handle
10850 .update(cx, |mw, window, cx| {
10851 mw.close_window(&CloseWindow, window, cx);
10852 })
10853 .unwrap();
10854 cx.run_until_parked();
10855
10856 // Workspace B should now be active since it has dirty items that need attention
10857 multi_workspace_handle
10858 .read_with(cx, |mw, _| {
10859 assert_eq!(
10860 mw.workspace(),
10861 &workspace_b,
10862 "workspace B should be activated when it prompts"
10863 );
10864 })
10865 .unwrap();
10866
10867 // User cancels the save prompt from workspace B
10868 cx.simulate_prompt_answer("Cancel");
10869 cx.run_until_parked();
10870
10871 // Window should still exist because workspace B's close was cancelled
10872 assert!(
10873 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10874 "window should still exist after cancelling one workspace's close"
10875 );
10876 }
10877
10878 #[gpui::test]
10879 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10880 init_test(cx);
10881
10882 // Register TestItem as a serializable item
10883 cx.update(|cx| {
10884 register_serializable_item::<TestItem>(cx);
10885 });
10886
10887 let fs = FakeFs::new(cx.executor());
10888 fs.insert_tree("/root", json!({ "one": "" })).await;
10889
10890 let project = Project::test(fs, ["root".as_ref()], cx).await;
10891 let (workspace, cx) =
10892 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10893
10894 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10895 let item1 = cx.new(|cx| {
10896 TestItem::new(cx)
10897 .with_dirty(true)
10898 .with_serialize(|| Some(Task::ready(Ok(()))))
10899 });
10900 let item2 = cx.new(|cx| {
10901 TestItem::new(cx)
10902 .with_dirty(true)
10903 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10904 .with_serialize(|| Some(Task::ready(Ok(()))))
10905 });
10906 workspace.update_in(cx, |w, window, cx| {
10907 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10908 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10909 });
10910 let task = workspace.update_in(cx, |w, window, cx| {
10911 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10912 });
10913 assert!(task.await.unwrap());
10914 }
10915
10916 #[gpui::test]
10917 async fn test_close_pane_items(cx: &mut TestAppContext) {
10918 init_test(cx);
10919
10920 let fs = FakeFs::new(cx.executor());
10921
10922 let project = Project::test(fs, None, cx).await;
10923 let (workspace, cx) =
10924 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10925
10926 let item1 = cx.new(|cx| {
10927 TestItem::new(cx)
10928 .with_dirty(true)
10929 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10930 });
10931 let item2 = cx.new(|cx| {
10932 TestItem::new(cx)
10933 .with_dirty(true)
10934 .with_conflict(true)
10935 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10936 });
10937 let item3 = cx.new(|cx| {
10938 TestItem::new(cx)
10939 .with_dirty(true)
10940 .with_conflict(true)
10941 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10942 });
10943 let item4 = cx.new(|cx| {
10944 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10945 let project_item = TestProjectItem::new_untitled(cx);
10946 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10947 project_item
10948 }])
10949 });
10950 let pane = workspace.update_in(cx, |workspace, window, cx| {
10951 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10952 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10953 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10954 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10955 workspace.active_pane().clone()
10956 });
10957
10958 let close_items = pane.update_in(cx, |pane, window, cx| {
10959 pane.activate_item(1, true, true, window, cx);
10960 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10961 let item1_id = item1.item_id();
10962 let item3_id = item3.item_id();
10963 let item4_id = item4.item_id();
10964 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10965 [item1_id, item3_id, item4_id].contains(&id)
10966 })
10967 });
10968 cx.executor().run_until_parked();
10969
10970 assert!(cx.has_pending_prompt());
10971 cx.simulate_prompt_answer("Save all");
10972
10973 cx.executor().run_until_parked();
10974
10975 // Item 1 is saved. There's a prompt to save item 3.
10976 pane.update(cx, |pane, cx| {
10977 assert_eq!(item1.read(cx).save_count, 1);
10978 assert_eq!(item1.read(cx).save_as_count, 0);
10979 assert_eq!(item1.read(cx).reload_count, 0);
10980 assert_eq!(pane.items_len(), 3);
10981 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10982 });
10983 assert!(cx.has_pending_prompt());
10984
10985 // Cancel saving item 3.
10986 cx.simulate_prompt_answer("Discard");
10987 cx.executor().run_until_parked();
10988
10989 // Item 3 is reloaded. There's a prompt to save item 4.
10990 pane.update(cx, |pane, cx| {
10991 assert_eq!(item3.read(cx).save_count, 0);
10992 assert_eq!(item3.read(cx).save_as_count, 0);
10993 assert_eq!(item3.read(cx).reload_count, 1);
10994 assert_eq!(pane.items_len(), 2);
10995 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10996 });
10997
10998 // There's a prompt for a path for item 4.
10999 cx.simulate_new_path_selection(|_| Some(Default::default()));
11000 close_items.await.unwrap();
11001
11002 // The requested items are closed.
11003 pane.update(cx, |pane, cx| {
11004 assert_eq!(item4.read(cx).save_count, 0);
11005 assert_eq!(item4.read(cx).save_as_count, 1);
11006 assert_eq!(item4.read(cx).reload_count, 0);
11007 assert_eq!(pane.items_len(), 1);
11008 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11009 });
11010 }
11011
11012 #[gpui::test]
11013 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
11014 init_test(cx);
11015
11016 let fs = FakeFs::new(cx.executor());
11017 let project = Project::test(fs, [], cx).await;
11018 let (workspace, cx) =
11019 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11020
11021 // Create several workspace items with single project entries, and two
11022 // workspace items with multiple project entries.
11023 let single_entry_items = (0..=4)
11024 .map(|project_entry_id| {
11025 cx.new(|cx| {
11026 TestItem::new(cx)
11027 .with_dirty(true)
11028 .with_project_items(&[dirty_project_item(
11029 project_entry_id,
11030 &format!("{project_entry_id}.txt"),
11031 cx,
11032 )])
11033 })
11034 })
11035 .collect::<Vec<_>>();
11036 let item_2_3 = cx.new(|cx| {
11037 TestItem::new(cx)
11038 .with_dirty(true)
11039 .with_buffer_kind(ItemBufferKind::Multibuffer)
11040 .with_project_items(&[
11041 single_entry_items[2].read(cx).project_items[0].clone(),
11042 single_entry_items[3].read(cx).project_items[0].clone(),
11043 ])
11044 });
11045 let item_3_4 = cx.new(|cx| {
11046 TestItem::new(cx)
11047 .with_dirty(true)
11048 .with_buffer_kind(ItemBufferKind::Multibuffer)
11049 .with_project_items(&[
11050 single_entry_items[3].read(cx).project_items[0].clone(),
11051 single_entry_items[4].read(cx).project_items[0].clone(),
11052 ])
11053 });
11054
11055 // Create two panes that contain the following project entries:
11056 // left pane:
11057 // multi-entry items: (2, 3)
11058 // single-entry items: 0, 2, 3, 4
11059 // right pane:
11060 // single-entry items: 4, 1
11061 // multi-entry items: (3, 4)
11062 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11063 let left_pane = workspace.active_pane().clone();
11064 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11065 workspace.add_item_to_active_pane(
11066 single_entry_items[0].boxed_clone(),
11067 None,
11068 true,
11069 window,
11070 cx,
11071 );
11072 workspace.add_item_to_active_pane(
11073 single_entry_items[2].boxed_clone(),
11074 None,
11075 true,
11076 window,
11077 cx,
11078 );
11079 workspace.add_item_to_active_pane(
11080 single_entry_items[3].boxed_clone(),
11081 None,
11082 true,
11083 window,
11084 cx,
11085 );
11086 workspace.add_item_to_active_pane(
11087 single_entry_items[4].boxed_clone(),
11088 None,
11089 true,
11090 window,
11091 cx,
11092 );
11093
11094 let right_pane =
11095 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11096
11097 let boxed_clone = single_entry_items[1].boxed_clone();
11098 let right_pane = window.spawn(cx, async move |cx| {
11099 right_pane.await.inspect(|right_pane| {
11100 right_pane
11101 .update_in(cx, |pane, window, cx| {
11102 pane.add_item(boxed_clone, true, true, None, window, cx);
11103 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11104 })
11105 .unwrap();
11106 })
11107 });
11108
11109 (left_pane, right_pane)
11110 });
11111 let right_pane = right_pane.await.unwrap();
11112 cx.focus(&right_pane);
11113
11114 let close = right_pane.update_in(cx, |pane, window, cx| {
11115 pane.close_all_items(&CloseAllItems::default(), window, cx)
11116 .unwrap()
11117 });
11118 cx.executor().run_until_parked();
11119
11120 let msg = cx.pending_prompt().unwrap().0;
11121 assert!(msg.contains("1.txt"));
11122 assert!(!msg.contains("2.txt"));
11123 assert!(!msg.contains("3.txt"));
11124 assert!(!msg.contains("4.txt"));
11125
11126 // With best-effort close, cancelling item 1 keeps it open but items 4
11127 // and (3,4) still close since their entries exist in left pane.
11128 cx.simulate_prompt_answer("Cancel");
11129 close.await;
11130
11131 right_pane.read_with(cx, |pane, _| {
11132 assert_eq!(pane.items_len(), 1);
11133 });
11134
11135 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11136 left_pane
11137 .update_in(cx, |left_pane, window, cx| {
11138 left_pane.close_item_by_id(
11139 single_entry_items[3].entity_id(),
11140 SaveIntent::Skip,
11141 window,
11142 cx,
11143 )
11144 })
11145 .await
11146 .unwrap();
11147
11148 let close = left_pane.update_in(cx, |pane, window, cx| {
11149 pane.close_all_items(&CloseAllItems::default(), window, cx)
11150 .unwrap()
11151 });
11152 cx.executor().run_until_parked();
11153
11154 let details = cx.pending_prompt().unwrap().1;
11155 assert!(details.contains("0.txt"));
11156 assert!(details.contains("3.txt"));
11157 assert!(details.contains("4.txt"));
11158 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11159 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11160 // assert!(!details.contains("2.txt"));
11161
11162 cx.simulate_prompt_answer("Save all");
11163 cx.executor().run_until_parked();
11164 close.await;
11165
11166 left_pane.read_with(cx, |pane, _| {
11167 assert_eq!(pane.items_len(), 0);
11168 });
11169 }
11170
11171 #[gpui::test]
11172 async fn test_autosave(cx: &mut gpui::TestAppContext) {
11173 init_test(cx);
11174
11175 let fs = FakeFs::new(cx.executor());
11176 let project = Project::test(fs, [], cx).await;
11177 let (workspace, cx) =
11178 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11179 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11180
11181 let item = cx.new(|cx| {
11182 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11183 });
11184 let item_id = item.entity_id();
11185 workspace.update_in(cx, |workspace, window, cx| {
11186 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11187 });
11188
11189 // Autosave on window change.
11190 item.update(cx, |item, cx| {
11191 SettingsStore::update_global(cx, |settings, cx| {
11192 settings.update_user_settings(cx, |settings| {
11193 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11194 })
11195 });
11196 item.is_dirty = true;
11197 });
11198
11199 // Deactivating the window saves the file.
11200 cx.deactivate_window();
11201 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11202
11203 // Re-activating the window doesn't save the file.
11204 cx.update(|window, _| window.activate_window());
11205 cx.executor().run_until_parked();
11206 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11207
11208 // Autosave on focus change.
11209 item.update_in(cx, |item, window, cx| {
11210 cx.focus_self(window);
11211 SettingsStore::update_global(cx, |settings, cx| {
11212 settings.update_user_settings(cx, |settings| {
11213 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11214 })
11215 });
11216 item.is_dirty = true;
11217 });
11218 // Blurring the item saves the file.
11219 item.update_in(cx, |_, window, _| window.blur());
11220 cx.executor().run_until_parked();
11221 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11222
11223 // Deactivating the window still saves the file.
11224 item.update_in(cx, |item, window, cx| {
11225 cx.focus_self(window);
11226 item.is_dirty = true;
11227 });
11228 cx.deactivate_window();
11229 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11230
11231 // Autosave after delay.
11232 item.update(cx, |item, cx| {
11233 SettingsStore::update_global(cx, |settings, cx| {
11234 settings.update_user_settings(cx, |settings| {
11235 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11236 milliseconds: 500.into(),
11237 });
11238 })
11239 });
11240 item.is_dirty = true;
11241 cx.emit(ItemEvent::Edit);
11242 });
11243
11244 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11245 cx.executor().advance_clock(Duration::from_millis(250));
11246 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11247
11248 // After delay expires, the file is saved.
11249 cx.executor().advance_clock(Duration::from_millis(250));
11250 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11251
11252 // Autosave after delay, should save earlier than delay if tab is closed
11253 item.update(cx, |item, cx| {
11254 item.is_dirty = true;
11255 cx.emit(ItemEvent::Edit);
11256 });
11257 cx.executor().advance_clock(Duration::from_millis(250));
11258 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11259
11260 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11261 pane.update_in(cx, |pane, window, cx| {
11262 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11263 })
11264 .await
11265 .unwrap();
11266 assert!(!cx.has_pending_prompt());
11267 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11268
11269 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11270 workspace.update_in(cx, |workspace, window, cx| {
11271 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11272 });
11273 item.update_in(cx, |item, _window, cx| {
11274 item.is_dirty = true;
11275 for project_item in &mut item.project_items {
11276 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11277 }
11278 });
11279 cx.run_until_parked();
11280 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11281
11282 // Autosave on focus change, ensuring closing the tab counts as such.
11283 item.update(cx, |item, cx| {
11284 SettingsStore::update_global(cx, |settings, cx| {
11285 settings.update_user_settings(cx, |settings| {
11286 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11287 })
11288 });
11289 item.is_dirty = true;
11290 for project_item in &mut item.project_items {
11291 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11292 }
11293 });
11294
11295 pane.update_in(cx, |pane, window, cx| {
11296 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11297 })
11298 .await
11299 .unwrap();
11300 assert!(!cx.has_pending_prompt());
11301 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11302
11303 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11304 workspace.update_in(cx, |workspace, window, cx| {
11305 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11306 });
11307 item.update_in(cx, |item, window, cx| {
11308 item.project_items[0].update(cx, |item, _| {
11309 item.entry_id = None;
11310 });
11311 item.is_dirty = true;
11312 window.blur();
11313 });
11314 cx.run_until_parked();
11315 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11316
11317 // Ensure autosave is prevented for deleted files also when closing the buffer.
11318 let _close_items = pane.update_in(cx, |pane, window, cx| {
11319 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11320 });
11321 cx.run_until_parked();
11322 assert!(cx.has_pending_prompt());
11323 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11324 }
11325
11326 #[gpui::test]
11327 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11328 init_test(cx);
11329
11330 let fs = FakeFs::new(cx.executor());
11331 let project = Project::test(fs, [], cx).await;
11332 let (workspace, cx) =
11333 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11334
11335 // Create a multibuffer-like item with two child focus handles,
11336 // simulating individual buffer editors within a multibuffer.
11337 let item = cx.new(|cx| {
11338 TestItem::new(cx)
11339 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11340 .with_child_focus_handles(2, cx)
11341 });
11342 workspace.update_in(cx, |workspace, window, cx| {
11343 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11344 });
11345
11346 // Set autosave to OnFocusChange and focus the first child handle,
11347 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11348 item.update_in(cx, |item, window, cx| {
11349 SettingsStore::update_global(cx, |settings, cx| {
11350 settings.update_user_settings(cx, |settings| {
11351 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11352 })
11353 });
11354 item.is_dirty = true;
11355 window.focus(&item.child_focus_handles[0], cx);
11356 });
11357 cx.executor().run_until_parked();
11358 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11359
11360 // Moving focus from one child to another within the same item should
11361 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11362 item.update_in(cx, |item, window, cx| {
11363 window.focus(&item.child_focus_handles[1], cx);
11364 });
11365 cx.executor().run_until_parked();
11366 item.read_with(cx, |item, _| {
11367 assert_eq!(
11368 item.save_count, 0,
11369 "Switching focus between children within the same item should not autosave"
11370 );
11371 });
11372
11373 // Blurring the item saves the file. This is the core regression scenario:
11374 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11375 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11376 // the leaf is always a child focus handle, so `on_blur` never detected
11377 // focus leaving the item.
11378 item.update_in(cx, |_, window, _| window.blur());
11379 cx.executor().run_until_parked();
11380 item.read_with(cx, |item, _| {
11381 assert_eq!(
11382 item.save_count, 1,
11383 "Blurring should trigger autosave when focus was on a child of the item"
11384 );
11385 });
11386
11387 // Deactivating the window should also trigger autosave when a child of
11388 // the multibuffer item currently owns focus.
11389 item.update_in(cx, |item, window, cx| {
11390 item.is_dirty = true;
11391 window.focus(&item.child_focus_handles[0], cx);
11392 });
11393 cx.executor().run_until_parked();
11394 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11395
11396 cx.deactivate_window();
11397 item.read_with(cx, |item, _| {
11398 assert_eq!(
11399 item.save_count, 2,
11400 "Deactivating window should trigger autosave when focus was on a child"
11401 );
11402 });
11403 }
11404
11405 #[gpui::test]
11406 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11407 init_test(cx);
11408
11409 let fs = FakeFs::new(cx.executor());
11410
11411 let project = Project::test(fs, [], cx).await;
11412 let (workspace, cx) =
11413 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11414
11415 let item = cx.new(|cx| {
11416 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11417 });
11418 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11419 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11420 let toolbar_notify_count = Rc::new(RefCell::new(0));
11421
11422 workspace.update_in(cx, |workspace, window, cx| {
11423 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11424 let toolbar_notification_count = toolbar_notify_count.clone();
11425 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11426 *toolbar_notification_count.borrow_mut() += 1
11427 })
11428 .detach();
11429 });
11430
11431 pane.read_with(cx, |pane, _| {
11432 assert!(!pane.can_navigate_backward());
11433 assert!(!pane.can_navigate_forward());
11434 });
11435
11436 item.update_in(cx, |item, _, cx| {
11437 item.set_state("one".to_string(), cx);
11438 });
11439
11440 // Toolbar must be notified to re-render the navigation buttons
11441 assert_eq!(*toolbar_notify_count.borrow(), 1);
11442
11443 pane.read_with(cx, |pane, _| {
11444 assert!(pane.can_navigate_backward());
11445 assert!(!pane.can_navigate_forward());
11446 });
11447
11448 workspace
11449 .update_in(cx, |workspace, window, cx| {
11450 workspace.go_back(pane.downgrade(), window, cx)
11451 })
11452 .await
11453 .unwrap();
11454
11455 assert_eq!(*toolbar_notify_count.borrow(), 2);
11456 pane.read_with(cx, |pane, _| {
11457 assert!(!pane.can_navigate_backward());
11458 assert!(pane.can_navigate_forward());
11459 });
11460 }
11461
11462 /// Tests that the navigation history deduplicates entries for the same item.
11463 ///
11464 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11465 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11466 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11467 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11468 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11469 ///
11470 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11471 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11472 #[gpui::test]
11473 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11474 init_test(cx);
11475
11476 let fs = FakeFs::new(cx.executor());
11477 let project = Project::test(fs, [], cx).await;
11478 let (workspace, cx) =
11479 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11480
11481 let item_a = cx.new(|cx| {
11482 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11483 });
11484 let item_b = cx.new(|cx| {
11485 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11486 });
11487 let item_c = cx.new(|cx| {
11488 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11489 });
11490
11491 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11492
11493 workspace.update_in(cx, |workspace, window, cx| {
11494 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11495 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11496 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11497 });
11498
11499 workspace.update_in(cx, |workspace, window, cx| {
11500 workspace.activate_item(&item_a, false, false, window, cx);
11501 });
11502 cx.run_until_parked();
11503
11504 workspace.update_in(cx, |workspace, window, cx| {
11505 workspace.activate_item(&item_b, false, false, window, cx);
11506 });
11507 cx.run_until_parked();
11508
11509 workspace.update_in(cx, |workspace, window, cx| {
11510 workspace.activate_item(&item_a, false, false, window, cx);
11511 });
11512 cx.run_until_parked();
11513
11514 workspace.update_in(cx, |workspace, window, cx| {
11515 workspace.activate_item(&item_b, false, false, window, cx);
11516 });
11517 cx.run_until_parked();
11518
11519 workspace.update_in(cx, |workspace, window, cx| {
11520 workspace.activate_item(&item_a, false, false, window, cx);
11521 });
11522 cx.run_until_parked();
11523
11524 workspace.update_in(cx, |workspace, window, cx| {
11525 workspace.activate_item(&item_b, false, false, window, cx);
11526 });
11527 cx.run_until_parked();
11528
11529 workspace.update_in(cx, |workspace, window, cx| {
11530 workspace.activate_item(&item_c, false, false, window, cx);
11531 });
11532 cx.run_until_parked();
11533
11534 let backward_count = pane.read_with(cx, |pane, cx| {
11535 let mut count = 0;
11536 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11537 count += 1;
11538 });
11539 count
11540 });
11541 assert!(
11542 backward_count <= 4,
11543 "Should have at most 4 entries, got {}",
11544 backward_count
11545 );
11546
11547 workspace
11548 .update_in(cx, |workspace, window, cx| {
11549 workspace.go_back(pane.downgrade(), window, cx)
11550 })
11551 .await
11552 .unwrap();
11553
11554 let active_item = workspace.read_with(cx, |workspace, cx| {
11555 workspace.active_item(cx).unwrap().item_id()
11556 });
11557 assert_eq!(
11558 active_item,
11559 item_b.entity_id(),
11560 "After first go_back, should be at item B"
11561 );
11562
11563 workspace
11564 .update_in(cx, |workspace, window, cx| {
11565 workspace.go_back(pane.downgrade(), window, cx)
11566 })
11567 .await
11568 .unwrap();
11569
11570 let active_item = workspace.read_with(cx, |workspace, cx| {
11571 workspace.active_item(cx).unwrap().item_id()
11572 });
11573 assert_eq!(
11574 active_item,
11575 item_a.entity_id(),
11576 "After second go_back, should be at item A"
11577 );
11578
11579 pane.read_with(cx, |pane, _| {
11580 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11581 });
11582 }
11583
11584 #[gpui::test]
11585 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11586 init_test(cx);
11587 let fs = FakeFs::new(cx.executor());
11588 let project = Project::test(fs, [], cx).await;
11589 let (multi_workspace, cx) =
11590 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11591 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11592
11593 workspace.update_in(cx, |workspace, window, cx| {
11594 let first_item = cx.new(|cx| {
11595 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11596 });
11597 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11598 workspace.split_pane(
11599 workspace.active_pane().clone(),
11600 SplitDirection::Right,
11601 window,
11602 cx,
11603 );
11604 workspace.split_pane(
11605 workspace.active_pane().clone(),
11606 SplitDirection::Right,
11607 window,
11608 cx,
11609 );
11610 });
11611
11612 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11613 let panes = workspace.center.panes();
11614 assert!(panes.len() >= 2);
11615 (
11616 panes.first().expect("at least one pane").entity_id(),
11617 panes.last().expect("at least one pane").entity_id(),
11618 )
11619 });
11620
11621 workspace.update_in(cx, |workspace, window, cx| {
11622 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11623 });
11624 workspace.update(cx, |workspace, _| {
11625 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11626 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11627 });
11628
11629 cx.dispatch_action(ActivateLastPane);
11630
11631 workspace.update(cx, |workspace, _| {
11632 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11633 });
11634 }
11635
11636 #[gpui::test]
11637 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11638 init_test(cx);
11639 let fs = FakeFs::new(cx.executor());
11640
11641 let project = Project::test(fs, [], cx).await;
11642 let (workspace, cx) =
11643 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11644
11645 let panel = workspace.update_in(cx, |workspace, window, cx| {
11646 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11647 workspace.add_panel(panel.clone(), window, cx);
11648
11649 workspace
11650 .right_dock()
11651 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11652
11653 panel
11654 });
11655
11656 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11657 pane.update_in(cx, |pane, window, cx| {
11658 let item = cx.new(TestItem::new);
11659 pane.add_item(Box::new(item), true, true, None, window, cx);
11660 });
11661
11662 // Transfer focus from center to panel
11663 workspace.update_in(cx, |workspace, window, cx| {
11664 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11665 });
11666
11667 workspace.update_in(cx, |workspace, window, cx| {
11668 assert!(workspace.right_dock().read(cx).is_open());
11669 assert!(!panel.is_zoomed(window, cx));
11670 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11671 });
11672
11673 // Transfer focus from panel to center
11674 workspace.update_in(cx, |workspace, window, cx| {
11675 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11676 });
11677
11678 workspace.update_in(cx, |workspace, window, cx| {
11679 assert!(workspace.right_dock().read(cx).is_open());
11680 assert!(!panel.is_zoomed(window, cx));
11681 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11682 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11683 });
11684
11685 // Close the dock
11686 workspace.update_in(cx, |workspace, window, cx| {
11687 workspace.toggle_dock(DockPosition::Right, window, cx);
11688 });
11689
11690 workspace.update_in(cx, |workspace, window, cx| {
11691 assert!(!workspace.right_dock().read(cx).is_open());
11692 assert!(!panel.is_zoomed(window, cx));
11693 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11694 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11695 });
11696
11697 // Open the dock
11698 workspace.update_in(cx, |workspace, window, cx| {
11699 workspace.toggle_dock(DockPosition::Right, window, cx);
11700 });
11701
11702 workspace.update_in(cx, |workspace, window, cx| {
11703 assert!(workspace.right_dock().read(cx).is_open());
11704 assert!(!panel.is_zoomed(window, cx));
11705 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11706 });
11707
11708 // Focus and zoom panel
11709 panel.update_in(cx, |panel, window, cx| {
11710 cx.focus_self(window);
11711 panel.set_zoomed(true, window, cx)
11712 });
11713
11714 workspace.update_in(cx, |workspace, window, cx| {
11715 assert!(workspace.right_dock().read(cx).is_open());
11716 assert!(panel.is_zoomed(window, cx));
11717 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11718 });
11719
11720 // Transfer focus to the center closes the dock
11721 workspace.update_in(cx, |workspace, window, cx| {
11722 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11723 });
11724
11725 workspace.update_in(cx, |workspace, window, cx| {
11726 assert!(!workspace.right_dock().read(cx).is_open());
11727 assert!(panel.is_zoomed(window, cx));
11728 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11729 });
11730
11731 // Transferring focus back to the panel keeps it zoomed
11732 workspace.update_in(cx, |workspace, window, cx| {
11733 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11734 });
11735
11736 workspace.update_in(cx, |workspace, window, cx| {
11737 assert!(workspace.right_dock().read(cx).is_open());
11738 assert!(panel.is_zoomed(window, cx));
11739 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11740 });
11741
11742 // Close the dock while it is zoomed
11743 workspace.update_in(cx, |workspace, window, cx| {
11744 workspace.toggle_dock(DockPosition::Right, window, cx)
11745 });
11746
11747 workspace.update_in(cx, |workspace, window, cx| {
11748 assert!(!workspace.right_dock().read(cx).is_open());
11749 assert!(panel.is_zoomed(window, cx));
11750 assert!(workspace.zoomed.is_none());
11751 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11752 });
11753
11754 // Opening the dock, when it's zoomed, retains focus
11755 workspace.update_in(cx, |workspace, window, cx| {
11756 workspace.toggle_dock(DockPosition::Right, window, cx)
11757 });
11758
11759 workspace.update_in(cx, |workspace, window, cx| {
11760 assert!(workspace.right_dock().read(cx).is_open());
11761 assert!(panel.is_zoomed(window, cx));
11762 assert!(workspace.zoomed.is_some());
11763 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11764 });
11765
11766 // Unzoom and close the panel, zoom the active pane.
11767 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11768 workspace.update_in(cx, |workspace, window, cx| {
11769 workspace.toggle_dock(DockPosition::Right, window, cx)
11770 });
11771 pane.update_in(cx, |pane, window, cx| {
11772 pane.toggle_zoom(&Default::default(), window, cx)
11773 });
11774
11775 // Opening a dock unzooms the pane.
11776 workspace.update_in(cx, |workspace, window, cx| {
11777 workspace.toggle_dock(DockPosition::Right, window, cx)
11778 });
11779 workspace.update_in(cx, |workspace, window, cx| {
11780 let pane = pane.read(cx);
11781 assert!(!pane.is_zoomed());
11782 assert!(!pane.focus_handle(cx).is_focused(window));
11783 assert!(workspace.right_dock().read(cx).is_open());
11784 assert!(workspace.zoomed.is_none());
11785 });
11786 }
11787
11788 #[gpui::test]
11789 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11790 init_test(cx);
11791 let fs = FakeFs::new(cx.executor());
11792
11793 let project = Project::test(fs, [], cx).await;
11794 let (workspace, cx) =
11795 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11796
11797 let panel = workspace.update_in(cx, |workspace, window, cx| {
11798 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11799 workspace.add_panel(panel.clone(), window, cx);
11800 panel
11801 });
11802
11803 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11804 pane.update_in(cx, |pane, window, cx| {
11805 let item = cx.new(TestItem::new);
11806 pane.add_item(Box::new(item), true, true, None, window, cx);
11807 });
11808
11809 // Enable close_panel_on_toggle
11810 cx.update_global(|store: &mut SettingsStore, cx| {
11811 store.update_user_settings(cx, |settings| {
11812 settings.workspace.close_panel_on_toggle = Some(true);
11813 });
11814 });
11815
11816 // Panel starts closed. Toggling should open and focus it.
11817 workspace.update_in(cx, |workspace, window, cx| {
11818 assert!(!workspace.right_dock().read(cx).is_open());
11819 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11820 });
11821
11822 workspace.update_in(cx, |workspace, window, cx| {
11823 assert!(
11824 workspace.right_dock().read(cx).is_open(),
11825 "Dock should be open after toggling from center"
11826 );
11827 assert!(
11828 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11829 "Panel should be focused after toggling from center"
11830 );
11831 });
11832
11833 // Panel is open and focused. Toggling should close the panel and
11834 // return focus to the center.
11835 workspace.update_in(cx, |workspace, window, cx| {
11836 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11837 });
11838
11839 workspace.update_in(cx, |workspace, window, cx| {
11840 assert!(
11841 !workspace.right_dock().read(cx).is_open(),
11842 "Dock should be closed after toggling from focused panel"
11843 );
11844 assert!(
11845 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11846 "Panel should not be focused after toggling from focused panel"
11847 );
11848 });
11849
11850 // Open the dock and focus something else so the panel is open but not
11851 // focused. Toggling should focus the panel (not close it).
11852 workspace.update_in(cx, |workspace, window, cx| {
11853 workspace
11854 .right_dock()
11855 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11856 window.focus(&pane.read(cx).focus_handle(cx), cx);
11857 });
11858
11859 workspace.update_in(cx, |workspace, window, cx| {
11860 assert!(workspace.right_dock().read(cx).is_open());
11861 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11862 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11863 });
11864
11865 workspace.update_in(cx, |workspace, window, cx| {
11866 assert!(
11867 workspace.right_dock().read(cx).is_open(),
11868 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11869 );
11870 assert!(
11871 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11872 "Panel should be focused after toggling an open-but-unfocused panel"
11873 );
11874 });
11875
11876 // Now disable the setting and verify the original behavior: toggling
11877 // from a focused panel moves focus to center but leaves the dock open.
11878 cx.update_global(|store: &mut SettingsStore, cx| {
11879 store.update_user_settings(cx, |settings| {
11880 settings.workspace.close_panel_on_toggle = Some(false);
11881 });
11882 });
11883
11884 workspace.update_in(cx, |workspace, window, cx| {
11885 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11886 });
11887
11888 workspace.update_in(cx, |workspace, window, cx| {
11889 assert!(
11890 workspace.right_dock().read(cx).is_open(),
11891 "Dock should remain open when setting is disabled"
11892 );
11893 assert!(
11894 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11895 "Panel should not be focused after toggling with setting disabled"
11896 );
11897 });
11898 }
11899
11900 #[gpui::test]
11901 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11902 init_test(cx);
11903 let fs = FakeFs::new(cx.executor());
11904
11905 let project = Project::test(fs, [], cx).await;
11906 let (workspace, cx) =
11907 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11908
11909 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11910 workspace.active_pane().clone()
11911 });
11912
11913 // Add an item to the pane so it can be zoomed
11914 workspace.update_in(cx, |workspace, window, cx| {
11915 let item = cx.new(TestItem::new);
11916 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11917 });
11918
11919 // Initially not zoomed
11920 workspace.update_in(cx, |workspace, _window, cx| {
11921 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11922 assert!(
11923 workspace.zoomed.is_none(),
11924 "Workspace should track no zoomed pane"
11925 );
11926 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11927 });
11928
11929 // Zoom In
11930 pane.update_in(cx, |pane, window, cx| {
11931 pane.zoom_in(&crate::ZoomIn, window, cx);
11932 });
11933
11934 workspace.update_in(cx, |workspace, window, cx| {
11935 assert!(
11936 pane.read(cx).is_zoomed(),
11937 "Pane should be zoomed after ZoomIn"
11938 );
11939 assert!(
11940 workspace.zoomed.is_some(),
11941 "Workspace should track the zoomed pane"
11942 );
11943 assert!(
11944 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11945 "ZoomIn should focus the pane"
11946 );
11947 });
11948
11949 // Zoom In again is a no-op
11950 pane.update_in(cx, |pane, window, cx| {
11951 pane.zoom_in(&crate::ZoomIn, window, cx);
11952 });
11953
11954 workspace.update_in(cx, |workspace, window, cx| {
11955 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11956 assert!(
11957 workspace.zoomed.is_some(),
11958 "Workspace still tracks zoomed pane"
11959 );
11960 assert!(
11961 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11962 "Pane remains focused after repeated ZoomIn"
11963 );
11964 });
11965
11966 // Zoom Out
11967 pane.update_in(cx, |pane, window, cx| {
11968 pane.zoom_out(&crate::ZoomOut, window, cx);
11969 });
11970
11971 workspace.update_in(cx, |workspace, _window, cx| {
11972 assert!(
11973 !pane.read(cx).is_zoomed(),
11974 "Pane should unzoom after ZoomOut"
11975 );
11976 assert!(
11977 workspace.zoomed.is_none(),
11978 "Workspace clears zoom tracking after ZoomOut"
11979 );
11980 });
11981
11982 // Zoom Out again is a no-op
11983 pane.update_in(cx, |pane, window, cx| {
11984 pane.zoom_out(&crate::ZoomOut, window, cx);
11985 });
11986
11987 workspace.update_in(cx, |workspace, _window, cx| {
11988 assert!(
11989 !pane.read(cx).is_zoomed(),
11990 "Second ZoomOut keeps pane unzoomed"
11991 );
11992 assert!(
11993 workspace.zoomed.is_none(),
11994 "Workspace remains without zoomed pane"
11995 );
11996 });
11997 }
11998
11999 #[gpui::test]
12000 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
12001 init_test(cx);
12002 let fs = FakeFs::new(cx.executor());
12003
12004 let project = Project::test(fs, [], cx).await;
12005 let (workspace, cx) =
12006 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12007 workspace.update_in(cx, |workspace, window, cx| {
12008 // Open two docks
12009 let left_dock = workspace.dock_at_position(DockPosition::Left);
12010 let right_dock = workspace.dock_at_position(DockPosition::Right);
12011
12012 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12013 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12014
12015 assert!(left_dock.read(cx).is_open());
12016 assert!(right_dock.read(cx).is_open());
12017 });
12018
12019 workspace.update_in(cx, |workspace, window, cx| {
12020 // Toggle all docks - should close both
12021 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12022
12023 let left_dock = workspace.dock_at_position(DockPosition::Left);
12024 let right_dock = workspace.dock_at_position(DockPosition::Right);
12025 assert!(!left_dock.read(cx).is_open());
12026 assert!(!right_dock.read(cx).is_open());
12027 });
12028
12029 workspace.update_in(cx, |workspace, window, cx| {
12030 // Toggle again - should reopen both
12031 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12032
12033 let left_dock = workspace.dock_at_position(DockPosition::Left);
12034 let right_dock = workspace.dock_at_position(DockPosition::Right);
12035 assert!(left_dock.read(cx).is_open());
12036 assert!(right_dock.read(cx).is_open());
12037 });
12038 }
12039
12040 #[gpui::test]
12041 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
12042 init_test(cx);
12043 let fs = FakeFs::new(cx.executor());
12044
12045 let project = Project::test(fs, [], cx).await;
12046 let (workspace, cx) =
12047 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12048 workspace.update_in(cx, |workspace, window, cx| {
12049 // Open two docks
12050 let left_dock = workspace.dock_at_position(DockPosition::Left);
12051 let right_dock = workspace.dock_at_position(DockPosition::Right);
12052
12053 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12054 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12055
12056 assert!(left_dock.read(cx).is_open());
12057 assert!(right_dock.read(cx).is_open());
12058 });
12059
12060 workspace.update_in(cx, |workspace, window, cx| {
12061 // Close them manually
12062 workspace.toggle_dock(DockPosition::Left, window, cx);
12063 workspace.toggle_dock(DockPosition::Right, window, cx);
12064
12065 let left_dock = workspace.dock_at_position(DockPosition::Left);
12066 let right_dock = workspace.dock_at_position(DockPosition::Right);
12067 assert!(!left_dock.read(cx).is_open());
12068 assert!(!right_dock.read(cx).is_open());
12069 });
12070
12071 workspace.update_in(cx, |workspace, window, cx| {
12072 // Toggle all docks - only last closed (right dock) should reopen
12073 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12074
12075 let left_dock = workspace.dock_at_position(DockPosition::Left);
12076 let right_dock = workspace.dock_at_position(DockPosition::Right);
12077 assert!(!left_dock.read(cx).is_open());
12078 assert!(right_dock.read(cx).is_open());
12079 });
12080 }
12081
12082 #[gpui::test]
12083 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12084 init_test(cx);
12085 let fs = FakeFs::new(cx.executor());
12086 let project = Project::test(fs, [], cx).await;
12087 let (multi_workspace, cx) =
12088 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12089 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12090
12091 // Open two docks (left and right) with one panel each
12092 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12093 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12094 workspace.add_panel(left_panel.clone(), window, cx);
12095
12096 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12097 workspace.add_panel(right_panel.clone(), window, cx);
12098
12099 workspace.toggle_dock(DockPosition::Left, window, cx);
12100 workspace.toggle_dock(DockPosition::Right, window, cx);
12101
12102 // Verify initial state
12103 assert!(
12104 workspace.left_dock().read(cx).is_open(),
12105 "Left dock should be open"
12106 );
12107 assert_eq!(
12108 workspace
12109 .left_dock()
12110 .read(cx)
12111 .visible_panel()
12112 .unwrap()
12113 .panel_id(),
12114 left_panel.panel_id(),
12115 "Left panel should be visible in left dock"
12116 );
12117 assert!(
12118 workspace.right_dock().read(cx).is_open(),
12119 "Right dock should be open"
12120 );
12121 assert_eq!(
12122 workspace
12123 .right_dock()
12124 .read(cx)
12125 .visible_panel()
12126 .unwrap()
12127 .panel_id(),
12128 right_panel.panel_id(),
12129 "Right panel should be visible in right dock"
12130 );
12131 assert!(
12132 !workspace.bottom_dock().read(cx).is_open(),
12133 "Bottom dock should be closed"
12134 );
12135
12136 (left_panel, right_panel)
12137 });
12138
12139 // Focus the left panel and move it to the next position (bottom dock)
12140 workspace.update_in(cx, |workspace, window, cx| {
12141 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12142 assert!(
12143 left_panel.read(cx).focus_handle(cx).is_focused(window),
12144 "Left panel should be focused"
12145 );
12146 });
12147
12148 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12149
12150 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12151 workspace.update(cx, |workspace, cx| {
12152 assert!(
12153 !workspace.left_dock().read(cx).is_open(),
12154 "Left dock should be closed"
12155 );
12156 assert!(
12157 workspace.bottom_dock().read(cx).is_open(),
12158 "Bottom dock should now be open"
12159 );
12160 assert_eq!(
12161 left_panel.read(cx).position,
12162 DockPosition::Bottom,
12163 "Left panel should now be in the bottom dock"
12164 );
12165 assert_eq!(
12166 workspace
12167 .bottom_dock()
12168 .read(cx)
12169 .visible_panel()
12170 .unwrap()
12171 .panel_id(),
12172 left_panel.panel_id(),
12173 "Left panel should be the visible panel in the bottom dock"
12174 );
12175 });
12176
12177 // Toggle all docks off
12178 workspace.update_in(cx, |workspace, window, cx| {
12179 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12180 assert!(
12181 !workspace.left_dock().read(cx).is_open(),
12182 "Left dock should be closed"
12183 );
12184 assert!(
12185 !workspace.right_dock().read(cx).is_open(),
12186 "Right dock should be closed"
12187 );
12188 assert!(
12189 !workspace.bottom_dock().read(cx).is_open(),
12190 "Bottom dock should be closed"
12191 );
12192 });
12193
12194 // Toggle all docks back on and verify positions are restored
12195 workspace.update_in(cx, |workspace, window, cx| {
12196 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12197 assert!(
12198 !workspace.left_dock().read(cx).is_open(),
12199 "Left dock should remain closed"
12200 );
12201 assert!(
12202 workspace.right_dock().read(cx).is_open(),
12203 "Right dock should remain open"
12204 );
12205 assert!(
12206 workspace.bottom_dock().read(cx).is_open(),
12207 "Bottom dock should remain open"
12208 );
12209 assert_eq!(
12210 left_panel.read(cx).position,
12211 DockPosition::Bottom,
12212 "Left panel should remain in the bottom dock"
12213 );
12214 assert_eq!(
12215 right_panel.read(cx).position,
12216 DockPosition::Right,
12217 "Right panel should remain in the right dock"
12218 );
12219 assert_eq!(
12220 workspace
12221 .bottom_dock()
12222 .read(cx)
12223 .visible_panel()
12224 .unwrap()
12225 .panel_id(),
12226 left_panel.panel_id(),
12227 "Left panel should be the visible panel in the right dock"
12228 );
12229 });
12230 }
12231
12232 #[gpui::test]
12233 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12234 init_test(cx);
12235
12236 let fs = FakeFs::new(cx.executor());
12237
12238 let project = Project::test(fs, None, cx).await;
12239 let (workspace, cx) =
12240 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12241
12242 // Let's arrange the panes like this:
12243 //
12244 // +-----------------------+
12245 // | top |
12246 // +------+--------+-------+
12247 // | left | center | right |
12248 // +------+--------+-------+
12249 // | bottom |
12250 // +-----------------------+
12251
12252 let top_item = cx.new(|cx| {
12253 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12254 });
12255 let bottom_item = cx.new(|cx| {
12256 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12257 });
12258 let left_item = cx.new(|cx| {
12259 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12260 });
12261 let right_item = cx.new(|cx| {
12262 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12263 });
12264 let center_item = cx.new(|cx| {
12265 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12266 });
12267
12268 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12269 let top_pane_id = workspace.active_pane().entity_id();
12270 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12271 workspace.split_pane(
12272 workspace.active_pane().clone(),
12273 SplitDirection::Down,
12274 window,
12275 cx,
12276 );
12277 top_pane_id
12278 });
12279 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12280 let bottom_pane_id = workspace.active_pane().entity_id();
12281 workspace.add_item_to_active_pane(
12282 Box::new(bottom_item.clone()),
12283 None,
12284 false,
12285 window,
12286 cx,
12287 );
12288 workspace.split_pane(
12289 workspace.active_pane().clone(),
12290 SplitDirection::Up,
12291 window,
12292 cx,
12293 );
12294 bottom_pane_id
12295 });
12296 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12297 let left_pane_id = workspace.active_pane().entity_id();
12298 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12299 workspace.split_pane(
12300 workspace.active_pane().clone(),
12301 SplitDirection::Right,
12302 window,
12303 cx,
12304 );
12305 left_pane_id
12306 });
12307 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12308 let right_pane_id = workspace.active_pane().entity_id();
12309 workspace.add_item_to_active_pane(
12310 Box::new(right_item.clone()),
12311 None,
12312 false,
12313 window,
12314 cx,
12315 );
12316 workspace.split_pane(
12317 workspace.active_pane().clone(),
12318 SplitDirection::Left,
12319 window,
12320 cx,
12321 );
12322 right_pane_id
12323 });
12324 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12325 let center_pane_id = workspace.active_pane().entity_id();
12326 workspace.add_item_to_active_pane(
12327 Box::new(center_item.clone()),
12328 None,
12329 false,
12330 window,
12331 cx,
12332 );
12333 center_pane_id
12334 });
12335 cx.executor().run_until_parked();
12336
12337 workspace.update_in(cx, |workspace, window, cx| {
12338 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12339
12340 // Join into next from center pane into right
12341 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12342 });
12343
12344 workspace.update_in(cx, |workspace, window, cx| {
12345 let active_pane = workspace.active_pane();
12346 assert_eq!(right_pane_id, active_pane.entity_id());
12347 assert_eq!(2, active_pane.read(cx).items_len());
12348 let item_ids_in_pane =
12349 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12350 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12351 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12352
12353 // Join into next from right pane into bottom
12354 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12355 });
12356
12357 workspace.update_in(cx, |workspace, window, cx| {
12358 let active_pane = workspace.active_pane();
12359 assert_eq!(bottom_pane_id, active_pane.entity_id());
12360 assert_eq!(3, active_pane.read(cx).items_len());
12361 let item_ids_in_pane =
12362 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12363 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12364 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12365 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12366
12367 // Join into next from bottom pane into left
12368 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12369 });
12370
12371 workspace.update_in(cx, |workspace, window, cx| {
12372 let active_pane = workspace.active_pane();
12373 assert_eq!(left_pane_id, active_pane.entity_id());
12374 assert_eq!(4, active_pane.read(cx).items_len());
12375 let item_ids_in_pane =
12376 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12377 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12378 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12379 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12380 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12381
12382 // Join into next from left pane into top
12383 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12384 });
12385
12386 workspace.update_in(cx, |workspace, window, cx| {
12387 let active_pane = workspace.active_pane();
12388 assert_eq!(top_pane_id, active_pane.entity_id());
12389 assert_eq!(5, active_pane.read(cx).items_len());
12390 let item_ids_in_pane =
12391 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12392 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12393 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12394 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12395 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12396 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12397
12398 // Single pane left: no-op
12399 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12400 });
12401
12402 workspace.update(cx, |workspace, _cx| {
12403 let active_pane = workspace.active_pane();
12404 assert_eq!(top_pane_id, active_pane.entity_id());
12405 });
12406 }
12407
12408 fn add_an_item_to_active_pane(
12409 cx: &mut VisualTestContext,
12410 workspace: &Entity<Workspace>,
12411 item_id: u64,
12412 ) -> Entity<TestItem> {
12413 let item = cx.new(|cx| {
12414 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12415 item_id,
12416 "item{item_id}.txt",
12417 cx,
12418 )])
12419 });
12420 workspace.update_in(cx, |workspace, window, cx| {
12421 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12422 });
12423 item
12424 }
12425
12426 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12427 workspace.update_in(cx, |workspace, window, cx| {
12428 workspace.split_pane(
12429 workspace.active_pane().clone(),
12430 SplitDirection::Right,
12431 window,
12432 cx,
12433 )
12434 })
12435 }
12436
12437 #[gpui::test]
12438 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12439 init_test(cx);
12440 let fs = FakeFs::new(cx.executor());
12441 let project = Project::test(fs, None, cx).await;
12442 let (workspace, cx) =
12443 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12444
12445 add_an_item_to_active_pane(cx, &workspace, 1);
12446 split_pane(cx, &workspace);
12447 add_an_item_to_active_pane(cx, &workspace, 2);
12448 split_pane(cx, &workspace); // empty pane
12449 split_pane(cx, &workspace);
12450 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12451
12452 cx.executor().run_until_parked();
12453
12454 workspace.update(cx, |workspace, cx| {
12455 let num_panes = workspace.panes().len();
12456 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12457 let active_item = workspace
12458 .active_pane()
12459 .read(cx)
12460 .active_item()
12461 .expect("item is in focus");
12462
12463 assert_eq!(num_panes, 4);
12464 assert_eq!(num_items_in_current_pane, 1);
12465 assert_eq!(active_item.item_id(), last_item.item_id());
12466 });
12467
12468 workspace.update_in(cx, |workspace, window, cx| {
12469 workspace.join_all_panes(window, cx);
12470 });
12471
12472 workspace.update(cx, |workspace, cx| {
12473 let num_panes = workspace.panes().len();
12474 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12475 let active_item = workspace
12476 .active_pane()
12477 .read(cx)
12478 .active_item()
12479 .expect("item is in focus");
12480
12481 assert_eq!(num_panes, 1);
12482 assert_eq!(num_items_in_current_pane, 3);
12483 assert_eq!(active_item.item_id(), last_item.item_id());
12484 });
12485 }
12486
12487 #[gpui::test]
12488 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12489 init_test(cx);
12490 let fs = FakeFs::new(cx.executor());
12491
12492 let project = Project::test(fs, [], cx).await;
12493 let (multi_workspace, cx) =
12494 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12495 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12496
12497 workspace.update(cx, |workspace, _cx| {
12498 workspace.bounds.size.width = px(800.);
12499 });
12500
12501 workspace.update_in(cx, |workspace, window, cx| {
12502 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12503 workspace.add_panel(panel, window, cx);
12504 workspace.toggle_dock(DockPosition::Right, window, cx);
12505 });
12506
12507 let (panel, resized_width, ratio_basis_width) =
12508 workspace.update_in(cx, |workspace, window, cx| {
12509 let item = cx.new(|cx| {
12510 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12511 });
12512 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12513
12514 let dock = workspace.right_dock().read(cx);
12515 let workspace_width = workspace.bounds.size.width;
12516 let initial_width = workspace
12517 .dock_size(&dock, window, cx)
12518 .expect("flexible dock should have an initial width");
12519
12520 assert_eq!(initial_width, workspace_width / 2.);
12521
12522 workspace.resize_right_dock(px(300.), window, cx);
12523
12524 let dock = workspace.right_dock().read(cx);
12525 let resized_width = workspace
12526 .dock_size(&dock, window, cx)
12527 .expect("flexible dock should keep its resized width");
12528
12529 assert_eq!(resized_width, px(300.));
12530
12531 let panel = workspace
12532 .right_dock()
12533 .read(cx)
12534 .visible_panel()
12535 .expect("flexible dock should have a visible panel")
12536 .panel_id();
12537
12538 (panel, resized_width, workspace_width)
12539 });
12540
12541 workspace.update_in(cx, |workspace, window, cx| {
12542 workspace.toggle_dock(DockPosition::Right, window, cx);
12543 workspace.toggle_dock(DockPosition::Right, window, cx);
12544
12545 let dock = workspace.right_dock().read(cx);
12546 let reopened_width = workspace
12547 .dock_size(&dock, window, cx)
12548 .expect("flexible dock should restore when reopened");
12549
12550 assert_eq!(reopened_width, resized_width);
12551
12552 let right_dock = workspace.right_dock().read(cx);
12553 let flexible_panel = right_dock
12554 .visible_panel()
12555 .expect("flexible dock should still have a visible panel");
12556 assert_eq!(flexible_panel.panel_id(), panel);
12557 assert_eq!(
12558 right_dock
12559 .stored_panel_size_state(flexible_panel.as_ref())
12560 .and_then(|size_state| size_state.flex),
12561 Some(
12562 resized_width.to_f64() as f32
12563 / (workspace.bounds.size.width - resized_width).to_f64() as f32
12564 )
12565 );
12566 });
12567
12568 workspace.update_in(cx, |workspace, window, cx| {
12569 workspace.split_pane(
12570 workspace.active_pane().clone(),
12571 SplitDirection::Right,
12572 window,
12573 cx,
12574 );
12575
12576 let dock = workspace.right_dock().read(cx);
12577 let split_width = workspace
12578 .dock_size(&dock, window, cx)
12579 .expect("flexible dock should keep its user-resized proportion");
12580
12581 assert_eq!(split_width, px(300.));
12582
12583 workspace.bounds.size.width = px(1600.);
12584
12585 let dock = workspace.right_dock().read(cx);
12586 let resized_window_width = workspace
12587 .dock_size(&dock, window, cx)
12588 .expect("flexible dock should preserve proportional size on window resize");
12589
12590 assert_eq!(
12591 resized_window_width,
12592 workspace.bounds.size.width
12593 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12594 );
12595 });
12596 }
12597
12598 #[gpui::test]
12599 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12600 init_test(cx);
12601 let fs = FakeFs::new(cx.executor());
12602
12603 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12604 {
12605 let project = Project::test(fs.clone(), [], cx).await;
12606 let (multi_workspace, cx) =
12607 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12608 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12609
12610 workspace.update(cx, |workspace, _cx| {
12611 workspace.set_random_database_id();
12612 workspace.bounds.size.width = px(800.);
12613 });
12614
12615 let panel = workspace.update_in(cx, |workspace, window, cx| {
12616 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12617 workspace.add_panel(panel.clone(), window, cx);
12618 workspace.toggle_dock(DockPosition::Left, window, cx);
12619 panel
12620 });
12621
12622 workspace.update_in(cx, |workspace, window, cx| {
12623 workspace.resize_left_dock(px(350.), window, cx);
12624 });
12625
12626 cx.run_until_parked();
12627
12628 let persisted = workspace.read_with(cx, |workspace, cx| {
12629 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12630 });
12631 assert_eq!(
12632 persisted.and_then(|s| s.size),
12633 Some(px(350.)),
12634 "fixed-width panel size should be persisted to KVP"
12635 );
12636
12637 // Remove the panel and re-add a fresh instance with the same key.
12638 // The new instance should have its size state restored from KVP.
12639 workspace.update_in(cx, |workspace, window, cx| {
12640 workspace.remove_panel(&panel, window, cx);
12641 });
12642
12643 workspace.update_in(cx, |workspace, window, cx| {
12644 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12645 workspace.add_panel(new_panel, window, cx);
12646
12647 let left_dock = workspace.left_dock().read(cx);
12648 let size_state = left_dock
12649 .panel::<TestPanel>()
12650 .and_then(|p| left_dock.stored_panel_size_state(&p));
12651 assert_eq!(
12652 size_state.and_then(|s| s.size),
12653 Some(px(350.)),
12654 "re-added fixed-width panel should restore persisted size from KVP"
12655 );
12656 });
12657 }
12658
12659 // Flexible panel: both pixel size and ratio are persisted and restored.
12660 {
12661 let project = Project::test(fs.clone(), [], cx).await;
12662 let (multi_workspace, cx) =
12663 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12664 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12665
12666 workspace.update(cx, |workspace, _cx| {
12667 workspace.set_random_database_id();
12668 workspace.bounds.size.width = px(800.);
12669 });
12670
12671 let panel = workspace.update_in(cx, |workspace, window, cx| {
12672 let item = cx.new(|cx| {
12673 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12674 });
12675 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12676
12677 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12678 workspace.add_panel(panel.clone(), window, cx);
12679 workspace.toggle_dock(DockPosition::Right, window, cx);
12680 panel
12681 });
12682
12683 workspace.update_in(cx, |workspace, window, cx| {
12684 workspace.resize_right_dock(px(300.), window, cx);
12685 });
12686
12687 cx.run_until_parked();
12688
12689 let persisted = workspace
12690 .read_with(cx, |workspace, cx| {
12691 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12692 })
12693 .expect("flexible panel state should be persisted to KVP");
12694 assert_eq!(
12695 persisted.size, None,
12696 "flexible panel should not persist a redundant pixel size"
12697 );
12698 let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12699
12700 // Remove the panel and re-add: both size and ratio should be restored.
12701 workspace.update_in(cx, |workspace, window, cx| {
12702 workspace.remove_panel(&panel, window, cx);
12703 });
12704
12705 workspace.update_in(cx, |workspace, window, cx| {
12706 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12707 workspace.add_panel(new_panel, window, cx);
12708
12709 let right_dock = workspace.right_dock().read(cx);
12710 let size_state = right_dock
12711 .panel::<TestPanel>()
12712 .and_then(|p| right_dock.stored_panel_size_state(&p))
12713 .expect("re-added flexible panel should have restored size state from KVP");
12714 assert_eq!(
12715 size_state.size, None,
12716 "re-added flexible panel should not have a persisted pixel size"
12717 );
12718 assert_eq!(
12719 size_state.flex,
12720 Some(original_ratio),
12721 "re-added flexible panel should restore persisted flex"
12722 );
12723 });
12724 }
12725 }
12726
12727 #[gpui::test]
12728 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12729 init_test(cx);
12730 let fs = FakeFs::new(cx.executor());
12731
12732 let project = Project::test(fs, [], cx).await;
12733 let (multi_workspace, cx) =
12734 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12735 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12736
12737 workspace.update(cx, |workspace, _cx| {
12738 workspace.bounds.size.width = px(900.);
12739 });
12740
12741 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12742 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12743 // and the center pane each take half the workspace width.
12744 workspace.update_in(cx, |workspace, window, cx| {
12745 let item = cx.new(|cx| {
12746 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12747 });
12748 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12749
12750 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12751 workspace.add_panel(panel, window, cx);
12752 workspace.toggle_dock(DockPosition::Left, window, cx);
12753
12754 let left_dock = workspace.left_dock().read(cx);
12755 let left_width = workspace
12756 .dock_size(&left_dock, window, cx)
12757 .expect("left dock should have an active panel");
12758
12759 assert_eq!(
12760 left_width,
12761 workspace.bounds.size.width / 2.,
12762 "flexible left panel should split evenly with the center pane"
12763 );
12764 });
12765
12766 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12767 // change horizontal width fractions, so the flexible panel stays at the same
12768 // width as each half of the split.
12769 workspace.update_in(cx, |workspace, window, cx| {
12770 workspace.split_pane(
12771 workspace.active_pane().clone(),
12772 SplitDirection::Down,
12773 window,
12774 cx,
12775 );
12776
12777 let left_dock = workspace.left_dock().read(cx);
12778 let left_width = workspace
12779 .dock_size(&left_dock, window, cx)
12780 .expect("left dock should still have an active panel after vertical split");
12781
12782 assert_eq!(
12783 left_width,
12784 workspace.bounds.size.width / 2.,
12785 "flexible left panel width should match each vertically-split pane"
12786 );
12787 });
12788
12789 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12790 // size reduces the available width, so the flexible left panel and the center
12791 // panes all shrink proportionally to accommodate it.
12792 workspace.update_in(cx, |workspace, window, cx| {
12793 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12794 workspace.add_panel(panel, window, cx);
12795 workspace.toggle_dock(DockPosition::Right, window, cx);
12796
12797 let right_dock = workspace.right_dock().read(cx);
12798 let right_width = workspace
12799 .dock_size(&right_dock, window, cx)
12800 .expect("right dock should have an active panel");
12801
12802 let left_dock = workspace.left_dock().read(cx);
12803 let left_width = workspace
12804 .dock_size(&left_dock, window, cx)
12805 .expect("left dock should still have an active panel");
12806
12807 let available_width = workspace.bounds.size.width - right_width;
12808 assert_eq!(
12809 left_width,
12810 available_width / 2.,
12811 "flexible left panel should shrink proportionally as the right dock takes space"
12812 );
12813 });
12814
12815 // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12816 // flex sizing and the workspace width is divided among left-flex, center
12817 // (implicit flex 1.0), and right-flex.
12818 workspace.update_in(cx, |workspace, window, cx| {
12819 let right_dock = workspace.right_dock().clone();
12820 let right_panel = right_dock
12821 .read(cx)
12822 .visible_panel()
12823 .expect("right dock should have a visible panel")
12824 .clone();
12825 workspace.toggle_dock_panel_flexible_size(
12826 &right_dock,
12827 right_panel.as_ref(),
12828 window,
12829 cx,
12830 );
12831
12832 let right_dock = right_dock.read(cx);
12833 let right_panel = right_dock
12834 .visible_panel()
12835 .expect("right dock should still have a visible panel");
12836 assert!(
12837 right_panel.has_flexible_size(window, cx),
12838 "right panel should now be flexible"
12839 );
12840
12841 let right_size_state = right_dock
12842 .stored_panel_size_state(right_panel.as_ref())
12843 .expect("right panel should have a stored size state after toggling");
12844 let right_flex = right_size_state
12845 .flex
12846 .expect("right panel should have a flex value after toggling");
12847
12848 let left_dock = workspace.left_dock().read(cx);
12849 let left_width = workspace
12850 .dock_size(&left_dock, window, cx)
12851 .expect("left dock should still have an active panel");
12852 let right_width = workspace
12853 .dock_size(&right_dock, window, cx)
12854 .expect("right dock should still have an active panel");
12855
12856 let left_flex = workspace
12857 .default_dock_flex(DockPosition::Left)
12858 .expect("left dock should have a default flex");
12859
12860 let total_flex = left_flex + 1.0 + right_flex;
12861 let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12862 let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12863 assert_eq!(
12864 left_width, expected_left,
12865 "flexible left panel should share workspace width via flex ratios"
12866 );
12867 assert_eq!(
12868 right_width, expected_right,
12869 "flexible right panel should share workspace width via flex ratios"
12870 );
12871 });
12872 }
12873
12874 struct TestModal(FocusHandle);
12875
12876 impl TestModal {
12877 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12878 Self(cx.focus_handle())
12879 }
12880 }
12881
12882 impl EventEmitter<DismissEvent> for TestModal {}
12883
12884 impl Focusable for TestModal {
12885 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12886 self.0.clone()
12887 }
12888 }
12889
12890 impl ModalView for TestModal {}
12891
12892 impl Render for TestModal {
12893 fn render(
12894 &mut self,
12895 _window: &mut Window,
12896 _cx: &mut Context<TestModal>,
12897 ) -> impl IntoElement {
12898 div().track_focus(&self.0)
12899 }
12900 }
12901
12902 #[gpui::test]
12903 async fn test_panels(cx: &mut gpui::TestAppContext) {
12904 init_test(cx);
12905 let fs = FakeFs::new(cx.executor());
12906
12907 let project = Project::test(fs, [], cx).await;
12908 let (multi_workspace, cx) =
12909 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12910 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12911
12912 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12913 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12914 workspace.add_panel(panel_1.clone(), window, cx);
12915 workspace.toggle_dock(DockPosition::Left, window, cx);
12916 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12917 workspace.add_panel(panel_2.clone(), window, cx);
12918 workspace.toggle_dock(DockPosition::Right, window, cx);
12919
12920 let left_dock = workspace.left_dock();
12921 assert_eq!(
12922 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12923 panel_1.panel_id()
12924 );
12925 assert_eq!(
12926 workspace.dock_size(&left_dock.read(cx), window, cx),
12927 Some(px(300.))
12928 );
12929
12930 workspace.resize_left_dock(px(1337.), window, cx);
12931 assert_eq!(
12932 workspace
12933 .right_dock()
12934 .read(cx)
12935 .visible_panel()
12936 .unwrap()
12937 .panel_id(),
12938 panel_2.panel_id(),
12939 );
12940
12941 (panel_1, panel_2)
12942 });
12943
12944 // Move panel_1 to the right
12945 panel_1.update_in(cx, |panel_1, window, cx| {
12946 panel_1.set_position(DockPosition::Right, window, cx)
12947 });
12948
12949 workspace.update_in(cx, |workspace, window, cx| {
12950 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12951 // Since it was the only panel on the left, the left dock should now be closed.
12952 assert!(!workspace.left_dock().read(cx).is_open());
12953 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12954 let right_dock = workspace.right_dock();
12955 assert_eq!(
12956 right_dock.read(cx).visible_panel().unwrap().panel_id(),
12957 panel_1.panel_id()
12958 );
12959 assert_eq!(
12960 right_dock
12961 .read(cx)
12962 .active_panel_size()
12963 .unwrap()
12964 .size
12965 .unwrap(),
12966 px(1337.)
12967 );
12968
12969 // Now we move panel_2 to the left
12970 panel_2.set_position(DockPosition::Left, window, cx);
12971 });
12972
12973 workspace.update(cx, |workspace, cx| {
12974 // Since panel_2 was not visible on the right, we don't open the left dock.
12975 assert!(!workspace.left_dock().read(cx).is_open());
12976 // And the right dock is unaffected in its displaying of panel_1
12977 assert!(workspace.right_dock().read(cx).is_open());
12978 assert_eq!(
12979 workspace
12980 .right_dock()
12981 .read(cx)
12982 .visible_panel()
12983 .unwrap()
12984 .panel_id(),
12985 panel_1.panel_id(),
12986 );
12987 });
12988
12989 // Move panel_1 back to the left
12990 panel_1.update_in(cx, |panel_1, window, cx| {
12991 panel_1.set_position(DockPosition::Left, window, cx)
12992 });
12993
12994 workspace.update_in(cx, |workspace, window, cx| {
12995 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12996 let left_dock = workspace.left_dock();
12997 assert!(left_dock.read(cx).is_open());
12998 assert_eq!(
12999 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13000 panel_1.panel_id()
13001 );
13002 assert_eq!(
13003 workspace.dock_size(&left_dock.read(cx), window, cx),
13004 Some(px(1337.))
13005 );
13006 // And the right dock should be closed as it no longer has any panels.
13007 assert!(!workspace.right_dock().read(cx).is_open());
13008
13009 // Now we move panel_1 to the bottom
13010 panel_1.set_position(DockPosition::Bottom, window, cx);
13011 });
13012
13013 workspace.update_in(cx, |workspace, window, cx| {
13014 // Since panel_1 was visible on the left, we close the left dock.
13015 assert!(!workspace.left_dock().read(cx).is_open());
13016 // The bottom dock is sized based on the panel's default size,
13017 // since the panel orientation changed from vertical to horizontal.
13018 let bottom_dock = workspace.bottom_dock();
13019 assert_eq!(
13020 workspace.dock_size(&bottom_dock.read(cx), window, cx),
13021 Some(px(300.))
13022 );
13023 // Close bottom dock and move panel_1 back to the left.
13024 bottom_dock.update(cx, |bottom_dock, cx| {
13025 bottom_dock.set_open(false, window, cx)
13026 });
13027 panel_1.set_position(DockPosition::Left, window, cx);
13028 });
13029
13030 // Emit activated event on panel 1
13031 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
13032
13033 // Now the left dock is open and panel_1 is active and focused.
13034 workspace.update_in(cx, |workspace, window, cx| {
13035 let left_dock = workspace.left_dock();
13036 assert!(left_dock.read(cx).is_open());
13037 assert_eq!(
13038 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13039 panel_1.panel_id(),
13040 );
13041 assert!(panel_1.focus_handle(cx).is_focused(window));
13042 });
13043
13044 // Emit closed event on panel 2, which is not active
13045 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13046
13047 // Wo don't close the left dock, because panel_2 wasn't the active panel
13048 workspace.update(cx, |workspace, cx| {
13049 let left_dock = workspace.left_dock();
13050 assert!(left_dock.read(cx).is_open());
13051 assert_eq!(
13052 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13053 panel_1.panel_id(),
13054 );
13055 });
13056
13057 // Emitting a ZoomIn event shows the panel as zoomed.
13058 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13059 workspace.read_with(cx, |workspace, _| {
13060 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13061 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13062 });
13063
13064 // Move panel to another dock while it is zoomed
13065 panel_1.update_in(cx, |panel, window, cx| {
13066 panel.set_position(DockPosition::Right, window, cx)
13067 });
13068 workspace.read_with(cx, |workspace, _| {
13069 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13070
13071 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13072 });
13073
13074 // This is a helper for getting a:
13075 // - valid focus on an element,
13076 // - that isn't a part of the panes and panels system of the Workspace,
13077 // - and doesn't trigger the 'on_focus_lost' API.
13078 let focus_other_view = {
13079 let workspace = workspace.clone();
13080 move |cx: &mut VisualTestContext| {
13081 workspace.update_in(cx, |workspace, window, cx| {
13082 if workspace.active_modal::<TestModal>(cx).is_some() {
13083 workspace.toggle_modal(window, cx, TestModal::new);
13084 workspace.toggle_modal(window, cx, TestModal::new);
13085 } else {
13086 workspace.toggle_modal(window, cx, TestModal::new);
13087 }
13088 })
13089 }
13090 };
13091
13092 // If focus is transferred to another view that's not a panel or another pane, we still show
13093 // the panel as zoomed.
13094 focus_other_view(cx);
13095 workspace.read_with(cx, |workspace, _| {
13096 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13097 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13098 });
13099
13100 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13101 workspace.update_in(cx, |_workspace, window, cx| {
13102 cx.focus_self(window);
13103 });
13104 workspace.read_with(cx, |workspace, _| {
13105 assert_eq!(workspace.zoomed, None);
13106 assert_eq!(workspace.zoomed_position, None);
13107 });
13108
13109 // If focus is transferred again to another view that's not a panel or a pane, we won't
13110 // show the panel as zoomed because it wasn't zoomed before.
13111 focus_other_view(cx);
13112 workspace.read_with(cx, |workspace, _| {
13113 assert_eq!(workspace.zoomed, None);
13114 assert_eq!(workspace.zoomed_position, None);
13115 });
13116
13117 // When the panel is activated, it is zoomed again.
13118 cx.dispatch_action(ToggleRightDock);
13119 workspace.read_with(cx, |workspace, _| {
13120 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13121 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13122 });
13123
13124 // Emitting a ZoomOut event unzooms the panel.
13125 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13126 workspace.read_with(cx, |workspace, _| {
13127 assert_eq!(workspace.zoomed, None);
13128 assert_eq!(workspace.zoomed_position, None);
13129 });
13130
13131 // Emit closed event on panel 1, which is active
13132 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13133
13134 // Now the left dock is closed, because panel_1 was the active panel
13135 workspace.update(cx, |workspace, cx| {
13136 let right_dock = workspace.right_dock();
13137 assert!(!right_dock.read(cx).is_open());
13138 });
13139 }
13140
13141 #[gpui::test]
13142 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13143 init_test(cx);
13144
13145 let fs = FakeFs::new(cx.background_executor.clone());
13146 let project = Project::test(fs, [], cx).await;
13147 let (workspace, cx) =
13148 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13149 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13150
13151 let dirty_regular_buffer = cx.new(|cx| {
13152 TestItem::new(cx)
13153 .with_dirty(true)
13154 .with_label("1.txt")
13155 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13156 });
13157 let dirty_regular_buffer_2 = cx.new(|cx| {
13158 TestItem::new(cx)
13159 .with_dirty(true)
13160 .with_label("2.txt")
13161 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13162 });
13163 let dirty_multi_buffer_with_both = cx.new(|cx| {
13164 TestItem::new(cx)
13165 .with_dirty(true)
13166 .with_buffer_kind(ItemBufferKind::Multibuffer)
13167 .with_label("Fake Project Search")
13168 .with_project_items(&[
13169 dirty_regular_buffer.read(cx).project_items[0].clone(),
13170 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13171 ])
13172 });
13173 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13174 workspace.update_in(cx, |workspace, window, cx| {
13175 workspace.add_item(
13176 pane.clone(),
13177 Box::new(dirty_regular_buffer.clone()),
13178 None,
13179 false,
13180 false,
13181 window,
13182 cx,
13183 );
13184 workspace.add_item(
13185 pane.clone(),
13186 Box::new(dirty_regular_buffer_2.clone()),
13187 None,
13188 false,
13189 false,
13190 window,
13191 cx,
13192 );
13193 workspace.add_item(
13194 pane.clone(),
13195 Box::new(dirty_multi_buffer_with_both.clone()),
13196 None,
13197 false,
13198 false,
13199 window,
13200 cx,
13201 );
13202 });
13203
13204 pane.update_in(cx, |pane, window, cx| {
13205 pane.activate_item(2, true, true, window, cx);
13206 assert_eq!(
13207 pane.active_item().unwrap().item_id(),
13208 multi_buffer_with_both_files_id,
13209 "Should select the multi buffer in the pane"
13210 );
13211 });
13212 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13213 pane.close_other_items(
13214 &CloseOtherItems {
13215 save_intent: Some(SaveIntent::Save),
13216 close_pinned: true,
13217 },
13218 None,
13219 window,
13220 cx,
13221 )
13222 });
13223 cx.background_executor.run_until_parked();
13224 assert!(!cx.has_pending_prompt());
13225 close_all_but_multi_buffer_task
13226 .await
13227 .expect("Closing all buffers but the multi buffer failed");
13228 pane.update(cx, |pane, cx| {
13229 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13230 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13231 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13232 assert_eq!(pane.items_len(), 1);
13233 assert_eq!(
13234 pane.active_item().unwrap().item_id(),
13235 multi_buffer_with_both_files_id,
13236 "Should have only the multi buffer left in the pane"
13237 );
13238 assert!(
13239 dirty_multi_buffer_with_both.read(cx).is_dirty,
13240 "The multi buffer containing the unsaved buffer should still be dirty"
13241 );
13242 });
13243
13244 dirty_regular_buffer.update(cx, |buffer, cx| {
13245 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13246 });
13247
13248 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13249 pane.close_active_item(
13250 &CloseActiveItem {
13251 save_intent: Some(SaveIntent::Close),
13252 close_pinned: false,
13253 },
13254 window,
13255 cx,
13256 )
13257 });
13258 cx.background_executor.run_until_parked();
13259 assert!(
13260 cx.has_pending_prompt(),
13261 "Dirty multi buffer should prompt a save dialog"
13262 );
13263 cx.simulate_prompt_answer("Save");
13264 cx.background_executor.run_until_parked();
13265 close_multi_buffer_task
13266 .await
13267 .expect("Closing the multi buffer failed");
13268 pane.update(cx, |pane, cx| {
13269 assert_eq!(
13270 dirty_multi_buffer_with_both.read(cx).save_count,
13271 1,
13272 "Multi buffer item should get be saved"
13273 );
13274 // Test impl does not save inner items, so we do not assert them
13275 assert_eq!(
13276 pane.items_len(),
13277 0,
13278 "No more items should be left in the pane"
13279 );
13280 assert!(pane.active_item().is_none());
13281 });
13282 }
13283
13284 #[gpui::test]
13285 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13286 cx: &mut TestAppContext,
13287 ) {
13288 init_test(cx);
13289
13290 let fs = FakeFs::new(cx.background_executor.clone());
13291 let project = Project::test(fs, [], cx).await;
13292 let (workspace, cx) =
13293 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13294 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13295
13296 let dirty_regular_buffer = cx.new(|cx| {
13297 TestItem::new(cx)
13298 .with_dirty(true)
13299 .with_label("1.txt")
13300 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13301 });
13302 let dirty_regular_buffer_2 = cx.new(|cx| {
13303 TestItem::new(cx)
13304 .with_dirty(true)
13305 .with_label("2.txt")
13306 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13307 });
13308 let clear_regular_buffer = cx.new(|cx| {
13309 TestItem::new(cx)
13310 .with_label("3.txt")
13311 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13312 });
13313
13314 let dirty_multi_buffer_with_both = cx.new(|cx| {
13315 TestItem::new(cx)
13316 .with_dirty(true)
13317 .with_buffer_kind(ItemBufferKind::Multibuffer)
13318 .with_label("Fake Project Search")
13319 .with_project_items(&[
13320 dirty_regular_buffer.read(cx).project_items[0].clone(),
13321 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13322 clear_regular_buffer.read(cx).project_items[0].clone(),
13323 ])
13324 });
13325 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13326 workspace.update_in(cx, |workspace, window, cx| {
13327 workspace.add_item(
13328 pane.clone(),
13329 Box::new(dirty_regular_buffer.clone()),
13330 None,
13331 false,
13332 false,
13333 window,
13334 cx,
13335 );
13336 workspace.add_item(
13337 pane.clone(),
13338 Box::new(dirty_multi_buffer_with_both.clone()),
13339 None,
13340 false,
13341 false,
13342 window,
13343 cx,
13344 );
13345 });
13346
13347 pane.update_in(cx, |pane, window, cx| {
13348 pane.activate_item(1, true, true, window, cx);
13349 assert_eq!(
13350 pane.active_item().unwrap().item_id(),
13351 multi_buffer_with_both_files_id,
13352 "Should select the multi buffer in the pane"
13353 );
13354 });
13355 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13356 pane.close_active_item(
13357 &CloseActiveItem {
13358 save_intent: None,
13359 close_pinned: false,
13360 },
13361 window,
13362 cx,
13363 )
13364 });
13365 cx.background_executor.run_until_parked();
13366 assert!(
13367 cx.has_pending_prompt(),
13368 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13369 );
13370 }
13371
13372 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13373 /// closed when they are deleted from disk.
13374 #[gpui::test]
13375 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13376 init_test(cx);
13377
13378 // Enable the close_on_disk_deletion setting
13379 cx.update_global(|store: &mut SettingsStore, cx| {
13380 store.update_user_settings(cx, |settings| {
13381 settings.workspace.close_on_file_delete = Some(true);
13382 });
13383 });
13384
13385 let fs = FakeFs::new(cx.background_executor.clone());
13386 let project = Project::test(fs, [], cx).await;
13387 let (workspace, cx) =
13388 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13389 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13390
13391 // Create a test item that simulates a file
13392 let item = cx.new(|cx| {
13393 TestItem::new(cx)
13394 .with_label("test.txt")
13395 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13396 });
13397
13398 // Add item to workspace
13399 workspace.update_in(cx, |workspace, window, cx| {
13400 workspace.add_item(
13401 pane.clone(),
13402 Box::new(item.clone()),
13403 None,
13404 false,
13405 false,
13406 window,
13407 cx,
13408 );
13409 });
13410
13411 // Verify the item is in the pane
13412 pane.read_with(cx, |pane, _| {
13413 assert_eq!(pane.items().count(), 1);
13414 });
13415
13416 // Simulate file deletion by setting the item's deleted state
13417 item.update(cx, |item, _| {
13418 item.set_has_deleted_file(true);
13419 });
13420
13421 // Emit UpdateTab event to trigger the close behavior
13422 cx.run_until_parked();
13423 item.update(cx, |_, cx| {
13424 cx.emit(ItemEvent::UpdateTab);
13425 });
13426
13427 // Allow the close operation to complete
13428 cx.run_until_parked();
13429
13430 // Verify the item was automatically closed
13431 pane.read_with(cx, |pane, _| {
13432 assert_eq!(
13433 pane.items().count(),
13434 0,
13435 "Item should be automatically closed when file is deleted"
13436 );
13437 });
13438 }
13439
13440 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13441 /// open with a strikethrough when they are deleted from disk.
13442 #[gpui::test]
13443 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13444 init_test(cx);
13445
13446 // Ensure close_on_disk_deletion is disabled (default)
13447 cx.update_global(|store: &mut SettingsStore, cx| {
13448 store.update_user_settings(cx, |settings| {
13449 settings.workspace.close_on_file_delete = Some(false);
13450 });
13451 });
13452
13453 let fs = FakeFs::new(cx.background_executor.clone());
13454 let project = Project::test(fs, [], cx).await;
13455 let (workspace, cx) =
13456 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13457 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13458
13459 // Create a test item that simulates a file
13460 let item = cx.new(|cx| {
13461 TestItem::new(cx)
13462 .with_label("test.txt")
13463 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13464 });
13465
13466 // Add item to workspace
13467 workspace.update_in(cx, |workspace, window, cx| {
13468 workspace.add_item(
13469 pane.clone(),
13470 Box::new(item.clone()),
13471 None,
13472 false,
13473 false,
13474 window,
13475 cx,
13476 );
13477 });
13478
13479 // Verify the item is in the pane
13480 pane.read_with(cx, |pane, _| {
13481 assert_eq!(pane.items().count(), 1);
13482 });
13483
13484 // Simulate file deletion
13485 item.update(cx, |item, _| {
13486 item.set_has_deleted_file(true);
13487 });
13488
13489 // Emit UpdateTab event
13490 cx.run_until_parked();
13491 item.update(cx, |_, cx| {
13492 cx.emit(ItemEvent::UpdateTab);
13493 });
13494
13495 // Allow any potential close operation to complete
13496 cx.run_until_parked();
13497
13498 // Verify the item remains open (with strikethrough)
13499 pane.read_with(cx, |pane, _| {
13500 assert_eq!(
13501 pane.items().count(),
13502 1,
13503 "Item should remain open when close_on_disk_deletion is disabled"
13504 );
13505 });
13506
13507 // Verify the item shows as deleted
13508 item.read_with(cx, |item, _| {
13509 assert!(
13510 item.has_deleted_file,
13511 "Item should be marked as having deleted file"
13512 );
13513 });
13514 }
13515
13516 /// Tests that dirty files are not automatically closed when deleted from disk,
13517 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13518 /// unsaved changes without being prompted.
13519 #[gpui::test]
13520 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13521 init_test(cx);
13522
13523 // Enable the close_on_file_delete setting
13524 cx.update_global(|store: &mut SettingsStore, cx| {
13525 store.update_user_settings(cx, |settings| {
13526 settings.workspace.close_on_file_delete = Some(true);
13527 });
13528 });
13529
13530 let fs = FakeFs::new(cx.background_executor.clone());
13531 let project = Project::test(fs, [], cx).await;
13532 let (workspace, cx) =
13533 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13534 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13535
13536 // Create a dirty test item
13537 let item = cx.new(|cx| {
13538 TestItem::new(cx)
13539 .with_dirty(true)
13540 .with_label("test.txt")
13541 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13542 });
13543
13544 // Add item to workspace
13545 workspace.update_in(cx, |workspace, window, cx| {
13546 workspace.add_item(
13547 pane.clone(),
13548 Box::new(item.clone()),
13549 None,
13550 false,
13551 false,
13552 window,
13553 cx,
13554 );
13555 });
13556
13557 // Simulate file deletion
13558 item.update(cx, |item, _| {
13559 item.set_has_deleted_file(true);
13560 });
13561
13562 // Emit UpdateTab event to trigger the close behavior
13563 cx.run_until_parked();
13564 item.update(cx, |_, cx| {
13565 cx.emit(ItemEvent::UpdateTab);
13566 });
13567
13568 // Allow any potential close operation to complete
13569 cx.run_until_parked();
13570
13571 // Verify the item remains open (dirty files are not auto-closed)
13572 pane.read_with(cx, |pane, _| {
13573 assert_eq!(
13574 pane.items().count(),
13575 1,
13576 "Dirty items should not be automatically closed even when file is deleted"
13577 );
13578 });
13579
13580 // Verify the item is marked as deleted and still dirty
13581 item.read_with(cx, |item, _| {
13582 assert!(
13583 item.has_deleted_file,
13584 "Item should be marked as having deleted file"
13585 );
13586 assert!(item.is_dirty, "Item should still be dirty");
13587 });
13588 }
13589
13590 /// Tests that navigation history is cleaned up when files are auto-closed
13591 /// due to deletion from disk.
13592 #[gpui::test]
13593 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13594 init_test(cx);
13595
13596 // Enable the close_on_file_delete setting
13597 cx.update_global(|store: &mut SettingsStore, cx| {
13598 store.update_user_settings(cx, |settings| {
13599 settings.workspace.close_on_file_delete = Some(true);
13600 });
13601 });
13602
13603 let fs = FakeFs::new(cx.background_executor.clone());
13604 let project = Project::test(fs, [], cx).await;
13605 let (workspace, cx) =
13606 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13607 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13608
13609 // Create test items
13610 let item1 = cx.new(|cx| {
13611 TestItem::new(cx)
13612 .with_label("test1.txt")
13613 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13614 });
13615 let item1_id = item1.item_id();
13616
13617 let item2 = cx.new(|cx| {
13618 TestItem::new(cx)
13619 .with_label("test2.txt")
13620 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13621 });
13622
13623 // Add items to workspace
13624 workspace.update_in(cx, |workspace, window, cx| {
13625 workspace.add_item(
13626 pane.clone(),
13627 Box::new(item1.clone()),
13628 None,
13629 false,
13630 false,
13631 window,
13632 cx,
13633 );
13634 workspace.add_item(
13635 pane.clone(),
13636 Box::new(item2.clone()),
13637 None,
13638 false,
13639 false,
13640 window,
13641 cx,
13642 );
13643 });
13644
13645 // Activate item1 to ensure it gets navigation entries
13646 pane.update_in(cx, |pane, window, cx| {
13647 pane.activate_item(0, true, true, window, cx);
13648 });
13649
13650 // Switch to item2 and back to create navigation history
13651 pane.update_in(cx, |pane, window, cx| {
13652 pane.activate_item(1, true, true, window, cx);
13653 });
13654 cx.run_until_parked();
13655
13656 pane.update_in(cx, |pane, window, cx| {
13657 pane.activate_item(0, true, true, window, cx);
13658 });
13659 cx.run_until_parked();
13660
13661 // Simulate file deletion for item1
13662 item1.update(cx, |item, _| {
13663 item.set_has_deleted_file(true);
13664 });
13665
13666 // Emit UpdateTab event to trigger the close behavior
13667 item1.update(cx, |_, cx| {
13668 cx.emit(ItemEvent::UpdateTab);
13669 });
13670 cx.run_until_parked();
13671
13672 // Verify item1 was closed
13673 pane.read_with(cx, |pane, _| {
13674 assert_eq!(
13675 pane.items().count(),
13676 1,
13677 "Should have 1 item remaining after auto-close"
13678 );
13679 });
13680
13681 // Check navigation history after close
13682 let has_item = pane.read_with(cx, |pane, cx| {
13683 let mut has_item = false;
13684 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13685 if entry.item.id() == item1_id {
13686 has_item = true;
13687 }
13688 });
13689 has_item
13690 });
13691
13692 assert!(
13693 !has_item,
13694 "Navigation history should not contain closed item entries"
13695 );
13696 }
13697
13698 #[gpui::test]
13699 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13700 cx: &mut TestAppContext,
13701 ) {
13702 init_test(cx);
13703
13704 let fs = FakeFs::new(cx.background_executor.clone());
13705 let project = Project::test(fs, [], cx).await;
13706 let (workspace, cx) =
13707 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13708 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13709
13710 let dirty_regular_buffer = cx.new(|cx| {
13711 TestItem::new(cx)
13712 .with_dirty(true)
13713 .with_label("1.txt")
13714 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13715 });
13716 let dirty_regular_buffer_2 = cx.new(|cx| {
13717 TestItem::new(cx)
13718 .with_dirty(true)
13719 .with_label("2.txt")
13720 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13721 });
13722 let clear_regular_buffer = cx.new(|cx| {
13723 TestItem::new(cx)
13724 .with_label("3.txt")
13725 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13726 });
13727
13728 let dirty_multi_buffer = cx.new(|cx| {
13729 TestItem::new(cx)
13730 .with_dirty(true)
13731 .with_buffer_kind(ItemBufferKind::Multibuffer)
13732 .with_label("Fake Project Search")
13733 .with_project_items(&[
13734 dirty_regular_buffer.read(cx).project_items[0].clone(),
13735 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13736 clear_regular_buffer.read(cx).project_items[0].clone(),
13737 ])
13738 });
13739 workspace.update_in(cx, |workspace, window, cx| {
13740 workspace.add_item(
13741 pane.clone(),
13742 Box::new(dirty_regular_buffer.clone()),
13743 None,
13744 false,
13745 false,
13746 window,
13747 cx,
13748 );
13749 workspace.add_item(
13750 pane.clone(),
13751 Box::new(dirty_regular_buffer_2.clone()),
13752 None,
13753 false,
13754 false,
13755 window,
13756 cx,
13757 );
13758 workspace.add_item(
13759 pane.clone(),
13760 Box::new(dirty_multi_buffer.clone()),
13761 None,
13762 false,
13763 false,
13764 window,
13765 cx,
13766 );
13767 });
13768
13769 pane.update_in(cx, |pane, window, cx| {
13770 pane.activate_item(2, true, true, window, cx);
13771 assert_eq!(
13772 pane.active_item().unwrap().item_id(),
13773 dirty_multi_buffer.item_id(),
13774 "Should select the multi buffer in the pane"
13775 );
13776 });
13777 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13778 pane.close_active_item(
13779 &CloseActiveItem {
13780 save_intent: None,
13781 close_pinned: false,
13782 },
13783 window,
13784 cx,
13785 )
13786 });
13787 cx.background_executor.run_until_parked();
13788 assert!(
13789 !cx.has_pending_prompt(),
13790 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13791 );
13792 close_multi_buffer_task
13793 .await
13794 .expect("Closing multi buffer failed");
13795 pane.update(cx, |pane, cx| {
13796 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13797 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13798 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13799 assert_eq!(
13800 pane.items()
13801 .map(|item| item.item_id())
13802 .sorted()
13803 .collect::<Vec<_>>(),
13804 vec![
13805 dirty_regular_buffer.item_id(),
13806 dirty_regular_buffer_2.item_id(),
13807 ],
13808 "Should have no multi buffer left in the pane"
13809 );
13810 assert!(dirty_regular_buffer.read(cx).is_dirty);
13811 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13812 });
13813 }
13814
13815 #[gpui::test]
13816 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13817 init_test(cx);
13818 let fs = FakeFs::new(cx.executor());
13819 let project = Project::test(fs, [], cx).await;
13820 let (multi_workspace, cx) =
13821 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13822 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13823
13824 // Add a new panel to the right dock, opening the dock and setting the
13825 // focus to the new panel.
13826 let panel = workspace.update_in(cx, |workspace, window, cx| {
13827 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13828 workspace.add_panel(panel.clone(), window, cx);
13829
13830 workspace
13831 .right_dock()
13832 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13833
13834 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13835
13836 panel
13837 });
13838
13839 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13840 // panel to the next valid position which, in this case, is the left
13841 // dock.
13842 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13843 workspace.update(cx, |workspace, cx| {
13844 assert!(workspace.left_dock().read(cx).is_open());
13845 assert_eq!(panel.read(cx).position, DockPosition::Left);
13846 });
13847
13848 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13849 // panel to the next valid position which, in this case, is the bottom
13850 // dock.
13851 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13852 workspace.update(cx, |workspace, cx| {
13853 assert!(workspace.bottom_dock().read(cx).is_open());
13854 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13855 });
13856
13857 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13858 // around moving the panel to its initial position, the right dock.
13859 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13860 workspace.update(cx, |workspace, cx| {
13861 assert!(workspace.right_dock().read(cx).is_open());
13862 assert_eq!(panel.read(cx).position, DockPosition::Right);
13863 });
13864
13865 // Remove focus from the panel, ensuring that, if the panel is not
13866 // focused, the `MoveFocusedPanelToNextPosition` action does not update
13867 // the panel's position, so the panel is still in the right dock.
13868 workspace.update_in(cx, |workspace, window, cx| {
13869 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13870 });
13871
13872 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13873 workspace.update(cx, |workspace, cx| {
13874 assert!(workspace.right_dock().read(cx).is_open());
13875 assert_eq!(panel.read(cx).position, DockPosition::Right);
13876 });
13877 }
13878
13879 #[gpui::test]
13880 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13881 init_test(cx);
13882
13883 let fs = FakeFs::new(cx.executor());
13884 let project = Project::test(fs, [], cx).await;
13885 let (workspace, cx) =
13886 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13887
13888 let item_1 = cx.new(|cx| {
13889 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13890 });
13891 workspace.update_in(cx, |workspace, window, cx| {
13892 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13893 workspace.move_item_to_pane_in_direction(
13894 &MoveItemToPaneInDirection {
13895 direction: SplitDirection::Right,
13896 focus: true,
13897 clone: false,
13898 },
13899 window,
13900 cx,
13901 );
13902 workspace.move_item_to_pane_at_index(
13903 &MoveItemToPane {
13904 destination: 3,
13905 focus: true,
13906 clone: false,
13907 },
13908 window,
13909 cx,
13910 );
13911
13912 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13913 assert_eq!(
13914 pane_items_paths(&workspace.active_pane, cx),
13915 vec!["first.txt".to_string()],
13916 "Single item was not moved anywhere"
13917 );
13918 });
13919
13920 let item_2 = cx.new(|cx| {
13921 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13922 });
13923 workspace.update_in(cx, |workspace, window, cx| {
13924 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13925 assert_eq!(
13926 pane_items_paths(&workspace.panes[0], cx),
13927 vec!["first.txt".to_string(), "second.txt".to_string()],
13928 );
13929 workspace.move_item_to_pane_in_direction(
13930 &MoveItemToPaneInDirection {
13931 direction: SplitDirection::Right,
13932 focus: true,
13933 clone: false,
13934 },
13935 window,
13936 cx,
13937 );
13938
13939 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13940 assert_eq!(
13941 pane_items_paths(&workspace.panes[0], cx),
13942 vec!["first.txt".to_string()],
13943 "After moving, one item should be left in the original pane"
13944 );
13945 assert_eq!(
13946 pane_items_paths(&workspace.panes[1], cx),
13947 vec!["second.txt".to_string()],
13948 "New item should have been moved to the new pane"
13949 );
13950 });
13951
13952 let item_3 = cx.new(|cx| {
13953 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13954 });
13955 workspace.update_in(cx, |workspace, window, cx| {
13956 let original_pane = workspace.panes[0].clone();
13957 workspace.set_active_pane(&original_pane, window, cx);
13958 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13959 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13960 assert_eq!(
13961 pane_items_paths(&workspace.active_pane, cx),
13962 vec!["first.txt".to_string(), "third.txt".to_string()],
13963 "New pane should be ready to move one item out"
13964 );
13965
13966 workspace.move_item_to_pane_at_index(
13967 &MoveItemToPane {
13968 destination: 3,
13969 focus: true,
13970 clone: false,
13971 },
13972 window,
13973 cx,
13974 );
13975 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13976 assert_eq!(
13977 pane_items_paths(&workspace.active_pane, cx),
13978 vec!["first.txt".to_string()],
13979 "After moving, one item should be left in the original pane"
13980 );
13981 assert_eq!(
13982 pane_items_paths(&workspace.panes[1], cx),
13983 vec!["second.txt".to_string()],
13984 "Previously created pane should be unchanged"
13985 );
13986 assert_eq!(
13987 pane_items_paths(&workspace.panes[2], cx),
13988 vec!["third.txt".to_string()],
13989 "New item should have been moved to the new pane"
13990 );
13991 });
13992 }
13993
13994 #[gpui::test]
13995 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13996 init_test(cx);
13997
13998 let fs = FakeFs::new(cx.executor());
13999 let project = Project::test(fs, [], cx).await;
14000 let (workspace, cx) =
14001 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14002
14003 let item_1 = cx.new(|cx| {
14004 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14005 });
14006 workspace.update_in(cx, |workspace, window, cx| {
14007 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14008 workspace.move_item_to_pane_in_direction(
14009 &MoveItemToPaneInDirection {
14010 direction: SplitDirection::Right,
14011 focus: true,
14012 clone: true,
14013 },
14014 window,
14015 cx,
14016 );
14017 });
14018 cx.run_until_parked();
14019 workspace.update_in(cx, |workspace, window, cx| {
14020 workspace.move_item_to_pane_at_index(
14021 &MoveItemToPane {
14022 destination: 3,
14023 focus: true,
14024 clone: true,
14025 },
14026 window,
14027 cx,
14028 );
14029 });
14030 cx.run_until_parked();
14031
14032 workspace.update(cx, |workspace, cx| {
14033 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
14034 for pane in workspace.panes() {
14035 assert_eq!(
14036 pane_items_paths(pane, cx),
14037 vec!["first.txt".to_string()],
14038 "Single item exists in all panes"
14039 );
14040 }
14041 });
14042
14043 // verify that the active pane has been updated after waiting for the
14044 // pane focus event to fire and resolve
14045 workspace.read_with(cx, |workspace, _app| {
14046 assert_eq!(
14047 workspace.active_pane(),
14048 &workspace.panes[2],
14049 "The third pane should be the active one: {:?}",
14050 workspace.panes
14051 );
14052 })
14053 }
14054
14055 #[gpui::test]
14056 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
14057 init_test(cx);
14058
14059 let fs = FakeFs::new(cx.executor());
14060 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14061
14062 let project = Project::test(fs, ["root".as_ref()], cx).await;
14063 let (workspace, cx) =
14064 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14065
14066 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14067 // Add item to pane A with project path
14068 let item_a = cx.new(|cx| {
14069 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14070 });
14071 workspace.update_in(cx, |workspace, window, cx| {
14072 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14073 });
14074
14075 // Split to create pane B
14076 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14077 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14078 });
14079
14080 // Add item with SAME project path to pane B, and pin it
14081 let item_b = cx.new(|cx| {
14082 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14083 });
14084 pane_b.update_in(cx, |pane, window, cx| {
14085 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14086 pane.set_pinned_count(1);
14087 });
14088
14089 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14090 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14091
14092 // close_pinned: false should only close the unpinned copy
14093 workspace.update_in(cx, |workspace, window, cx| {
14094 workspace.close_item_in_all_panes(
14095 &CloseItemInAllPanes {
14096 save_intent: Some(SaveIntent::Close),
14097 close_pinned: false,
14098 },
14099 window,
14100 cx,
14101 )
14102 });
14103 cx.executor().run_until_parked();
14104
14105 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14106 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14107 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14108 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14109
14110 // Split again, seeing as closing the previous item also closed its
14111 // pane, so only pane remains, which does not allow us to properly test
14112 // that both items close when `close_pinned: true`.
14113 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14114 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14115 });
14116
14117 // Add an item with the same project path to pane C so that
14118 // close_item_in_all_panes can determine what to close across all panes
14119 // (it reads the active item from the active pane, and split_pane
14120 // creates an empty pane).
14121 let item_c = cx.new(|cx| {
14122 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14123 });
14124 pane_c.update_in(cx, |pane, window, cx| {
14125 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14126 });
14127
14128 // close_pinned: true should close the pinned copy too
14129 workspace.update_in(cx, |workspace, window, cx| {
14130 let panes_count = workspace.panes().len();
14131 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14132
14133 workspace.close_item_in_all_panes(
14134 &CloseItemInAllPanes {
14135 save_intent: Some(SaveIntent::Close),
14136 close_pinned: true,
14137 },
14138 window,
14139 cx,
14140 )
14141 });
14142 cx.executor().run_until_parked();
14143
14144 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14145 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14146 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14147 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14148 }
14149
14150 mod register_project_item_tests {
14151
14152 use super::*;
14153
14154 // View
14155 struct TestPngItemView {
14156 focus_handle: FocusHandle,
14157 }
14158 // Model
14159 struct TestPngItem {}
14160
14161 impl project::ProjectItem for TestPngItem {
14162 fn try_open(
14163 _project: &Entity<Project>,
14164 path: &ProjectPath,
14165 cx: &mut App,
14166 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14167 if path.path.extension().unwrap() == "png" {
14168 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14169 } else {
14170 None
14171 }
14172 }
14173
14174 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14175 None
14176 }
14177
14178 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14179 None
14180 }
14181
14182 fn is_dirty(&self) -> bool {
14183 false
14184 }
14185 }
14186
14187 impl Item for TestPngItemView {
14188 type Event = ();
14189 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14190 "".into()
14191 }
14192 }
14193 impl EventEmitter<()> for TestPngItemView {}
14194 impl Focusable for TestPngItemView {
14195 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14196 self.focus_handle.clone()
14197 }
14198 }
14199
14200 impl Render for TestPngItemView {
14201 fn render(
14202 &mut self,
14203 _window: &mut Window,
14204 _cx: &mut Context<Self>,
14205 ) -> impl IntoElement {
14206 Empty
14207 }
14208 }
14209
14210 impl ProjectItem for TestPngItemView {
14211 type Item = TestPngItem;
14212
14213 fn for_project_item(
14214 _project: Entity<Project>,
14215 _pane: Option<&Pane>,
14216 _item: Entity<Self::Item>,
14217 _: &mut Window,
14218 cx: &mut Context<Self>,
14219 ) -> Self
14220 where
14221 Self: Sized,
14222 {
14223 Self {
14224 focus_handle: cx.focus_handle(),
14225 }
14226 }
14227 }
14228
14229 // View
14230 struct TestIpynbItemView {
14231 focus_handle: FocusHandle,
14232 }
14233 // Model
14234 struct TestIpynbItem {}
14235
14236 impl project::ProjectItem for TestIpynbItem {
14237 fn try_open(
14238 _project: &Entity<Project>,
14239 path: &ProjectPath,
14240 cx: &mut App,
14241 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14242 if path.path.extension().unwrap() == "ipynb" {
14243 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14244 } else {
14245 None
14246 }
14247 }
14248
14249 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14250 None
14251 }
14252
14253 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14254 None
14255 }
14256
14257 fn is_dirty(&self) -> bool {
14258 false
14259 }
14260 }
14261
14262 impl Item for TestIpynbItemView {
14263 type Event = ();
14264 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14265 "".into()
14266 }
14267 }
14268 impl EventEmitter<()> for TestIpynbItemView {}
14269 impl Focusable for TestIpynbItemView {
14270 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14271 self.focus_handle.clone()
14272 }
14273 }
14274
14275 impl Render for TestIpynbItemView {
14276 fn render(
14277 &mut self,
14278 _window: &mut Window,
14279 _cx: &mut Context<Self>,
14280 ) -> impl IntoElement {
14281 Empty
14282 }
14283 }
14284
14285 impl ProjectItem for TestIpynbItemView {
14286 type Item = TestIpynbItem;
14287
14288 fn for_project_item(
14289 _project: Entity<Project>,
14290 _pane: Option<&Pane>,
14291 _item: Entity<Self::Item>,
14292 _: &mut Window,
14293 cx: &mut Context<Self>,
14294 ) -> Self
14295 where
14296 Self: Sized,
14297 {
14298 Self {
14299 focus_handle: cx.focus_handle(),
14300 }
14301 }
14302 }
14303
14304 struct TestAlternatePngItemView {
14305 focus_handle: FocusHandle,
14306 }
14307
14308 impl Item for TestAlternatePngItemView {
14309 type Event = ();
14310 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14311 "".into()
14312 }
14313 }
14314
14315 impl EventEmitter<()> for TestAlternatePngItemView {}
14316 impl Focusable for TestAlternatePngItemView {
14317 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14318 self.focus_handle.clone()
14319 }
14320 }
14321
14322 impl Render for TestAlternatePngItemView {
14323 fn render(
14324 &mut self,
14325 _window: &mut Window,
14326 _cx: &mut Context<Self>,
14327 ) -> impl IntoElement {
14328 Empty
14329 }
14330 }
14331
14332 impl ProjectItem for TestAlternatePngItemView {
14333 type Item = TestPngItem;
14334
14335 fn for_project_item(
14336 _project: Entity<Project>,
14337 _pane: Option<&Pane>,
14338 _item: Entity<Self::Item>,
14339 _: &mut Window,
14340 cx: &mut Context<Self>,
14341 ) -> Self
14342 where
14343 Self: Sized,
14344 {
14345 Self {
14346 focus_handle: cx.focus_handle(),
14347 }
14348 }
14349 }
14350
14351 #[gpui::test]
14352 async fn test_register_project_item(cx: &mut TestAppContext) {
14353 init_test(cx);
14354
14355 cx.update(|cx| {
14356 register_project_item::<TestPngItemView>(cx);
14357 register_project_item::<TestIpynbItemView>(cx);
14358 });
14359
14360 let fs = FakeFs::new(cx.executor());
14361 fs.insert_tree(
14362 "/root1",
14363 json!({
14364 "one.png": "BINARYDATAHERE",
14365 "two.ipynb": "{ totally a notebook }",
14366 "three.txt": "editing text, sure why not?"
14367 }),
14368 )
14369 .await;
14370
14371 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14372 let (workspace, cx) =
14373 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14374
14375 let worktree_id = project.update(cx, |project, cx| {
14376 project.worktrees(cx).next().unwrap().read(cx).id()
14377 });
14378
14379 let handle = workspace
14380 .update_in(cx, |workspace, window, cx| {
14381 let project_path = (worktree_id, rel_path("one.png"));
14382 workspace.open_path(project_path, None, true, window, cx)
14383 })
14384 .await
14385 .unwrap();
14386
14387 // Now we can check if the handle we got back errored or not
14388 assert_eq!(
14389 handle.to_any_view().entity_type(),
14390 TypeId::of::<TestPngItemView>()
14391 );
14392
14393 let handle = workspace
14394 .update_in(cx, |workspace, window, cx| {
14395 let project_path = (worktree_id, rel_path("two.ipynb"));
14396 workspace.open_path(project_path, None, true, window, cx)
14397 })
14398 .await
14399 .unwrap();
14400
14401 assert_eq!(
14402 handle.to_any_view().entity_type(),
14403 TypeId::of::<TestIpynbItemView>()
14404 );
14405
14406 let handle = workspace
14407 .update_in(cx, |workspace, window, cx| {
14408 let project_path = (worktree_id, rel_path("three.txt"));
14409 workspace.open_path(project_path, None, true, window, cx)
14410 })
14411 .await;
14412 assert!(handle.is_err());
14413 }
14414
14415 #[gpui::test]
14416 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14417 init_test(cx);
14418
14419 cx.update(|cx| {
14420 register_project_item::<TestPngItemView>(cx);
14421 register_project_item::<TestAlternatePngItemView>(cx);
14422 });
14423
14424 let fs = FakeFs::new(cx.executor());
14425 fs.insert_tree(
14426 "/root1",
14427 json!({
14428 "one.png": "BINARYDATAHERE",
14429 "two.ipynb": "{ totally a notebook }",
14430 "three.txt": "editing text, sure why not?"
14431 }),
14432 )
14433 .await;
14434 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14435 let (workspace, cx) =
14436 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14437 let worktree_id = project.update(cx, |project, cx| {
14438 project.worktrees(cx).next().unwrap().read(cx).id()
14439 });
14440
14441 let handle = workspace
14442 .update_in(cx, |workspace, window, cx| {
14443 let project_path = (worktree_id, rel_path("one.png"));
14444 workspace.open_path(project_path, None, true, window, cx)
14445 })
14446 .await
14447 .unwrap();
14448
14449 // This _must_ be the second item registered
14450 assert_eq!(
14451 handle.to_any_view().entity_type(),
14452 TypeId::of::<TestAlternatePngItemView>()
14453 );
14454
14455 let handle = workspace
14456 .update_in(cx, |workspace, window, cx| {
14457 let project_path = (worktree_id, rel_path("three.txt"));
14458 workspace.open_path(project_path, None, true, window, cx)
14459 })
14460 .await;
14461 assert!(handle.is_err());
14462 }
14463 }
14464
14465 #[gpui::test]
14466 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14467 init_test(cx);
14468
14469 let fs = FakeFs::new(cx.executor());
14470 let project = Project::test(fs, [], cx).await;
14471 let (workspace, _cx) =
14472 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14473
14474 // Test with status bar shown (default)
14475 workspace.read_with(cx, |workspace, cx| {
14476 let visible = workspace.status_bar_visible(cx);
14477 assert!(visible, "Status bar should be visible by default");
14478 });
14479
14480 // Test with status bar hidden
14481 cx.update_global(|store: &mut SettingsStore, cx| {
14482 store.update_user_settings(cx, |settings| {
14483 settings.status_bar.get_or_insert_default().show = Some(false);
14484 });
14485 });
14486
14487 workspace.read_with(cx, |workspace, cx| {
14488 let visible = workspace.status_bar_visible(cx);
14489 assert!(!visible, "Status bar should be hidden when show is false");
14490 });
14491
14492 // Test with status bar shown explicitly
14493 cx.update_global(|store: &mut SettingsStore, cx| {
14494 store.update_user_settings(cx, |settings| {
14495 settings.status_bar.get_or_insert_default().show = Some(true);
14496 });
14497 });
14498
14499 workspace.read_with(cx, |workspace, cx| {
14500 let visible = workspace.status_bar_visible(cx);
14501 assert!(visible, "Status bar should be visible when show is true");
14502 });
14503 }
14504
14505 #[gpui::test]
14506 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14507 init_test(cx);
14508
14509 let fs = FakeFs::new(cx.executor());
14510 let project = Project::test(fs, [], cx).await;
14511 let (multi_workspace, cx) =
14512 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14513 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14514 let panel = workspace.update_in(cx, |workspace, window, cx| {
14515 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14516 workspace.add_panel(panel.clone(), window, cx);
14517
14518 workspace
14519 .right_dock()
14520 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14521
14522 panel
14523 });
14524
14525 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14526 let item_a = cx.new(TestItem::new);
14527 let item_b = cx.new(TestItem::new);
14528 let item_a_id = item_a.entity_id();
14529 let item_b_id = item_b.entity_id();
14530
14531 pane.update_in(cx, |pane, window, cx| {
14532 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14533 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14534 });
14535
14536 pane.read_with(cx, |pane, _| {
14537 assert_eq!(pane.items_len(), 2);
14538 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14539 });
14540
14541 workspace.update_in(cx, |workspace, window, cx| {
14542 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14543 });
14544
14545 workspace.update_in(cx, |_, window, cx| {
14546 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14547 });
14548
14549 // Assert that the `pane::CloseActiveItem` action is handled at the
14550 // workspace level when one of the dock panels is focused and, in that
14551 // case, the center pane's active item is closed but the focus is not
14552 // moved.
14553 cx.dispatch_action(pane::CloseActiveItem::default());
14554 cx.run_until_parked();
14555
14556 pane.read_with(cx, |pane, _| {
14557 assert_eq!(pane.items_len(), 1);
14558 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14559 });
14560
14561 workspace.update_in(cx, |workspace, window, cx| {
14562 assert!(workspace.right_dock().read(cx).is_open());
14563 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14564 });
14565 }
14566
14567 #[gpui::test]
14568 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14569 init_test(cx);
14570 let fs = FakeFs::new(cx.executor());
14571
14572 let project_a = Project::test(fs.clone(), [], cx).await;
14573 let project_b = Project::test(fs, [], cx).await;
14574
14575 let multi_workspace_handle =
14576 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14577 cx.run_until_parked();
14578
14579 multi_workspace_handle
14580 .update(cx, |mw, _window, cx| {
14581 mw.open_sidebar(cx);
14582 })
14583 .unwrap();
14584
14585 let workspace_a = multi_workspace_handle
14586 .read_with(cx, |mw, _| mw.workspace().clone())
14587 .unwrap();
14588
14589 let _workspace_b = multi_workspace_handle
14590 .update(cx, |mw, window, cx| {
14591 mw.test_add_workspace(project_b, window, cx)
14592 })
14593 .unwrap();
14594
14595 // Switch to workspace A
14596 multi_workspace_handle
14597 .update(cx, |mw, window, cx| {
14598 let workspace = mw.workspaces().next().unwrap().clone();
14599 mw.activate(workspace, window, cx);
14600 })
14601 .unwrap();
14602
14603 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14604
14605 // Add a panel to workspace A's right dock and open the dock
14606 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14607 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14608 workspace.add_panel(panel.clone(), window, cx);
14609 workspace
14610 .right_dock()
14611 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14612 panel
14613 });
14614
14615 // Focus the panel through the workspace (matching existing test pattern)
14616 workspace_a.update_in(cx, |workspace, window, cx| {
14617 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14618 });
14619
14620 // Zoom the panel
14621 panel.update_in(cx, |panel, window, cx| {
14622 panel.set_zoomed(true, window, cx);
14623 });
14624
14625 // Verify the panel is zoomed and the dock is open
14626 workspace_a.update_in(cx, |workspace, window, cx| {
14627 assert!(
14628 workspace.right_dock().read(cx).is_open(),
14629 "dock should be open before switch"
14630 );
14631 assert!(
14632 panel.is_zoomed(window, cx),
14633 "panel should be zoomed before switch"
14634 );
14635 assert!(
14636 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14637 "panel should be focused before switch"
14638 );
14639 });
14640
14641 // Switch to workspace B
14642 multi_workspace_handle
14643 .update(cx, |mw, window, cx| {
14644 let workspace = mw.workspaces().nth(1).unwrap().clone();
14645 mw.activate(workspace, window, cx);
14646 })
14647 .unwrap();
14648 cx.run_until_parked();
14649
14650 // Switch back to workspace A
14651 multi_workspace_handle
14652 .update(cx, |mw, window, cx| {
14653 let workspace = mw.workspaces().next().unwrap().clone();
14654 mw.activate(workspace, window, cx);
14655 })
14656 .unwrap();
14657 cx.run_until_parked();
14658
14659 // Verify the panel is still zoomed and the dock is still open
14660 workspace_a.update_in(cx, |workspace, window, cx| {
14661 assert!(
14662 workspace.right_dock().read(cx).is_open(),
14663 "dock should still be open after switching back"
14664 );
14665 assert!(
14666 panel.is_zoomed(window, cx),
14667 "panel should still be zoomed after switching back"
14668 );
14669 });
14670 }
14671
14672 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14673 pane.read(cx)
14674 .items()
14675 .flat_map(|item| {
14676 item.project_paths(cx)
14677 .into_iter()
14678 .map(|path| path.path.display(PathStyle::local()).into_owned())
14679 })
14680 .collect()
14681 }
14682
14683 pub fn init_test(cx: &mut TestAppContext) {
14684 cx.update(|cx| {
14685 let settings_store = SettingsStore::test(cx);
14686 cx.set_global(settings_store);
14687 cx.set_global(db::AppDatabase::test_new());
14688 theme_settings::init(theme::LoadThemes::JustBase, cx);
14689 });
14690 }
14691
14692 #[gpui::test]
14693 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14694 use settings::{ThemeName, ThemeSelection};
14695 use theme::SystemAppearance;
14696 use zed_actions::theme::ToggleMode;
14697
14698 init_test(cx);
14699
14700 let fs = FakeFs::new(cx.executor());
14701 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14702
14703 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14704 .await;
14705
14706 // Build a test project and workspace view so the test can invoke
14707 // the workspace action handler the same way the UI would.
14708 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14709 let (workspace, cx) =
14710 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14711
14712 // Seed the settings file with a plain static light theme so the
14713 // first toggle always starts from a known persisted state.
14714 workspace.update_in(cx, |_workspace, _window, cx| {
14715 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14716 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14717 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14718 });
14719 });
14720 cx.executor().advance_clock(Duration::from_millis(200));
14721 cx.run_until_parked();
14722
14723 // Confirm the initial persisted settings contain the static theme
14724 // we just wrote before any toggling happens.
14725 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14726 assert!(settings_text.contains(r#""theme": "One Light""#));
14727
14728 // Toggle once. This should migrate the persisted theme settings
14729 // into light/dark slots and enable system mode.
14730 workspace.update_in(cx, |workspace, window, cx| {
14731 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14732 });
14733 cx.executor().advance_clock(Duration::from_millis(200));
14734 cx.run_until_parked();
14735
14736 // 1. Static -> Dynamic
14737 // this assertion checks theme changed from static to dynamic.
14738 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14739 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14740 assert_eq!(
14741 parsed["theme"],
14742 serde_json::json!({
14743 "mode": "system",
14744 "light": "One Light",
14745 "dark": "One Dark"
14746 })
14747 );
14748
14749 // 2. Toggle again, suppose it will change the mode to light
14750 workspace.update_in(cx, |workspace, window, cx| {
14751 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14752 });
14753 cx.executor().advance_clock(Duration::from_millis(200));
14754 cx.run_until_parked();
14755
14756 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14757 assert!(settings_text.contains(r#""mode": "light""#));
14758 }
14759
14760 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14761 let item = TestProjectItem::new(id, path, cx);
14762 item.update(cx, |item, _| {
14763 item.is_dirty = true;
14764 });
14765 item
14766 }
14767
14768 #[gpui::test]
14769 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14770 cx: &mut gpui::TestAppContext,
14771 ) {
14772 init_test(cx);
14773 let fs = FakeFs::new(cx.executor());
14774
14775 let project = Project::test(fs, [], cx).await;
14776 let (workspace, cx) =
14777 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14778
14779 let panel = workspace.update_in(cx, |workspace, window, cx| {
14780 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14781 workspace.add_panel(panel.clone(), window, cx);
14782 workspace
14783 .right_dock()
14784 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14785 panel
14786 });
14787
14788 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14789 pane.update_in(cx, |pane, window, cx| {
14790 let item = cx.new(TestItem::new);
14791 pane.add_item(Box::new(item), true, true, None, window, cx);
14792 });
14793
14794 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14795 // mirrors the real-world flow and avoids side effects from directly
14796 // focusing the panel while the center pane is active.
14797 workspace.update_in(cx, |workspace, window, cx| {
14798 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14799 });
14800
14801 panel.update_in(cx, |panel, window, cx| {
14802 panel.set_zoomed(true, window, cx);
14803 });
14804
14805 workspace.update_in(cx, |workspace, window, cx| {
14806 assert!(workspace.right_dock().read(cx).is_open());
14807 assert!(panel.is_zoomed(window, cx));
14808 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14809 });
14810
14811 // Simulate a spurious pane::Event::Focus on the center pane while the
14812 // panel still has focus. This mirrors what happens during macOS window
14813 // activation: the center pane fires a focus event even though actual
14814 // focus remains on the dock panel.
14815 pane.update_in(cx, |_, _, cx| {
14816 cx.emit(pane::Event::Focus);
14817 });
14818
14819 // The dock must remain open because the panel had focus at the time the
14820 // event was processed. Before the fix, dock_to_preserve was None for
14821 // panels that don't implement pane(), causing the dock to close.
14822 workspace.update_in(cx, |workspace, window, cx| {
14823 assert!(
14824 workspace.right_dock().read(cx).is_open(),
14825 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14826 );
14827 assert!(panel.is_zoomed(window, cx));
14828 });
14829 }
14830
14831 #[gpui::test]
14832 async fn test_panels_stay_open_after_position_change_and_settings_update(
14833 cx: &mut gpui::TestAppContext,
14834 ) {
14835 init_test(cx);
14836 let fs = FakeFs::new(cx.executor());
14837 let project = Project::test(fs, [], cx).await;
14838 let (workspace, cx) =
14839 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14840
14841 // Add two panels to the left dock and open it.
14842 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14843 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14844 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14845 workspace.add_panel(panel_a.clone(), window, cx);
14846 workspace.add_panel(panel_b.clone(), window, cx);
14847 workspace.left_dock().update(cx, |dock, cx| {
14848 dock.set_open(true, window, cx);
14849 dock.activate_panel(0, window, cx);
14850 });
14851 (panel_a, panel_b)
14852 });
14853
14854 workspace.update_in(cx, |workspace, _, cx| {
14855 assert!(workspace.left_dock().read(cx).is_open());
14856 });
14857
14858 // Simulate a feature flag changing default dock positions: both panels
14859 // move from Left to Right.
14860 workspace.update_in(cx, |_workspace, _window, cx| {
14861 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14862 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14863 cx.update_global::<SettingsStore, _>(|_, _| {});
14864 });
14865
14866 // Both panels should now be in the right dock.
14867 workspace.update_in(cx, |workspace, _, cx| {
14868 let right_dock = workspace.right_dock().read(cx);
14869 assert_eq!(right_dock.panels_len(), 2);
14870 });
14871
14872 // Open the right dock and activate panel_b (simulating the user
14873 // opening the panel after it moved).
14874 workspace.update_in(cx, |workspace, window, cx| {
14875 workspace.right_dock().update(cx, |dock, cx| {
14876 dock.set_open(true, window, cx);
14877 dock.activate_panel(1, window, cx);
14878 });
14879 });
14880
14881 // Now trigger another SettingsStore change
14882 workspace.update_in(cx, |_workspace, _window, cx| {
14883 cx.update_global::<SettingsStore, _>(|_, _| {});
14884 });
14885
14886 workspace.update_in(cx, |workspace, _, cx| {
14887 assert!(
14888 workspace.right_dock().read(cx).is_open(),
14889 "Right dock should still be open after a settings change"
14890 );
14891 assert_eq!(
14892 workspace.right_dock().read(cx).panels_len(),
14893 2,
14894 "Both panels should still be in the right dock"
14895 );
14896 });
14897 }
14898}