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 None,
9697 cx,
9698 )
9699 .await
9700 })
9701}
9702
9703pub fn open_remote_project_with_existing_connection(
9704 connection_options: RemoteConnectionOptions,
9705 project: Entity<Project>,
9706 paths: Vec<PathBuf>,
9707 app_state: Arc<AppState>,
9708 window: WindowHandle<MultiWorkspace>,
9709 provisional_project_group_key: Option<ProjectGroupKey>,
9710 cx: &mut AsyncApp,
9711) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9712 cx.spawn(async move |cx| {
9713 let (workspace_id, serialized_workspace) =
9714 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9715
9716 open_remote_project_inner(
9717 project,
9718 paths,
9719 workspace_id,
9720 serialized_workspace,
9721 app_state,
9722 window,
9723 provisional_project_group_key,
9724 cx,
9725 )
9726 .await
9727 })
9728}
9729
9730async fn open_remote_project_inner(
9731 project: Entity<Project>,
9732 paths: Vec<PathBuf>,
9733 workspace_id: WorkspaceId,
9734 serialized_workspace: Option<SerializedWorkspace>,
9735 app_state: Arc<AppState>,
9736 window: WindowHandle<MultiWorkspace>,
9737 provisional_project_group_key: Option<ProjectGroupKey>,
9738 cx: &mut AsyncApp,
9739) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9740 let db = cx.update(|cx| WorkspaceDb::global(cx));
9741 let toolchains = db.toolchains(workspace_id).await?;
9742 for (toolchain, worktree_path, path) in toolchains {
9743 project
9744 .update(cx, |this, cx| {
9745 let Some(worktree_id) =
9746 this.find_worktree(&worktree_path, cx)
9747 .and_then(|(worktree, rel_path)| {
9748 if rel_path.is_empty() {
9749 Some(worktree.read(cx).id())
9750 } else {
9751 None
9752 }
9753 })
9754 else {
9755 return Task::ready(None);
9756 };
9757
9758 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9759 })
9760 .await;
9761 }
9762 let mut project_paths_to_open = vec![];
9763 let mut project_path_errors = vec![];
9764
9765 for path in paths {
9766 let result = cx
9767 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9768 .await;
9769 match result {
9770 Ok((_, project_path)) => {
9771 project_paths_to_open.push((path.clone(), Some(project_path)));
9772 }
9773 Err(error) => {
9774 project_path_errors.push(error);
9775 }
9776 };
9777 }
9778
9779 if project_paths_to_open.is_empty() {
9780 return Err(project_path_errors.pop().context("no paths given")?);
9781 }
9782
9783 let workspace = window.update(cx, |multi_workspace, window, cx| {
9784 telemetry::event!("SSH Project Opened");
9785
9786 let new_workspace = cx.new(|cx| {
9787 let mut workspace =
9788 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9789 workspace.update_history(cx);
9790
9791 if let Some(ref serialized) = serialized_workspace {
9792 workspace.centered_layout = serialized.centered_layout;
9793 }
9794
9795 workspace
9796 });
9797
9798 if let Some(project_group_key) = provisional_project_group_key.clone() {
9799 multi_workspace.set_provisional_project_group_key(&new_workspace, project_group_key);
9800 }
9801 multi_workspace.activate(new_workspace.clone(), window, cx);
9802 new_workspace
9803 })?;
9804
9805 let items = window
9806 .update(cx, |_, window, cx| {
9807 window.activate_window();
9808 workspace.update(cx, |_workspace, cx| {
9809 open_items(serialized_workspace, project_paths_to_open, window, cx)
9810 })
9811 })?
9812 .await?;
9813
9814 workspace.update(cx, |workspace, cx| {
9815 for error in project_path_errors {
9816 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9817 if let Some(path) = error.error_tag("path") {
9818 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9819 }
9820 } else {
9821 workspace.show_error(&error, cx)
9822 }
9823 }
9824 });
9825
9826 Ok(items.into_iter().map(|item| item?.ok()).collect())
9827}
9828
9829fn deserialize_remote_project(
9830 connection_options: RemoteConnectionOptions,
9831 paths: Vec<PathBuf>,
9832 cx: &AsyncApp,
9833) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9834 let db = cx.update(|cx| WorkspaceDb::global(cx));
9835 cx.background_spawn(async move {
9836 let remote_connection_id = db
9837 .get_or_create_remote_connection(connection_options)
9838 .await?;
9839
9840 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9841
9842 let workspace_id = if let Some(workspace_id) =
9843 serialized_workspace.as_ref().map(|workspace| workspace.id)
9844 {
9845 workspace_id
9846 } else {
9847 db.next_id().await?
9848 };
9849
9850 Ok((workspace_id, serialized_workspace))
9851 })
9852}
9853
9854pub fn join_in_room_project(
9855 project_id: u64,
9856 follow_user_id: u64,
9857 app_state: Arc<AppState>,
9858 cx: &mut App,
9859) -> Task<Result<()>> {
9860 let windows = cx.windows();
9861 cx.spawn(async move |cx| {
9862 let existing_window_and_workspace: Option<(
9863 WindowHandle<MultiWorkspace>,
9864 Entity<Workspace>,
9865 )> = windows.into_iter().find_map(|window_handle| {
9866 window_handle
9867 .downcast::<MultiWorkspace>()
9868 .and_then(|window_handle| {
9869 window_handle
9870 .update(cx, |multi_workspace, _window, cx| {
9871 for workspace in multi_workspace.workspaces() {
9872 if workspace.read(cx).project().read(cx).remote_id()
9873 == Some(project_id)
9874 {
9875 return Some((window_handle, workspace.clone()));
9876 }
9877 }
9878 None
9879 })
9880 .unwrap_or(None)
9881 })
9882 });
9883
9884 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9885 existing_window_and_workspace
9886 {
9887 existing_window
9888 .update(cx, |multi_workspace, window, cx| {
9889 multi_workspace.activate(target_workspace, window, cx);
9890 })
9891 .ok();
9892 existing_window
9893 } else {
9894 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9895 let project = cx
9896 .update(|cx| {
9897 active_call.0.join_project(
9898 project_id,
9899 app_state.languages.clone(),
9900 app_state.fs.clone(),
9901 cx,
9902 )
9903 })
9904 .await?;
9905
9906 let window_bounds_override = window_bounds_env_override();
9907 cx.update(|cx| {
9908 let mut options = (app_state.build_window_options)(None, cx);
9909 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9910 cx.open_window(options, |window, cx| {
9911 let workspace = cx.new(|cx| {
9912 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9913 });
9914 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9915 })
9916 })?
9917 };
9918
9919 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9920 cx.activate(true);
9921 window.activate_window();
9922
9923 // We set the active workspace above, so this is the correct workspace.
9924 let workspace = multi_workspace.workspace().clone();
9925 workspace.update(cx, |workspace, cx| {
9926 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9927 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9928 .or_else(|| {
9929 // If we couldn't follow the given user, follow the host instead.
9930 let collaborator = workspace
9931 .project()
9932 .read(cx)
9933 .collaborators()
9934 .values()
9935 .find(|collaborator| collaborator.is_host)?;
9936 Some(collaborator.peer_id)
9937 });
9938
9939 if let Some(follow_peer_id) = follow_peer_id {
9940 workspace.follow(follow_peer_id, window, cx);
9941 }
9942 });
9943 })?;
9944
9945 anyhow::Ok(())
9946 })
9947}
9948
9949pub fn reload(cx: &mut App) {
9950 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9951 let mut workspace_windows = cx
9952 .windows()
9953 .into_iter()
9954 .filter_map(|window| window.downcast::<MultiWorkspace>())
9955 .collect::<Vec<_>>();
9956
9957 // If multiple windows have unsaved changes, and need a save prompt,
9958 // prompt in the active window before switching to a different window.
9959 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9960
9961 let mut prompt = None;
9962 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9963 prompt = window
9964 .update(cx, |_, window, cx| {
9965 window.prompt(
9966 PromptLevel::Info,
9967 "Are you sure you want to restart?",
9968 None,
9969 &["Restart", "Cancel"],
9970 cx,
9971 )
9972 })
9973 .ok();
9974 }
9975
9976 cx.spawn(async move |cx| {
9977 if let Some(prompt) = prompt {
9978 let answer = prompt.await?;
9979 if answer != 0 {
9980 return anyhow::Ok(());
9981 }
9982 }
9983
9984 // If the user cancels any save prompt, then keep the app open.
9985 for window in workspace_windows {
9986 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9987 let workspace = multi_workspace.workspace().clone();
9988 workspace.update(cx, |workspace, cx| {
9989 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9990 })
9991 }) && !should_close.await?
9992 {
9993 return anyhow::Ok(());
9994 }
9995 }
9996 cx.update(|cx| cx.restart());
9997 anyhow::Ok(())
9998 })
9999 .detach_and_log_err(cx);
10000}
10001
10002fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
10003 let mut parts = value.split(',');
10004 let x: usize = parts.next()?.parse().ok()?;
10005 let y: usize = parts.next()?.parse().ok()?;
10006 Some(point(px(x as f32), px(y as f32)))
10007}
10008
10009fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
10010 let mut parts = value.split(',');
10011 let width: usize = parts.next()?.parse().ok()?;
10012 let height: usize = parts.next()?.parse().ok()?;
10013 Some(size(px(width as f32), px(height as f32)))
10014}
10015
10016/// Add client-side decorations (rounded corners, shadows, resize handling) when
10017/// appropriate.
10018///
10019/// The `border_radius_tiling` parameter allows overriding which corners get
10020/// rounded, independently of the actual window tiling state. This is used
10021/// specifically for the workspace switcher sidebar: when the sidebar is open,
10022/// we want square corners on the left (so the sidebar appears flush with the
10023/// window edge) but we still need the shadow padding for proper visual
10024/// appearance. Unlike actual window tiling, this only affects border radius -
10025/// not padding or shadows.
10026pub fn client_side_decorations(
10027 element: impl IntoElement,
10028 window: &mut Window,
10029 cx: &mut App,
10030 border_radius_tiling: Tiling,
10031) -> Stateful<Div> {
10032 const BORDER_SIZE: Pixels = px(1.0);
10033 let decorations = window.window_decorations();
10034 let tiling = match decorations {
10035 Decorations::Server => Tiling::default(),
10036 Decorations::Client { tiling } => tiling,
10037 };
10038
10039 match decorations {
10040 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
10041 Decorations::Server => window.set_client_inset(px(0.0)),
10042 }
10043
10044 struct GlobalResizeEdge(ResizeEdge);
10045 impl Global for GlobalResizeEdge {}
10046
10047 div()
10048 .id("window-backdrop")
10049 .bg(transparent_black())
10050 .map(|div| match decorations {
10051 Decorations::Server => div,
10052 Decorations::Client { .. } => div
10053 .when(
10054 !(tiling.top
10055 || tiling.right
10056 || border_radius_tiling.top
10057 || border_radius_tiling.right),
10058 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10059 )
10060 .when(
10061 !(tiling.top
10062 || tiling.left
10063 || border_radius_tiling.top
10064 || border_radius_tiling.left),
10065 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10066 )
10067 .when(
10068 !(tiling.bottom
10069 || tiling.right
10070 || border_radius_tiling.bottom
10071 || border_radius_tiling.right),
10072 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10073 )
10074 .when(
10075 !(tiling.bottom
10076 || tiling.left
10077 || border_radius_tiling.bottom
10078 || border_radius_tiling.left),
10079 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10080 )
10081 .when(!tiling.top, |div| {
10082 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10083 })
10084 .when(!tiling.bottom, |div| {
10085 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10086 })
10087 .when(!tiling.left, |div| {
10088 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10089 })
10090 .when(!tiling.right, |div| {
10091 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10092 })
10093 .on_mouse_move(move |e, window, cx| {
10094 let size = window.window_bounds().get_bounds().size;
10095 let pos = e.position;
10096
10097 let new_edge =
10098 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10099
10100 let edge = cx.try_global::<GlobalResizeEdge>();
10101 if new_edge != edge.map(|edge| edge.0) {
10102 window
10103 .window_handle()
10104 .update(cx, |workspace, _, cx| {
10105 cx.notify(workspace.entity_id());
10106 })
10107 .ok();
10108 }
10109 })
10110 .on_mouse_down(MouseButton::Left, move |e, window, _| {
10111 let size = window.window_bounds().get_bounds().size;
10112 let pos = e.position;
10113
10114 let edge = match resize_edge(
10115 pos,
10116 theme::CLIENT_SIDE_DECORATION_SHADOW,
10117 size,
10118 tiling,
10119 ) {
10120 Some(value) => value,
10121 None => return,
10122 };
10123
10124 window.start_window_resize(edge);
10125 }),
10126 })
10127 .size_full()
10128 .child(
10129 div()
10130 .cursor(CursorStyle::Arrow)
10131 .map(|div| match decorations {
10132 Decorations::Server => div,
10133 Decorations::Client { .. } => div
10134 .border_color(cx.theme().colors().border)
10135 .when(
10136 !(tiling.top
10137 || tiling.right
10138 || border_radius_tiling.top
10139 || border_radius_tiling.right),
10140 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10141 )
10142 .when(
10143 !(tiling.top
10144 || tiling.left
10145 || border_radius_tiling.top
10146 || border_radius_tiling.left),
10147 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10148 )
10149 .when(
10150 !(tiling.bottom
10151 || tiling.right
10152 || border_radius_tiling.bottom
10153 || border_radius_tiling.right),
10154 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10155 )
10156 .when(
10157 !(tiling.bottom
10158 || tiling.left
10159 || border_radius_tiling.bottom
10160 || border_radius_tiling.left),
10161 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10162 )
10163 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10164 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10165 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10166 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10167 .when(!tiling.is_tiled(), |div| {
10168 div.shadow(vec![gpui::BoxShadow {
10169 color: Hsla {
10170 h: 0.,
10171 s: 0.,
10172 l: 0.,
10173 a: 0.4,
10174 },
10175 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10176 spread_radius: px(0.),
10177 offset: point(px(0.0), px(0.0)),
10178 }])
10179 }),
10180 })
10181 .on_mouse_move(|_e, _, cx| {
10182 cx.stop_propagation();
10183 })
10184 .size_full()
10185 .child(element),
10186 )
10187 .map(|div| match decorations {
10188 Decorations::Server => div,
10189 Decorations::Client { tiling, .. } => div.child(
10190 canvas(
10191 |_bounds, window, _| {
10192 window.insert_hitbox(
10193 Bounds::new(
10194 point(px(0.0), px(0.0)),
10195 window.window_bounds().get_bounds().size,
10196 ),
10197 HitboxBehavior::Normal,
10198 )
10199 },
10200 move |_bounds, hitbox, window, cx| {
10201 let mouse = window.mouse_position();
10202 let size = window.window_bounds().get_bounds().size;
10203 let Some(edge) =
10204 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10205 else {
10206 return;
10207 };
10208 cx.set_global(GlobalResizeEdge(edge));
10209 window.set_cursor_style(
10210 match edge {
10211 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10212 ResizeEdge::Left | ResizeEdge::Right => {
10213 CursorStyle::ResizeLeftRight
10214 }
10215 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10216 CursorStyle::ResizeUpLeftDownRight
10217 }
10218 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10219 CursorStyle::ResizeUpRightDownLeft
10220 }
10221 },
10222 &hitbox,
10223 );
10224 },
10225 )
10226 .size_full()
10227 .absolute(),
10228 ),
10229 })
10230}
10231
10232fn resize_edge(
10233 pos: Point<Pixels>,
10234 shadow_size: Pixels,
10235 window_size: Size<Pixels>,
10236 tiling: Tiling,
10237) -> Option<ResizeEdge> {
10238 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10239 if bounds.contains(&pos) {
10240 return None;
10241 }
10242
10243 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10244 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10245 if !tiling.top && top_left_bounds.contains(&pos) {
10246 return Some(ResizeEdge::TopLeft);
10247 }
10248
10249 let top_right_bounds = Bounds::new(
10250 Point::new(window_size.width - corner_size.width, px(0.)),
10251 corner_size,
10252 );
10253 if !tiling.top && top_right_bounds.contains(&pos) {
10254 return Some(ResizeEdge::TopRight);
10255 }
10256
10257 let bottom_left_bounds = Bounds::new(
10258 Point::new(px(0.), window_size.height - corner_size.height),
10259 corner_size,
10260 );
10261 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10262 return Some(ResizeEdge::BottomLeft);
10263 }
10264
10265 let bottom_right_bounds = Bounds::new(
10266 Point::new(
10267 window_size.width - corner_size.width,
10268 window_size.height - corner_size.height,
10269 ),
10270 corner_size,
10271 );
10272 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10273 return Some(ResizeEdge::BottomRight);
10274 }
10275
10276 if !tiling.top && pos.y < shadow_size {
10277 Some(ResizeEdge::Top)
10278 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10279 Some(ResizeEdge::Bottom)
10280 } else if !tiling.left && pos.x < shadow_size {
10281 Some(ResizeEdge::Left)
10282 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10283 Some(ResizeEdge::Right)
10284 } else {
10285 None
10286 }
10287}
10288
10289fn join_pane_into_active(
10290 active_pane: &Entity<Pane>,
10291 pane: &Entity<Pane>,
10292 window: &mut Window,
10293 cx: &mut App,
10294) {
10295 if pane == active_pane {
10296 } else if pane.read(cx).items_len() == 0 {
10297 pane.update(cx, |_, cx| {
10298 cx.emit(pane::Event::Remove {
10299 focus_on_pane: None,
10300 });
10301 })
10302 } else {
10303 move_all_items(pane, active_pane, window, cx);
10304 }
10305}
10306
10307fn move_all_items(
10308 from_pane: &Entity<Pane>,
10309 to_pane: &Entity<Pane>,
10310 window: &mut Window,
10311 cx: &mut App,
10312) {
10313 let destination_is_different = from_pane != to_pane;
10314 let mut moved_items = 0;
10315 for (item_ix, item_handle) in from_pane
10316 .read(cx)
10317 .items()
10318 .enumerate()
10319 .map(|(ix, item)| (ix, item.clone()))
10320 .collect::<Vec<_>>()
10321 {
10322 let ix = item_ix - moved_items;
10323 if destination_is_different {
10324 // Close item from previous pane
10325 from_pane.update(cx, |source, cx| {
10326 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10327 });
10328 moved_items += 1;
10329 }
10330
10331 // This automatically removes duplicate items in the pane
10332 to_pane.update(cx, |destination, cx| {
10333 destination.add_item(item_handle, true, true, None, window, cx);
10334 window.focus(&destination.focus_handle(cx), cx)
10335 });
10336 }
10337}
10338
10339pub fn move_item(
10340 source: &Entity<Pane>,
10341 destination: &Entity<Pane>,
10342 item_id_to_move: EntityId,
10343 destination_index: usize,
10344 activate: bool,
10345 window: &mut Window,
10346 cx: &mut App,
10347) {
10348 let Some((item_ix, item_handle)) = source
10349 .read(cx)
10350 .items()
10351 .enumerate()
10352 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10353 .map(|(ix, item)| (ix, item.clone()))
10354 else {
10355 // Tab was closed during drag
10356 return;
10357 };
10358
10359 if source != destination {
10360 // Close item from previous pane
10361 source.update(cx, |source, cx| {
10362 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10363 });
10364 }
10365
10366 // This automatically removes duplicate items in the pane
10367 destination.update(cx, |destination, cx| {
10368 destination.add_item_inner(
10369 item_handle,
10370 activate,
10371 activate,
10372 activate,
10373 Some(destination_index),
10374 window,
10375 cx,
10376 );
10377 if activate {
10378 window.focus(&destination.focus_handle(cx), cx)
10379 }
10380 });
10381}
10382
10383pub fn move_active_item(
10384 source: &Entity<Pane>,
10385 destination: &Entity<Pane>,
10386 focus_destination: bool,
10387 close_if_empty: bool,
10388 window: &mut Window,
10389 cx: &mut App,
10390) {
10391 if source == destination {
10392 return;
10393 }
10394 let Some(active_item) = source.read(cx).active_item() else {
10395 return;
10396 };
10397 source.update(cx, |source_pane, cx| {
10398 let item_id = active_item.item_id();
10399 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10400 destination.update(cx, |target_pane, cx| {
10401 target_pane.add_item(
10402 active_item,
10403 focus_destination,
10404 focus_destination,
10405 Some(target_pane.items_len()),
10406 window,
10407 cx,
10408 );
10409 });
10410 });
10411}
10412
10413pub fn clone_active_item(
10414 workspace_id: Option<WorkspaceId>,
10415 source: &Entity<Pane>,
10416 destination: &Entity<Pane>,
10417 focus_destination: bool,
10418 window: &mut Window,
10419 cx: &mut App,
10420) {
10421 if source == destination {
10422 return;
10423 }
10424 let Some(active_item) = source.read(cx).active_item() else {
10425 return;
10426 };
10427 if !active_item.can_split(cx) {
10428 return;
10429 }
10430 let destination = destination.downgrade();
10431 let task = active_item.clone_on_split(workspace_id, window, cx);
10432 window
10433 .spawn(cx, async move |cx| {
10434 let Some(clone) = task.await else {
10435 return;
10436 };
10437 destination
10438 .update_in(cx, |target_pane, window, cx| {
10439 target_pane.add_item(
10440 clone,
10441 focus_destination,
10442 focus_destination,
10443 Some(target_pane.items_len()),
10444 window,
10445 cx,
10446 );
10447 })
10448 .log_err();
10449 })
10450 .detach();
10451}
10452
10453#[derive(Debug)]
10454pub struct WorkspacePosition {
10455 pub window_bounds: Option<WindowBounds>,
10456 pub display: Option<Uuid>,
10457 pub centered_layout: bool,
10458}
10459
10460pub fn remote_workspace_position_from_db(
10461 connection_options: RemoteConnectionOptions,
10462 paths_to_open: &[PathBuf],
10463 cx: &App,
10464) -> Task<Result<WorkspacePosition>> {
10465 let paths = paths_to_open.to_vec();
10466 let db = WorkspaceDb::global(cx);
10467 let kvp = db::kvp::KeyValueStore::global(cx);
10468
10469 cx.background_spawn(async move {
10470 let remote_connection_id = db
10471 .get_or_create_remote_connection(connection_options)
10472 .await
10473 .context("fetching serialized ssh project")?;
10474 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10475
10476 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10477 (Some(WindowBounds::Windowed(bounds)), None)
10478 } else {
10479 let restorable_bounds = serialized_workspace
10480 .as_ref()
10481 .and_then(|workspace| {
10482 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10483 })
10484 .or_else(|| persistence::read_default_window_bounds(&kvp));
10485
10486 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10487 (Some(serialized_bounds), Some(serialized_display))
10488 } else {
10489 (None, None)
10490 }
10491 };
10492
10493 let centered_layout = serialized_workspace
10494 .as_ref()
10495 .map(|w| w.centered_layout)
10496 .unwrap_or(false);
10497
10498 Ok(WorkspacePosition {
10499 window_bounds,
10500 display,
10501 centered_layout,
10502 })
10503 })
10504}
10505
10506pub fn with_active_or_new_workspace(
10507 cx: &mut App,
10508 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10509) {
10510 match cx
10511 .active_window()
10512 .and_then(|w| w.downcast::<MultiWorkspace>())
10513 {
10514 Some(multi_workspace) => {
10515 cx.defer(move |cx| {
10516 multi_workspace
10517 .update(cx, |multi_workspace, window, cx| {
10518 let workspace = multi_workspace.workspace().clone();
10519 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10520 })
10521 .log_err();
10522 });
10523 }
10524 None => {
10525 let app_state = AppState::global(cx);
10526 open_new(
10527 OpenOptions::default(),
10528 app_state,
10529 cx,
10530 move |workspace, window, cx| f(workspace, window, cx),
10531 )
10532 .detach_and_log_err(cx);
10533 }
10534 }
10535}
10536
10537/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10538/// key. This migration path only runs once per panel per workspace.
10539fn load_legacy_panel_size(
10540 panel_key: &str,
10541 dock_position: DockPosition,
10542 workspace: &Workspace,
10543 cx: &mut App,
10544) -> Option<Pixels> {
10545 #[derive(Deserialize)]
10546 struct LegacyPanelState {
10547 #[serde(default)]
10548 width: Option<Pixels>,
10549 #[serde(default)]
10550 height: Option<Pixels>,
10551 }
10552
10553 let workspace_id = workspace
10554 .database_id()
10555 .map(|id| i64::from(id).to_string())
10556 .or_else(|| workspace.session_id())?;
10557
10558 let legacy_key = match panel_key {
10559 "ProjectPanel" => {
10560 format!("{}-{:?}", "ProjectPanel", workspace_id)
10561 }
10562 "OutlinePanel" => {
10563 format!("{}-{:?}", "OutlinePanel", workspace_id)
10564 }
10565 "GitPanel" => {
10566 format!("{}-{:?}", "GitPanel", workspace_id)
10567 }
10568 "TerminalPanel" => {
10569 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10570 }
10571 _ => return None,
10572 };
10573
10574 let kvp = db::kvp::KeyValueStore::global(cx);
10575 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10576 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10577 let size = match dock_position {
10578 DockPosition::Bottom => state.height,
10579 DockPosition::Left | DockPosition::Right => state.width,
10580 }?;
10581
10582 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10583 .detach_and_log_err(cx);
10584
10585 Some(size)
10586}
10587
10588#[cfg(test)]
10589mod tests {
10590 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10591
10592 use super::*;
10593 use crate::{
10594 dock::{PanelEvent, test::TestPanel},
10595 item::{
10596 ItemBufferKind, ItemEvent,
10597 test::{TestItem, TestProjectItem},
10598 },
10599 };
10600 use fs::FakeFs;
10601 use gpui::{
10602 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10603 UpdateGlobal, VisualTestContext, px,
10604 };
10605 use project::{Project, ProjectEntryId};
10606 use serde_json::json;
10607 use settings::SettingsStore;
10608 use util::path;
10609 use util::rel_path::rel_path;
10610
10611 #[gpui::test]
10612 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10613 init_test(cx);
10614
10615 let fs = FakeFs::new(cx.executor());
10616 let project = Project::test(fs, [], cx).await;
10617 let (workspace, cx) =
10618 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10619
10620 // Adding an item with no ambiguity renders the tab without detail.
10621 let item1 = cx.new(|cx| {
10622 let mut item = TestItem::new(cx);
10623 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10624 item
10625 });
10626 workspace.update_in(cx, |workspace, window, cx| {
10627 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10628 });
10629 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10630
10631 // Adding an item that creates ambiguity increases the level of detail on
10632 // both tabs.
10633 let item2 = cx.new_window_entity(|_window, cx| {
10634 let mut item = TestItem::new(cx);
10635 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10636 item
10637 });
10638 workspace.update_in(cx, |workspace, window, cx| {
10639 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10640 });
10641 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10642 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10643
10644 // Adding an item that creates ambiguity increases the level of detail only
10645 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10646 // we stop at the highest detail available.
10647 let item3 = cx.new(|cx| {
10648 let mut item = TestItem::new(cx);
10649 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10650 item
10651 });
10652 workspace.update_in(cx, |workspace, window, cx| {
10653 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10654 });
10655 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10656 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10657 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10658 }
10659
10660 #[gpui::test]
10661 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10662 init_test(cx);
10663
10664 let fs = FakeFs::new(cx.executor());
10665 fs.insert_tree(
10666 "/root1",
10667 json!({
10668 "one.txt": "",
10669 "two.txt": "",
10670 }),
10671 )
10672 .await;
10673 fs.insert_tree(
10674 "/root2",
10675 json!({
10676 "three.txt": "",
10677 }),
10678 )
10679 .await;
10680
10681 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10682 let (workspace, cx) =
10683 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10684 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10685 let worktree_id = project.update(cx, |project, cx| {
10686 project.worktrees(cx).next().unwrap().read(cx).id()
10687 });
10688
10689 let item1 = cx.new(|cx| {
10690 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10691 });
10692 let item2 = cx.new(|cx| {
10693 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10694 });
10695
10696 // Add an item to an empty pane
10697 workspace.update_in(cx, |workspace, window, cx| {
10698 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10699 });
10700 project.update(cx, |project, cx| {
10701 assert_eq!(
10702 project.active_entry(),
10703 project
10704 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10705 .map(|e| e.id)
10706 );
10707 });
10708 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10709
10710 // Add a second item to a non-empty pane
10711 workspace.update_in(cx, |workspace, window, cx| {
10712 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10713 });
10714 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10715 project.update(cx, |project, cx| {
10716 assert_eq!(
10717 project.active_entry(),
10718 project
10719 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10720 .map(|e| e.id)
10721 );
10722 });
10723
10724 // Close the active item
10725 pane.update_in(cx, |pane, window, cx| {
10726 pane.close_active_item(&Default::default(), window, cx)
10727 })
10728 .await
10729 .unwrap();
10730 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10731 project.update(cx, |project, cx| {
10732 assert_eq!(
10733 project.active_entry(),
10734 project
10735 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10736 .map(|e| e.id)
10737 );
10738 });
10739
10740 // Add a project folder
10741 project
10742 .update(cx, |project, cx| {
10743 project.find_or_create_worktree("root2", true, cx)
10744 })
10745 .await
10746 .unwrap();
10747 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10748
10749 // Remove a project folder
10750 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10751 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10752 }
10753
10754 #[gpui::test]
10755 async fn test_close_window(cx: &mut TestAppContext) {
10756 init_test(cx);
10757
10758 let fs = FakeFs::new(cx.executor());
10759 fs.insert_tree("/root", json!({ "one": "" })).await;
10760
10761 let project = Project::test(fs, ["root".as_ref()], cx).await;
10762 let (workspace, cx) =
10763 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10764
10765 // When there are no dirty items, there's nothing to do.
10766 let item1 = cx.new(TestItem::new);
10767 workspace.update_in(cx, |w, window, cx| {
10768 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10769 });
10770 let task = workspace.update_in(cx, |w, window, cx| {
10771 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10772 });
10773 assert!(task.await.unwrap());
10774
10775 // When there are dirty untitled items, prompt to save each one. If the user
10776 // cancels any prompt, then abort.
10777 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10778 let item3 = cx.new(|cx| {
10779 TestItem::new(cx)
10780 .with_dirty(true)
10781 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10782 });
10783 workspace.update_in(cx, |w, window, cx| {
10784 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10785 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10786 });
10787 let task = workspace.update_in(cx, |w, window, cx| {
10788 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10789 });
10790 cx.executor().run_until_parked();
10791 cx.simulate_prompt_answer("Cancel"); // cancel save all
10792 cx.executor().run_until_parked();
10793 assert!(!cx.has_pending_prompt());
10794 assert!(!task.await.unwrap());
10795 }
10796
10797 #[gpui::test]
10798 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10799 init_test(cx);
10800
10801 let fs = FakeFs::new(cx.executor());
10802 fs.insert_tree("/root", json!({ "one": "" })).await;
10803
10804 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10805 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10806 let multi_workspace_handle =
10807 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10808 cx.run_until_parked();
10809
10810 multi_workspace_handle
10811 .update(cx, |mw, _window, cx| {
10812 mw.open_sidebar(cx);
10813 })
10814 .unwrap();
10815
10816 let workspace_a = multi_workspace_handle
10817 .read_with(cx, |mw, _| mw.workspace().clone())
10818 .unwrap();
10819
10820 let workspace_b = multi_workspace_handle
10821 .update(cx, |mw, window, cx| {
10822 mw.test_add_workspace(project_b, window, cx)
10823 })
10824 .unwrap();
10825
10826 // Activate workspace A
10827 multi_workspace_handle
10828 .update(cx, |mw, window, cx| {
10829 let workspace = mw.workspaces().next().unwrap().clone();
10830 mw.activate(workspace, window, cx);
10831 })
10832 .unwrap();
10833
10834 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10835
10836 // Workspace A has a clean item
10837 let item_a = cx.new(TestItem::new);
10838 workspace_a.update_in(cx, |w, window, cx| {
10839 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10840 });
10841
10842 // Workspace B has a dirty item
10843 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10844 workspace_b.update_in(cx, |w, window, cx| {
10845 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10846 });
10847
10848 // Verify workspace A is active
10849 multi_workspace_handle
10850 .read_with(cx, |mw, _| {
10851 assert_eq!(mw.workspace(), &workspace_a);
10852 })
10853 .unwrap();
10854
10855 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10856 multi_workspace_handle
10857 .update(cx, |mw, window, cx| {
10858 mw.close_window(&CloseWindow, window, cx);
10859 })
10860 .unwrap();
10861 cx.run_until_parked();
10862
10863 // Workspace B should now be active since it has dirty items that need attention
10864 multi_workspace_handle
10865 .read_with(cx, |mw, _| {
10866 assert_eq!(
10867 mw.workspace(),
10868 &workspace_b,
10869 "workspace B should be activated when it prompts"
10870 );
10871 })
10872 .unwrap();
10873
10874 // User cancels the save prompt from workspace B
10875 cx.simulate_prompt_answer("Cancel");
10876 cx.run_until_parked();
10877
10878 // Window should still exist because workspace B's close was cancelled
10879 assert!(
10880 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10881 "window should still exist after cancelling one workspace's close"
10882 );
10883 }
10884
10885 #[gpui::test]
10886 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10887 init_test(cx);
10888
10889 // Register TestItem as a serializable item
10890 cx.update(|cx| {
10891 register_serializable_item::<TestItem>(cx);
10892 });
10893
10894 let fs = FakeFs::new(cx.executor());
10895 fs.insert_tree("/root", json!({ "one": "" })).await;
10896
10897 let project = Project::test(fs, ["root".as_ref()], cx).await;
10898 let (workspace, cx) =
10899 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10900
10901 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10902 let item1 = cx.new(|cx| {
10903 TestItem::new(cx)
10904 .with_dirty(true)
10905 .with_serialize(|| Some(Task::ready(Ok(()))))
10906 });
10907 let item2 = cx.new(|cx| {
10908 TestItem::new(cx)
10909 .with_dirty(true)
10910 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10911 .with_serialize(|| Some(Task::ready(Ok(()))))
10912 });
10913 workspace.update_in(cx, |w, window, cx| {
10914 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10915 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10916 });
10917 let task = workspace.update_in(cx, |w, window, cx| {
10918 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10919 });
10920 assert!(task.await.unwrap());
10921 }
10922
10923 #[gpui::test]
10924 async fn test_close_pane_items(cx: &mut TestAppContext) {
10925 init_test(cx);
10926
10927 let fs = FakeFs::new(cx.executor());
10928
10929 let project = Project::test(fs, None, cx).await;
10930 let (workspace, cx) =
10931 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10932
10933 let item1 = cx.new(|cx| {
10934 TestItem::new(cx)
10935 .with_dirty(true)
10936 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10937 });
10938 let item2 = cx.new(|cx| {
10939 TestItem::new(cx)
10940 .with_dirty(true)
10941 .with_conflict(true)
10942 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10943 });
10944 let item3 = cx.new(|cx| {
10945 TestItem::new(cx)
10946 .with_dirty(true)
10947 .with_conflict(true)
10948 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10949 });
10950 let item4 = cx.new(|cx| {
10951 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10952 let project_item = TestProjectItem::new_untitled(cx);
10953 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10954 project_item
10955 }])
10956 });
10957 let pane = workspace.update_in(cx, |workspace, window, cx| {
10958 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10959 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10960 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10961 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10962 workspace.active_pane().clone()
10963 });
10964
10965 let close_items = pane.update_in(cx, |pane, window, cx| {
10966 pane.activate_item(1, true, true, window, cx);
10967 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10968 let item1_id = item1.item_id();
10969 let item3_id = item3.item_id();
10970 let item4_id = item4.item_id();
10971 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10972 [item1_id, item3_id, item4_id].contains(&id)
10973 })
10974 });
10975 cx.executor().run_until_parked();
10976
10977 assert!(cx.has_pending_prompt());
10978 cx.simulate_prompt_answer("Save all");
10979
10980 cx.executor().run_until_parked();
10981
10982 // Item 1 is saved. There's a prompt to save item 3.
10983 pane.update(cx, |pane, cx| {
10984 assert_eq!(item1.read(cx).save_count, 1);
10985 assert_eq!(item1.read(cx).save_as_count, 0);
10986 assert_eq!(item1.read(cx).reload_count, 0);
10987 assert_eq!(pane.items_len(), 3);
10988 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10989 });
10990 assert!(cx.has_pending_prompt());
10991
10992 // Cancel saving item 3.
10993 cx.simulate_prompt_answer("Discard");
10994 cx.executor().run_until_parked();
10995
10996 // Item 3 is reloaded. There's a prompt to save item 4.
10997 pane.update(cx, |pane, cx| {
10998 assert_eq!(item3.read(cx).save_count, 0);
10999 assert_eq!(item3.read(cx).save_as_count, 0);
11000 assert_eq!(item3.read(cx).reload_count, 1);
11001 assert_eq!(pane.items_len(), 2);
11002 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
11003 });
11004
11005 // There's a prompt for a path for item 4.
11006 cx.simulate_new_path_selection(|_| Some(Default::default()));
11007 close_items.await.unwrap();
11008
11009 // The requested items are closed.
11010 pane.update(cx, |pane, cx| {
11011 assert_eq!(item4.read(cx).save_count, 0);
11012 assert_eq!(item4.read(cx).save_as_count, 1);
11013 assert_eq!(item4.read(cx).reload_count, 0);
11014 assert_eq!(pane.items_len(), 1);
11015 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11016 });
11017 }
11018
11019 #[gpui::test]
11020 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
11021 init_test(cx);
11022
11023 let fs = FakeFs::new(cx.executor());
11024 let project = Project::test(fs, [], cx).await;
11025 let (workspace, cx) =
11026 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11027
11028 // Create several workspace items with single project entries, and two
11029 // workspace items with multiple project entries.
11030 let single_entry_items = (0..=4)
11031 .map(|project_entry_id| {
11032 cx.new(|cx| {
11033 TestItem::new(cx)
11034 .with_dirty(true)
11035 .with_project_items(&[dirty_project_item(
11036 project_entry_id,
11037 &format!("{project_entry_id}.txt"),
11038 cx,
11039 )])
11040 })
11041 })
11042 .collect::<Vec<_>>();
11043 let item_2_3 = cx.new(|cx| {
11044 TestItem::new(cx)
11045 .with_dirty(true)
11046 .with_buffer_kind(ItemBufferKind::Multibuffer)
11047 .with_project_items(&[
11048 single_entry_items[2].read(cx).project_items[0].clone(),
11049 single_entry_items[3].read(cx).project_items[0].clone(),
11050 ])
11051 });
11052 let item_3_4 = cx.new(|cx| {
11053 TestItem::new(cx)
11054 .with_dirty(true)
11055 .with_buffer_kind(ItemBufferKind::Multibuffer)
11056 .with_project_items(&[
11057 single_entry_items[3].read(cx).project_items[0].clone(),
11058 single_entry_items[4].read(cx).project_items[0].clone(),
11059 ])
11060 });
11061
11062 // Create two panes that contain the following project entries:
11063 // left pane:
11064 // multi-entry items: (2, 3)
11065 // single-entry items: 0, 2, 3, 4
11066 // right pane:
11067 // single-entry items: 4, 1
11068 // multi-entry items: (3, 4)
11069 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11070 let left_pane = workspace.active_pane().clone();
11071 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11072 workspace.add_item_to_active_pane(
11073 single_entry_items[0].boxed_clone(),
11074 None,
11075 true,
11076 window,
11077 cx,
11078 );
11079 workspace.add_item_to_active_pane(
11080 single_entry_items[2].boxed_clone(),
11081 None,
11082 true,
11083 window,
11084 cx,
11085 );
11086 workspace.add_item_to_active_pane(
11087 single_entry_items[3].boxed_clone(),
11088 None,
11089 true,
11090 window,
11091 cx,
11092 );
11093 workspace.add_item_to_active_pane(
11094 single_entry_items[4].boxed_clone(),
11095 None,
11096 true,
11097 window,
11098 cx,
11099 );
11100
11101 let right_pane =
11102 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11103
11104 let boxed_clone = single_entry_items[1].boxed_clone();
11105 let right_pane = window.spawn(cx, async move |cx| {
11106 right_pane.await.inspect(|right_pane| {
11107 right_pane
11108 .update_in(cx, |pane, window, cx| {
11109 pane.add_item(boxed_clone, true, true, None, window, cx);
11110 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11111 })
11112 .unwrap();
11113 })
11114 });
11115
11116 (left_pane, right_pane)
11117 });
11118 let right_pane = right_pane.await.unwrap();
11119 cx.focus(&right_pane);
11120
11121 let close = right_pane.update_in(cx, |pane, window, cx| {
11122 pane.close_all_items(&CloseAllItems::default(), window, cx)
11123 .unwrap()
11124 });
11125 cx.executor().run_until_parked();
11126
11127 let msg = cx.pending_prompt().unwrap().0;
11128 assert!(msg.contains("1.txt"));
11129 assert!(!msg.contains("2.txt"));
11130 assert!(!msg.contains("3.txt"));
11131 assert!(!msg.contains("4.txt"));
11132
11133 // With best-effort close, cancelling item 1 keeps it open but items 4
11134 // and (3,4) still close since their entries exist in left pane.
11135 cx.simulate_prompt_answer("Cancel");
11136 close.await;
11137
11138 right_pane.read_with(cx, |pane, _| {
11139 assert_eq!(pane.items_len(), 1);
11140 });
11141
11142 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11143 left_pane
11144 .update_in(cx, |left_pane, window, cx| {
11145 left_pane.close_item_by_id(
11146 single_entry_items[3].entity_id(),
11147 SaveIntent::Skip,
11148 window,
11149 cx,
11150 )
11151 })
11152 .await
11153 .unwrap();
11154
11155 let close = left_pane.update_in(cx, |pane, window, cx| {
11156 pane.close_all_items(&CloseAllItems::default(), window, cx)
11157 .unwrap()
11158 });
11159 cx.executor().run_until_parked();
11160
11161 let details = cx.pending_prompt().unwrap().1;
11162 assert!(details.contains("0.txt"));
11163 assert!(details.contains("3.txt"));
11164 assert!(details.contains("4.txt"));
11165 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11166 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11167 // assert!(!details.contains("2.txt"));
11168
11169 cx.simulate_prompt_answer("Save all");
11170 cx.executor().run_until_parked();
11171 close.await;
11172
11173 left_pane.read_with(cx, |pane, _| {
11174 assert_eq!(pane.items_len(), 0);
11175 });
11176 }
11177
11178 #[gpui::test]
11179 async fn test_autosave(cx: &mut gpui::TestAppContext) {
11180 init_test(cx);
11181
11182 let fs = FakeFs::new(cx.executor());
11183 let project = Project::test(fs, [], cx).await;
11184 let (workspace, cx) =
11185 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11186 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11187
11188 let item = cx.new(|cx| {
11189 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11190 });
11191 let item_id = item.entity_id();
11192 workspace.update_in(cx, |workspace, window, cx| {
11193 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11194 });
11195
11196 // Autosave on window change.
11197 item.update(cx, |item, cx| {
11198 SettingsStore::update_global(cx, |settings, cx| {
11199 settings.update_user_settings(cx, |settings| {
11200 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11201 })
11202 });
11203 item.is_dirty = true;
11204 });
11205
11206 // Deactivating the window saves the file.
11207 cx.deactivate_window();
11208 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11209
11210 // Re-activating the window doesn't save the file.
11211 cx.update(|window, _| window.activate_window());
11212 cx.executor().run_until_parked();
11213 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11214
11215 // Autosave on focus change.
11216 item.update_in(cx, |item, window, cx| {
11217 cx.focus_self(window);
11218 SettingsStore::update_global(cx, |settings, cx| {
11219 settings.update_user_settings(cx, |settings| {
11220 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11221 })
11222 });
11223 item.is_dirty = true;
11224 });
11225 // Blurring the item saves the file.
11226 item.update_in(cx, |_, window, _| window.blur());
11227 cx.executor().run_until_parked();
11228 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11229
11230 // Deactivating the window still saves the file.
11231 item.update_in(cx, |item, window, cx| {
11232 cx.focus_self(window);
11233 item.is_dirty = true;
11234 });
11235 cx.deactivate_window();
11236 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11237
11238 // Autosave after delay.
11239 item.update(cx, |item, cx| {
11240 SettingsStore::update_global(cx, |settings, cx| {
11241 settings.update_user_settings(cx, |settings| {
11242 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11243 milliseconds: 500.into(),
11244 });
11245 })
11246 });
11247 item.is_dirty = true;
11248 cx.emit(ItemEvent::Edit);
11249 });
11250
11251 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11252 cx.executor().advance_clock(Duration::from_millis(250));
11253 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11254
11255 // After delay expires, the file is saved.
11256 cx.executor().advance_clock(Duration::from_millis(250));
11257 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11258
11259 // Autosave after delay, should save earlier than delay if tab is closed
11260 item.update(cx, |item, cx| {
11261 item.is_dirty = true;
11262 cx.emit(ItemEvent::Edit);
11263 });
11264 cx.executor().advance_clock(Duration::from_millis(250));
11265 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11266
11267 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11268 pane.update_in(cx, |pane, window, cx| {
11269 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11270 })
11271 .await
11272 .unwrap();
11273 assert!(!cx.has_pending_prompt());
11274 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11275
11276 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11277 workspace.update_in(cx, |workspace, window, cx| {
11278 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11279 });
11280 item.update_in(cx, |item, _window, cx| {
11281 item.is_dirty = true;
11282 for project_item in &mut item.project_items {
11283 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11284 }
11285 });
11286 cx.run_until_parked();
11287 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11288
11289 // Autosave on focus change, ensuring closing the tab counts as such.
11290 item.update(cx, |item, cx| {
11291 SettingsStore::update_global(cx, |settings, cx| {
11292 settings.update_user_settings(cx, |settings| {
11293 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11294 })
11295 });
11296 item.is_dirty = true;
11297 for project_item in &mut item.project_items {
11298 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11299 }
11300 });
11301
11302 pane.update_in(cx, |pane, window, cx| {
11303 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11304 })
11305 .await
11306 .unwrap();
11307 assert!(!cx.has_pending_prompt());
11308 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11309
11310 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11311 workspace.update_in(cx, |workspace, window, cx| {
11312 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11313 });
11314 item.update_in(cx, |item, window, cx| {
11315 item.project_items[0].update(cx, |item, _| {
11316 item.entry_id = None;
11317 });
11318 item.is_dirty = true;
11319 window.blur();
11320 });
11321 cx.run_until_parked();
11322 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11323
11324 // Ensure autosave is prevented for deleted files also when closing the buffer.
11325 let _close_items = pane.update_in(cx, |pane, window, cx| {
11326 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11327 });
11328 cx.run_until_parked();
11329 assert!(cx.has_pending_prompt());
11330 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11331 }
11332
11333 #[gpui::test]
11334 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11335 init_test(cx);
11336
11337 let fs = FakeFs::new(cx.executor());
11338 let project = Project::test(fs, [], cx).await;
11339 let (workspace, cx) =
11340 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11341
11342 // Create a multibuffer-like item with two child focus handles,
11343 // simulating individual buffer editors within a multibuffer.
11344 let item = cx.new(|cx| {
11345 TestItem::new(cx)
11346 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11347 .with_child_focus_handles(2, cx)
11348 });
11349 workspace.update_in(cx, |workspace, window, cx| {
11350 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11351 });
11352
11353 // Set autosave to OnFocusChange and focus the first child handle,
11354 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11355 item.update_in(cx, |item, window, cx| {
11356 SettingsStore::update_global(cx, |settings, cx| {
11357 settings.update_user_settings(cx, |settings| {
11358 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11359 })
11360 });
11361 item.is_dirty = true;
11362 window.focus(&item.child_focus_handles[0], cx);
11363 });
11364 cx.executor().run_until_parked();
11365 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11366
11367 // Moving focus from one child to another within the same item should
11368 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11369 item.update_in(cx, |item, window, cx| {
11370 window.focus(&item.child_focus_handles[1], cx);
11371 });
11372 cx.executor().run_until_parked();
11373 item.read_with(cx, |item, _| {
11374 assert_eq!(
11375 item.save_count, 0,
11376 "Switching focus between children within the same item should not autosave"
11377 );
11378 });
11379
11380 // Blurring the item saves the file. This is the core regression scenario:
11381 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11382 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11383 // the leaf is always a child focus handle, so `on_blur` never detected
11384 // focus leaving the item.
11385 item.update_in(cx, |_, window, _| window.blur());
11386 cx.executor().run_until_parked();
11387 item.read_with(cx, |item, _| {
11388 assert_eq!(
11389 item.save_count, 1,
11390 "Blurring should trigger autosave when focus was on a child of the item"
11391 );
11392 });
11393
11394 // Deactivating the window should also trigger autosave when a child of
11395 // the multibuffer item currently owns focus.
11396 item.update_in(cx, |item, window, cx| {
11397 item.is_dirty = true;
11398 window.focus(&item.child_focus_handles[0], cx);
11399 });
11400 cx.executor().run_until_parked();
11401 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11402
11403 cx.deactivate_window();
11404 item.read_with(cx, |item, _| {
11405 assert_eq!(
11406 item.save_count, 2,
11407 "Deactivating window should trigger autosave when focus was on a child"
11408 );
11409 });
11410 }
11411
11412 #[gpui::test]
11413 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11414 init_test(cx);
11415
11416 let fs = FakeFs::new(cx.executor());
11417
11418 let project = Project::test(fs, [], cx).await;
11419 let (workspace, cx) =
11420 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11421
11422 let item = cx.new(|cx| {
11423 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11424 });
11425 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11426 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11427 let toolbar_notify_count = Rc::new(RefCell::new(0));
11428
11429 workspace.update_in(cx, |workspace, window, cx| {
11430 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11431 let toolbar_notification_count = toolbar_notify_count.clone();
11432 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11433 *toolbar_notification_count.borrow_mut() += 1
11434 })
11435 .detach();
11436 });
11437
11438 pane.read_with(cx, |pane, _| {
11439 assert!(!pane.can_navigate_backward());
11440 assert!(!pane.can_navigate_forward());
11441 });
11442
11443 item.update_in(cx, |item, _, cx| {
11444 item.set_state("one".to_string(), cx);
11445 });
11446
11447 // Toolbar must be notified to re-render the navigation buttons
11448 assert_eq!(*toolbar_notify_count.borrow(), 1);
11449
11450 pane.read_with(cx, |pane, _| {
11451 assert!(pane.can_navigate_backward());
11452 assert!(!pane.can_navigate_forward());
11453 });
11454
11455 workspace
11456 .update_in(cx, |workspace, window, cx| {
11457 workspace.go_back(pane.downgrade(), window, cx)
11458 })
11459 .await
11460 .unwrap();
11461
11462 assert_eq!(*toolbar_notify_count.borrow(), 2);
11463 pane.read_with(cx, |pane, _| {
11464 assert!(!pane.can_navigate_backward());
11465 assert!(pane.can_navigate_forward());
11466 });
11467 }
11468
11469 /// Tests that the navigation history deduplicates entries for the same item.
11470 ///
11471 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11472 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11473 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11474 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11475 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11476 ///
11477 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11478 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11479 #[gpui::test]
11480 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11481 init_test(cx);
11482
11483 let fs = FakeFs::new(cx.executor());
11484 let project = Project::test(fs, [], cx).await;
11485 let (workspace, cx) =
11486 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11487
11488 let item_a = cx.new(|cx| {
11489 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11490 });
11491 let item_b = cx.new(|cx| {
11492 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11493 });
11494 let item_c = cx.new(|cx| {
11495 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11496 });
11497
11498 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11499
11500 workspace.update_in(cx, |workspace, window, cx| {
11501 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11502 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11503 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11504 });
11505
11506 workspace.update_in(cx, |workspace, window, cx| {
11507 workspace.activate_item(&item_a, false, false, window, cx);
11508 });
11509 cx.run_until_parked();
11510
11511 workspace.update_in(cx, |workspace, window, cx| {
11512 workspace.activate_item(&item_b, false, false, window, cx);
11513 });
11514 cx.run_until_parked();
11515
11516 workspace.update_in(cx, |workspace, window, cx| {
11517 workspace.activate_item(&item_a, false, false, window, cx);
11518 });
11519 cx.run_until_parked();
11520
11521 workspace.update_in(cx, |workspace, window, cx| {
11522 workspace.activate_item(&item_b, false, false, window, cx);
11523 });
11524 cx.run_until_parked();
11525
11526 workspace.update_in(cx, |workspace, window, cx| {
11527 workspace.activate_item(&item_a, false, false, window, cx);
11528 });
11529 cx.run_until_parked();
11530
11531 workspace.update_in(cx, |workspace, window, cx| {
11532 workspace.activate_item(&item_b, false, false, window, cx);
11533 });
11534 cx.run_until_parked();
11535
11536 workspace.update_in(cx, |workspace, window, cx| {
11537 workspace.activate_item(&item_c, false, false, window, cx);
11538 });
11539 cx.run_until_parked();
11540
11541 let backward_count = pane.read_with(cx, |pane, cx| {
11542 let mut count = 0;
11543 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11544 count += 1;
11545 });
11546 count
11547 });
11548 assert!(
11549 backward_count <= 4,
11550 "Should have at most 4 entries, got {}",
11551 backward_count
11552 );
11553
11554 workspace
11555 .update_in(cx, |workspace, window, cx| {
11556 workspace.go_back(pane.downgrade(), window, cx)
11557 })
11558 .await
11559 .unwrap();
11560
11561 let active_item = workspace.read_with(cx, |workspace, cx| {
11562 workspace.active_item(cx).unwrap().item_id()
11563 });
11564 assert_eq!(
11565 active_item,
11566 item_b.entity_id(),
11567 "After first go_back, should be at item B"
11568 );
11569
11570 workspace
11571 .update_in(cx, |workspace, window, cx| {
11572 workspace.go_back(pane.downgrade(), window, cx)
11573 })
11574 .await
11575 .unwrap();
11576
11577 let active_item = workspace.read_with(cx, |workspace, cx| {
11578 workspace.active_item(cx).unwrap().item_id()
11579 });
11580 assert_eq!(
11581 active_item,
11582 item_a.entity_id(),
11583 "After second go_back, should be at item A"
11584 );
11585
11586 pane.read_with(cx, |pane, _| {
11587 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11588 });
11589 }
11590
11591 #[gpui::test]
11592 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11593 init_test(cx);
11594 let fs = FakeFs::new(cx.executor());
11595 let project = Project::test(fs, [], cx).await;
11596 let (multi_workspace, cx) =
11597 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11598 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11599
11600 workspace.update_in(cx, |workspace, window, cx| {
11601 let first_item = cx.new(|cx| {
11602 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11603 });
11604 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11605 workspace.split_pane(
11606 workspace.active_pane().clone(),
11607 SplitDirection::Right,
11608 window,
11609 cx,
11610 );
11611 workspace.split_pane(
11612 workspace.active_pane().clone(),
11613 SplitDirection::Right,
11614 window,
11615 cx,
11616 );
11617 });
11618
11619 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11620 let panes = workspace.center.panes();
11621 assert!(panes.len() >= 2);
11622 (
11623 panes.first().expect("at least one pane").entity_id(),
11624 panes.last().expect("at least one pane").entity_id(),
11625 )
11626 });
11627
11628 workspace.update_in(cx, |workspace, window, cx| {
11629 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11630 });
11631 workspace.update(cx, |workspace, _| {
11632 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11633 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11634 });
11635
11636 cx.dispatch_action(ActivateLastPane);
11637
11638 workspace.update(cx, |workspace, _| {
11639 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11640 });
11641 }
11642
11643 #[gpui::test]
11644 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11645 init_test(cx);
11646 let fs = FakeFs::new(cx.executor());
11647
11648 let project = Project::test(fs, [], cx).await;
11649 let (workspace, cx) =
11650 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11651
11652 let panel = workspace.update_in(cx, |workspace, window, cx| {
11653 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11654 workspace.add_panel(panel.clone(), window, cx);
11655
11656 workspace
11657 .right_dock()
11658 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11659
11660 panel
11661 });
11662
11663 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11664 pane.update_in(cx, |pane, window, cx| {
11665 let item = cx.new(TestItem::new);
11666 pane.add_item(Box::new(item), true, true, None, window, cx);
11667 });
11668
11669 // Transfer focus from center to panel
11670 workspace.update_in(cx, |workspace, window, cx| {
11671 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11672 });
11673
11674 workspace.update_in(cx, |workspace, window, cx| {
11675 assert!(workspace.right_dock().read(cx).is_open());
11676 assert!(!panel.is_zoomed(window, cx));
11677 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11678 });
11679
11680 // Transfer focus from panel to center
11681 workspace.update_in(cx, |workspace, window, cx| {
11682 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11683 });
11684
11685 workspace.update_in(cx, |workspace, window, cx| {
11686 assert!(workspace.right_dock().read(cx).is_open());
11687 assert!(!panel.is_zoomed(window, cx));
11688 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11689 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11690 });
11691
11692 // Close the dock
11693 workspace.update_in(cx, |workspace, window, cx| {
11694 workspace.toggle_dock(DockPosition::Right, window, cx);
11695 });
11696
11697 workspace.update_in(cx, |workspace, window, cx| {
11698 assert!(!workspace.right_dock().read(cx).is_open());
11699 assert!(!panel.is_zoomed(window, cx));
11700 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11701 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11702 });
11703
11704 // Open the dock
11705 workspace.update_in(cx, |workspace, window, cx| {
11706 workspace.toggle_dock(DockPosition::Right, window, cx);
11707 });
11708
11709 workspace.update_in(cx, |workspace, window, cx| {
11710 assert!(workspace.right_dock().read(cx).is_open());
11711 assert!(!panel.is_zoomed(window, cx));
11712 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11713 });
11714
11715 // Focus and zoom panel
11716 panel.update_in(cx, |panel, window, cx| {
11717 cx.focus_self(window);
11718 panel.set_zoomed(true, window, cx)
11719 });
11720
11721 workspace.update_in(cx, |workspace, window, cx| {
11722 assert!(workspace.right_dock().read(cx).is_open());
11723 assert!(panel.is_zoomed(window, cx));
11724 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11725 });
11726
11727 // Transfer focus to the center closes the dock
11728 workspace.update_in(cx, |workspace, window, cx| {
11729 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11730 });
11731
11732 workspace.update_in(cx, |workspace, window, cx| {
11733 assert!(!workspace.right_dock().read(cx).is_open());
11734 assert!(panel.is_zoomed(window, cx));
11735 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11736 });
11737
11738 // Transferring focus back to the panel keeps it zoomed
11739 workspace.update_in(cx, |workspace, window, cx| {
11740 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11741 });
11742
11743 workspace.update_in(cx, |workspace, window, cx| {
11744 assert!(workspace.right_dock().read(cx).is_open());
11745 assert!(panel.is_zoomed(window, cx));
11746 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11747 });
11748
11749 // Close the dock while it is zoomed
11750 workspace.update_in(cx, |workspace, window, cx| {
11751 workspace.toggle_dock(DockPosition::Right, window, cx)
11752 });
11753
11754 workspace.update_in(cx, |workspace, window, cx| {
11755 assert!(!workspace.right_dock().read(cx).is_open());
11756 assert!(panel.is_zoomed(window, cx));
11757 assert!(workspace.zoomed.is_none());
11758 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11759 });
11760
11761 // Opening the dock, when it's zoomed, retains focus
11762 workspace.update_in(cx, |workspace, window, cx| {
11763 workspace.toggle_dock(DockPosition::Right, window, cx)
11764 });
11765
11766 workspace.update_in(cx, |workspace, window, cx| {
11767 assert!(workspace.right_dock().read(cx).is_open());
11768 assert!(panel.is_zoomed(window, cx));
11769 assert!(workspace.zoomed.is_some());
11770 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11771 });
11772
11773 // Unzoom and close the panel, zoom the active pane.
11774 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11775 workspace.update_in(cx, |workspace, window, cx| {
11776 workspace.toggle_dock(DockPosition::Right, window, cx)
11777 });
11778 pane.update_in(cx, |pane, window, cx| {
11779 pane.toggle_zoom(&Default::default(), window, cx)
11780 });
11781
11782 // Opening a dock unzooms the pane.
11783 workspace.update_in(cx, |workspace, window, cx| {
11784 workspace.toggle_dock(DockPosition::Right, window, cx)
11785 });
11786 workspace.update_in(cx, |workspace, window, cx| {
11787 let pane = pane.read(cx);
11788 assert!(!pane.is_zoomed());
11789 assert!(!pane.focus_handle(cx).is_focused(window));
11790 assert!(workspace.right_dock().read(cx).is_open());
11791 assert!(workspace.zoomed.is_none());
11792 });
11793 }
11794
11795 #[gpui::test]
11796 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11797 init_test(cx);
11798 let fs = FakeFs::new(cx.executor());
11799
11800 let project = Project::test(fs, [], cx).await;
11801 let (workspace, cx) =
11802 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11803
11804 let panel = workspace.update_in(cx, |workspace, window, cx| {
11805 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11806 workspace.add_panel(panel.clone(), window, cx);
11807 panel
11808 });
11809
11810 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11811 pane.update_in(cx, |pane, window, cx| {
11812 let item = cx.new(TestItem::new);
11813 pane.add_item(Box::new(item), true, true, None, window, cx);
11814 });
11815
11816 // Enable close_panel_on_toggle
11817 cx.update_global(|store: &mut SettingsStore, cx| {
11818 store.update_user_settings(cx, |settings| {
11819 settings.workspace.close_panel_on_toggle = Some(true);
11820 });
11821 });
11822
11823 // Panel starts closed. Toggling should open and focus it.
11824 workspace.update_in(cx, |workspace, window, cx| {
11825 assert!(!workspace.right_dock().read(cx).is_open());
11826 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11827 });
11828
11829 workspace.update_in(cx, |workspace, window, cx| {
11830 assert!(
11831 workspace.right_dock().read(cx).is_open(),
11832 "Dock should be open after toggling from center"
11833 );
11834 assert!(
11835 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11836 "Panel should be focused after toggling from center"
11837 );
11838 });
11839
11840 // Panel is open and focused. Toggling should close the panel and
11841 // return focus to the center.
11842 workspace.update_in(cx, |workspace, window, cx| {
11843 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11844 });
11845
11846 workspace.update_in(cx, |workspace, window, cx| {
11847 assert!(
11848 !workspace.right_dock().read(cx).is_open(),
11849 "Dock should be closed after toggling from focused panel"
11850 );
11851 assert!(
11852 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11853 "Panel should not be focused after toggling from focused panel"
11854 );
11855 });
11856
11857 // Open the dock and focus something else so the panel is open but not
11858 // focused. Toggling should focus the panel (not close it).
11859 workspace.update_in(cx, |workspace, window, cx| {
11860 workspace
11861 .right_dock()
11862 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11863 window.focus(&pane.read(cx).focus_handle(cx), cx);
11864 });
11865
11866 workspace.update_in(cx, |workspace, window, cx| {
11867 assert!(workspace.right_dock().read(cx).is_open());
11868 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11869 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11870 });
11871
11872 workspace.update_in(cx, |workspace, window, cx| {
11873 assert!(
11874 workspace.right_dock().read(cx).is_open(),
11875 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11876 );
11877 assert!(
11878 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11879 "Panel should be focused after toggling an open-but-unfocused panel"
11880 );
11881 });
11882
11883 // Now disable the setting and verify the original behavior: toggling
11884 // from a focused panel moves focus to center but leaves the dock open.
11885 cx.update_global(|store: &mut SettingsStore, cx| {
11886 store.update_user_settings(cx, |settings| {
11887 settings.workspace.close_panel_on_toggle = Some(false);
11888 });
11889 });
11890
11891 workspace.update_in(cx, |workspace, window, cx| {
11892 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11893 });
11894
11895 workspace.update_in(cx, |workspace, window, cx| {
11896 assert!(
11897 workspace.right_dock().read(cx).is_open(),
11898 "Dock should remain open when setting is disabled"
11899 );
11900 assert!(
11901 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11902 "Panel should not be focused after toggling with setting disabled"
11903 );
11904 });
11905 }
11906
11907 #[gpui::test]
11908 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11909 init_test(cx);
11910 let fs = FakeFs::new(cx.executor());
11911
11912 let project = Project::test(fs, [], cx).await;
11913 let (workspace, cx) =
11914 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11915
11916 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11917 workspace.active_pane().clone()
11918 });
11919
11920 // Add an item to the pane so it can be zoomed
11921 workspace.update_in(cx, |workspace, window, cx| {
11922 let item = cx.new(TestItem::new);
11923 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11924 });
11925
11926 // Initially not zoomed
11927 workspace.update_in(cx, |workspace, _window, cx| {
11928 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11929 assert!(
11930 workspace.zoomed.is_none(),
11931 "Workspace should track no zoomed pane"
11932 );
11933 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11934 });
11935
11936 // Zoom In
11937 pane.update_in(cx, |pane, window, cx| {
11938 pane.zoom_in(&crate::ZoomIn, window, cx);
11939 });
11940
11941 workspace.update_in(cx, |workspace, window, cx| {
11942 assert!(
11943 pane.read(cx).is_zoomed(),
11944 "Pane should be zoomed after ZoomIn"
11945 );
11946 assert!(
11947 workspace.zoomed.is_some(),
11948 "Workspace should track the zoomed pane"
11949 );
11950 assert!(
11951 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11952 "ZoomIn should focus the pane"
11953 );
11954 });
11955
11956 // Zoom In again is a no-op
11957 pane.update_in(cx, |pane, window, cx| {
11958 pane.zoom_in(&crate::ZoomIn, window, cx);
11959 });
11960
11961 workspace.update_in(cx, |workspace, window, cx| {
11962 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11963 assert!(
11964 workspace.zoomed.is_some(),
11965 "Workspace still tracks zoomed pane"
11966 );
11967 assert!(
11968 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11969 "Pane remains focused after repeated ZoomIn"
11970 );
11971 });
11972
11973 // Zoom Out
11974 pane.update_in(cx, |pane, window, cx| {
11975 pane.zoom_out(&crate::ZoomOut, window, cx);
11976 });
11977
11978 workspace.update_in(cx, |workspace, _window, cx| {
11979 assert!(
11980 !pane.read(cx).is_zoomed(),
11981 "Pane should unzoom after ZoomOut"
11982 );
11983 assert!(
11984 workspace.zoomed.is_none(),
11985 "Workspace clears zoom tracking after ZoomOut"
11986 );
11987 });
11988
11989 // Zoom Out again is a no-op
11990 pane.update_in(cx, |pane, window, cx| {
11991 pane.zoom_out(&crate::ZoomOut, window, cx);
11992 });
11993
11994 workspace.update_in(cx, |workspace, _window, cx| {
11995 assert!(
11996 !pane.read(cx).is_zoomed(),
11997 "Second ZoomOut keeps pane unzoomed"
11998 );
11999 assert!(
12000 workspace.zoomed.is_none(),
12001 "Workspace remains without zoomed pane"
12002 );
12003 });
12004 }
12005
12006 #[gpui::test]
12007 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
12008 init_test(cx);
12009 let fs = FakeFs::new(cx.executor());
12010
12011 let project = Project::test(fs, [], cx).await;
12012 let (workspace, cx) =
12013 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12014 workspace.update_in(cx, |workspace, window, cx| {
12015 // Open two docks
12016 let left_dock = workspace.dock_at_position(DockPosition::Left);
12017 let right_dock = workspace.dock_at_position(DockPosition::Right);
12018
12019 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12020 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12021
12022 assert!(left_dock.read(cx).is_open());
12023 assert!(right_dock.read(cx).is_open());
12024 });
12025
12026 workspace.update_in(cx, |workspace, window, cx| {
12027 // Toggle all docks - should close both
12028 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12029
12030 let left_dock = workspace.dock_at_position(DockPosition::Left);
12031 let right_dock = workspace.dock_at_position(DockPosition::Right);
12032 assert!(!left_dock.read(cx).is_open());
12033 assert!(!right_dock.read(cx).is_open());
12034 });
12035
12036 workspace.update_in(cx, |workspace, window, cx| {
12037 // Toggle again - should reopen both
12038 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12039
12040 let left_dock = workspace.dock_at_position(DockPosition::Left);
12041 let right_dock = workspace.dock_at_position(DockPosition::Right);
12042 assert!(left_dock.read(cx).is_open());
12043 assert!(right_dock.read(cx).is_open());
12044 });
12045 }
12046
12047 #[gpui::test]
12048 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
12049 init_test(cx);
12050 let fs = FakeFs::new(cx.executor());
12051
12052 let project = Project::test(fs, [], cx).await;
12053 let (workspace, cx) =
12054 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12055 workspace.update_in(cx, |workspace, window, cx| {
12056 // Open two docks
12057 let left_dock = workspace.dock_at_position(DockPosition::Left);
12058 let right_dock = workspace.dock_at_position(DockPosition::Right);
12059
12060 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12061 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12062
12063 assert!(left_dock.read(cx).is_open());
12064 assert!(right_dock.read(cx).is_open());
12065 });
12066
12067 workspace.update_in(cx, |workspace, window, cx| {
12068 // Close them manually
12069 workspace.toggle_dock(DockPosition::Left, window, cx);
12070 workspace.toggle_dock(DockPosition::Right, window, cx);
12071
12072 let left_dock = workspace.dock_at_position(DockPosition::Left);
12073 let right_dock = workspace.dock_at_position(DockPosition::Right);
12074 assert!(!left_dock.read(cx).is_open());
12075 assert!(!right_dock.read(cx).is_open());
12076 });
12077
12078 workspace.update_in(cx, |workspace, window, cx| {
12079 // Toggle all docks - only last closed (right dock) should reopen
12080 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12081
12082 let left_dock = workspace.dock_at_position(DockPosition::Left);
12083 let right_dock = workspace.dock_at_position(DockPosition::Right);
12084 assert!(!left_dock.read(cx).is_open());
12085 assert!(right_dock.read(cx).is_open());
12086 });
12087 }
12088
12089 #[gpui::test]
12090 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12091 init_test(cx);
12092 let fs = FakeFs::new(cx.executor());
12093 let project = Project::test(fs, [], cx).await;
12094 let (multi_workspace, cx) =
12095 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12096 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12097
12098 // Open two docks (left and right) with one panel each
12099 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12100 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12101 workspace.add_panel(left_panel.clone(), window, cx);
12102
12103 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12104 workspace.add_panel(right_panel.clone(), window, cx);
12105
12106 workspace.toggle_dock(DockPosition::Left, window, cx);
12107 workspace.toggle_dock(DockPosition::Right, window, cx);
12108
12109 // Verify initial state
12110 assert!(
12111 workspace.left_dock().read(cx).is_open(),
12112 "Left dock should be open"
12113 );
12114 assert_eq!(
12115 workspace
12116 .left_dock()
12117 .read(cx)
12118 .visible_panel()
12119 .unwrap()
12120 .panel_id(),
12121 left_panel.panel_id(),
12122 "Left panel should be visible in left dock"
12123 );
12124 assert!(
12125 workspace.right_dock().read(cx).is_open(),
12126 "Right dock should be open"
12127 );
12128 assert_eq!(
12129 workspace
12130 .right_dock()
12131 .read(cx)
12132 .visible_panel()
12133 .unwrap()
12134 .panel_id(),
12135 right_panel.panel_id(),
12136 "Right panel should be visible in right dock"
12137 );
12138 assert!(
12139 !workspace.bottom_dock().read(cx).is_open(),
12140 "Bottom dock should be closed"
12141 );
12142
12143 (left_panel, right_panel)
12144 });
12145
12146 // Focus the left panel and move it to the next position (bottom dock)
12147 workspace.update_in(cx, |workspace, window, cx| {
12148 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12149 assert!(
12150 left_panel.read(cx).focus_handle(cx).is_focused(window),
12151 "Left panel should be focused"
12152 );
12153 });
12154
12155 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12156
12157 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12158 workspace.update(cx, |workspace, cx| {
12159 assert!(
12160 !workspace.left_dock().read(cx).is_open(),
12161 "Left dock should be closed"
12162 );
12163 assert!(
12164 workspace.bottom_dock().read(cx).is_open(),
12165 "Bottom dock should now be open"
12166 );
12167 assert_eq!(
12168 left_panel.read(cx).position,
12169 DockPosition::Bottom,
12170 "Left panel should now be in the bottom dock"
12171 );
12172 assert_eq!(
12173 workspace
12174 .bottom_dock()
12175 .read(cx)
12176 .visible_panel()
12177 .unwrap()
12178 .panel_id(),
12179 left_panel.panel_id(),
12180 "Left panel should be the visible panel in the bottom dock"
12181 );
12182 });
12183
12184 // Toggle all docks off
12185 workspace.update_in(cx, |workspace, window, cx| {
12186 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12187 assert!(
12188 !workspace.left_dock().read(cx).is_open(),
12189 "Left dock should be closed"
12190 );
12191 assert!(
12192 !workspace.right_dock().read(cx).is_open(),
12193 "Right dock should be closed"
12194 );
12195 assert!(
12196 !workspace.bottom_dock().read(cx).is_open(),
12197 "Bottom dock should be closed"
12198 );
12199 });
12200
12201 // Toggle all docks back on and verify positions are restored
12202 workspace.update_in(cx, |workspace, window, cx| {
12203 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12204 assert!(
12205 !workspace.left_dock().read(cx).is_open(),
12206 "Left dock should remain closed"
12207 );
12208 assert!(
12209 workspace.right_dock().read(cx).is_open(),
12210 "Right dock should remain open"
12211 );
12212 assert!(
12213 workspace.bottom_dock().read(cx).is_open(),
12214 "Bottom dock should remain open"
12215 );
12216 assert_eq!(
12217 left_panel.read(cx).position,
12218 DockPosition::Bottom,
12219 "Left panel should remain in the bottom dock"
12220 );
12221 assert_eq!(
12222 right_panel.read(cx).position,
12223 DockPosition::Right,
12224 "Right panel should remain in the right dock"
12225 );
12226 assert_eq!(
12227 workspace
12228 .bottom_dock()
12229 .read(cx)
12230 .visible_panel()
12231 .unwrap()
12232 .panel_id(),
12233 left_panel.panel_id(),
12234 "Left panel should be the visible panel in the right dock"
12235 );
12236 });
12237 }
12238
12239 #[gpui::test]
12240 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12241 init_test(cx);
12242
12243 let fs = FakeFs::new(cx.executor());
12244
12245 let project = Project::test(fs, None, cx).await;
12246 let (workspace, cx) =
12247 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12248
12249 // Let's arrange the panes like this:
12250 //
12251 // +-----------------------+
12252 // | top |
12253 // +------+--------+-------+
12254 // | left | center | right |
12255 // +------+--------+-------+
12256 // | bottom |
12257 // +-----------------------+
12258
12259 let top_item = cx.new(|cx| {
12260 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12261 });
12262 let bottom_item = cx.new(|cx| {
12263 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12264 });
12265 let left_item = cx.new(|cx| {
12266 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12267 });
12268 let right_item = cx.new(|cx| {
12269 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12270 });
12271 let center_item = cx.new(|cx| {
12272 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12273 });
12274
12275 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12276 let top_pane_id = workspace.active_pane().entity_id();
12277 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12278 workspace.split_pane(
12279 workspace.active_pane().clone(),
12280 SplitDirection::Down,
12281 window,
12282 cx,
12283 );
12284 top_pane_id
12285 });
12286 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12287 let bottom_pane_id = workspace.active_pane().entity_id();
12288 workspace.add_item_to_active_pane(
12289 Box::new(bottom_item.clone()),
12290 None,
12291 false,
12292 window,
12293 cx,
12294 );
12295 workspace.split_pane(
12296 workspace.active_pane().clone(),
12297 SplitDirection::Up,
12298 window,
12299 cx,
12300 );
12301 bottom_pane_id
12302 });
12303 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12304 let left_pane_id = workspace.active_pane().entity_id();
12305 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12306 workspace.split_pane(
12307 workspace.active_pane().clone(),
12308 SplitDirection::Right,
12309 window,
12310 cx,
12311 );
12312 left_pane_id
12313 });
12314 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12315 let right_pane_id = workspace.active_pane().entity_id();
12316 workspace.add_item_to_active_pane(
12317 Box::new(right_item.clone()),
12318 None,
12319 false,
12320 window,
12321 cx,
12322 );
12323 workspace.split_pane(
12324 workspace.active_pane().clone(),
12325 SplitDirection::Left,
12326 window,
12327 cx,
12328 );
12329 right_pane_id
12330 });
12331 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12332 let center_pane_id = workspace.active_pane().entity_id();
12333 workspace.add_item_to_active_pane(
12334 Box::new(center_item.clone()),
12335 None,
12336 false,
12337 window,
12338 cx,
12339 );
12340 center_pane_id
12341 });
12342 cx.executor().run_until_parked();
12343
12344 workspace.update_in(cx, |workspace, window, cx| {
12345 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12346
12347 // Join into next from center pane into right
12348 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12349 });
12350
12351 workspace.update_in(cx, |workspace, window, cx| {
12352 let active_pane = workspace.active_pane();
12353 assert_eq!(right_pane_id, active_pane.entity_id());
12354 assert_eq!(2, active_pane.read(cx).items_len());
12355 let item_ids_in_pane =
12356 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12357 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12358 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12359
12360 // Join into next from right pane into bottom
12361 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12362 });
12363
12364 workspace.update_in(cx, |workspace, window, cx| {
12365 let active_pane = workspace.active_pane();
12366 assert_eq!(bottom_pane_id, active_pane.entity_id());
12367 assert_eq!(3, active_pane.read(cx).items_len());
12368 let item_ids_in_pane =
12369 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12370 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12371 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12372 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12373
12374 // Join into next from bottom pane into left
12375 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12376 });
12377
12378 workspace.update_in(cx, |workspace, window, cx| {
12379 let active_pane = workspace.active_pane();
12380 assert_eq!(left_pane_id, active_pane.entity_id());
12381 assert_eq!(4, active_pane.read(cx).items_len());
12382 let item_ids_in_pane =
12383 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12384 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12385 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12386 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12387 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12388
12389 // Join into next from left pane into top
12390 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12391 });
12392
12393 workspace.update_in(cx, |workspace, window, cx| {
12394 let active_pane = workspace.active_pane();
12395 assert_eq!(top_pane_id, active_pane.entity_id());
12396 assert_eq!(5, active_pane.read(cx).items_len());
12397 let item_ids_in_pane =
12398 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12399 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12400 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12401 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12402 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12403 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12404
12405 // Single pane left: no-op
12406 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12407 });
12408
12409 workspace.update(cx, |workspace, _cx| {
12410 let active_pane = workspace.active_pane();
12411 assert_eq!(top_pane_id, active_pane.entity_id());
12412 });
12413 }
12414
12415 fn add_an_item_to_active_pane(
12416 cx: &mut VisualTestContext,
12417 workspace: &Entity<Workspace>,
12418 item_id: u64,
12419 ) -> Entity<TestItem> {
12420 let item = cx.new(|cx| {
12421 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12422 item_id,
12423 "item{item_id}.txt",
12424 cx,
12425 )])
12426 });
12427 workspace.update_in(cx, |workspace, window, cx| {
12428 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12429 });
12430 item
12431 }
12432
12433 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12434 workspace.update_in(cx, |workspace, window, cx| {
12435 workspace.split_pane(
12436 workspace.active_pane().clone(),
12437 SplitDirection::Right,
12438 window,
12439 cx,
12440 )
12441 })
12442 }
12443
12444 #[gpui::test]
12445 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12446 init_test(cx);
12447 let fs = FakeFs::new(cx.executor());
12448 let project = Project::test(fs, None, cx).await;
12449 let (workspace, cx) =
12450 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12451
12452 add_an_item_to_active_pane(cx, &workspace, 1);
12453 split_pane(cx, &workspace);
12454 add_an_item_to_active_pane(cx, &workspace, 2);
12455 split_pane(cx, &workspace); // empty pane
12456 split_pane(cx, &workspace);
12457 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12458
12459 cx.executor().run_until_parked();
12460
12461 workspace.update(cx, |workspace, cx| {
12462 let num_panes = workspace.panes().len();
12463 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12464 let active_item = workspace
12465 .active_pane()
12466 .read(cx)
12467 .active_item()
12468 .expect("item is in focus");
12469
12470 assert_eq!(num_panes, 4);
12471 assert_eq!(num_items_in_current_pane, 1);
12472 assert_eq!(active_item.item_id(), last_item.item_id());
12473 });
12474
12475 workspace.update_in(cx, |workspace, window, cx| {
12476 workspace.join_all_panes(window, cx);
12477 });
12478
12479 workspace.update(cx, |workspace, cx| {
12480 let num_panes = workspace.panes().len();
12481 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12482 let active_item = workspace
12483 .active_pane()
12484 .read(cx)
12485 .active_item()
12486 .expect("item is in focus");
12487
12488 assert_eq!(num_panes, 1);
12489 assert_eq!(num_items_in_current_pane, 3);
12490 assert_eq!(active_item.item_id(), last_item.item_id());
12491 });
12492 }
12493
12494 #[gpui::test]
12495 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12496 init_test(cx);
12497 let fs = FakeFs::new(cx.executor());
12498
12499 let project = Project::test(fs, [], cx).await;
12500 let (multi_workspace, cx) =
12501 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12502 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12503
12504 workspace.update(cx, |workspace, _cx| {
12505 workspace.bounds.size.width = px(800.);
12506 });
12507
12508 workspace.update_in(cx, |workspace, window, cx| {
12509 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12510 workspace.add_panel(panel, window, cx);
12511 workspace.toggle_dock(DockPosition::Right, window, cx);
12512 });
12513
12514 let (panel, resized_width, ratio_basis_width) =
12515 workspace.update_in(cx, |workspace, window, cx| {
12516 let item = cx.new(|cx| {
12517 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12518 });
12519 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12520
12521 let dock = workspace.right_dock().read(cx);
12522 let workspace_width = workspace.bounds.size.width;
12523 let initial_width = workspace
12524 .dock_size(&dock, window, cx)
12525 .expect("flexible dock should have an initial width");
12526
12527 assert_eq!(initial_width, workspace_width / 2.);
12528
12529 workspace.resize_right_dock(px(300.), window, cx);
12530
12531 let dock = workspace.right_dock().read(cx);
12532 let resized_width = workspace
12533 .dock_size(&dock, window, cx)
12534 .expect("flexible dock should keep its resized width");
12535
12536 assert_eq!(resized_width, px(300.));
12537
12538 let panel = workspace
12539 .right_dock()
12540 .read(cx)
12541 .visible_panel()
12542 .expect("flexible dock should have a visible panel")
12543 .panel_id();
12544
12545 (panel, resized_width, workspace_width)
12546 });
12547
12548 workspace.update_in(cx, |workspace, window, cx| {
12549 workspace.toggle_dock(DockPosition::Right, window, cx);
12550 workspace.toggle_dock(DockPosition::Right, window, cx);
12551
12552 let dock = workspace.right_dock().read(cx);
12553 let reopened_width = workspace
12554 .dock_size(&dock, window, cx)
12555 .expect("flexible dock should restore when reopened");
12556
12557 assert_eq!(reopened_width, resized_width);
12558
12559 let right_dock = workspace.right_dock().read(cx);
12560 let flexible_panel = right_dock
12561 .visible_panel()
12562 .expect("flexible dock should still have a visible panel");
12563 assert_eq!(flexible_panel.panel_id(), panel);
12564 assert_eq!(
12565 right_dock
12566 .stored_panel_size_state(flexible_panel.as_ref())
12567 .and_then(|size_state| size_state.flex),
12568 Some(
12569 resized_width.to_f64() as f32
12570 / (workspace.bounds.size.width - resized_width).to_f64() as f32
12571 )
12572 );
12573 });
12574
12575 workspace.update_in(cx, |workspace, window, cx| {
12576 workspace.split_pane(
12577 workspace.active_pane().clone(),
12578 SplitDirection::Right,
12579 window,
12580 cx,
12581 );
12582
12583 let dock = workspace.right_dock().read(cx);
12584 let split_width = workspace
12585 .dock_size(&dock, window, cx)
12586 .expect("flexible dock should keep its user-resized proportion");
12587
12588 assert_eq!(split_width, px(300.));
12589
12590 workspace.bounds.size.width = px(1600.);
12591
12592 let dock = workspace.right_dock().read(cx);
12593 let resized_window_width = workspace
12594 .dock_size(&dock, window, cx)
12595 .expect("flexible dock should preserve proportional size on window resize");
12596
12597 assert_eq!(
12598 resized_window_width,
12599 workspace.bounds.size.width
12600 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12601 );
12602 });
12603 }
12604
12605 #[gpui::test]
12606 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12607 init_test(cx);
12608 let fs = FakeFs::new(cx.executor());
12609
12610 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12611 {
12612 let project = Project::test(fs.clone(), [], cx).await;
12613 let (multi_workspace, cx) =
12614 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12615 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12616
12617 workspace.update(cx, |workspace, _cx| {
12618 workspace.set_random_database_id();
12619 workspace.bounds.size.width = px(800.);
12620 });
12621
12622 let panel = workspace.update_in(cx, |workspace, window, cx| {
12623 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12624 workspace.add_panel(panel.clone(), window, cx);
12625 workspace.toggle_dock(DockPosition::Left, window, cx);
12626 panel
12627 });
12628
12629 workspace.update_in(cx, |workspace, window, cx| {
12630 workspace.resize_left_dock(px(350.), window, cx);
12631 });
12632
12633 cx.run_until_parked();
12634
12635 let persisted = workspace.read_with(cx, |workspace, cx| {
12636 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12637 });
12638 assert_eq!(
12639 persisted.and_then(|s| s.size),
12640 Some(px(350.)),
12641 "fixed-width panel size should be persisted to KVP"
12642 );
12643
12644 // Remove the panel and re-add a fresh instance with the same key.
12645 // The new instance should have its size state restored from KVP.
12646 workspace.update_in(cx, |workspace, window, cx| {
12647 workspace.remove_panel(&panel, window, cx);
12648 });
12649
12650 workspace.update_in(cx, |workspace, window, cx| {
12651 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12652 workspace.add_panel(new_panel, window, cx);
12653
12654 let left_dock = workspace.left_dock().read(cx);
12655 let size_state = left_dock
12656 .panel::<TestPanel>()
12657 .and_then(|p| left_dock.stored_panel_size_state(&p));
12658 assert_eq!(
12659 size_state.and_then(|s| s.size),
12660 Some(px(350.)),
12661 "re-added fixed-width panel should restore persisted size from KVP"
12662 );
12663 });
12664 }
12665
12666 // Flexible panel: both pixel size and ratio are persisted and restored.
12667 {
12668 let project = Project::test(fs.clone(), [], cx).await;
12669 let (multi_workspace, cx) =
12670 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12671 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12672
12673 workspace.update(cx, |workspace, _cx| {
12674 workspace.set_random_database_id();
12675 workspace.bounds.size.width = px(800.);
12676 });
12677
12678 let panel = workspace.update_in(cx, |workspace, window, cx| {
12679 let item = cx.new(|cx| {
12680 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12681 });
12682 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12683
12684 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12685 workspace.add_panel(panel.clone(), window, cx);
12686 workspace.toggle_dock(DockPosition::Right, window, cx);
12687 panel
12688 });
12689
12690 workspace.update_in(cx, |workspace, window, cx| {
12691 workspace.resize_right_dock(px(300.), window, cx);
12692 });
12693
12694 cx.run_until_parked();
12695
12696 let persisted = workspace
12697 .read_with(cx, |workspace, cx| {
12698 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12699 })
12700 .expect("flexible panel state should be persisted to KVP");
12701 assert_eq!(
12702 persisted.size, None,
12703 "flexible panel should not persist a redundant pixel size"
12704 );
12705 let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12706
12707 // Remove the panel and re-add: both size and ratio should be restored.
12708 workspace.update_in(cx, |workspace, window, cx| {
12709 workspace.remove_panel(&panel, window, cx);
12710 });
12711
12712 workspace.update_in(cx, |workspace, window, cx| {
12713 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12714 workspace.add_panel(new_panel, window, cx);
12715
12716 let right_dock = workspace.right_dock().read(cx);
12717 let size_state = right_dock
12718 .panel::<TestPanel>()
12719 .and_then(|p| right_dock.stored_panel_size_state(&p))
12720 .expect("re-added flexible panel should have restored size state from KVP");
12721 assert_eq!(
12722 size_state.size, None,
12723 "re-added flexible panel should not have a persisted pixel size"
12724 );
12725 assert_eq!(
12726 size_state.flex,
12727 Some(original_ratio),
12728 "re-added flexible panel should restore persisted flex"
12729 );
12730 });
12731 }
12732 }
12733
12734 #[gpui::test]
12735 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12736 init_test(cx);
12737 let fs = FakeFs::new(cx.executor());
12738
12739 let project = Project::test(fs, [], cx).await;
12740 let (multi_workspace, cx) =
12741 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12742 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12743
12744 workspace.update(cx, |workspace, _cx| {
12745 workspace.bounds.size.width = px(900.);
12746 });
12747
12748 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12749 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12750 // and the center pane each take half the workspace width.
12751 workspace.update_in(cx, |workspace, window, cx| {
12752 let item = cx.new(|cx| {
12753 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12754 });
12755 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12756
12757 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12758 workspace.add_panel(panel, window, cx);
12759 workspace.toggle_dock(DockPosition::Left, window, cx);
12760
12761 let left_dock = workspace.left_dock().read(cx);
12762 let left_width = workspace
12763 .dock_size(&left_dock, window, cx)
12764 .expect("left dock should have an active panel");
12765
12766 assert_eq!(
12767 left_width,
12768 workspace.bounds.size.width / 2.,
12769 "flexible left panel should split evenly with the center pane"
12770 );
12771 });
12772
12773 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12774 // change horizontal width fractions, so the flexible panel stays at the same
12775 // width as each half of the split.
12776 workspace.update_in(cx, |workspace, window, cx| {
12777 workspace.split_pane(
12778 workspace.active_pane().clone(),
12779 SplitDirection::Down,
12780 window,
12781 cx,
12782 );
12783
12784 let left_dock = workspace.left_dock().read(cx);
12785 let left_width = workspace
12786 .dock_size(&left_dock, window, cx)
12787 .expect("left dock should still have an active panel after vertical split");
12788
12789 assert_eq!(
12790 left_width,
12791 workspace.bounds.size.width / 2.,
12792 "flexible left panel width should match each vertically-split pane"
12793 );
12794 });
12795
12796 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12797 // size reduces the available width, so the flexible left panel and the center
12798 // panes all shrink proportionally to accommodate it.
12799 workspace.update_in(cx, |workspace, window, cx| {
12800 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12801 workspace.add_panel(panel, window, cx);
12802 workspace.toggle_dock(DockPosition::Right, window, cx);
12803
12804 let right_dock = workspace.right_dock().read(cx);
12805 let right_width = workspace
12806 .dock_size(&right_dock, window, cx)
12807 .expect("right dock should have an active panel");
12808
12809 let left_dock = workspace.left_dock().read(cx);
12810 let left_width = workspace
12811 .dock_size(&left_dock, window, cx)
12812 .expect("left dock should still have an active panel");
12813
12814 let available_width = workspace.bounds.size.width - right_width;
12815 assert_eq!(
12816 left_width,
12817 available_width / 2.,
12818 "flexible left panel should shrink proportionally as the right dock takes space"
12819 );
12820 });
12821
12822 // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12823 // flex sizing and the workspace width is divided among left-flex, center
12824 // (implicit flex 1.0), and right-flex.
12825 workspace.update_in(cx, |workspace, window, cx| {
12826 let right_dock = workspace.right_dock().clone();
12827 let right_panel = right_dock
12828 .read(cx)
12829 .visible_panel()
12830 .expect("right dock should have a visible panel")
12831 .clone();
12832 workspace.toggle_dock_panel_flexible_size(
12833 &right_dock,
12834 right_panel.as_ref(),
12835 window,
12836 cx,
12837 );
12838
12839 let right_dock = right_dock.read(cx);
12840 let right_panel = right_dock
12841 .visible_panel()
12842 .expect("right dock should still have a visible panel");
12843 assert!(
12844 right_panel.has_flexible_size(window, cx),
12845 "right panel should now be flexible"
12846 );
12847
12848 let right_size_state = right_dock
12849 .stored_panel_size_state(right_panel.as_ref())
12850 .expect("right panel should have a stored size state after toggling");
12851 let right_flex = right_size_state
12852 .flex
12853 .expect("right panel should have a flex value after toggling");
12854
12855 let left_dock = workspace.left_dock().read(cx);
12856 let left_width = workspace
12857 .dock_size(&left_dock, window, cx)
12858 .expect("left dock should still have an active panel");
12859 let right_width = workspace
12860 .dock_size(&right_dock, window, cx)
12861 .expect("right dock should still have an active panel");
12862
12863 let left_flex = workspace
12864 .default_dock_flex(DockPosition::Left)
12865 .expect("left dock should have a default flex");
12866
12867 let total_flex = left_flex + 1.0 + right_flex;
12868 let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12869 let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12870 assert_eq!(
12871 left_width, expected_left,
12872 "flexible left panel should share workspace width via flex ratios"
12873 );
12874 assert_eq!(
12875 right_width, expected_right,
12876 "flexible right panel should share workspace width via flex ratios"
12877 );
12878 });
12879 }
12880
12881 struct TestModal(FocusHandle);
12882
12883 impl TestModal {
12884 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12885 Self(cx.focus_handle())
12886 }
12887 }
12888
12889 impl EventEmitter<DismissEvent> for TestModal {}
12890
12891 impl Focusable for TestModal {
12892 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12893 self.0.clone()
12894 }
12895 }
12896
12897 impl ModalView for TestModal {}
12898
12899 impl Render for TestModal {
12900 fn render(
12901 &mut self,
12902 _window: &mut Window,
12903 _cx: &mut Context<TestModal>,
12904 ) -> impl IntoElement {
12905 div().track_focus(&self.0)
12906 }
12907 }
12908
12909 #[gpui::test]
12910 async fn test_panels(cx: &mut gpui::TestAppContext) {
12911 init_test(cx);
12912 let fs = FakeFs::new(cx.executor());
12913
12914 let project = Project::test(fs, [], cx).await;
12915 let (multi_workspace, cx) =
12916 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12917 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12918
12919 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12920 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12921 workspace.add_panel(panel_1.clone(), window, cx);
12922 workspace.toggle_dock(DockPosition::Left, window, cx);
12923 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12924 workspace.add_panel(panel_2.clone(), window, cx);
12925 workspace.toggle_dock(DockPosition::Right, window, cx);
12926
12927 let left_dock = workspace.left_dock();
12928 assert_eq!(
12929 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12930 panel_1.panel_id()
12931 );
12932 assert_eq!(
12933 workspace.dock_size(&left_dock.read(cx), window, cx),
12934 Some(px(300.))
12935 );
12936
12937 workspace.resize_left_dock(px(1337.), window, cx);
12938 assert_eq!(
12939 workspace
12940 .right_dock()
12941 .read(cx)
12942 .visible_panel()
12943 .unwrap()
12944 .panel_id(),
12945 panel_2.panel_id(),
12946 );
12947
12948 (panel_1, panel_2)
12949 });
12950
12951 // Move panel_1 to the right
12952 panel_1.update_in(cx, |panel_1, window, cx| {
12953 panel_1.set_position(DockPosition::Right, window, cx)
12954 });
12955
12956 workspace.update_in(cx, |workspace, window, cx| {
12957 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12958 // Since it was the only panel on the left, the left dock should now be closed.
12959 assert!(!workspace.left_dock().read(cx).is_open());
12960 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12961 let right_dock = workspace.right_dock();
12962 assert_eq!(
12963 right_dock.read(cx).visible_panel().unwrap().panel_id(),
12964 panel_1.panel_id()
12965 );
12966 assert_eq!(
12967 right_dock
12968 .read(cx)
12969 .active_panel_size()
12970 .unwrap()
12971 .size
12972 .unwrap(),
12973 px(1337.)
12974 );
12975
12976 // Now we move panel_2 to the left
12977 panel_2.set_position(DockPosition::Left, window, cx);
12978 });
12979
12980 workspace.update(cx, |workspace, cx| {
12981 // Since panel_2 was not visible on the right, we don't open the left dock.
12982 assert!(!workspace.left_dock().read(cx).is_open());
12983 // And the right dock is unaffected in its displaying of panel_1
12984 assert!(workspace.right_dock().read(cx).is_open());
12985 assert_eq!(
12986 workspace
12987 .right_dock()
12988 .read(cx)
12989 .visible_panel()
12990 .unwrap()
12991 .panel_id(),
12992 panel_1.panel_id(),
12993 );
12994 });
12995
12996 // Move panel_1 back to the left
12997 panel_1.update_in(cx, |panel_1, window, cx| {
12998 panel_1.set_position(DockPosition::Left, window, cx)
12999 });
13000
13001 workspace.update_in(cx, |workspace, window, cx| {
13002 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
13003 let left_dock = workspace.left_dock();
13004 assert!(left_dock.read(cx).is_open());
13005 assert_eq!(
13006 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13007 panel_1.panel_id()
13008 );
13009 assert_eq!(
13010 workspace.dock_size(&left_dock.read(cx), window, cx),
13011 Some(px(1337.))
13012 );
13013 // And the right dock should be closed as it no longer has any panels.
13014 assert!(!workspace.right_dock().read(cx).is_open());
13015
13016 // Now we move panel_1 to the bottom
13017 panel_1.set_position(DockPosition::Bottom, window, cx);
13018 });
13019
13020 workspace.update_in(cx, |workspace, window, cx| {
13021 // Since panel_1 was visible on the left, we close the left dock.
13022 assert!(!workspace.left_dock().read(cx).is_open());
13023 // The bottom dock is sized based on the panel's default size,
13024 // since the panel orientation changed from vertical to horizontal.
13025 let bottom_dock = workspace.bottom_dock();
13026 assert_eq!(
13027 workspace.dock_size(&bottom_dock.read(cx), window, cx),
13028 Some(px(300.))
13029 );
13030 // Close bottom dock and move panel_1 back to the left.
13031 bottom_dock.update(cx, |bottom_dock, cx| {
13032 bottom_dock.set_open(false, window, cx)
13033 });
13034 panel_1.set_position(DockPosition::Left, window, cx);
13035 });
13036
13037 // Emit activated event on panel 1
13038 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
13039
13040 // Now the left dock is open and panel_1 is active and focused.
13041 workspace.update_in(cx, |workspace, window, cx| {
13042 let left_dock = workspace.left_dock();
13043 assert!(left_dock.read(cx).is_open());
13044 assert_eq!(
13045 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13046 panel_1.panel_id(),
13047 );
13048 assert!(panel_1.focus_handle(cx).is_focused(window));
13049 });
13050
13051 // Emit closed event on panel 2, which is not active
13052 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13053
13054 // Wo don't close the left dock, because panel_2 wasn't the active panel
13055 workspace.update(cx, |workspace, cx| {
13056 let left_dock = workspace.left_dock();
13057 assert!(left_dock.read(cx).is_open());
13058 assert_eq!(
13059 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13060 panel_1.panel_id(),
13061 );
13062 });
13063
13064 // Emitting a ZoomIn event shows the panel as zoomed.
13065 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13066 workspace.read_with(cx, |workspace, _| {
13067 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13068 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13069 });
13070
13071 // Move panel to another dock while it is zoomed
13072 panel_1.update_in(cx, |panel, window, cx| {
13073 panel.set_position(DockPosition::Right, window, cx)
13074 });
13075 workspace.read_with(cx, |workspace, _| {
13076 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13077
13078 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13079 });
13080
13081 // This is a helper for getting a:
13082 // - valid focus on an element,
13083 // - that isn't a part of the panes and panels system of the Workspace,
13084 // - and doesn't trigger the 'on_focus_lost' API.
13085 let focus_other_view = {
13086 let workspace = workspace.clone();
13087 move |cx: &mut VisualTestContext| {
13088 workspace.update_in(cx, |workspace, window, cx| {
13089 if workspace.active_modal::<TestModal>(cx).is_some() {
13090 workspace.toggle_modal(window, cx, TestModal::new);
13091 workspace.toggle_modal(window, cx, TestModal::new);
13092 } else {
13093 workspace.toggle_modal(window, cx, TestModal::new);
13094 }
13095 })
13096 }
13097 };
13098
13099 // If focus is transferred to another view that's not a panel or another pane, we still show
13100 // the panel as zoomed.
13101 focus_other_view(cx);
13102 workspace.read_with(cx, |workspace, _| {
13103 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13104 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13105 });
13106
13107 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13108 workspace.update_in(cx, |_workspace, window, cx| {
13109 cx.focus_self(window);
13110 });
13111 workspace.read_with(cx, |workspace, _| {
13112 assert_eq!(workspace.zoomed, None);
13113 assert_eq!(workspace.zoomed_position, None);
13114 });
13115
13116 // If focus is transferred again to another view that's not a panel or a pane, we won't
13117 // show the panel as zoomed because it wasn't zoomed before.
13118 focus_other_view(cx);
13119 workspace.read_with(cx, |workspace, _| {
13120 assert_eq!(workspace.zoomed, None);
13121 assert_eq!(workspace.zoomed_position, None);
13122 });
13123
13124 // When the panel is activated, it is zoomed again.
13125 cx.dispatch_action(ToggleRightDock);
13126 workspace.read_with(cx, |workspace, _| {
13127 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13128 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13129 });
13130
13131 // Emitting a ZoomOut event unzooms the panel.
13132 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13133 workspace.read_with(cx, |workspace, _| {
13134 assert_eq!(workspace.zoomed, None);
13135 assert_eq!(workspace.zoomed_position, None);
13136 });
13137
13138 // Emit closed event on panel 1, which is active
13139 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13140
13141 // Now the left dock is closed, because panel_1 was the active panel
13142 workspace.update(cx, |workspace, cx| {
13143 let right_dock = workspace.right_dock();
13144 assert!(!right_dock.read(cx).is_open());
13145 });
13146 }
13147
13148 #[gpui::test]
13149 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13150 init_test(cx);
13151
13152 let fs = FakeFs::new(cx.background_executor.clone());
13153 let project = Project::test(fs, [], cx).await;
13154 let (workspace, cx) =
13155 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13156 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13157
13158 let dirty_regular_buffer = cx.new(|cx| {
13159 TestItem::new(cx)
13160 .with_dirty(true)
13161 .with_label("1.txt")
13162 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13163 });
13164 let dirty_regular_buffer_2 = cx.new(|cx| {
13165 TestItem::new(cx)
13166 .with_dirty(true)
13167 .with_label("2.txt")
13168 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13169 });
13170 let dirty_multi_buffer_with_both = cx.new(|cx| {
13171 TestItem::new(cx)
13172 .with_dirty(true)
13173 .with_buffer_kind(ItemBufferKind::Multibuffer)
13174 .with_label("Fake Project Search")
13175 .with_project_items(&[
13176 dirty_regular_buffer.read(cx).project_items[0].clone(),
13177 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13178 ])
13179 });
13180 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13181 workspace.update_in(cx, |workspace, window, cx| {
13182 workspace.add_item(
13183 pane.clone(),
13184 Box::new(dirty_regular_buffer.clone()),
13185 None,
13186 false,
13187 false,
13188 window,
13189 cx,
13190 );
13191 workspace.add_item(
13192 pane.clone(),
13193 Box::new(dirty_regular_buffer_2.clone()),
13194 None,
13195 false,
13196 false,
13197 window,
13198 cx,
13199 );
13200 workspace.add_item(
13201 pane.clone(),
13202 Box::new(dirty_multi_buffer_with_both.clone()),
13203 None,
13204 false,
13205 false,
13206 window,
13207 cx,
13208 );
13209 });
13210
13211 pane.update_in(cx, |pane, window, cx| {
13212 pane.activate_item(2, true, true, window, cx);
13213 assert_eq!(
13214 pane.active_item().unwrap().item_id(),
13215 multi_buffer_with_both_files_id,
13216 "Should select the multi buffer in the pane"
13217 );
13218 });
13219 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13220 pane.close_other_items(
13221 &CloseOtherItems {
13222 save_intent: Some(SaveIntent::Save),
13223 close_pinned: true,
13224 },
13225 None,
13226 window,
13227 cx,
13228 )
13229 });
13230 cx.background_executor.run_until_parked();
13231 assert!(!cx.has_pending_prompt());
13232 close_all_but_multi_buffer_task
13233 .await
13234 .expect("Closing all buffers but the multi buffer failed");
13235 pane.update(cx, |pane, cx| {
13236 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13237 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13238 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13239 assert_eq!(pane.items_len(), 1);
13240 assert_eq!(
13241 pane.active_item().unwrap().item_id(),
13242 multi_buffer_with_both_files_id,
13243 "Should have only the multi buffer left in the pane"
13244 );
13245 assert!(
13246 dirty_multi_buffer_with_both.read(cx).is_dirty,
13247 "The multi buffer containing the unsaved buffer should still be dirty"
13248 );
13249 });
13250
13251 dirty_regular_buffer.update(cx, |buffer, cx| {
13252 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13253 });
13254
13255 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13256 pane.close_active_item(
13257 &CloseActiveItem {
13258 save_intent: Some(SaveIntent::Close),
13259 close_pinned: false,
13260 },
13261 window,
13262 cx,
13263 )
13264 });
13265 cx.background_executor.run_until_parked();
13266 assert!(
13267 cx.has_pending_prompt(),
13268 "Dirty multi buffer should prompt a save dialog"
13269 );
13270 cx.simulate_prompt_answer("Save");
13271 cx.background_executor.run_until_parked();
13272 close_multi_buffer_task
13273 .await
13274 .expect("Closing the multi buffer failed");
13275 pane.update(cx, |pane, cx| {
13276 assert_eq!(
13277 dirty_multi_buffer_with_both.read(cx).save_count,
13278 1,
13279 "Multi buffer item should get be saved"
13280 );
13281 // Test impl does not save inner items, so we do not assert them
13282 assert_eq!(
13283 pane.items_len(),
13284 0,
13285 "No more items should be left in the pane"
13286 );
13287 assert!(pane.active_item().is_none());
13288 });
13289 }
13290
13291 #[gpui::test]
13292 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13293 cx: &mut TestAppContext,
13294 ) {
13295 init_test(cx);
13296
13297 let fs = FakeFs::new(cx.background_executor.clone());
13298 let project = Project::test(fs, [], cx).await;
13299 let (workspace, cx) =
13300 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13301 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13302
13303 let dirty_regular_buffer = cx.new(|cx| {
13304 TestItem::new(cx)
13305 .with_dirty(true)
13306 .with_label("1.txt")
13307 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13308 });
13309 let dirty_regular_buffer_2 = cx.new(|cx| {
13310 TestItem::new(cx)
13311 .with_dirty(true)
13312 .with_label("2.txt")
13313 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13314 });
13315 let clear_regular_buffer = cx.new(|cx| {
13316 TestItem::new(cx)
13317 .with_label("3.txt")
13318 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13319 });
13320
13321 let dirty_multi_buffer_with_both = cx.new(|cx| {
13322 TestItem::new(cx)
13323 .with_dirty(true)
13324 .with_buffer_kind(ItemBufferKind::Multibuffer)
13325 .with_label("Fake Project Search")
13326 .with_project_items(&[
13327 dirty_regular_buffer.read(cx).project_items[0].clone(),
13328 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13329 clear_regular_buffer.read(cx).project_items[0].clone(),
13330 ])
13331 });
13332 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13333 workspace.update_in(cx, |workspace, window, cx| {
13334 workspace.add_item(
13335 pane.clone(),
13336 Box::new(dirty_regular_buffer.clone()),
13337 None,
13338 false,
13339 false,
13340 window,
13341 cx,
13342 );
13343 workspace.add_item(
13344 pane.clone(),
13345 Box::new(dirty_multi_buffer_with_both.clone()),
13346 None,
13347 false,
13348 false,
13349 window,
13350 cx,
13351 );
13352 });
13353
13354 pane.update_in(cx, |pane, window, cx| {
13355 pane.activate_item(1, true, true, window, cx);
13356 assert_eq!(
13357 pane.active_item().unwrap().item_id(),
13358 multi_buffer_with_both_files_id,
13359 "Should select the multi buffer in the pane"
13360 );
13361 });
13362 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13363 pane.close_active_item(
13364 &CloseActiveItem {
13365 save_intent: None,
13366 close_pinned: false,
13367 },
13368 window,
13369 cx,
13370 )
13371 });
13372 cx.background_executor.run_until_parked();
13373 assert!(
13374 cx.has_pending_prompt(),
13375 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13376 );
13377 }
13378
13379 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13380 /// closed when they are deleted from disk.
13381 #[gpui::test]
13382 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13383 init_test(cx);
13384
13385 // Enable the close_on_disk_deletion setting
13386 cx.update_global(|store: &mut SettingsStore, cx| {
13387 store.update_user_settings(cx, |settings| {
13388 settings.workspace.close_on_file_delete = Some(true);
13389 });
13390 });
13391
13392 let fs = FakeFs::new(cx.background_executor.clone());
13393 let project = Project::test(fs, [], cx).await;
13394 let (workspace, cx) =
13395 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13396 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13397
13398 // Create a test item that simulates a file
13399 let item = cx.new(|cx| {
13400 TestItem::new(cx)
13401 .with_label("test.txt")
13402 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13403 });
13404
13405 // Add item to workspace
13406 workspace.update_in(cx, |workspace, window, cx| {
13407 workspace.add_item(
13408 pane.clone(),
13409 Box::new(item.clone()),
13410 None,
13411 false,
13412 false,
13413 window,
13414 cx,
13415 );
13416 });
13417
13418 // Verify the item is in the pane
13419 pane.read_with(cx, |pane, _| {
13420 assert_eq!(pane.items().count(), 1);
13421 });
13422
13423 // Simulate file deletion by setting the item's deleted state
13424 item.update(cx, |item, _| {
13425 item.set_has_deleted_file(true);
13426 });
13427
13428 // Emit UpdateTab event to trigger the close behavior
13429 cx.run_until_parked();
13430 item.update(cx, |_, cx| {
13431 cx.emit(ItemEvent::UpdateTab);
13432 });
13433
13434 // Allow the close operation to complete
13435 cx.run_until_parked();
13436
13437 // Verify the item was automatically closed
13438 pane.read_with(cx, |pane, _| {
13439 assert_eq!(
13440 pane.items().count(),
13441 0,
13442 "Item should be automatically closed when file is deleted"
13443 );
13444 });
13445 }
13446
13447 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13448 /// open with a strikethrough when they are deleted from disk.
13449 #[gpui::test]
13450 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13451 init_test(cx);
13452
13453 // Ensure close_on_disk_deletion is disabled (default)
13454 cx.update_global(|store: &mut SettingsStore, cx| {
13455 store.update_user_settings(cx, |settings| {
13456 settings.workspace.close_on_file_delete = Some(false);
13457 });
13458 });
13459
13460 let fs = FakeFs::new(cx.background_executor.clone());
13461 let project = Project::test(fs, [], cx).await;
13462 let (workspace, cx) =
13463 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13464 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13465
13466 // Create a test item that simulates a file
13467 let item = cx.new(|cx| {
13468 TestItem::new(cx)
13469 .with_label("test.txt")
13470 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13471 });
13472
13473 // Add item to workspace
13474 workspace.update_in(cx, |workspace, window, cx| {
13475 workspace.add_item(
13476 pane.clone(),
13477 Box::new(item.clone()),
13478 None,
13479 false,
13480 false,
13481 window,
13482 cx,
13483 );
13484 });
13485
13486 // Verify the item is in the pane
13487 pane.read_with(cx, |pane, _| {
13488 assert_eq!(pane.items().count(), 1);
13489 });
13490
13491 // Simulate file deletion
13492 item.update(cx, |item, _| {
13493 item.set_has_deleted_file(true);
13494 });
13495
13496 // Emit UpdateTab event
13497 cx.run_until_parked();
13498 item.update(cx, |_, cx| {
13499 cx.emit(ItemEvent::UpdateTab);
13500 });
13501
13502 // Allow any potential close operation to complete
13503 cx.run_until_parked();
13504
13505 // Verify the item remains open (with strikethrough)
13506 pane.read_with(cx, |pane, _| {
13507 assert_eq!(
13508 pane.items().count(),
13509 1,
13510 "Item should remain open when close_on_disk_deletion is disabled"
13511 );
13512 });
13513
13514 // Verify the item shows as deleted
13515 item.read_with(cx, |item, _| {
13516 assert!(
13517 item.has_deleted_file,
13518 "Item should be marked as having deleted file"
13519 );
13520 });
13521 }
13522
13523 /// Tests that dirty files are not automatically closed when deleted from disk,
13524 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13525 /// unsaved changes without being prompted.
13526 #[gpui::test]
13527 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13528 init_test(cx);
13529
13530 // Enable the close_on_file_delete setting
13531 cx.update_global(|store: &mut SettingsStore, cx| {
13532 store.update_user_settings(cx, |settings| {
13533 settings.workspace.close_on_file_delete = Some(true);
13534 });
13535 });
13536
13537 let fs = FakeFs::new(cx.background_executor.clone());
13538 let project = Project::test(fs, [], cx).await;
13539 let (workspace, cx) =
13540 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13541 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13542
13543 // Create a dirty test item
13544 let item = cx.new(|cx| {
13545 TestItem::new(cx)
13546 .with_dirty(true)
13547 .with_label("test.txt")
13548 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13549 });
13550
13551 // Add item to workspace
13552 workspace.update_in(cx, |workspace, window, cx| {
13553 workspace.add_item(
13554 pane.clone(),
13555 Box::new(item.clone()),
13556 None,
13557 false,
13558 false,
13559 window,
13560 cx,
13561 );
13562 });
13563
13564 // Simulate file deletion
13565 item.update(cx, |item, _| {
13566 item.set_has_deleted_file(true);
13567 });
13568
13569 // Emit UpdateTab event to trigger the close behavior
13570 cx.run_until_parked();
13571 item.update(cx, |_, cx| {
13572 cx.emit(ItemEvent::UpdateTab);
13573 });
13574
13575 // Allow any potential close operation to complete
13576 cx.run_until_parked();
13577
13578 // Verify the item remains open (dirty files are not auto-closed)
13579 pane.read_with(cx, |pane, _| {
13580 assert_eq!(
13581 pane.items().count(),
13582 1,
13583 "Dirty items should not be automatically closed even when file is deleted"
13584 );
13585 });
13586
13587 // Verify the item is marked as deleted and still dirty
13588 item.read_with(cx, |item, _| {
13589 assert!(
13590 item.has_deleted_file,
13591 "Item should be marked as having deleted file"
13592 );
13593 assert!(item.is_dirty, "Item should still be dirty");
13594 });
13595 }
13596
13597 /// Tests that navigation history is cleaned up when files are auto-closed
13598 /// due to deletion from disk.
13599 #[gpui::test]
13600 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13601 init_test(cx);
13602
13603 // Enable the close_on_file_delete setting
13604 cx.update_global(|store: &mut SettingsStore, cx| {
13605 store.update_user_settings(cx, |settings| {
13606 settings.workspace.close_on_file_delete = Some(true);
13607 });
13608 });
13609
13610 let fs = FakeFs::new(cx.background_executor.clone());
13611 let project = Project::test(fs, [], cx).await;
13612 let (workspace, cx) =
13613 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13614 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13615
13616 // Create test items
13617 let item1 = cx.new(|cx| {
13618 TestItem::new(cx)
13619 .with_label("test1.txt")
13620 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13621 });
13622 let item1_id = item1.item_id();
13623
13624 let item2 = cx.new(|cx| {
13625 TestItem::new(cx)
13626 .with_label("test2.txt")
13627 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13628 });
13629
13630 // Add items to workspace
13631 workspace.update_in(cx, |workspace, window, cx| {
13632 workspace.add_item(
13633 pane.clone(),
13634 Box::new(item1.clone()),
13635 None,
13636 false,
13637 false,
13638 window,
13639 cx,
13640 );
13641 workspace.add_item(
13642 pane.clone(),
13643 Box::new(item2.clone()),
13644 None,
13645 false,
13646 false,
13647 window,
13648 cx,
13649 );
13650 });
13651
13652 // Activate item1 to ensure it gets navigation entries
13653 pane.update_in(cx, |pane, window, cx| {
13654 pane.activate_item(0, true, true, window, cx);
13655 });
13656
13657 // Switch to item2 and back to create navigation history
13658 pane.update_in(cx, |pane, window, cx| {
13659 pane.activate_item(1, true, true, window, cx);
13660 });
13661 cx.run_until_parked();
13662
13663 pane.update_in(cx, |pane, window, cx| {
13664 pane.activate_item(0, true, true, window, cx);
13665 });
13666 cx.run_until_parked();
13667
13668 // Simulate file deletion for item1
13669 item1.update(cx, |item, _| {
13670 item.set_has_deleted_file(true);
13671 });
13672
13673 // Emit UpdateTab event to trigger the close behavior
13674 item1.update(cx, |_, cx| {
13675 cx.emit(ItemEvent::UpdateTab);
13676 });
13677 cx.run_until_parked();
13678
13679 // Verify item1 was closed
13680 pane.read_with(cx, |pane, _| {
13681 assert_eq!(
13682 pane.items().count(),
13683 1,
13684 "Should have 1 item remaining after auto-close"
13685 );
13686 });
13687
13688 // Check navigation history after close
13689 let has_item = pane.read_with(cx, |pane, cx| {
13690 let mut has_item = false;
13691 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13692 if entry.item.id() == item1_id {
13693 has_item = true;
13694 }
13695 });
13696 has_item
13697 });
13698
13699 assert!(
13700 !has_item,
13701 "Navigation history should not contain closed item entries"
13702 );
13703 }
13704
13705 #[gpui::test]
13706 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13707 cx: &mut TestAppContext,
13708 ) {
13709 init_test(cx);
13710
13711 let fs = FakeFs::new(cx.background_executor.clone());
13712 let project = Project::test(fs, [], cx).await;
13713 let (workspace, cx) =
13714 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13715 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13716
13717 let dirty_regular_buffer = cx.new(|cx| {
13718 TestItem::new(cx)
13719 .with_dirty(true)
13720 .with_label("1.txt")
13721 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13722 });
13723 let dirty_regular_buffer_2 = cx.new(|cx| {
13724 TestItem::new(cx)
13725 .with_dirty(true)
13726 .with_label("2.txt")
13727 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13728 });
13729 let clear_regular_buffer = cx.new(|cx| {
13730 TestItem::new(cx)
13731 .with_label("3.txt")
13732 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13733 });
13734
13735 let dirty_multi_buffer = cx.new(|cx| {
13736 TestItem::new(cx)
13737 .with_dirty(true)
13738 .with_buffer_kind(ItemBufferKind::Multibuffer)
13739 .with_label("Fake Project Search")
13740 .with_project_items(&[
13741 dirty_regular_buffer.read(cx).project_items[0].clone(),
13742 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13743 clear_regular_buffer.read(cx).project_items[0].clone(),
13744 ])
13745 });
13746 workspace.update_in(cx, |workspace, window, cx| {
13747 workspace.add_item(
13748 pane.clone(),
13749 Box::new(dirty_regular_buffer.clone()),
13750 None,
13751 false,
13752 false,
13753 window,
13754 cx,
13755 );
13756 workspace.add_item(
13757 pane.clone(),
13758 Box::new(dirty_regular_buffer_2.clone()),
13759 None,
13760 false,
13761 false,
13762 window,
13763 cx,
13764 );
13765 workspace.add_item(
13766 pane.clone(),
13767 Box::new(dirty_multi_buffer.clone()),
13768 None,
13769 false,
13770 false,
13771 window,
13772 cx,
13773 );
13774 });
13775
13776 pane.update_in(cx, |pane, window, cx| {
13777 pane.activate_item(2, true, true, window, cx);
13778 assert_eq!(
13779 pane.active_item().unwrap().item_id(),
13780 dirty_multi_buffer.item_id(),
13781 "Should select the multi buffer in the pane"
13782 );
13783 });
13784 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13785 pane.close_active_item(
13786 &CloseActiveItem {
13787 save_intent: None,
13788 close_pinned: false,
13789 },
13790 window,
13791 cx,
13792 )
13793 });
13794 cx.background_executor.run_until_parked();
13795 assert!(
13796 !cx.has_pending_prompt(),
13797 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13798 );
13799 close_multi_buffer_task
13800 .await
13801 .expect("Closing multi buffer failed");
13802 pane.update(cx, |pane, cx| {
13803 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13804 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13805 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13806 assert_eq!(
13807 pane.items()
13808 .map(|item| item.item_id())
13809 .sorted()
13810 .collect::<Vec<_>>(),
13811 vec![
13812 dirty_regular_buffer.item_id(),
13813 dirty_regular_buffer_2.item_id(),
13814 ],
13815 "Should have no multi buffer left in the pane"
13816 );
13817 assert!(dirty_regular_buffer.read(cx).is_dirty);
13818 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13819 });
13820 }
13821
13822 #[gpui::test]
13823 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13824 init_test(cx);
13825 let fs = FakeFs::new(cx.executor());
13826 let project = Project::test(fs, [], cx).await;
13827 let (multi_workspace, cx) =
13828 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13829 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13830
13831 // Add a new panel to the right dock, opening the dock and setting the
13832 // focus to the new panel.
13833 let panel = workspace.update_in(cx, |workspace, window, cx| {
13834 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13835 workspace.add_panel(panel.clone(), window, cx);
13836
13837 workspace
13838 .right_dock()
13839 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13840
13841 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13842
13843 panel
13844 });
13845
13846 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13847 // panel to the next valid position which, in this case, is the left
13848 // dock.
13849 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13850 workspace.update(cx, |workspace, cx| {
13851 assert!(workspace.left_dock().read(cx).is_open());
13852 assert_eq!(panel.read(cx).position, DockPosition::Left);
13853 });
13854
13855 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13856 // panel to the next valid position which, in this case, is the bottom
13857 // dock.
13858 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13859 workspace.update(cx, |workspace, cx| {
13860 assert!(workspace.bottom_dock().read(cx).is_open());
13861 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13862 });
13863
13864 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13865 // around moving the panel to its initial position, the right dock.
13866 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13867 workspace.update(cx, |workspace, cx| {
13868 assert!(workspace.right_dock().read(cx).is_open());
13869 assert_eq!(panel.read(cx).position, DockPosition::Right);
13870 });
13871
13872 // Remove focus from the panel, ensuring that, if the panel is not
13873 // focused, the `MoveFocusedPanelToNextPosition` action does not update
13874 // the panel's position, so the panel is still in the right dock.
13875 workspace.update_in(cx, |workspace, window, cx| {
13876 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13877 });
13878
13879 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13880 workspace.update(cx, |workspace, cx| {
13881 assert!(workspace.right_dock().read(cx).is_open());
13882 assert_eq!(panel.read(cx).position, DockPosition::Right);
13883 });
13884 }
13885
13886 #[gpui::test]
13887 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13888 init_test(cx);
13889
13890 let fs = FakeFs::new(cx.executor());
13891 let project = Project::test(fs, [], cx).await;
13892 let (workspace, cx) =
13893 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13894
13895 let item_1 = cx.new(|cx| {
13896 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13897 });
13898 workspace.update_in(cx, |workspace, window, cx| {
13899 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13900 workspace.move_item_to_pane_in_direction(
13901 &MoveItemToPaneInDirection {
13902 direction: SplitDirection::Right,
13903 focus: true,
13904 clone: false,
13905 },
13906 window,
13907 cx,
13908 );
13909 workspace.move_item_to_pane_at_index(
13910 &MoveItemToPane {
13911 destination: 3,
13912 focus: true,
13913 clone: false,
13914 },
13915 window,
13916 cx,
13917 );
13918
13919 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13920 assert_eq!(
13921 pane_items_paths(&workspace.active_pane, cx),
13922 vec!["first.txt".to_string()],
13923 "Single item was not moved anywhere"
13924 );
13925 });
13926
13927 let item_2 = cx.new(|cx| {
13928 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13929 });
13930 workspace.update_in(cx, |workspace, window, cx| {
13931 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13932 assert_eq!(
13933 pane_items_paths(&workspace.panes[0], cx),
13934 vec!["first.txt".to_string(), "second.txt".to_string()],
13935 );
13936 workspace.move_item_to_pane_in_direction(
13937 &MoveItemToPaneInDirection {
13938 direction: SplitDirection::Right,
13939 focus: true,
13940 clone: false,
13941 },
13942 window,
13943 cx,
13944 );
13945
13946 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13947 assert_eq!(
13948 pane_items_paths(&workspace.panes[0], cx),
13949 vec!["first.txt".to_string()],
13950 "After moving, one item should be left in the original pane"
13951 );
13952 assert_eq!(
13953 pane_items_paths(&workspace.panes[1], cx),
13954 vec!["second.txt".to_string()],
13955 "New item should have been moved to the new pane"
13956 );
13957 });
13958
13959 let item_3 = cx.new(|cx| {
13960 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13961 });
13962 workspace.update_in(cx, |workspace, window, cx| {
13963 let original_pane = workspace.panes[0].clone();
13964 workspace.set_active_pane(&original_pane, window, cx);
13965 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13966 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13967 assert_eq!(
13968 pane_items_paths(&workspace.active_pane, cx),
13969 vec!["first.txt".to_string(), "third.txt".to_string()],
13970 "New pane should be ready to move one item out"
13971 );
13972
13973 workspace.move_item_to_pane_at_index(
13974 &MoveItemToPane {
13975 destination: 3,
13976 focus: true,
13977 clone: false,
13978 },
13979 window,
13980 cx,
13981 );
13982 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13983 assert_eq!(
13984 pane_items_paths(&workspace.active_pane, cx),
13985 vec!["first.txt".to_string()],
13986 "After moving, one item should be left in the original pane"
13987 );
13988 assert_eq!(
13989 pane_items_paths(&workspace.panes[1], cx),
13990 vec!["second.txt".to_string()],
13991 "Previously created pane should be unchanged"
13992 );
13993 assert_eq!(
13994 pane_items_paths(&workspace.panes[2], cx),
13995 vec!["third.txt".to_string()],
13996 "New item should have been moved to the new pane"
13997 );
13998 });
13999 }
14000
14001 #[gpui::test]
14002 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
14003 init_test(cx);
14004
14005 let fs = FakeFs::new(cx.executor());
14006 let project = Project::test(fs, [], cx).await;
14007 let (workspace, cx) =
14008 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14009
14010 let item_1 = cx.new(|cx| {
14011 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14012 });
14013 workspace.update_in(cx, |workspace, window, cx| {
14014 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14015 workspace.move_item_to_pane_in_direction(
14016 &MoveItemToPaneInDirection {
14017 direction: SplitDirection::Right,
14018 focus: true,
14019 clone: true,
14020 },
14021 window,
14022 cx,
14023 );
14024 });
14025 cx.run_until_parked();
14026 workspace.update_in(cx, |workspace, window, cx| {
14027 workspace.move_item_to_pane_at_index(
14028 &MoveItemToPane {
14029 destination: 3,
14030 focus: true,
14031 clone: true,
14032 },
14033 window,
14034 cx,
14035 );
14036 });
14037 cx.run_until_parked();
14038
14039 workspace.update(cx, |workspace, cx| {
14040 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
14041 for pane in workspace.panes() {
14042 assert_eq!(
14043 pane_items_paths(pane, cx),
14044 vec!["first.txt".to_string()],
14045 "Single item exists in all panes"
14046 );
14047 }
14048 });
14049
14050 // verify that the active pane has been updated after waiting for the
14051 // pane focus event to fire and resolve
14052 workspace.read_with(cx, |workspace, _app| {
14053 assert_eq!(
14054 workspace.active_pane(),
14055 &workspace.panes[2],
14056 "The third pane should be the active one: {:?}",
14057 workspace.panes
14058 );
14059 })
14060 }
14061
14062 #[gpui::test]
14063 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
14064 init_test(cx);
14065
14066 let fs = FakeFs::new(cx.executor());
14067 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14068
14069 let project = Project::test(fs, ["root".as_ref()], cx).await;
14070 let (workspace, cx) =
14071 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14072
14073 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14074 // Add item to pane A with project path
14075 let item_a = cx.new(|cx| {
14076 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14077 });
14078 workspace.update_in(cx, |workspace, window, cx| {
14079 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14080 });
14081
14082 // Split to create pane B
14083 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14084 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14085 });
14086
14087 // Add item with SAME project path to pane B, and pin it
14088 let item_b = cx.new(|cx| {
14089 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14090 });
14091 pane_b.update_in(cx, |pane, window, cx| {
14092 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14093 pane.set_pinned_count(1);
14094 });
14095
14096 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14097 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14098
14099 // close_pinned: false should only close the unpinned copy
14100 workspace.update_in(cx, |workspace, window, cx| {
14101 workspace.close_item_in_all_panes(
14102 &CloseItemInAllPanes {
14103 save_intent: Some(SaveIntent::Close),
14104 close_pinned: false,
14105 },
14106 window,
14107 cx,
14108 )
14109 });
14110 cx.executor().run_until_parked();
14111
14112 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14113 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14114 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14115 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14116
14117 // Split again, seeing as closing the previous item also closed its
14118 // pane, so only pane remains, which does not allow us to properly test
14119 // that both items close when `close_pinned: true`.
14120 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14121 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14122 });
14123
14124 // Add an item with the same project path to pane C so that
14125 // close_item_in_all_panes can determine what to close across all panes
14126 // (it reads the active item from the active pane, and split_pane
14127 // creates an empty pane).
14128 let item_c = cx.new(|cx| {
14129 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14130 });
14131 pane_c.update_in(cx, |pane, window, cx| {
14132 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14133 });
14134
14135 // close_pinned: true should close the pinned copy too
14136 workspace.update_in(cx, |workspace, window, cx| {
14137 let panes_count = workspace.panes().len();
14138 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14139
14140 workspace.close_item_in_all_panes(
14141 &CloseItemInAllPanes {
14142 save_intent: Some(SaveIntent::Close),
14143 close_pinned: true,
14144 },
14145 window,
14146 cx,
14147 )
14148 });
14149 cx.executor().run_until_parked();
14150
14151 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14152 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14153 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14154 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14155 }
14156
14157 mod register_project_item_tests {
14158
14159 use super::*;
14160
14161 // View
14162 struct TestPngItemView {
14163 focus_handle: FocusHandle,
14164 }
14165 // Model
14166 struct TestPngItem {}
14167
14168 impl project::ProjectItem for TestPngItem {
14169 fn try_open(
14170 _project: &Entity<Project>,
14171 path: &ProjectPath,
14172 cx: &mut App,
14173 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14174 if path.path.extension().unwrap() == "png" {
14175 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14176 } else {
14177 None
14178 }
14179 }
14180
14181 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14182 None
14183 }
14184
14185 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14186 None
14187 }
14188
14189 fn is_dirty(&self) -> bool {
14190 false
14191 }
14192 }
14193
14194 impl Item for TestPngItemView {
14195 type Event = ();
14196 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14197 "".into()
14198 }
14199 }
14200 impl EventEmitter<()> for TestPngItemView {}
14201 impl Focusable for TestPngItemView {
14202 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14203 self.focus_handle.clone()
14204 }
14205 }
14206
14207 impl Render for TestPngItemView {
14208 fn render(
14209 &mut self,
14210 _window: &mut Window,
14211 _cx: &mut Context<Self>,
14212 ) -> impl IntoElement {
14213 Empty
14214 }
14215 }
14216
14217 impl ProjectItem for TestPngItemView {
14218 type Item = TestPngItem;
14219
14220 fn for_project_item(
14221 _project: Entity<Project>,
14222 _pane: Option<&Pane>,
14223 _item: Entity<Self::Item>,
14224 _: &mut Window,
14225 cx: &mut Context<Self>,
14226 ) -> Self
14227 where
14228 Self: Sized,
14229 {
14230 Self {
14231 focus_handle: cx.focus_handle(),
14232 }
14233 }
14234 }
14235
14236 // View
14237 struct TestIpynbItemView {
14238 focus_handle: FocusHandle,
14239 }
14240 // Model
14241 struct TestIpynbItem {}
14242
14243 impl project::ProjectItem for TestIpynbItem {
14244 fn try_open(
14245 _project: &Entity<Project>,
14246 path: &ProjectPath,
14247 cx: &mut App,
14248 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14249 if path.path.extension().unwrap() == "ipynb" {
14250 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14251 } else {
14252 None
14253 }
14254 }
14255
14256 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14257 None
14258 }
14259
14260 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14261 None
14262 }
14263
14264 fn is_dirty(&self) -> bool {
14265 false
14266 }
14267 }
14268
14269 impl Item for TestIpynbItemView {
14270 type Event = ();
14271 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14272 "".into()
14273 }
14274 }
14275 impl EventEmitter<()> for TestIpynbItemView {}
14276 impl Focusable for TestIpynbItemView {
14277 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14278 self.focus_handle.clone()
14279 }
14280 }
14281
14282 impl Render for TestIpynbItemView {
14283 fn render(
14284 &mut self,
14285 _window: &mut Window,
14286 _cx: &mut Context<Self>,
14287 ) -> impl IntoElement {
14288 Empty
14289 }
14290 }
14291
14292 impl ProjectItem for TestIpynbItemView {
14293 type Item = TestIpynbItem;
14294
14295 fn for_project_item(
14296 _project: Entity<Project>,
14297 _pane: Option<&Pane>,
14298 _item: Entity<Self::Item>,
14299 _: &mut Window,
14300 cx: &mut Context<Self>,
14301 ) -> Self
14302 where
14303 Self: Sized,
14304 {
14305 Self {
14306 focus_handle: cx.focus_handle(),
14307 }
14308 }
14309 }
14310
14311 struct TestAlternatePngItemView {
14312 focus_handle: FocusHandle,
14313 }
14314
14315 impl Item for TestAlternatePngItemView {
14316 type Event = ();
14317 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14318 "".into()
14319 }
14320 }
14321
14322 impl EventEmitter<()> for TestAlternatePngItemView {}
14323 impl Focusable for TestAlternatePngItemView {
14324 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14325 self.focus_handle.clone()
14326 }
14327 }
14328
14329 impl Render for TestAlternatePngItemView {
14330 fn render(
14331 &mut self,
14332 _window: &mut Window,
14333 _cx: &mut Context<Self>,
14334 ) -> impl IntoElement {
14335 Empty
14336 }
14337 }
14338
14339 impl ProjectItem for TestAlternatePngItemView {
14340 type Item = TestPngItem;
14341
14342 fn for_project_item(
14343 _project: Entity<Project>,
14344 _pane: Option<&Pane>,
14345 _item: Entity<Self::Item>,
14346 _: &mut Window,
14347 cx: &mut Context<Self>,
14348 ) -> Self
14349 where
14350 Self: Sized,
14351 {
14352 Self {
14353 focus_handle: cx.focus_handle(),
14354 }
14355 }
14356 }
14357
14358 #[gpui::test]
14359 async fn test_register_project_item(cx: &mut TestAppContext) {
14360 init_test(cx);
14361
14362 cx.update(|cx| {
14363 register_project_item::<TestPngItemView>(cx);
14364 register_project_item::<TestIpynbItemView>(cx);
14365 });
14366
14367 let fs = FakeFs::new(cx.executor());
14368 fs.insert_tree(
14369 "/root1",
14370 json!({
14371 "one.png": "BINARYDATAHERE",
14372 "two.ipynb": "{ totally a notebook }",
14373 "three.txt": "editing text, sure why not?"
14374 }),
14375 )
14376 .await;
14377
14378 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14379 let (workspace, cx) =
14380 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14381
14382 let worktree_id = project.update(cx, |project, cx| {
14383 project.worktrees(cx).next().unwrap().read(cx).id()
14384 });
14385
14386 let handle = workspace
14387 .update_in(cx, |workspace, window, cx| {
14388 let project_path = (worktree_id, rel_path("one.png"));
14389 workspace.open_path(project_path, None, true, window, cx)
14390 })
14391 .await
14392 .unwrap();
14393
14394 // Now we can check if the handle we got back errored or not
14395 assert_eq!(
14396 handle.to_any_view().entity_type(),
14397 TypeId::of::<TestPngItemView>()
14398 );
14399
14400 let handle = workspace
14401 .update_in(cx, |workspace, window, cx| {
14402 let project_path = (worktree_id, rel_path("two.ipynb"));
14403 workspace.open_path(project_path, None, true, window, cx)
14404 })
14405 .await
14406 .unwrap();
14407
14408 assert_eq!(
14409 handle.to_any_view().entity_type(),
14410 TypeId::of::<TestIpynbItemView>()
14411 );
14412
14413 let handle = workspace
14414 .update_in(cx, |workspace, window, cx| {
14415 let project_path = (worktree_id, rel_path("three.txt"));
14416 workspace.open_path(project_path, None, true, window, cx)
14417 })
14418 .await;
14419 assert!(handle.is_err());
14420 }
14421
14422 #[gpui::test]
14423 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14424 init_test(cx);
14425
14426 cx.update(|cx| {
14427 register_project_item::<TestPngItemView>(cx);
14428 register_project_item::<TestAlternatePngItemView>(cx);
14429 });
14430
14431 let fs = FakeFs::new(cx.executor());
14432 fs.insert_tree(
14433 "/root1",
14434 json!({
14435 "one.png": "BINARYDATAHERE",
14436 "two.ipynb": "{ totally a notebook }",
14437 "three.txt": "editing text, sure why not?"
14438 }),
14439 )
14440 .await;
14441 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14442 let (workspace, cx) =
14443 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14444 let worktree_id = project.update(cx, |project, cx| {
14445 project.worktrees(cx).next().unwrap().read(cx).id()
14446 });
14447
14448 let handle = workspace
14449 .update_in(cx, |workspace, window, cx| {
14450 let project_path = (worktree_id, rel_path("one.png"));
14451 workspace.open_path(project_path, None, true, window, cx)
14452 })
14453 .await
14454 .unwrap();
14455
14456 // This _must_ be the second item registered
14457 assert_eq!(
14458 handle.to_any_view().entity_type(),
14459 TypeId::of::<TestAlternatePngItemView>()
14460 );
14461
14462 let handle = workspace
14463 .update_in(cx, |workspace, window, cx| {
14464 let project_path = (worktree_id, rel_path("three.txt"));
14465 workspace.open_path(project_path, None, true, window, cx)
14466 })
14467 .await;
14468 assert!(handle.is_err());
14469 }
14470 }
14471
14472 #[gpui::test]
14473 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14474 init_test(cx);
14475
14476 let fs = FakeFs::new(cx.executor());
14477 let project = Project::test(fs, [], cx).await;
14478 let (workspace, _cx) =
14479 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14480
14481 // Test with status bar shown (default)
14482 workspace.read_with(cx, |workspace, cx| {
14483 let visible = workspace.status_bar_visible(cx);
14484 assert!(visible, "Status bar should be visible by default");
14485 });
14486
14487 // Test with status bar hidden
14488 cx.update_global(|store: &mut SettingsStore, cx| {
14489 store.update_user_settings(cx, |settings| {
14490 settings.status_bar.get_or_insert_default().show = Some(false);
14491 });
14492 });
14493
14494 workspace.read_with(cx, |workspace, cx| {
14495 let visible = workspace.status_bar_visible(cx);
14496 assert!(!visible, "Status bar should be hidden when show is false");
14497 });
14498
14499 // Test with status bar shown explicitly
14500 cx.update_global(|store: &mut SettingsStore, cx| {
14501 store.update_user_settings(cx, |settings| {
14502 settings.status_bar.get_or_insert_default().show = Some(true);
14503 });
14504 });
14505
14506 workspace.read_with(cx, |workspace, cx| {
14507 let visible = workspace.status_bar_visible(cx);
14508 assert!(visible, "Status bar should be visible when show is true");
14509 });
14510 }
14511
14512 #[gpui::test]
14513 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14514 init_test(cx);
14515
14516 let fs = FakeFs::new(cx.executor());
14517 let project = Project::test(fs, [], cx).await;
14518 let (multi_workspace, cx) =
14519 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14520 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14521 let panel = workspace.update_in(cx, |workspace, window, cx| {
14522 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14523 workspace.add_panel(panel.clone(), window, cx);
14524
14525 workspace
14526 .right_dock()
14527 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14528
14529 panel
14530 });
14531
14532 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14533 let item_a = cx.new(TestItem::new);
14534 let item_b = cx.new(TestItem::new);
14535 let item_a_id = item_a.entity_id();
14536 let item_b_id = item_b.entity_id();
14537
14538 pane.update_in(cx, |pane, window, cx| {
14539 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14540 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14541 });
14542
14543 pane.read_with(cx, |pane, _| {
14544 assert_eq!(pane.items_len(), 2);
14545 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14546 });
14547
14548 workspace.update_in(cx, |workspace, window, cx| {
14549 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14550 });
14551
14552 workspace.update_in(cx, |_, window, cx| {
14553 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14554 });
14555
14556 // Assert that the `pane::CloseActiveItem` action is handled at the
14557 // workspace level when one of the dock panels is focused and, in that
14558 // case, the center pane's active item is closed but the focus is not
14559 // moved.
14560 cx.dispatch_action(pane::CloseActiveItem::default());
14561 cx.run_until_parked();
14562
14563 pane.read_with(cx, |pane, _| {
14564 assert_eq!(pane.items_len(), 1);
14565 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14566 });
14567
14568 workspace.update_in(cx, |workspace, window, cx| {
14569 assert!(workspace.right_dock().read(cx).is_open());
14570 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14571 });
14572 }
14573
14574 #[gpui::test]
14575 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14576 init_test(cx);
14577 let fs = FakeFs::new(cx.executor());
14578
14579 let project_a = Project::test(fs.clone(), [], cx).await;
14580 let project_b = Project::test(fs, [], cx).await;
14581
14582 let multi_workspace_handle =
14583 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14584 cx.run_until_parked();
14585
14586 multi_workspace_handle
14587 .update(cx, |mw, _window, cx| {
14588 mw.open_sidebar(cx);
14589 })
14590 .unwrap();
14591
14592 let workspace_a = multi_workspace_handle
14593 .read_with(cx, |mw, _| mw.workspace().clone())
14594 .unwrap();
14595
14596 let _workspace_b = multi_workspace_handle
14597 .update(cx, |mw, window, cx| {
14598 mw.test_add_workspace(project_b, window, cx)
14599 })
14600 .unwrap();
14601
14602 // Switch to workspace A
14603 multi_workspace_handle
14604 .update(cx, |mw, window, cx| {
14605 let workspace = mw.workspaces().next().unwrap().clone();
14606 mw.activate(workspace, window, cx);
14607 })
14608 .unwrap();
14609
14610 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14611
14612 // Add a panel to workspace A's right dock and open the dock
14613 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14614 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14615 workspace.add_panel(panel.clone(), window, cx);
14616 workspace
14617 .right_dock()
14618 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14619 panel
14620 });
14621
14622 // Focus the panel through the workspace (matching existing test pattern)
14623 workspace_a.update_in(cx, |workspace, window, cx| {
14624 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14625 });
14626
14627 // Zoom the panel
14628 panel.update_in(cx, |panel, window, cx| {
14629 panel.set_zoomed(true, window, cx);
14630 });
14631
14632 // Verify the panel is zoomed and the dock is open
14633 workspace_a.update_in(cx, |workspace, window, cx| {
14634 assert!(
14635 workspace.right_dock().read(cx).is_open(),
14636 "dock should be open before switch"
14637 );
14638 assert!(
14639 panel.is_zoomed(window, cx),
14640 "panel should be zoomed before switch"
14641 );
14642 assert!(
14643 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14644 "panel should be focused before switch"
14645 );
14646 });
14647
14648 // Switch to workspace B
14649 multi_workspace_handle
14650 .update(cx, |mw, window, cx| {
14651 let workspace = mw.workspaces().nth(1).unwrap().clone();
14652 mw.activate(workspace, window, cx);
14653 })
14654 .unwrap();
14655 cx.run_until_parked();
14656
14657 // Switch back to workspace A
14658 multi_workspace_handle
14659 .update(cx, |mw, window, cx| {
14660 let workspace = mw.workspaces().next().unwrap().clone();
14661 mw.activate(workspace, window, cx);
14662 })
14663 .unwrap();
14664 cx.run_until_parked();
14665
14666 // Verify the panel is still zoomed and the dock is still open
14667 workspace_a.update_in(cx, |workspace, window, cx| {
14668 assert!(
14669 workspace.right_dock().read(cx).is_open(),
14670 "dock should still be open after switching back"
14671 );
14672 assert!(
14673 panel.is_zoomed(window, cx),
14674 "panel should still be zoomed after switching back"
14675 );
14676 });
14677 }
14678
14679 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14680 pane.read(cx)
14681 .items()
14682 .flat_map(|item| {
14683 item.project_paths(cx)
14684 .into_iter()
14685 .map(|path| path.path.display(PathStyle::local()).into_owned())
14686 })
14687 .collect()
14688 }
14689
14690 pub fn init_test(cx: &mut TestAppContext) {
14691 cx.update(|cx| {
14692 let settings_store = SettingsStore::test(cx);
14693 cx.set_global(settings_store);
14694 cx.set_global(db::AppDatabase::test_new());
14695 theme_settings::init(theme::LoadThemes::JustBase, cx);
14696 });
14697 }
14698
14699 #[gpui::test]
14700 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14701 use settings::{ThemeName, ThemeSelection};
14702 use theme::SystemAppearance;
14703 use zed_actions::theme::ToggleMode;
14704
14705 init_test(cx);
14706
14707 let fs = FakeFs::new(cx.executor());
14708 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14709
14710 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14711 .await;
14712
14713 // Build a test project and workspace view so the test can invoke
14714 // the workspace action handler the same way the UI would.
14715 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14716 let (workspace, cx) =
14717 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14718
14719 // Seed the settings file with a plain static light theme so the
14720 // first toggle always starts from a known persisted state.
14721 workspace.update_in(cx, |_workspace, _window, cx| {
14722 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14723 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14724 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14725 });
14726 });
14727 cx.executor().advance_clock(Duration::from_millis(200));
14728 cx.run_until_parked();
14729
14730 // Confirm the initial persisted settings contain the static theme
14731 // we just wrote before any toggling happens.
14732 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14733 assert!(settings_text.contains(r#""theme": "One Light""#));
14734
14735 // Toggle once. This should migrate the persisted theme settings
14736 // into light/dark slots and enable system mode.
14737 workspace.update_in(cx, |workspace, window, cx| {
14738 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14739 });
14740 cx.executor().advance_clock(Duration::from_millis(200));
14741 cx.run_until_parked();
14742
14743 // 1. Static -> Dynamic
14744 // this assertion checks theme changed from static to dynamic.
14745 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14746 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14747 assert_eq!(
14748 parsed["theme"],
14749 serde_json::json!({
14750 "mode": "system",
14751 "light": "One Light",
14752 "dark": "One Dark"
14753 })
14754 );
14755
14756 // 2. Toggle again, suppose it will change the mode to light
14757 workspace.update_in(cx, |workspace, window, cx| {
14758 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14759 });
14760 cx.executor().advance_clock(Duration::from_millis(200));
14761 cx.run_until_parked();
14762
14763 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14764 assert!(settings_text.contains(r#""mode": "light""#));
14765 }
14766
14767 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14768 let item = TestProjectItem::new(id, path, cx);
14769 item.update(cx, |item, _| {
14770 item.is_dirty = true;
14771 });
14772 item
14773 }
14774
14775 #[gpui::test]
14776 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14777 cx: &mut gpui::TestAppContext,
14778 ) {
14779 init_test(cx);
14780 let fs = FakeFs::new(cx.executor());
14781
14782 let project = Project::test(fs, [], cx).await;
14783 let (workspace, cx) =
14784 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14785
14786 let panel = workspace.update_in(cx, |workspace, window, cx| {
14787 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14788 workspace.add_panel(panel.clone(), window, cx);
14789 workspace
14790 .right_dock()
14791 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14792 panel
14793 });
14794
14795 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14796 pane.update_in(cx, |pane, window, cx| {
14797 let item = cx.new(TestItem::new);
14798 pane.add_item(Box::new(item), true, true, None, window, cx);
14799 });
14800
14801 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14802 // mirrors the real-world flow and avoids side effects from directly
14803 // focusing the panel while the center pane is active.
14804 workspace.update_in(cx, |workspace, window, cx| {
14805 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14806 });
14807
14808 panel.update_in(cx, |panel, window, cx| {
14809 panel.set_zoomed(true, window, cx);
14810 });
14811
14812 workspace.update_in(cx, |workspace, window, cx| {
14813 assert!(workspace.right_dock().read(cx).is_open());
14814 assert!(panel.is_zoomed(window, cx));
14815 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14816 });
14817
14818 // Simulate a spurious pane::Event::Focus on the center pane while the
14819 // panel still has focus. This mirrors what happens during macOS window
14820 // activation: the center pane fires a focus event even though actual
14821 // focus remains on the dock panel.
14822 pane.update_in(cx, |_, _, cx| {
14823 cx.emit(pane::Event::Focus);
14824 });
14825
14826 // The dock must remain open because the panel had focus at the time the
14827 // event was processed. Before the fix, dock_to_preserve was None for
14828 // panels that don't implement pane(), causing the dock to close.
14829 workspace.update_in(cx, |workspace, window, cx| {
14830 assert!(
14831 workspace.right_dock().read(cx).is_open(),
14832 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14833 );
14834 assert!(panel.is_zoomed(window, cx));
14835 });
14836 }
14837
14838 #[gpui::test]
14839 async fn test_panels_stay_open_after_position_change_and_settings_update(
14840 cx: &mut gpui::TestAppContext,
14841 ) {
14842 init_test(cx);
14843 let fs = FakeFs::new(cx.executor());
14844 let project = Project::test(fs, [], cx).await;
14845 let (workspace, cx) =
14846 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14847
14848 // Add two panels to the left dock and open it.
14849 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14850 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14851 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14852 workspace.add_panel(panel_a.clone(), window, cx);
14853 workspace.add_panel(panel_b.clone(), window, cx);
14854 workspace.left_dock().update(cx, |dock, cx| {
14855 dock.set_open(true, window, cx);
14856 dock.activate_panel(0, window, cx);
14857 });
14858 (panel_a, panel_b)
14859 });
14860
14861 workspace.update_in(cx, |workspace, _, cx| {
14862 assert!(workspace.left_dock().read(cx).is_open());
14863 });
14864
14865 // Simulate a feature flag changing default dock positions: both panels
14866 // move from Left to Right.
14867 workspace.update_in(cx, |_workspace, _window, cx| {
14868 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14869 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14870 cx.update_global::<SettingsStore, _>(|_, _| {});
14871 });
14872
14873 // Both panels should now be in the right dock.
14874 workspace.update_in(cx, |workspace, _, cx| {
14875 let right_dock = workspace.right_dock().read(cx);
14876 assert_eq!(right_dock.panels_len(), 2);
14877 });
14878
14879 // Open the right dock and activate panel_b (simulating the user
14880 // opening the panel after it moved).
14881 workspace.update_in(cx, |workspace, window, cx| {
14882 workspace.right_dock().update(cx, |dock, cx| {
14883 dock.set_open(true, window, cx);
14884 dock.activate_panel(1, window, cx);
14885 });
14886 });
14887
14888 // Now trigger another SettingsStore change
14889 workspace.update_in(cx, |_workspace, _window, cx| {
14890 cx.update_global::<SettingsStore, _>(|_, _| {});
14891 });
14892
14893 workspace.update_in(cx, |workspace, _, cx| {
14894 assert!(
14895 workspace.right_dock().read(cx).is_open(),
14896 "Right dock should still be open after a settings change"
14897 );
14898 assert_eq!(
14899 workspace.right_dock().read(cx).panels_len(),
14900 2,
14901 "Both panels should still be in the right dock"
14902 );
14903 });
14904 }
14905}