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, NextProject, NextThread, PreviousProject,
36 PreviousThread, ShowFewerThreads, ShowMoreThreads, Sidebar, SidebarEvent, SidebarHandle,
37 SidebarRenderState, SidebarSide, ToggleWorkspaceSidebar, sidebar_side_context_menu,
38};
39pub use path_list::{PathList, SerializedPathList};
40pub use toast_layer::{ToastAction, ToastLayer, ToastView};
41
42use anyhow::{Context as _, Result, anyhow};
43use client::{
44 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
45 proto::{self, ErrorCode, PanelId, PeerId},
46};
47use collections::{HashMap, HashSet, hash_map};
48use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
49use fs::Fs;
50use futures::{
51 Future, FutureExt, StreamExt,
52 channel::{
53 mpsc::{self, UnboundedReceiver, UnboundedSender},
54 oneshot,
55 },
56 future::{Shared, try_join_all},
57};
58use gpui::{
59 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Axis, Bounds,
60 Context, CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
61 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
62 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
63 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
64 WindowOptions, actions, canvas, point, relative, size, transparent_black,
65};
66pub use history_manager::*;
67pub use item::{
68 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
69 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
70};
71use itertools::Itertools;
72use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
73pub use modal_layer::*;
74use node_runtime::NodeRuntime;
75use notifications::{
76 DetachAndPromptErr, Notifications, dismiss_app_notification,
77 simple_message_notification::MessageNotification,
78};
79pub use pane::*;
80pub use pane_group::{
81 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
82 SplitDirection,
83};
84use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
85pub use persistence::{
86 WorkspaceDb, delete_unloaded_items,
87 model::{
88 DockStructure, ItemId, MultiWorkspaceState, SerializedMultiWorkspace,
89 SerializedWorkspaceLocation, SessionWorkspace,
90 },
91 read_serialized_multi_workspaces, resolve_worktree_workspaces,
92};
93use postage::stream::Stream;
94use project::{
95 DirectoryLister, Project, ProjectEntryId, ProjectGroupKey, ProjectPath, ResolvedPath, Worktree,
96 WorktreeId, WorktreeSettings,
97 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
98 project_settings::ProjectSettings,
99 toolchain_store::ToolchainStoreEvent,
100 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
101};
102use remote::{
103 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
104 remote_client::ConnectionIdentifier,
105};
106use schemars::JsonSchema;
107use serde::Deserialize;
108use session::AppSession;
109use settings::{
110 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
111};
112
113use sqlez::{
114 bindable::{Bind, Column, StaticColumnCount},
115 statement::Statement,
116};
117use status_bar::StatusBar;
118pub use status_bar::StatusItemView;
119use std::{
120 any::TypeId,
121 borrow::Cow,
122 cell::RefCell,
123 cmp,
124 collections::VecDeque,
125 env,
126 hash::Hash,
127 path::{Path, PathBuf},
128 process::ExitStatus,
129 rc::Rc,
130 sync::{
131 Arc, LazyLock,
132 atomic::{AtomicBool, AtomicUsize},
133 },
134 time::Duration,
135};
136use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
137use theme::{ActiveTheme, SystemAppearance};
138use theme_settings::ThemeSettings;
139pub use toolbar::{
140 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
141};
142pub use ui;
143use ui::{Window, prelude::*};
144use util::{
145 ResultExt, TryFutureExt,
146 paths::{PathStyle, SanitizedPath},
147 rel_path::RelPath,
148 serde::default_true,
149};
150use uuid::Uuid;
151pub use workspace_settings::{
152 AutosaveSetting, BottomDockLayout, FocusFollowsMouse, RestoreOnStartupBehavior,
153 StatusBarSettings, TabBarSettings, WorkspaceSettings,
154};
155use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
156
157use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::NotificationId};
158use crate::{
159 persistence::{
160 SerializedAxis,
161 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
162 },
163 security_modal::SecurityModal,
164};
165
166pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
167
168static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
169 env::var("ZED_WINDOW_SIZE")
170 .ok()
171 .as_deref()
172 .and_then(parse_pixel_size_env_var)
173});
174
175static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
176 env::var("ZED_WINDOW_POSITION")
177 .ok()
178 .as_deref()
179 .and_then(parse_pixel_position_env_var)
180});
181
182pub trait TerminalProvider {
183 fn spawn(
184 &self,
185 task: SpawnInTerminal,
186 window: &mut Window,
187 cx: &mut App,
188 ) -> Task<Option<Result<ExitStatus>>>;
189}
190
191pub trait DebuggerProvider {
192 // `active_buffer` is used to resolve build task's name against language-specific tasks.
193 fn start_session(
194 &self,
195 definition: DebugScenario,
196 task_context: SharedTaskContext,
197 active_buffer: Option<Entity<Buffer>>,
198 worktree_id: Option<WorktreeId>,
199 window: &mut Window,
200 cx: &mut App,
201 );
202
203 fn spawn_task_or_modal(
204 &self,
205 workspace: &mut Workspace,
206 action: &Spawn,
207 window: &mut Window,
208 cx: &mut Context<Workspace>,
209 );
210
211 fn task_scheduled(&self, cx: &mut App);
212 fn debug_scenario_scheduled(&self, cx: &mut App);
213 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
214
215 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
216}
217
218/// Opens a file or directory.
219#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
220#[action(namespace = workspace)]
221pub struct Open {
222 /// When true, opens in a new window. When false, adds to the current
223 /// window as a new workspace (multi-workspace).
224 #[serde(default = "Open::default_create_new_window")]
225 pub create_new_window: bool,
226}
227
228impl Open {
229 pub const DEFAULT: Self = Self {
230 create_new_window: true,
231 };
232
233 /// Used by `#[serde(default)]` on the `create_new_window` field so that
234 /// the serde default and `Open::DEFAULT` stay in sync.
235 fn default_create_new_window() -> bool {
236 Self::DEFAULT.create_new_window
237 }
238}
239
240impl Default for Open {
241 fn default() -> Self {
242 Self::DEFAULT
243 }
244}
245
246actions!(
247 workspace,
248 [
249 /// Activates the next pane in the workspace.
250 ActivateNextPane,
251 /// Activates the previous pane in the workspace.
252 ActivatePreviousPane,
253 /// Activates the last pane in the workspace.
254 ActivateLastPane,
255 /// Switches to the next window.
256 ActivateNextWindow,
257 /// Switches to the previous window.
258 ActivatePreviousWindow,
259 /// Adds a folder to the current project.
260 AddFolderToProject,
261 /// Clears all notifications.
262 ClearAllNotifications,
263 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
264 ClearNavigationHistory,
265 /// Closes the active dock.
266 CloseActiveDock,
267 /// Closes all docks.
268 CloseAllDocks,
269 /// Toggles all docks.
270 ToggleAllDocks,
271 /// Closes the current window.
272 CloseWindow,
273 /// Closes the current project.
274 CloseProject,
275 /// Opens the feedback dialog.
276 Feedback,
277 /// Follows the next collaborator in the session.
278 FollowNextCollaborator,
279 /// Moves the focused panel to the next position.
280 MoveFocusedPanelToNextPosition,
281 /// Creates a new file.
282 NewFile,
283 /// Creates a new file in a vertical split.
284 NewFileSplitVertical,
285 /// Creates a new file in a horizontal split.
286 NewFileSplitHorizontal,
287 /// Opens a new search.
288 NewSearch,
289 /// Opens a new window.
290 NewWindow,
291 /// Opens multiple files.
292 OpenFiles,
293 /// Opens the current location in terminal.
294 OpenInTerminal,
295 /// Opens the component preview.
296 OpenComponentPreview,
297 /// Reloads the active item.
298 ReloadActiveItem,
299 /// Resets the active dock to its default size.
300 ResetActiveDockSize,
301 /// Resets all open docks to their default sizes.
302 ResetOpenDocksSize,
303 /// Reloads the application
304 Reload,
305 /// Saves the current file with a new name.
306 SaveAs,
307 /// Saves without formatting.
308 SaveWithoutFormat,
309 /// Shuts down all debug adapters.
310 ShutdownDebugAdapters,
311 /// Suppresses the current notification.
312 SuppressNotification,
313 /// Toggles the bottom dock.
314 ToggleBottomDock,
315 /// Toggles centered layout mode.
316 ToggleCenteredLayout,
317 /// Toggles edit prediction feature globally for all files.
318 ToggleEditPrediction,
319 /// Toggles the left dock.
320 ToggleLeftDock,
321 /// Toggles the right dock.
322 ToggleRightDock,
323 /// Toggles zoom on the active pane.
324 ToggleZoom,
325 /// Toggles read-only mode for the active item (if supported by that item).
326 ToggleReadOnlyFile,
327 /// Zooms in on the active pane.
328 ZoomIn,
329 /// Zooms out of the active pane.
330 ZoomOut,
331 /// If any worktrees are in restricted mode, shows a modal with possible actions.
332 /// If the modal is shown already, closes it without trusting any worktree.
333 ToggleWorktreeSecurity,
334 /// Clears all trusted worktrees, placing them in restricted mode on next open.
335 /// Requires restart to take effect on already opened projects.
336 ClearTrustedWorktrees,
337 /// Stops following a collaborator.
338 Unfollow,
339 /// Restores the banner.
340 RestoreBanner,
341 /// Toggles expansion of the selected item.
342 ToggleExpandItem,
343 ]
344);
345
346/// Activates a specific pane by its index.
347#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
348#[action(namespace = workspace)]
349pub struct ActivatePane(pub usize);
350
351/// Moves an item to a specific pane by index.
352#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
353#[action(namespace = workspace)]
354#[serde(deny_unknown_fields)]
355pub struct MoveItemToPane {
356 #[serde(default = "default_1")]
357 pub destination: usize,
358 #[serde(default = "default_true")]
359 pub focus: bool,
360 #[serde(default)]
361 pub clone: bool,
362}
363
364fn default_1() -> usize {
365 1
366}
367
368/// Moves an item to a pane in the specified direction.
369#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
370#[action(namespace = workspace)]
371#[serde(deny_unknown_fields)]
372pub struct MoveItemToPaneInDirection {
373 #[serde(default = "default_right")]
374 pub direction: SplitDirection,
375 #[serde(default = "default_true")]
376 pub focus: bool,
377 #[serde(default)]
378 pub clone: bool,
379}
380
381/// Creates a new file in a split of the desired direction.
382#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
383#[action(namespace = workspace)]
384#[serde(deny_unknown_fields)]
385pub struct NewFileSplit(pub SplitDirection);
386
387fn default_right() -> SplitDirection {
388 SplitDirection::Right
389}
390
391/// Saves all open files in the workspace.
392#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
393#[action(namespace = workspace)]
394#[serde(deny_unknown_fields)]
395pub struct SaveAll {
396 #[serde(default)]
397 pub save_intent: Option<SaveIntent>,
398}
399
400/// Saves the current file with the specified options.
401#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
402#[action(namespace = workspace)]
403#[serde(deny_unknown_fields)]
404pub struct Save {
405 #[serde(default)]
406 pub save_intent: Option<SaveIntent>,
407}
408
409/// Moves Focus to the central panes in the workspace.
410#[derive(Clone, Debug, PartialEq, Eq, Action)]
411#[action(namespace = workspace)]
412pub struct FocusCenterPane;
413
414/// Closes all items and panes in the workspace.
415#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
416#[action(namespace = workspace)]
417#[serde(deny_unknown_fields)]
418pub struct CloseAllItemsAndPanes {
419 #[serde(default)]
420 pub save_intent: Option<SaveIntent>,
421}
422
423/// Closes all inactive tabs and panes in the workspace.
424#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
425#[action(namespace = workspace)]
426#[serde(deny_unknown_fields)]
427pub struct CloseInactiveTabsAndPanes {
428 #[serde(default)]
429 pub save_intent: Option<SaveIntent>,
430}
431
432/// Closes the active item across all panes.
433#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
434#[action(namespace = workspace)]
435#[serde(deny_unknown_fields)]
436pub struct CloseItemInAllPanes {
437 #[serde(default)]
438 pub save_intent: Option<SaveIntent>,
439 #[serde(default)]
440 pub close_pinned: bool,
441}
442
443/// Sends a sequence of keystrokes to the active element.
444#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
445#[action(namespace = workspace)]
446pub struct SendKeystrokes(pub String);
447
448actions!(
449 project_symbols,
450 [
451 /// Toggles the project symbols search.
452 #[action(name = "Toggle")]
453 ToggleProjectSymbols
454 ]
455);
456
457/// Toggles the file finder interface.
458#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
459#[action(namespace = file_finder, name = "Toggle")]
460#[serde(deny_unknown_fields)]
461pub struct ToggleFileFinder {
462 #[serde(default)]
463 pub separate_history: bool,
464}
465
466/// Opens a new terminal in the center.
467#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
468#[action(namespace = workspace)]
469#[serde(deny_unknown_fields)]
470pub struct NewCenterTerminal {
471 /// If true, creates a local terminal even in remote projects.
472 #[serde(default)]
473 pub local: bool,
474}
475
476/// Opens a new terminal.
477#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
478#[action(namespace = workspace)]
479#[serde(deny_unknown_fields)]
480pub struct NewTerminal {
481 /// If true, creates a local terminal even in remote projects.
482 #[serde(default)]
483 pub local: bool,
484}
485
486/// Increases size of a currently focused dock by a given amount of pixels.
487#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
488#[action(namespace = workspace)]
489#[serde(deny_unknown_fields)]
490pub struct IncreaseActiveDockSize {
491 /// For 0px parameter, uses UI font size value.
492 #[serde(default)]
493 pub px: u32,
494}
495
496/// Decreases size of a currently focused dock by a given amount of pixels.
497#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
498#[action(namespace = workspace)]
499#[serde(deny_unknown_fields)]
500pub struct DecreaseActiveDockSize {
501 /// For 0px parameter, uses UI font size value.
502 #[serde(default)]
503 pub px: u32,
504}
505
506/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
507#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
508#[action(namespace = workspace)]
509#[serde(deny_unknown_fields)]
510pub struct IncreaseOpenDocksSize {
511 /// For 0px parameter, uses UI font size value.
512 #[serde(default)]
513 pub px: u32,
514}
515
516/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
517#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
518#[action(namespace = workspace)]
519#[serde(deny_unknown_fields)]
520pub struct DecreaseOpenDocksSize {
521 /// For 0px parameter, uses UI font size value.
522 #[serde(default)]
523 pub px: u32,
524}
525
526actions!(
527 workspace,
528 [
529 /// Activates the pane to the left.
530 ActivatePaneLeft,
531 /// Activates the pane to the right.
532 ActivatePaneRight,
533 /// Activates the pane above.
534 ActivatePaneUp,
535 /// Activates the pane below.
536 ActivatePaneDown,
537 /// Swaps the current pane with the one to the left.
538 SwapPaneLeft,
539 /// Swaps the current pane with the one to the right.
540 SwapPaneRight,
541 /// Swaps the current pane with the one above.
542 SwapPaneUp,
543 /// Swaps the current pane with the one below.
544 SwapPaneDown,
545 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
546 SwapPaneAdjacent,
547 /// Move the current pane to be at the far left.
548 MovePaneLeft,
549 /// Move the current pane to be at the far right.
550 MovePaneRight,
551 /// Move the current pane to be at the very top.
552 MovePaneUp,
553 /// Move the current pane to be at the very bottom.
554 MovePaneDown,
555 ]
556);
557
558#[derive(PartialEq, Eq, Debug)]
559pub enum CloseIntent {
560 /// Quit the program entirely.
561 Quit,
562 /// Close a window.
563 CloseWindow,
564 /// Replace the workspace in an existing window.
565 ReplaceWindow,
566}
567
568#[derive(Clone)]
569pub struct Toast {
570 id: NotificationId,
571 msg: Cow<'static, str>,
572 autohide: bool,
573 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
574}
575
576impl Toast {
577 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
578 Toast {
579 id,
580 msg: msg.into(),
581 on_click: None,
582 autohide: false,
583 }
584 }
585
586 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
587 where
588 M: Into<Cow<'static, str>>,
589 F: Fn(&mut Window, &mut App) + 'static,
590 {
591 self.on_click = Some((message.into(), Arc::new(on_click)));
592 self
593 }
594
595 pub fn autohide(mut self) -> Self {
596 self.autohide = true;
597 self
598 }
599}
600
601impl PartialEq for Toast {
602 fn eq(&self, other: &Self) -> bool {
603 self.id == other.id
604 && self.msg == other.msg
605 && self.on_click.is_some() == other.on_click.is_some()
606 }
607}
608
609/// Opens a new terminal with the specified working directory.
610#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
611#[action(namespace = workspace)]
612#[serde(deny_unknown_fields)]
613pub struct OpenTerminal {
614 pub working_directory: PathBuf,
615 /// If true, creates a local terminal even in remote projects.
616 #[serde(default)]
617 pub local: bool,
618}
619
620#[derive(
621 Clone,
622 Copy,
623 Debug,
624 Default,
625 Hash,
626 PartialEq,
627 Eq,
628 PartialOrd,
629 Ord,
630 serde::Serialize,
631 serde::Deserialize,
632)]
633pub struct WorkspaceId(i64);
634
635impl WorkspaceId {
636 pub fn from_i64(value: i64) -> Self {
637 Self(value)
638 }
639}
640
641impl StaticColumnCount for WorkspaceId {}
642impl Bind for WorkspaceId {
643 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
644 self.0.bind(statement, start_index)
645 }
646}
647impl Column for WorkspaceId {
648 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
649 i64::column(statement, start_index)
650 .map(|(i, next_index)| (Self(i), next_index))
651 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
652 }
653}
654impl From<WorkspaceId> for i64 {
655 fn from(val: WorkspaceId) -> Self {
656 val.0
657 }
658}
659
660fn prompt_and_open_paths(
661 app_state: Arc<AppState>,
662 options: PathPromptOptions,
663 create_new_window: bool,
664 cx: &mut App,
665) {
666 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
667 workspace_window
668 .update(cx, |multi_workspace, window, cx| {
669 let workspace = multi_workspace.workspace().clone();
670 workspace.update(cx, |workspace, cx| {
671 prompt_for_open_path_and_open(
672 workspace,
673 app_state,
674 options,
675 create_new_window,
676 window,
677 cx,
678 );
679 });
680 })
681 .ok();
682 } else {
683 let task = Workspace::new_local(
684 Vec::new(),
685 app_state.clone(),
686 None,
687 None,
688 None,
689 OpenMode::Activate,
690 cx,
691 );
692 cx.spawn(async move |cx| {
693 let OpenResult { window, .. } = task.await?;
694 window.update(cx, |multi_workspace, window, cx| {
695 window.activate_window();
696 let workspace = multi_workspace.workspace().clone();
697 workspace.update(cx, |workspace, cx| {
698 prompt_for_open_path_and_open(
699 workspace,
700 app_state,
701 options,
702 create_new_window,
703 window,
704 cx,
705 );
706 });
707 })?;
708 anyhow::Ok(())
709 })
710 .detach_and_log_err(cx);
711 }
712}
713
714pub fn prompt_for_open_path_and_open(
715 workspace: &mut Workspace,
716 app_state: Arc<AppState>,
717 options: PathPromptOptions,
718 create_new_window: bool,
719 window: &mut Window,
720 cx: &mut Context<Workspace>,
721) {
722 let paths = workspace.prompt_for_open_path(
723 options,
724 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
725 window,
726 cx,
727 );
728 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
729 cx.spawn_in(window, async move |this, cx| {
730 let Some(paths) = paths.await.log_err().flatten() else {
731 return;
732 };
733 if !create_new_window {
734 if let Some(handle) = multi_workspace_handle {
735 if let Some(task) = handle
736 .update(cx, |multi_workspace, window, cx| {
737 multi_workspace.open_project(paths, OpenMode::Activate, window, cx)
738 })
739 .log_err()
740 {
741 task.await.log_err();
742 }
743 return;
744 }
745 }
746 if let Some(task) = this
747 .update_in(cx, |this, window, cx| {
748 this.open_workspace_for_paths(OpenMode::NewWindow, paths, window, cx)
749 })
750 .log_err()
751 {
752 task.await.log_err();
753 }
754 })
755 .detach();
756}
757
758pub fn init(app_state: Arc<AppState>, cx: &mut App) {
759 component::init();
760 theme_preview::init(cx);
761 toast_layer::init(cx);
762 history_manager::init(app_state.fs.clone(), cx);
763
764 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
765 .on_action(|_: &Reload, cx| reload(cx))
766 .on_action(|action: &Open, cx: &mut App| {
767 let app_state = AppState::global(cx);
768 prompt_and_open_paths(
769 app_state,
770 PathPromptOptions {
771 files: true,
772 directories: true,
773 multiple: true,
774 prompt: None,
775 },
776 action.create_new_window,
777 cx,
778 );
779 })
780 .on_action(|_: &OpenFiles, cx: &mut App| {
781 let directories = cx.can_select_mixed_files_and_dirs();
782 let app_state = AppState::global(cx);
783 prompt_and_open_paths(
784 app_state,
785 PathPromptOptions {
786 files: true,
787 directories,
788 multiple: true,
789 prompt: None,
790 },
791 true,
792 cx,
793 );
794 });
795}
796
797type BuildProjectItemFn =
798 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
799
800type BuildProjectItemForPathFn =
801 fn(
802 &Entity<Project>,
803 &ProjectPath,
804 &mut Window,
805 &mut App,
806 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
807
808#[derive(Clone, Default)]
809struct ProjectItemRegistry {
810 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
811 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
812}
813
814impl ProjectItemRegistry {
815 fn register<T: ProjectItem>(&mut self) {
816 self.build_project_item_fns_by_type.insert(
817 TypeId::of::<T::Item>(),
818 |item, project, pane, window, cx| {
819 let item = item.downcast().unwrap();
820 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
821 as Box<dyn ItemHandle>
822 },
823 );
824 self.build_project_item_for_path_fns
825 .push(|project, project_path, window, cx| {
826 let project_path = project_path.clone();
827 let is_file = project
828 .read(cx)
829 .entry_for_path(&project_path, cx)
830 .is_some_and(|entry| entry.is_file());
831 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
832 let is_local = project.read(cx).is_local();
833 let project_item =
834 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
835 let project = project.clone();
836 Some(window.spawn(cx, async move |cx| {
837 match project_item.await.with_context(|| {
838 format!(
839 "opening project path {:?}",
840 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
841 )
842 }) {
843 Ok(project_item) => {
844 let project_item = project_item;
845 let project_entry_id: Option<ProjectEntryId> =
846 project_item.read_with(cx, project::ProjectItem::entry_id);
847 let build_workspace_item = Box::new(
848 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
849 Box::new(cx.new(|cx| {
850 T::for_project_item(
851 project,
852 Some(pane),
853 project_item,
854 window,
855 cx,
856 )
857 })) as Box<dyn ItemHandle>
858 },
859 ) as Box<_>;
860 Ok((project_entry_id, build_workspace_item))
861 }
862 Err(e) => {
863 log::warn!("Failed to open a project item: {e:#}");
864 if e.error_code() == ErrorCode::Internal {
865 if let Some(abs_path) =
866 entry_abs_path.as_deref().filter(|_| is_file)
867 {
868 if let Some(broken_project_item_view) =
869 cx.update(|window, cx| {
870 T::for_broken_project_item(
871 abs_path, is_local, &e, window, cx,
872 )
873 })?
874 {
875 let build_workspace_item = Box::new(
876 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
877 cx.new(|_| broken_project_item_view).boxed_clone()
878 },
879 )
880 as Box<_>;
881 return Ok((None, build_workspace_item));
882 }
883 }
884 }
885 Err(e)
886 }
887 }
888 }))
889 });
890 }
891
892 fn open_path(
893 &self,
894 project: &Entity<Project>,
895 path: &ProjectPath,
896 window: &mut Window,
897 cx: &mut App,
898 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
899 let Some(open_project_item) = self
900 .build_project_item_for_path_fns
901 .iter()
902 .rev()
903 .find_map(|open_project_item| open_project_item(project, path, window, cx))
904 else {
905 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
906 };
907 open_project_item
908 }
909
910 fn build_item<T: project::ProjectItem>(
911 &self,
912 item: Entity<T>,
913 project: Entity<Project>,
914 pane: Option<&Pane>,
915 window: &mut Window,
916 cx: &mut App,
917 ) -> Option<Box<dyn ItemHandle>> {
918 let build = self
919 .build_project_item_fns_by_type
920 .get(&TypeId::of::<T>())?;
921 Some(build(item.into_any(), project, pane, window, cx))
922 }
923}
924
925type WorkspaceItemBuilder =
926 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
927
928impl Global for ProjectItemRegistry {}
929
930/// Registers a [ProjectItem] for the app. When opening a file, all the registered
931/// items will get a chance to open the file, starting from the project item that
932/// was added last.
933pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
934 cx.default_global::<ProjectItemRegistry>().register::<I>();
935}
936
937#[derive(Default)]
938pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
939
940struct FollowableViewDescriptor {
941 from_state_proto: fn(
942 Entity<Workspace>,
943 ViewId,
944 &mut Option<proto::view::Variant>,
945 &mut Window,
946 &mut App,
947 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
948 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
949}
950
951impl Global for FollowableViewRegistry {}
952
953impl FollowableViewRegistry {
954 pub fn register<I: FollowableItem>(cx: &mut App) {
955 cx.default_global::<Self>().0.insert(
956 TypeId::of::<I>(),
957 FollowableViewDescriptor {
958 from_state_proto: |workspace, id, state, window, cx| {
959 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
960 cx.foreground_executor()
961 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
962 })
963 },
964 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
965 },
966 );
967 }
968
969 pub fn from_state_proto(
970 workspace: Entity<Workspace>,
971 view_id: ViewId,
972 mut state: Option<proto::view::Variant>,
973 window: &mut Window,
974 cx: &mut App,
975 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
976 cx.update_default_global(|this: &mut Self, cx| {
977 this.0.values().find_map(|descriptor| {
978 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
979 })
980 })
981 }
982
983 pub fn to_followable_view(
984 view: impl Into<AnyView>,
985 cx: &App,
986 ) -> Option<Box<dyn FollowableItemHandle>> {
987 let this = cx.try_global::<Self>()?;
988 let view = view.into();
989 let descriptor = this.0.get(&view.entity_type())?;
990 Some((descriptor.to_followable_view)(&view))
991 }
992}
993
994#[derive(Copy, Clone)]
995struct SerializableItemDescriptor {
996 deserialize: fn(
997 Entity<Project>,
998 WeakEntity<Workspace>,
999 WorkspaceId,
1000 ItemId,
1001 &mut Window,
1002 &mut Context<Pane>,
1003 ) -> Task<Result<Box<dyn ItemHandle>>>,
1004 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
1005 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
1006}
1007
1008#[derive(Default)]
1009struct SerializableItemRegistry {
1010 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
1011 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
1012}
1013
1014impl Global for SerializableItemRegistry {}
1015
1016impl SerializableItemRegistry {
1017 fn deserialize(
1018 item_kind: &str,
1019 project: Entity<Project>,
1020 workspace: WeakEntity<Workspace>,
1021 workspace_id: WorkspaceId,
1022 item_item: ItemId,
1023 window: &mut Window,
1024 cx: &mut Context<Pane>,
1025 ) -> Task<Result<Box<dyn ItemHandle>>> {
1026 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1027 return Task::ready(Err(anyhow!(
1028 "cannot deserialize {}, descriptor not found",
1029 item_kind
1030 )));
1031 };
1032
1033 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1034 }
1035
1036 fn cleanup(
1037 item_kind: &str,
1038 workspace_id: WorkspaceId,
1039 loaded_items: Vec<ItemId>,
1040 window: &mut Window,
1041 cx: &mut App,
1042 ) -> Task<Result<()>> {
1043 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1044 return Task::ready(Err(anyhow!(
1045 "cannot cleanup {}, descriptor not found",
1046 item_kind
1047 )));
1048 };
1049
1050 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1051 }
1052
1053 fn view_to_serializable_item_handle(
1054 view: AnyView,
1055 cx: &App,
1056 ) -> Option<Box<dyn SerializableItemHandle>> {
1057 let this = cx.try_global::<Self>()?;
1058 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1059 Some((descriptor.view_to_serializable_item)(view))
1060 }
1061
1062 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1063 let this = cx.try_global::<Self>()?;
1064 this.descriptors_by_kind.get(item_kind).copied()
1065 }
1066}
1067
1068pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1069 let serialized_item_kind = I::serialized_item_kind();
1070
1071 let registry = cx.default_global::<SerializableItemRegistry>();
1072 let descriptor = SerializableItemDescriptor {
1073 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1074 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1075 cx.foreground_executor()
1076 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1077 },
1078 cleanup: |workspace_id, loaded_items, window, cx| {
1079 I::cleanup(workspace_id, loaded_items, window, cx)
1080 },
1081 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1082 };
1083 registry
1084 .descriptors_by_kind
1085 .insert(Arc::from(serialized_item_kind), descriptor);
1086 registry
1087 .descriptors_by_type
1088 .insert(TypeId::of::<I>(), descriptor);
1089}
1090
1091pub struct AppState {
1092 pub languages: Arc<LanguageRegistry>,
1093 pub client: Arc<Client>,
1094 pub user_store: Entity<UserStore>,
1095 pub workspace_store: Entity<WorkspaceStore>,
1096 pub fs: Arc<dyn fs::Fs>,
1097 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1098 pub node_runtime: NodeRuntime,
1099 pub session: Entity<AppSession>,
1100}
1101
1102struct GlobalAppState(Arc<AppState>);
1103
1104impl Global for GlobalAppState {}
1105
1106pub struct WorkspaceStore {
1107 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1108 client: Arc<Client>,
1109 _subscriptions: Vec<client::Subscription>,
1110}
1111
1112#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1113pub enum CollaboratorId {
1114 PeerId(PeerId),
1115 Agent,
1116}
1117
1118impl From<PeerId> for CollaboratorId {
1119 fn from(peer_id: PeerId) -> Self {
1120 CollaboratorId::PeerId(peer_id)
1121 }
1122}
1123
1124impl From<&PeerId> for CollaboratorId {
1125 fn from(peer_id: &PeerId) -> Self {
1126 CollaboratorId::PeerId(*peer_id)
1127 }
1128}
1129
1130#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1131struct Follower {
1132 project_id: Option<u64>,
1133 peer_id: PeerId,
1134}
1135
1136impl AppState {
1137 #[track_caller]
1138 pub fn global(cx: &App) -> Arc<Self> {
1139 cx.global::<GlobalAppState>().0.clone()
1140 }
1141 pub fn try_global(cx: &App) -> Option<Arc<Self>> {
1142 cx.try_global::<GlobalAppState>()
1143 .map(|state| state.0.clone())
1144 }
1145 pub fn set_global(state: Arc<AppState>, cx: &mut App) {
1146 cx.set_global(GlobalAppState(state));
1147 }
1148
1149 #[cfg(any(test, feature = "test-support"))]
1150 pub fn test(cx: &mut App) -> Arc<Self> {
1151 use fs::Fs;
1152 use node_runtime::NodeRuntime;
1153 use session::Session;
1154 use settings::SettingsStore;
1155
1156 if !cx.has_global::<SettingsStore>() {
1157 let settings_store = SettingsStore::test(cx);
1158 cx.set_global(settings_store);
1159 }
1160
1161 let fs = fs::FakeFs::new(cx.background_executor().clone());
1162 <dyn Fs>::set_global(fs.clone(), cx);
1163 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1164 let clock = Arc::new(clock::FakeSystemClock::new());
1165 let http_client = http_client::FakeHttpClient::with_404_response();
1166 let client = Client::new(clock, http_client, cx);
1167 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1168 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1169 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1170
1171 theme_settings::init(theme::LoadThemes::JustBase, cx);
1172 client::init(&client, cx);
1173
1174 Arc::new(Self {
1175 client,
1176 fs,
1177 languages,
1178 user_store,
1179 workspace_store,
1180 node_runtime: NodeRuntime::unavailable(),
1181 build_window_options: |_, _| Default::default(),
1182 session,
1183 })
1184 }
1185}
1186
1187struct DelayedDebouncedEditAction {
1188 task: Option<Task<()>>,
1189 cancel_channel: Option<oneshot::Sender<()>>,
1190}
1191
1192impl DelayedDebouncedEditAction {
1193 fn new() -> DelayedDebouncedEditAction {
1194 DelayedDebouncedEditAction {
1195 task: None,
1196 cancel_channel: None,
1197 }
1198 }
1199
1200 fn fire_new<F>(
1201 &mut self,
1202 delay: Duration,
1203 window: &mut Window,
1204 cx: &mut Context<Workspace>,
1205 func: F,
1206 ) where
1207 F: 'static
1208 + Send
1209 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1210 {
1211 if let Some(channel) = self.cancel_channel.take() {
1212 _ = channel.send(());
1213 }
1214
1215 let (sender, mut receiver) = oneshot::channel::<()>();
1216 self.cancel_channel = Some(sender);
1217
1218 let previous_task = self.task.take();
1219 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1220 let mut timer = cx.background_executor().timer(delay).fuse();
1221 if let Some(previous_task) = previous_task {
1222 previous_task.await;
1223 }
1224
1225 futures::select_biased! {
1226 _ = receiver => return,
1227 _ = timer => {}
1228 }
1229
1230 if let Some(result) = workspace
1231 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1232 .log_err()
1233 {
1234 result.await.log_err();
1235 }
1236 }));
1237 }
1238}
1239
1240pub enum Event {
1241 PaneAdded(Entity<Pane>),
1242 PaneRemoved,
1243 ItemAdded {
1244 item: Box<dyn ItemHandle>,
1245 },
1246 ActiveItemChanged,
1247 ItemRemoved {
1248 item_id: EntityId,
1249 },
1250 UserSavedItem {
1251 pane: WeakEntity<Pane>,
1252 item: Box<dyn WeakItemHandle>,
1253 save_intent: SaveIntent,
1254 },
1255 ContactRequestedJoin(u64),
1256 WorkspaceCreated(WeakEntity<Workspace>),
1257 OpenBundledFile {
1258 text: Cow<'static, str>,
1259 title: &'static str,
1260 language: &'static str,
1261 },
1262 ZoomChanged,
1263 ModalOpened,
1264 Activate,
1265 PanelAdded(AnyView),
1266}
1267
1268#[derive(Debug, Clone)]
1269pub enum OpenVisible {
1270 All,
1271 None,
1272 OnlyFiles,
1273 OnlyDirectories,
1274}
1275
1276enum WorkspaceLocation {
1277 // Valid local paths or SSH project to serialize
1278 Location(SerializedWorkspaceLocation, PathList),
1279 // No valid location found hence clear session id
1280 DetachFromSession,
1281 // No valid location found to serialize
1282 None,
1283}
1284
1285type PromptForNewPath = Box<
1286 dyn Fn(
1287 &mut Workspace,
1288 DirectoryLister,
1289 Option<String>,
1290 &mut Window,
1291 &mut Context<Workspace>,
1292 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1293>;
1294
1295type PromptForOpenPath = Box<
1296 dyn Fn(
1297 &mut Workspace,
1298 DirectoryLister,
1299 &mut Window,
1300 &mut Context<Workspace>,
1301 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1302>;
1303
1304#[derive(Default)]
1305struct DispatchingKeystrokes {
1306 dispatched: HashSet<Vec<Keystroke>>,
1307 queue: VecDeque<Keystroke>,
1308 task: Option<Shared<Task<()>>>,
1309}
1310
1311/// Collects everything project-related for a certain window opened.
1312/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1313///
1314/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1315/// The `Workspace` owns everybody's state and serves as a default, "global context",
1316/// that can be used to register a global action to be triggered from any place in the window.
1317pub struct Workspace {
1318 weak_self: WeakEntity<Self>,
1319 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1320 zoomed: Option<AnyWeakView>,
1321 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1322 zoomed_position: Option<DockPosition>,
1323 center: PaneGroup,
1324 left_dock: Entity<Dock>,
1325 bottom_dock: Entity<Dock>,
1326 right_dock: Entity<Dock>,
1327 panes: Vec<Entity<Pane>>,
1328 active_worktree_override: Option<WorktreeId>,
1329 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1330 active_pane: Entity<Pane>,
1331 last_active_center_pane: Option<WeakEntity<Pane>>,
1332 last_active_view_id: Option<proto::ViewId>,
1333 status_bar: Entity<StatusBar>,
1334 pub(crate) modal_layer: Entity<ModalLayer>,
1335 toast_layer: Entity<ToastLayer>,
1336 titlebar_item: Option<AnyView>,
1337 notifications: Notifications,
1338 suppressed_notifications: HashSet<NotificationId>,
1339 project: Entity<Project>,
1340 follower_states: HashMap<CollaboratorId, FollowerState>,
1341 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1342 window_edited: bool,
1343 last_window_title: Option<String>,
1344 dirty_items: HashMap<EntityId, Subscription>,
1345 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1346 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1347 database_id: Option<WorkspaceId>,
1348 app_state: Arc<AppState>,
1349 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1350 _subscriptions: Vec<Subscription>,
1351 _apply_leader_updates: Task<Result<()>>,
1352 _observe_current_user: Task<Result<()>>,
1353 _schedule_serialize_workspace: Option<Task<()>>,
1354 _serialize_workspace_task: Option<Task<()>>,
1355 _schedule_serialize_ssh_paths: Option<Task<()>>,
1356 pane_history_timestamp: Arc<AtomicUsize>,
1357 bounds: Bounds<Pixels>,
1358 pub centered_layout: bool,
1359 bounds_save_task_queued: Option<Task<()>>,
1360 on_prompt_for_new_path: Option<PromptForNewPath>,
1361 on_prompt_for_open_path: Option<PromptForOpenPath>,
1362 terminal_provider: Option<Box<dyn TerminalProvider>>,
1363 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1364 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1365 _items_serializer: Task<Result<()>>,
1366 session_id: Option<String>,
1367 scheduled_tasks: Vec<Task<()>>,
1368 last_open_dock_positions: Vec<DockPosition>,
1369 removing: bool,
1370 open_in_dev_container: bool,
1371 _dev_container_task: Option<Task<Result<()>>>,
1372 _panels_task: Option<Task<Result<()>>>,
1373 sidebar_focus_handle: Option<FocusHandle>,
1374 multi_workspace: Option<WeakEntity<MultiWorkspace>>,
1375}
1376
1377impl EventEmitter<Event> for Workspace {}
1378
1379#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1380pub struct ViewId {
1381 pub creator: CollaboratorId,
1382 pub id: u64,
1383}
1384
1385pub struct FollowerState {
1386 center_pane: Entity<Pane>,
1387 dock_pane: Option<Entity<Pane>>,
1388 active_view_id: Option<ViewId>,
1389 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1390}
1391
1392struct FollowerView {
1393 view: Box<dyn FollowableItemHandle>,
1394 location: Option<proto::PanelId>,
1395}
1396
1397#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1398pub enum OpenMode {
1399 /// Open the workspace in a new window.
1400 NewWindow,
1401 /// Add to the window's multi workspace without activating it (used during deserialization).
1402 Add,
1403 /// Add to the window's multi workspace and activate it.
1404 #[default]
1405 Activate,
1406}
1407
1408impl Workspace {
1409 pub fn new(
1410 workspace_id: Option<WorkspaceId>,
1411 project: Entity<Project>,
1412 app_state: Arc<AppState>,
1413 window: &mut Window,
1414 cx: &mut Context<Self>,
1415 ) -> Self {
1416 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1417 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1418 if let TrustedWorktreesEvent::Trusted(..) = e {
1419 // Do not persist auto trusted worktrees
1420 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1421 worktrees_store.update(cx, |worktrees_store, cx| {
1422 worktrees_store.schedule_serialization(
1423 cx,
1424 |new_trusted_worktrees, cx| {
1425 let timeout =
1426 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1427 let db = WorkspaceDb::global(cx);
1428 cx.background_spawn(async move {
1429 timeout.await;
1430 db.save_trusted_worktrees(new_trusted_worktrees)
1431 .await
1432 .log_err();
1433 })
1434 },
1435 )
1436 });
1437 }
1438 }
1439 })
1440 .detach();
1441
1442 cx.observe_global::<SettingsStore>(|_, cx| {
1443 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1444 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1445 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1446 trusted_worktrees.auto_trust_all(cx);
1447 })
1448 }
1449 }
1450 })
1451 .detach();
1452 }
1453
1454 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1455 match event {
1456 project::Event::RemoteIdChanged(_) => {
1457 this.update_window_title(window, cx);
1458 }
1459
1460 project::Event::CollaboratorLeft(peer_id) => {
1461 this.collaborator_left(*peer_id, window, cx);
1462 }
1463
1464 &project::Event::WorktreeRemoved(_) => {
1465 this.update_window_title(window, cx);
1466 this.serialize_workspace(window, cx);
1467 this.update_history(cx);
1468 }
1469
1470 &project::Event::WorktreeAdded(id) => {
1471 this.update_window_title(window, cx);
1472 if this
1473 .project()
1474 .read(cx)
1475 .worktree_for_id(id, cx)
1476 .is_some_and(|wt| wt.read(cx).is_visible())
1477 {
1478 this.serialize_workspace(window, cx);
1479 this.update_history(cx);
1480 }
1481 }
1482 project::Event::WorktreeUpdatedEntries(..) => {
1483 this.update_window_title(window, cx);
1484 this.serialize_workspace(window, cx);
1485 }
1486
1487 project::Event::DisconnectedFromHost => {
1488 this.update_window_edited(window, cx);
1489 let leaders_to_unfollow =
1490 this.follower_states.keys().copied().collect::<Vec<_>>();
1491 for leader_id in leaders_to_unfollow {
1492 this.unfollow(leader_id, window, cx);
1493 }
1494 }
1495
1496 project::Event::DisconnectedFromRemote {
1497 server_not_running: _,
1498 } => {
1499 this.update_window_edited(window, cx);
1500 }
1501
1502 project::Event::Closed => {
1503 window.remove_window();
1504 }
1505
1506 project::Event::DeletedEntry(_, entry_id) => {
1507 for pane in this.panes.iter() {
1508 pane.update(cx, |pane, cx| {
1509 pane.handle_deleted_project_item(*entry_id, window, cx)
1510 });
1511 }
1512 }
1513
1514 project::Event::Toast {
1515 notification_id,
1516 message,
1517 link,
1518 } => this.show_notification(
1519 NotificationId::named(notification_id.clone()),
1520 cx,
1521 |cx| {
1522 let mut notification = MessageNotification::new(message.clone(), cx);
1523 if let Some(link) = link {
1524 notification = notification
1525 .more_info_message(link.label)
1526 .more_info_url(link.url);
1527 }
1528
1529 cx.new(|_| notification)
1530 },
1531 ),
1532
1533 project::Event::HideToast { notification_id } => {
1534 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1535 }
1536
1537 project::Event::LanguageServerPrompt(request) => {
1538 struct LanguageServerPrompt;
1539
1540 this.show_notification(
1541 NotificationId::composite::<LanguageServerPrompt>(request.id),
1542 cx,
1543 |cx| {
1544 cx.new(|cx| {
1545 notifications::LanguageServerPrompt::new(request.clone(), cx)
1546 })
1547 },
1548 );
1549 }
1550
1551 project::Event::AgentLocationChanged => {
1552 this.handle_agent_location_changed(window, cx)
1553 }
1554
1555 _ => {}
1556 }
1557 cx.notify()
1558 })
1559 .detach();
1560
1561 cx.subscribe_in(
1562 &project.read(cx).breakpoint_store(),
1563 window,
1564 |workspace, _, event, window, cx| match event {
1565 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1566 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1567 workspace.serialize_workspace(window, cx);
1568 }
1569 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1570 },
1571 )
1572 .detach();
1573 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1574 cx.subscribe_in(
1575 &toolchain_store,
1576 window,
1577 |workspace, _, event, window, cx| match event {
1578 ToolchainStoreEvent::CustomToolchainsModified => {
1579 workspace.serialize_workspace(window, cx);
1580 }
1581 _ => {}
1582 },
1583 )
1584 .detach();
1585 }
1586
1587 cx.on_focus_lost(window, |this, window, cx| {
1588 let focus_handle = this.focus_handle(cx);
1589 window.focus(&focus_handle, cx);
1590 })
1591 .detach();
1592
1593 let weak_handle = cx.entity().downgrade();
1594 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1595
1596 let center_pane = cx.new(|cx| {
1597 let mut center_pane = Pane::new(
1598 weak_handle.clone(),
1599 project.clone(),
1600 pane_history_timestamp.clone(),
1601 None,
1602 NewFile.boxed_clone(),
1603 true,
1604 window,
1605 cx,
1606 );
1607 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1608 center_pane.set_should_display_welcome_page(true);
1609 center_pane
1610 });
1611 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1612 .detach();
1613
1614 window.focus(¢er_pane.focus_handle(cx), cx);
1615
1616 cx.emit(Event::PaneAdded(center_pane.clone()));
1617
1618 let any_window_handle = window.window_handle();
1619 app_state.workspace_store.update(cx, |store, _| {
1620 store
1621 .workspaces
1622 .insert((any_window_handle, weak_handle.clone()));
1623 });
1624
1625 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1626 let mut connection_status = app_state.client.status();
1627 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1628 current_user.next().await;
1629 connection_status.next().await;
1630 let mut stream =
1631 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1632
1633 while stream.recv().await.is_some() {
1634 this.update(cx, |_, cx| cx.notify())?;
1635 }
1636 anyhow::Ok(())
1637 });
1638
1639 // All leader updates are enqueued and then processed in a single task, so
1640 // that each asynchronous operation can be run in order.
1641 let (leader_updates_tx, mut leader_updates_rx) =
1642 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1643 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1644 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1645 Self::process_leader_update(&this, leader_id, update, cx)
1646 .await
1647 .log_err();
1648 }
1649
1650 Ok(())
1651 });
1652
1653 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1654 let modal_layer = cx.new(|_| ModalLayer::new());
1655 let toast_layer = cx.new(|_| ToastLayer::new());
1656 cx.subscribe(
1657 &modal_layer,
1658 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1659 cx.emit(Event::ModalOpened);
1660 },
1661 )
1662 .detach();
1663
1664 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1665 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1666 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1667 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1668 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1669 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1670 let multi_workspace = window
1671 .root::<MultiWorkspace>()
1672 .flatten()
1673 .map(|mw| mw.downgrade());
1674 let status_bar = cx.new(|cx| {
1675 let mut status_bar =
1676 StatusBar::new(¢er_pane.clone(), multi_workspace.clone(), window, cx);
1677 status_bar.add_left_item(left_dock_buttons, window, cx);
1678 status_bar.add_right_item(right_dock_buttons, window, cx);
1679 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1680 status_bar
1681 });
1682
1683 let session_id = app_state.session.read(cx).id().to_owned();
1684
1685 let mut active_call = None;
1686 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1687 let subscriptions =
1688 vec![
1689 call.0
1690 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1691 ];
1692 active_call = Some((call, subscriptions));
1693 }
1694
1695 let (serializable_items_tx, serializable_items_rx) =
1696 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1697 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1698 Self::serialize_items(&this, serializable_items_rx, cx).await
1699 });
1700
1701 let subscriptions = vec![
1702 cx.observe_window_activation(window, Self::on_window_activation_changed),
1703 cx.observe_window_bounds(window, move |this, window, cx| {
1704 if this.bounds_save_task_queued.is_some() {
1705 return;
1706 }
1707 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1708 cx.background_executor()
1709 .timer(Duration::from_millis(100))
1710 .await;
1711 this.update_in(cx, |this, window, cx| {
1712 this.save_window_bounds(window, cx).detach();
1713 this.bounds_save_task_queued.take();
1714 })
1715 .ok();
1716 }));
1717 cx.notify();
1718 }),
1719 cx.observe_window_appearance(window, |_, window, cx| {
1720 let window_appearance = window.appearance();
1721
1722 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1723
1724 theme_settings::reload_theme(cx);
1725 theme_settings::reload_icon_theme(cx);
1726 }),
1727 cx.on_release({
1728 let weak_handle = weak_handle.clone();
1729 move |this, cx| {
1730 this.app_state.workspace_store.update(cx, move |store, _| {
1731 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1732 })
1733 }
1734 }),
1735 ];
1736
1737 cx.defer_in(window, move |this, window, cx| {
1738 this.update_window_title(window, cx);
1739 this.show_initial_notifications(cx);
1740 });
1741
1742 let mut center = PaneGroup::new(center_pane.clone());
1743 center.set_is_center(true);
1744 center.mark_positions(cx);
1745
1746 Workspace {
1747 weak_self: weak_handle.clone(),
1748 zoomed: None,
1749 zoomed_position: None,
1750 previous_dock_drag_coordinates: None,
1751 center,
1752 panes: vec![center_pane.clone()],
1753 panes_by_item: Default::default(),
1754 active_pane: center_pane.clone(),
1755 last_active_center_pane: Some(center_pane.downgrade()),
1756 last_active_view_id: None,
1757 status_bar,
1758 modal_layer,
1759 toast_layer,
1760 titlebar_item: None,
1761 active_worktree_override: None,
1762 notifications: Notifications::default(),
1763 suppressed_notifications: HashSet::default(),
1764 left_dock,
1765 bottom_dock,
1766 right_dock,
1767 _panels_task: None,
1768 project: project.clone(),
1769 follower_states: Default::default(),
1770 last_leaders_by_pane: Default::default(),
1771 dispatching_keystrokes: Default::default(),
1772 window_edited: false,
1773 last_window_title: None,
1774 dirty_items: Default::default(),
1775 active_call,
1776 database_id: workspace_id,
1777 app_state,
1778 _observe_current_user,
1779 _apply_leader_updates,
1780 _schedule_serialize_workspace: None,
1781 _serialize_workspace_task: None,
1782 _schedule_serialize_ssh_paths: None,
1783 leader_updates_tx,
1784 _subscriptions: subscriptions,
1785 pane_history_timestamp,
1786 workspace_actions: Default::default(),
1787 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1788 bounds: Default::default(),
1789 centered_layout: false,
1790 bounds_save_task_queued: None,
1791 on_prompt_for_new_path: None,
1792 on_prompt_for_open_path: None,
1793 terminal_provider: None,
1794 debugger_provider: None,
1795 serializable_items_tx,
1796 _items_serializer,
1797 session_id: Some(session_id),
1798
1799 scheduled_tasks: Vec::new(),
1800 last_open_dock_positions: Vec::new(),
1801 removing: false,
1802 sidebar_focus_handle: None,
1803 multi_workspace,
1804 open_in_dev_container: false,
1805 _dev_container_task: None,
1806 }
1807 }
1808
1809 pub fn new_local(
1810 abs_paths: Vec<PathBuf>,
1811 app_state: Arc<AppState>,
1812 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1813 env: Option<HashMap<String, String>>,
1814 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1815 open_mode: OpenMode,
1816 cx: &mut App,
1817 ) -> Task<anyhow::Result<OpenResult>> {
1818 let project_handle = Project::local(
1819 app_state.client.clone(),
1820 app_state.node_runtime.clone(),
1821 app_state.user_store.clone(),
1822 app_state.languages.clone(),
1823 app_state.fs.clone(),
1824 env,
1825 Default::default(),
1826 cx,
1827 );
1828
1829 let db = WorkspaceDb::global(cx);
1830 let kvp = db::kvp::KeyValueStore::global(cx);
1831 cx.spawn(async move |cx| {
1832 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1833 for path in abs_paths.into_iter() {
1834 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1835 paths_to_open.push(canonical)
1836 } else {
1837 paths_to_open.push(path)
1838 }
1839 }
1840
1841 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1842
1843 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1844 paths_to_open = paths.ordered_paths().cloned().collect();
1845 if !paths.is_lexicographically_ordered() {
1846 project_handle.update(cx, |project, cx| {
1847 project.set_worktrees_reordered(true, cx);
1848 });
1849 }
1850 }
1851
1852 // Get project paths for all of the abs_paths
1853 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1854 Vec::with_capacity(paths_to_open.len());
1855
1856 for path in paths_to_open.into_iter() {
1857 if let Some((_, project_entry)) = cx
1858 .update(|cx| {
1859 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1860 })
1861 .await
1862 .log_err()
1863 {
1864 project_paths.push((path, Some(project_entry)));
1865 } else {
1866 project_paths.push((path, None));
1867 }
1868 }
1869
1870 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1871 serialized_workspace.id
1872 } else {
1873 db.next_id().await.unwrap_or_else(|_| Default::default())
1874 };
1875
1876 let toolchains = db.toolchains(workspace_id).await?;
1877
1878 for (toolchain, worktree_path, path) in toolchains {
1879 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1880 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1881 this.find_worktree(&worktree_path, cx)
1882 .and_then(|(worktree, rel_path)| {
1883 if rel_path.is_empty() {
1884 Some(worktree.read(cx).id())
1885 } else {
1886 None
1887 }
1888 })
1889 }) else {
1890 // We did not find a worktree with a given path, but that's whatever.
1891 continue;
1892 };
1893 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1894 continue;
1895 }
1896
1897 project_handle
1898 .update(cx, |this, cx| {
1899 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1900 })
1901 .await;
1902 }
1903 if let Some(workspace) = serialized_workspace.as_ref() {
1904 project_handle.update(cx, |this, cx| {
1905 for (scope, toolchains) in &workspace.user_toolchains {
1906 for toolchain in toolchains {
1907 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1908 }
1909 }
1910 });
1911 }
1912
1913 let window_to_replace = match open_mode {
1914 OpenMode::NewWindow => None,
1915 _ => requesting_window,
1916 };
1917
1918 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1919 if let Some(window) = window_to_replace {
1920 let centered_layout = serialized_workspace
1921 .as_ref()
1922 .map(|w| w.centered_layout)
1923 .unwrap_or(false);
1924
1925 let workspace = window.update(cx, |multi_workspace, window, cx| {
1926 let workspace = cx.new(|cx| {
1927 let mut workspace = Workspace::new(
1928 Some(workspace_id),
1929 project_handle.clone(),
1930 app_state.clone(),
1931 window,
1932 cx,
1933 );
1934
1935 workspace.centered_layout = centered_layout;
1936
1937 // Call init callback to add items before window renders
1938 if let Some(init) = init {
1939 init(&mut workspace, window, cx);
1940 }
1941
1942 workspace
1943 });
1944 match open_mode {
1945 OpenMode::Activate => {
1946 multi_workspace.activate(workspace.clone(), window, cx);
1947 }
1948 OpenMode::Add => {
1949 multi_workspace.add(workspace.clone(), &*window, cx);
1950 }
1951 OpenMode::NewWindow => {
1952 unreachable!()
1953 }
1954 }
1955 workspace
1956 })?;
1957 (window, workspace)
1958 } else {
1959 let window_bounds_override = window_bounds_env_override();
1960
1961 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1962 (Some(WindowBounds::Windowed(bounds)), None)
1963 } else if let Some(workspace) = serialized_workspace.as_ref()
1964 && let Some(display) = workspace.display
1965 && let Some(bounds) = workspace.window_bounds.as_ref()
1966 {
1967 // Reopening an existing workspace - restore its saved bounds
1968 (Some(bounds.0), Some(display))
1969 } else if let Some((display, bounds)) =
1970 persistence::read_default_window_bounds(&kvp)
1971 {
1972 // New or empty workspace - use the last known window bounds
1973 (Some(bounds), Some(display))
1974 } else {
1975 // New window - let GPUI's default_bounds() handle cascading
1976 (None, None)
1977 };
1978
1979 // Use the serialized workspace to construct the new window
1980 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1981 options.window_bounds = window_bounds;
1982 let centered_layout = serialized_workspace
1983 .as_ref()
1984 .map(|w| w.centered_layout)
1985 .unwrap_or(false);
1986 let window = cx.open_window(options, {
1987 let app_state = app_state.clone();
1988 let project_handle = project_handle.clone();
1989 move |window, cx| {
1990 let workspace = cx.new(|cx| {
1991 let mut workspace = Workspace::new(
1992 Some(workspace_id),
1993 project_handle,
1994 app_state,
1995 window,
1996 cx,
1997 );
1998 workspace.centered_layout = centered_layout;
1999
2000 // Call init callback to add items before window renders
2001 if let Some(init) = init {
2002 init(&mut workspace, window, cx);
2003 }
2004
2005 workspace
2006 });
2007 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
2008 }
2009 })?;
2010 let workspace =
2011 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
2012 multi_workspace.workspace().clone()
2013 })?;
2014 (window, workspace)
2015 };
2016
2017 notify_if_database_failed(window, cx);
2018 // Check if this is an empty workspace (no paths to open)
2019 // An empty workspace is one where project_paths is empty
2020 let is_empty_workspace = project_paths.is_empty();
2021 // Check if serialized workspace has paths before it's moved
2022 let serialized_workspace_has_paths = serialized_workspace
2023 .as_ref()
2024 .map(|ws| !ws.paths.is_empty())
2025 .unwrap_or(false);
2026
2027 let opened_items = window
2028 .update(cx, |_, window, cx| {
2029 workspace.update(cx, |_workspace: &mut Workspace, cx| {
2030 open_items(serialized_workspace, project_paths, window, cx)
2031 })
2032 })?
2033 .await
2034 .unwrap_or_default();
2035
2036 // Restore default dock state for empty workspaces
2037 // Only restore if:
2038 // 1. This is an empty workspace (no paths), AND
2039 // 2. The serialized workspace either doesn't exist or has no paths
2040 if is_empty_workspace && !serialized_workspace_has_paths {
2041 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
2042 window
2043 .update(cx, |_, window, cx| {
2044 workspace.update(cx, |workspace, cx| {
2045 for (dock, serialized_dock) in [
2046 (&workspace.right_dock, &default_docks.right),
2047 (&workspace.left_dock, &default_docks.left),
2048 (&workspace.bottom_dock, &default_docks.bottom),
2049 ] {
2050 dock.update(cx, |dock, cx| {
2051 dock.serialized_dock = Some(serialized_dock.clone());
2052 dock.restore_state(window, cx);
2053 });
2054 }
2055 cx.notify();
2056 });
2057 })
2058 .log_err();
2059 }
2060 }
2061
2062 window
2063 .update(cx, |_, _window, cx| {
2064 workspace.update(cx, |this: &mut Workspace, cx| {
2065 this.update_history(cx);
2066 });
2067 })
2068 .log_err();
2069 Ok(OpenResult {
2070 window,
2071 workspace,
2072 opened_items,
2073 })
2074 })
2075 }
2076
2077 pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
2078 self.project.read(cx).project_group_key(cx)
2079 }
2080
2081 pub fn weak_handle(&self) -> WeakEntity<Self> {
2082 self.weak_self.clone()
2083 }
2084
2085 pub fn left_dock(&self) -> &Entity<Dock> {
2086 &self.left_dock
2087 }
2088
2089 pub fn bottom_dock(&self) -> &Entity<Dock> {
2090 &self.bottom_dock
2091 }
2092
2093 pub fn set_bottom_dock_layout(
2094 &mut self,
2095 layout: BottomDockLayout,
2096 window: &mut Window,
2097 cx: &mut Context<Self>,
2098 ) {
2099 let fs = self.project().read(cx).fs();
2100 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2101 content.workspace.bottom_dock_layout = Some(layout);
2102 });
2103
2104 cx.notify();
2105 self.serialize_workspace(window, cx);
2106 }
2107
2108 pub fn right_dock(&self) -> &Entity<Dock> {
2109 &self.right_dock
2110 }
2111
2112 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2113 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2114 }
2115
2116 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2117 let left_dock = self.left_dock.read(cx);
2118 let left_visible = left_dock.is_open();
2119 let left_active_panel = left_dock
2120 .active_panel()
2121 .map(|panel| panel.persistent_name().to_string());
2122 // `zoomed_position` is kept in sync with individual panel zoom state
2123 // by the dock code in `Dock::new` and `Dock::add_panel`.
2124 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2125
2126 let right_dock = self.right_dock.read(cx);
2127 let right_visible = right_dock.is_open();
2128 let right_active_panel = right_dock
2129 .active_panel()
2130 .map(|panel| panel.persistent_name().to_string());
2131 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2132
2133 let bottom_dock = self.bottom_dock.read(cx);
2134 let bottom_visible = bottom_dock.is_open();
2135 let bottom_active_panel = bottom_dock
2136 .active_panel()
2137 .map(|panel| panel.persistent_name().to_string());
2138 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2139
2140 DockStructure {
2141 left: DockData {
2142 visible: left_visible,
2143 active_panel: left_active_panel,
2144 zoom: left_dock_zoom,
2145 },
2146 right: DockData {
2147 visible: right_visible,
2148 active_panel: right_active_panel,
2149 zoom: right_dock_zoom,
2150 },
2151 bottom: DockData {
2152 visible: bottom_visible,
2153 active_panel: bottom_active_panel,
2154 zoom: bottom_dock_zoom,
2155 },
2156 }
2157 }
2158
2159 pub fn set_dock_structure(
2160 &self,
2161 docks: DockStructure,
2162 window: &mut Window,
2163 cx: &mut Context<Self>,
2164 ) {
2165 for (dock, data) in [
2166 (&self.left_dock, docks.left),
2167 (&self.bottom_dock, docks.bottom),
2168 (&self.right_dock, docks.right),
2169 ] {
2170 dock.update(cx, |dock, cx| {
2171 dock.serialized_dock = Some(data);
2172 dock.restore_state(window, cx);
2173 });
2174 }
2175 }
2176
2177 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2178 self.items(cx)
2179 .filter_map(|item| {
2180 let project_path = item.project_path(cx)?;
2181 self.project.read(cx).absolute_path(&project_path, cx)
2182 })
2183 .collect()
2184 }
2185
2186 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2187 match position {
2188 DockPosition::Left => &self.left_dock,
2189 DockPosition::Bottom => &self.bottom_dock,
2190 DockPosition::Right => &self.right_dock,
2191 }
2192 }
2193
2194 pub fn agent_panel_position(&self, cx: &App) -> Option<DockPosition> {
2195 self.all_docks().into_iter().find_map(|dock| {
2196 let dock = dock.read(cx);
2197 dock.has_agent_panel(cx).then_some(dock.position())
2198 })
2199 }
2200
2201 pub fn panel_size_state<T: Panel>(&self, cx: &App) -> Option<dock::PanelSizeState> {
2202 self.all_docks().into_iter().find_map(|dock| {
2203 let dock = dock.read(cx);
2204 let panel = dock.panel::<T>()?;
2205 dock.stored_panel_size_state(&panel)
2206 })
2207 }
2208
2209 pub fn persisted_panel_size_state(
2210 &self,
2211 panel_key: &'static str,
2212 cx: &App,
2213 ) -> Option<dock::PanelSizeState> {
2214 dock::Dock::load_persisted_size_state(self, panel_key, cx)
2215 }
2216
2217 pub fn persist_panel_size_state(
2218 &self,
2219 panel_key: &str,
2220 size_state: dock::PanelSizeState,
2221 cx: &mut App,
2222 ) {
2223 let Some(workspace_id) = self
2224 .database_id()
2225 .map(|id| i64::from(id).to_string())
2226 .or(self.session_id())
2227 else {
2228 return;
2229 };
2230
2231 let kvp = db::kvp::KeyValueStore::global(cx);
2232 let panel_key = panel_key.to_string();
2233 cx.background_spawn(async move {
2234 let scope = kvp.scoped(dock::PANEL_SIZE_STATE_KEY);
2235 scope
2236 .write(
2237 format!("{workspace_id}:{panel_key}"),
2238 serde_json::to_string(&size_state)?,
2239 )
2240 .await
2241 })
2242 .detach_and_log_err(cx);
2243 }
2244
2245 pub fn set_panel_size_state<T: Panel>(
2246 &mut self,
2247 size_state: dock::PanelSizeState,
2248 window: &mut Window,
2249 cx: &mut Context<Self>,
2250 ) -> bool {
2251 let Some(panel) = self.panel::<T>(cx) else {
2252 return false;
2253 };
2254
2255 let dock = self.dock_at_position(panel.position(window, cx));
2256 let did_set = dock.update(cx, |dock, cx| {
2257 dock.set_panel_size_state(&panel, size_state, cx)
2258 });
2259
2260 if did_set {
2261 self.persist_panel_size_state(T::panel_key(), size_state, cx);
2262 }
2263
2264 did_set
2265 }
2266
2267 pub fn toggle_dock_panel_flexible_size(
2268 &self,
2269 dock: &Entity<Dock>,
2270 panel: &dyn PanelHandle,
2271 window: &mut Window,
2272 cx: &mut App,
2273 ) {
2274 let position = dock.read(cx).position();
2275 let current_size = self.dock_size(&dock.read(cx), window, cx);
2276 let current_flex =
2277 current_size.and_then(|size| self.dock_flex_for_size(position, size, window, cx));
2278 dock.update(cx, |dock, cx| {
2279 dock.toggle_panel_flexible_size(panel, current_size, current_flex, window, cx);
2280 });
2281 }
2282
2283 fn dock_size(&self, dock: &Dock, window: &Window, cx: &App) -> Option<Pixels> {
2284 let panel = dock.active_panel()?;
2285 let size_state = dock
2286 .stored_panel_size_state(panel.as_ref())
2287 .unwrap_or_default();
2288 let position = dock.position();
2289
2290 let use_flex = panel.has_flexible_size(window, cx);
2291
2292 if position.axis() == Axis::Horizontal
2293 && use_flex
2294 && let Some(flex) = size_state.flex.or_else(|| self.default_dock_flex(position))
2295 {
2296 let workspace_width = self.bounds.size.width;
2297 if workspace_width <= Pixels::ZERO {
2298 return None;
2299 }
2300 let flex = flex.max(0.001);
2301 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2302 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2303 // Both docks are flex items sharing the full workspace width.
2304 let total_flex = flex + 1.0 + opposite_flex;
2305 return Some((flex / total_flex * workspace_width).max(RESIZE_HANDLE_SIZE));
2306 } else {
2307 // Opposite dock is fixed-width; flex items share (W - fixed).
2308 let opposite_fixed = opposite
2309 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2310 .unwrap_or_default();
2311 let available = (workspace_width - opposite_fixed).max(RESIZE_HANDLE_SIZE);
2312 return Some((flex / (flex + 1.0) * available).max(RESIZE_HANDLE_SIZE));
2313 }
2314 }
2315
2316 Some(
2317 size_state
2318 .size
2319 .unwrap_or_else(|| panel.default_size(window, cx)),
2320 )
2321 }
2322
2323 pub fn dock_flex_for_size(
2324 &self,
2325 position: DockPosition,
2326 size: Pixels,
2327 window: &Window,
2328 cx: &App,
2329 ) -> Option<f32> {
2330 if position.axis() != Axis::Horizontal {
2331 return None;
2332 }
2333
2334 let workspace_width = self.bounds.size.width;
2335 if workspace_width <= Pixels::ZERO {
2336 return None;
2337 }
2338
2339 let opposite = self.opposite_dock_panel_and_size_state(position, window, cx);
2340 if let Some(opposite_flex) = opposite.as_ref().and_then(|(_, s)| s.flex) {
2341 let size = size.clamp(px(0.), workspace_width - px(1.));
2342 Some((size * (1.0 + opposite_flex) / (workspace_width - size)).max(0.0))
2343 } else {
2344 let opposite_width = opposite
2345 .map(|(panel, s)| s.size.unwrap_or_else(|| panel.default_size(window, cx)))
2346 .unwrap_or_default();
2347 let available = (workspace_width - opposite_width).max(RESIZE_HANDLE_SIZE);
2348 let remaining = (available - size).max(px(1.));
2349 Some((size / remaining).max(0.0))
2350 }
2351 }
2352
2353 fn opposite_dock_panel_and_size_state(
2354 &self,
2355 position: DockPosition,
2356 window: &Window,
2357 cx: &App,
2358 ) -> Option<(Arc<dyn PanelHandle>, PanelSizeState)> {
2359 let opposite_position = match position {
2360 DockPosition::Left => DockPosition::Right,
2361 DockPosition::Right => DockPosition::Left,
2362 DockPosition::Bottom => return None,
2363 };
2364
2365 let opposite_dock = self.dock_at_position(opposite_position).read(cx);
2366 let panel = opposite_dock.visible_panel()?;
2367 let mut size_state = opposite_dock
2368 .stored_panel_size_state(panel.as_ref())
2369 .unwrap_or_default();
2370 if size_state.flex.is_none() && panel.has_flexible_size(window, cx) {
2371 size_state.flex = self.default_dock_flex(opposite_position);
2372 }
2373 Some((panel.clone(), size_state))
2374 }
2375
2376 pub fn default_dock_flex(&self, position: DockPosition) -> Option<f32> {
2377 if position.axis() != Axis::Horizontal {
2378 return None;
2379 }
2380
2381 let pane = self.last_active_center_pane.clone()?.upgrade()?;
2382 Some(self.center.width_fraction_for_pane(&pane).unwrap_or(1.0))
2383 }
2384
2385 pub fn is_edited(&self) -> bool {
2386 self.window_edited
2387 }
2388
2389 pub fn add_panel<T: Panel>(
2390 &mut self,
2391 panel: Entity<T>,
2392 window: &mut Window,
2393 cx: &mut Context<Self>,
2394 ) {
2395 let focus_handle = panel.panel_focus_handle(cx);
2396 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2397 .detach();
2398
2399 let dock_position = panel.position(window, cx);
2400 let dock = self.dock_at_position(dock_position);
2401 let any_panel = panel.to_any();
2402 let persisted_size_state =
2403 self.persisted_panel_size_state(T::panel_key(), cx)
2404 .or_else(|| {
2405 load_legacy_panel_size(T::panel_key(), dock_position, self, cx).map(|size| {
2406 let state = dock::PanelSizeState {
2407 size: Some(size),
2408 flex: None,
2409 };
2410 self.persist_panel_size_state(T::panel_key(), state, cx);
2411 state
2412 })
2413 });
2414
2415 dock.update(cx, |dock, cx| {
2416 let index = dock.add_panel(panel.clone(), self.weak_self.clone(), window, cx);
2417 if let Some(size_state) = persisted_size_state {
2418 dock.set_panel_size_state(&panel, size_state, cx);
2419 }
2420 index
2421 });
2422
2423 cx.emit(Event::PanelAdded(any_panel));
2424 }
2425
2426 pub fn remove_panel<T: Panel>(
2427 &mut self,
2428 panel: &Entity<T>,
2429 window: &mut Window,
2430 cx: &mut Context<Self>,
2431 ) {
2432 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2433 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2434 }
2435 }
2436
2437 pub fn status_bar(&self) -> &Entity<StatusBar> {
2438 &self.status_bar
2439 }
2440
2441 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2442 self.sidebar_focus_handle = handle;
2443 }
2444
2445 pub fn status_bar_visible(&self, cx: &App) -> bool {
2446 StatusBarSettings::get_global(cx).show
2447 }
2448
2449 pub fn multi_workspace(&self) -> Option<&WeakEntity<MultiWorkspace>> {
2450 self.multi_workspace.as_ref()
2451 }
2452
2453 pub fn set_multi_workspace(
2454 &mut self,
2455 multi_workspace: WeakEntity<MultiWorkspace>,
2456 cx: &mut App,
2457 ) {
2458 self.status_bar.update(cx, |status_bar, cx| {
2459 status_bar.set_multi_workspace(multi_workspace.clone(), cx);
2460 });
2461 self.multi_workspace = Some(multi_workspace);
2462 }
2463
2464 pub fn app_state(&self) -> &Arc<AppState> {
2465 &self.app_state
2466 }
2467
2468 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2469 self._panels_task = Some(task);
2470 }
2471
2472 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2473 self._panels_task.take()
2474 }
2475
2476 pub fn user_store(&self) -> &Entity<UserStore> {
2477 &self.app_state.user_store
2478 }
2479
2480 pub fn project(&self) -> &Entity<Project> {
2481 &self.project
2482 }
2483
2484 pub fn path_style(&self, cx: &App) -> PathStyle {
2485 self.project.read(cx).path_style(cx)
2486 }
2487
2488 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2489 let mut history: HashMap<EntityId, usize> = HashMap::default();
2490
2491 for pane_handle in &self.panes {
2492 let pane = pane_handle.read(cx);
2493
2494 for entry in pane.activation_history() {
2495 history.insert(
2496 entry.entity_id,
2497 history
2498 .get(&entry.entity_id)
2499 .cloned()
2500 .unwrap_or(0)
2501 .max(entry.timestamp),
2502 );
2503 }
2504 }
2505
2506 history
2507 }
2508
2509 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2510 let mut recent_item: Option<Entity<T>> = None;
2511 let mut recent_timestamp = 0;
2512 for pane_handle in &self.panes {
2513 let pane = pane_handle.read(cx);
2514 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2515 pane.items().map(|item| (item.item_id(), item)).collect();
2516 for entry in pane.activation_history() {
2517 if entry.timestamp > recent_timestamp
2518 && let Some(&item) = item_map.get(&entry.entity_id)
2519 && let Some(typed_item) = item.act_as::<T>(cx)
2520 {
2521 recent_timestamp = entry.timestamp;
2522 recent_item = Some(typed_item);
2523 }
2524 }
2525 }
2526 recent_item
2527 }
2528
2529 pub fn recent_navigation_history_iter(
2530 &self,
2531 cx: &App,
2532 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2533 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2534 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2535
2536 for pane in &self.panes {
2537 let pane = pane.read(cx);
2538
2539 pane.nav_history()
2540 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2541 if let Some(fs_path) = &fs_path {
2542 abs_paths_opened
2543 .entry(fs_path.clone())
2544 .or_default()
2545 .insert(project_path.clone());
2546 }
2547 let timestamp = entry.timestamp;
2548 match history.entry(project_path) {
2549 hash_map::Entry::Occupied(mut entry) => {
2550 let (_, old_timestamp) = entry.get();
2551 if ×tamp > old_timestamp {
2552 entry.insert((fs_path, timestamp));
2553 }
2554 }
2555 hash_map::Entry::Vacant(entry) => {
2556 entry.insert((fs_path, timestamp));
2557 }
2558 }
2559 });
2560
2561 if let Some(item) = pane.active_item()
2562 && let Some(project_path) = item.project_path(cx)
2563 {
2564 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2565
2566 if let Some(fs_path) = &fs_path {
2567 abs_paths_opened
2568 .entry(fs_path.clone())
2569 .or_default()
2570 .insert(project_path.clone());
2571 }
2572
2573 history.insert(project_path, (fs_path, std::usize::MAX));
2574 }
2575 }
2576
2577 history
2578 .into_iter()
2579 .sorted_by_key(|(_, (_, order))| *order)
2580 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2581 .rev()
2582 .filter(move |(history_path, abs_path)| {
2583 let latest_project_path_opened = abs_path
2584 .as_ref()
2585 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2586 .and_then(|project_paths| {
2587 project_paths
2588 .iter()
2589 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2590 });
2591
2592 latest_project_path_opened.is_none_or(|path| path == history_path)
2593 })
2594 }
2595
2596 pub fn recent_navigation_history(
2597 &self,
2598 limit: Option<usize>,
2599 cx: &App,
2600 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2601 self.recent_navigation_history_iter(cx)
2602 .take(limit.unwrap_or(usize::MAX))
2603 .collect()
2604 }
2605
2606 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2607 for pane in &self.panes {
2608 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2609 }
2610 }
2611
2612 fn navigate_history(
2613 &mut self,
2614 pane: WeakEntity<Pane>,
2615 mode: NavigationMode,
2616 window: &mut Window,
2617 cx: &mut Context<Workspace>,
2618 ) -> Task<Result<()>> {
2619 self.navigate_history_impl(
2620 pane,
2621 mode,
2622 window,
2623 &mut |history, cx| history.pop(mode, cx),
2624 cx,
2625 )
2626 }
2627
2628 fn navigate_tag_history(
2629 &mut self,
2630 pane: WeakEntity<Pane>,
2631 mode: TagNavigationMode,
2632 window: &mut Window,
2633 cx: &mut Context<Workspace>,
2634 ) -> Task<Result<()>> {
2635 self.navigate_history_impl(
2636 pane,
2637 NavigationMode::Normal,
2638 window,
2639 &mut |history, _cx| history.pop_tag(mode),
2640 cx,
2641 )
2642 }
2643
2644 fn navigate_history_impl(
2645 &mut self,
2646 pane: WeakEntity<Pane>,
2647 mode: NavigationMode,
2648 window: &mut Window,
2649 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2650 cx: &mut Context<Workspace>,
2651 ) -> Task<Result<()>> {
2652 let to_load = if let Some(pane) = pane.upgrade() {
2653 pane.update(cx, |pane, cx| {
2654 window.focus(&pane.focus_handle(cx), cx);
2655 loop {
2656 // Retrieve the weak item handle from the history.
2657 let entry = cb(pane.nav_history_mut(), cx)?;
2658
2659 // If the item is still present in this pane, then activate it.
2660 if let Some(index) = entry
2661 .item
2662 .upgrade()
2663 .and_then(|v| pane.index_for_item(v.as_ref()))
2664 {
2665 let prev_active_item_index = pane.active_item_index();
2666 pane.nav_history_mut().set_mode(mode);
2667 pane.activate_item(index, true, true, window, cx);
2668 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2669
2670 let mut navigated = prev_active_item_index != pane.active_item_index();
2671 if let Some(data) = entry.data {
2672 navigated |= pane.active_item()?.navigate(data, window, cx);
2673 }
2674
2675 if navigated {
2676 break None;
2677 }
2678 } else {
2679 // If the item is no longer present in this pane, then retrieve its
2680 // path info in order to reopen it.
2681 break pane
2682 .nav_history()
2683 .path_for_item(entry.item.id())
2684 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2685 }
2686 }
2687 })
2688 } else {
2689 None
2690 };
2691
2692 if let Some((project_path, abs_path, entry)) = to_load {
2693 // If the item was no longer present, then load it again from its previous path, first try the local path
2694 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2695
2696 cx.spawn_in(window, async move |workspace, cx| {
2697 let open_by_project_path = open_by_project_path.await;
2698 let mut navigated = false;
2699 match open_by_project_path
2700 .with_context(|| format!("Navigating to {project_path:?}"))
2701 {
2702 Ok((project_entry_id, build_item)) => {
2703 let prev_active_item_id = pane.update(cx, |pane, _| {
2704 pane.nav_history_mut().set_mode(mode);
2705 pane.active_item().map(|p| p.item_id())
2706 })?;
2707
2708 pane.update_in(cx, |pane, window, cx| {
2709 let item = pane.open_item(
2710 project_entry_id,
2711 project_path,
2712 true,
2713 entry.is_preview,
2714 true,
2715 None,
2716 window, cx,
2717 build_item,
2718 );
2719 navigated |= Some(item.item_id()) != prev_active_item_id;
2720 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2721 if let Some(data) = entry.data {
2722 navigated |= item.navigate(data, window, cx);
2723 }
2724 })?;
2725 }
2726 Err(open_by_project_path_e) => {
2727 // Fall back to opening by abs path, in case an external file was opened and closed,
2728 // and its worktree is now dropped
2729 if let Some(abs_path) = abs_path {
2730 let prev_active_item_id = pane.update(cx, |pane, _| {
2731 pane.nav_history_mut().set_mode(mode);
2732 pane.active_item().map(|p| p.item_id())
2733 })?;
2734 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2735 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2736 })?;
2737 match open_by_abs_path
2738 .await
2739 .with_context(|| format!("Navigating to {abs_path:?}"))
2740 {
2741 Ok(item) => {
2742 pane.update_in(cx, |pane, window, cx| {
2743 navigated |= Some(item.item_id()) != prev_active_item_id;
2744 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2745 if let Some(data) = entry.data {
2746 navigated |= item.navigate(data, window, cx);
2747 }
2748 })?;
2749 }
2750 Err(open_by_abs_path_e) => {
2751 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2752 }
2753 }
2754 }
2755 }
2756 }
2757
2758 if !navigated {
2759 workspace
2760 .update_in(cx, |workspace, window, cx| {
2761 Self::navigate_history(workspace, pane, mode, window, cx)
2762 })?
2763 .await?;
2764 }
2765
2766 Ok(())
2767 })
2768 } else {
2769 Task::ready(Ok(()))
2770 }
2771 }
2772
2773 pub fn go_back(
2774 &mut self,
2775 pane: WeakEntity<Pane>,
2776 window: &mut Window,
2777 cx: &mut Context<Workspace>,
2778 ) -> Task<Result<()>> {
2779 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2780 }
2781
2782 pub fn go_forward(
2783 &mut self,
2784 pane: WeakEntity<Pane>,
2785 window: &mut Window,
2786 cx: &mut Context<Workspace>,
2787 ) -> Task<Result<()>> {
2788 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2789 }
2790
2791 pub fn reopen_closed_item(
2792 &mut self,
2793 window: &mut Window,
2794 cx: &mut Context<Workspace>,
2795 ) -> Task<Result<()>> {
2796 self.navigate_history(
2797 self.active_pane().downgrade(),
2798 NavigationMode::ReopeningClosedItem,
2799 window,
2800 cx,
2801 )
2802 }
2803
2804 pub fn client(&self) -> &Arc<Client> {
2805 &self.app_state.client
2806 }
2807
2808 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2809 self.titlebar_item = Some(item);
2810 cx.notify();
2811 }
2812
2813 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2814 self.on_prompt_for_new_path = Some(prompt)
2815 }
2816
2817 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2818 self.on_prompt_for_open_path = Some(prompt)
2819 }
2820
2821 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2822 self.terminal_provider = Some(Box::new(provider));
2823 }
2824
2825 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2826 self.debugger_provider = Some(Arc::new(provider));
2827 }
2828
2829 pub fn set_open_in_dev_container(&mut self, value: bool) {
2830 self.open_in_dev_container = value;
2831 }
2832
2833 pub fn open_in_dev_container(&self) -> bool {
2834 self.open_in_dev_container
2835 }
2836
2837 pub fn set_dev_container_task(&mut self, task: Task<Result<()>>) {
2838 self._dev_container_task = Some(task);
2839 }
2840
2841 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2842 self.debugger_provider.clone()
2843 }
2844
2845 pub fn prompt_for_open_path(
2846 &mut self,
2847 path_prompt_options: PathPromptOptions,
2848 lister: DirectoryLister,
2849 window: &mut Window,
2850 cx: &mut Context<Self>,
2851 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2852 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2853 let prompt = self.on_prompt_for_open_path.take().unwrap();
2854 let rx = prompt(self, lister, window, cx);
2855 self.on_prompt_for_open_path = Some(prompt);
2856 rx
2857 } else {
2858 let (tx, rx) = oneshot::channel();
2859 let abs_path = cx.prompt_for_paths(path_prompt_options);
2860
2861 cx.spawn_in(window, async move |workspace, cx| {
2862 let Ok(result) = abs_path.await else {
2863 return Ok(());
2864 };
2865
2866 match result {
2867 Ok(result) => {
2868 tx.send(result).ok();
2869 }
2870 Err(err) => {
2871 let rx = workspace.update_in(cx, |workspace, window, cx| {
2872 workspace.show_portal_error(err.to_string(), cx);
2873 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2874 let rx = prompt(workspace, lister, window, cx);
2875 workspace.on_prompt_for_open_path = Some(prompt);
2876 rx
2877 })?;
2878 if let Ok(path) = rx.await {
2879 tx.send(path).ok();
2880 }
2881 }
2882 };
2883 anyhow::Ok(())
2884 })
2885 .detach();
2886
2887 rx
2888 }
2889 }
2890
2891 pub fn prompt_for_new_path(
2892 &mut self,
2893 lister: DirectoryLister,
2894 suggested_name: Option<String>,
2895 window: &mut Window,
2896 cx: &mut Context<Self>,
2897 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2898 if self.project.read(cx).is_via_collab()
2899 || self.project.read(cx).is_via_remote_server()
2900 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2901 {
2902 let prompt = self.on_prompt_for_new_path.take().unwrap();
2903 let rx = prompt(self, lister, suggested_name, window, cx);
2904 self.on_prompt_for_new_path = Some(prompt);
2905 return rx;
2906 }
2907
2908 let (tx, rx) = oneshot::channel();
2909 cx.spawn_in(window, async move |workspace, cx| {
2910 let abs_path = workspace.update(cx, |workspace, cx| {
2911 let relative_to = workspace
2912 .most_recent_active_path(cx)
2913 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2914 .or_else(|| {
2915 let project = workspace.project.read(cx);
2916 project.visible_worktrees(cx).find_map(|worktree| {
2917 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2918 })
2919 })
2920 .or_else(std::env::home_dir)
2921 .unwrap_or_else(|| PathBuf::from(""));
2922 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2923 })?;
2924 let abs_path = match abs_path.await? {
2925 Ok(path) => path,
2926 Err(err) => {
2927 let rx = workspace.update_in(cx, |workspace, window, cx| {
2928 workspace.show_portal_error(err.to_string(), cx);
2929
2930 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2931 let rx = prompt(workspace, lister, suggested_name, window, cx);
2932 workspace.on_prompt_for_new_path = Some(prompt);
2933 rx
2934 })?;
2935 if let Ok(path) = rx.await {
2936 tx.send(path).ok();
2937 }
2938 return anyhow::Ok(());
2939 }
2940 };
2941
2942 tx.send(abs_path.map(|path| vec![path])).ok();
2943 anyhow::Ok(())
2944 })
2945 .detach();
2946
2947 rx
2948 }
2949
2950 pub fn titlebar_item(&self) -> Option<AnyView> {
2951 self.titlebar_item.clone()
2952 }
2953
2954 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2955 /// When set, git-related operations should use this worktree instead of deriving
2956 /// the active worktree from the focused file.
2957 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2958 self.active_worktree_override
2959 }
2960
2961 pub fn set_active_worktree_override(
2962 &mut self,
2963 worktree_id: Option<WorktreeId>,
2964 cx: &mut Context<Self>,
2965 ) {
2966 self.active_worktree_override = worktree_id;
2967 cx.notify();
2968 }
2969
2970 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2971 self.active_worktree_override = None;
2972 cx.notify();
2973 }
2974
2975 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2976 ///
2977 /// If the given workspace has a local project, then it will be passed
2978 /// to the callback. Otherwise, a new empty window will be created.
2979 pub fn with_local_workspace<T, F>(
2980 &mut self,
2981 window: &mut Window,
2982 cx: &mut Context<Self>,
2983 callback: F,
2984 ) -> Task<Result<T>>
2985 where
2986 T: 'static,
2987 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2988 {
2989 if self.project.read(cx).is_local() {
2990 Task::ready(Ok(callback(self, window, cx)))
2991 } else {
2992 let env = self.project.read(cx).cli_environment(cx);
2993 let task = Self::new_local(
2994 Vec::new(),
2995 self.app_state.clone(),
2996 None,
2997 env,
2998 None,
2999 OpenMode::Activate,
3000 cx,
3001 );
3002 cx.spawn_in(window, async move |_vh, cx| {
3003 let OpenResult {
3004 window: multi_workspace_window,
3005 ..
3006 } = task.await?;
3007 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3008 let workspace = multi_workspace.workspace().clone();
3009 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3010 })
3011 })
3012 }
3013 }
3014
3015 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
3016 ///
3017 /// If the given workspace has a local project, then it will be passed
3018 /// to the callback. Otherwise, a new empty window will be created.
3019 pub fn with_local_or_wsl_workspace<T, F>(
3020 &mut self,
3021 window: &mut Window,
3022 cx: &mut Context<Self>,
3023 callback: F,
3024 ) -> Task<Result<T>>
3025 where
3026 T: 'static,
3027 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
3028 {
3029 let project = self.project.read(cx);
3030 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
3031 Task::ready(Ok(callback(self, window, cx)))
3032 } else {
3033 let env = self.project.read(cx).cli_environment(cx);
3034 let task = Self::new_local(
3035 Vec::new(),
3036 self.app_state.clone(),
3037 None,
3038 env,
3039 None,
3040 OpenMode::Activate,
3041 cx,
3042 );
3043 cx.spawn_in(window, async move |_vh, cx| {
3044 let OpenResult {
3045 window: multi_workspace_window,
3046 ..
3047 } = task.await?;
3048 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
3049 let workspace = multi_workspace.workspace().clone();
3050 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
3051 })
3052 })
3053 }
3054 }
3055
3056 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3057 self.project.read(cx).worktrees(cx)
3058 }
3059
3060 pub fn visible_worktrees<'a>(
3061 &self,
3062 cx: &'a App,
3063 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
3064 self.project.read(cx).visible_worktrees(cx)
3065 }
3066
3067 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
3068 let futures = self
3069 .worktrees(cx)
3070 .filter_map(|worktree| worktree.read(cx).as_local())
3071 .map(|worktree| worktree.scan_complete())
3072 .collect::<Vec<_>>();
3073 async move {
3074 for future in futures {
3075 future.await;
3076 }
3077 }
3078 }
3079
3080 pub fn close_global(cx: &mut App) {
3081 cx.defer(|cx| {
3082 cx.windows().iter().find(|window| {
3083 window
3084 .update(cx, |_, window, _| {
3085 if window.is_window_active() {
3086 //This can only get called when the window's project connection has been lost
3087 //so we don't need to prompt the user for anything and instead just close the window
3088 window.remove_window();
3089 true
3090 } else {
3091 false
3092 }
3093 })
3094 .unwrap_or(false)
3095 });
3096 });
3097 }
3098
3099 pub fn move_focused_panel_to_next_position(
3100 &mut self,
3101 _: &MoveFocusedPanelToNextPosition,
3102 window: &mut Window,
3103 cx: &mut Context<Self>,
3104 ) {
3105 let docks = self.all_docks();
3106 let active_dock = docks
3107 .into_iter()
3108 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
3109
3110 if let Some(dock) = active_dock {
3111 dock.update(cx, |dock, cx| {
3112 let active_panel = dock
3113 .active_panel()
3114 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
3115
3116 if let Some(panel) = active_panel {
3117 panel.move_to_next_position(window, cx);
3118 }
3119 })
3120 }
3121 }
3122
3123 pub fn prepare_to_close(
3124 &mut self,
3125 close_intent: CloseIntent,
3126 window: &mut Window,
3127 cx: &mut Context<Self>,
3128 ) -> Task<Result<bool>> {
3129 let active_call = self.active_global_call();
3130
3131 cx.spawn_in(window, async move |this, cx| {
3132 this.update(cx, |this, _| {
3133 if close_intent == CloseIntent::CloseWindow {
3134 this.removing = true;
3135 }
3136 })?;
3137
3138 let workspace_count = cx.update(|_window, cx| {
3139 cx.windows()
3140 .iter()
3141 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
3142 .count()
3143 })?;
3144
3145 #[cfg(target_os = "macos")]
3146 let save_last_workspace = false;
3147
3148 // On Linux and Windows, closing the last window should restore the last workspace.
3149 #[cfg(not(target_os = "macos"))]
3150 let save_last_workspace = {
3151 let remaining_workspaces = cx.update(|_window, cx| {
3152 cx.windows()
3153 .iter()
3154 .filter_map(|window| window.downcast::<MultiWorkspace>())
3155 .filter_map(|multi_workspace| {
3156 multi_workspace
3157 .update(cx, |multi_workspace, _, cx| {
3158 multi_workspace.workspace().read(cx).removing
3159 })
3160 .ok()
3161 })
3162 .filter(|removing| !removing)
3163 .count()
3164 })?;
3165
3166 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
3167 };
3168
3169 if let Some(active_call) = active_call
3170 && workspace_count == 1
3171 && cx
3172 .update(|_window, cx| active_call.0.is_in_room(cx))
3173 .unwrap_or(false)
3174 {
3175 if close_intent == CloseIntent::CloseWindow {
3176 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
3177 let answer = cx.update(|window, cx| {
3178 window.prompt(
3179 PromptLevel::Warning,
3180 "Do you want to leave the current call?",
3181 None,
3182 &["Close window and hang up", "Cancel"],
3183 cx,
3184 )
3185 })?;
3186
3187 if answer.await.log_err() == Some(1) {
3188 return anyhow::Ok(false);
3189 } else {
3190 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
3191 task.await.log_err();
3192 }
3193 }
3194 }
3195 if close_intent == CloseIntent::ReplaceWindow {
3196 _ = cx.update(|_window, cx| {
3197 let multi_workspace = cx
3198 .windows()
3199 .iter()
3200 .filter_map(|window| window.downcast::<MultiWorkspace>())
3201 .next()
3202 .unwrap();
3203 let project = multi_workspace
3204 .read(cx)?
3205 .workspace()
3206 .read(cx)
3207 .project
3208 .clone();
3209 if project.read(cx).is_shared() {
3210 active_call.0.unshare_project(project, cx)?;
3211 }
3212 Ok::<_, anyhow::Error>(())
3213 });
3214 }
3215 }
3216
3217 let save_result = this
3218 .update_in(cx, |this, window, cx| {
3219 this.save_all_internal(SaveIntent::Close, window, cx)
3220 })?
3221 .await;
3222
3223 // If we're not quitting, but closing, we remove the workspace from
3224 // the current session.
3225 if close_intent != CloseIntent::Quit
3226 && !save_last_workspace
3227 && save_result.as_ref().is_ok_and(|&res| res)
3228 {
3229 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
3230 .await;
3231 }
3232
3233 save_result
3234 })
3235 }
3236
3237 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
3238 self.save_all_internal(
3239 action.save_intent.unwrap_or(SaveIntent::SaveAll),
3240 window,
3241 cx,
3242 )
3243 .detach_and_log_err(cx);
3244 }
3245
3246 fn send_keystrokes(
3247 &mut self,
3248 action: &SendKeystrokes,
3249 window: &mut Window,
3250 cx: &mut Context<Self>,
3251 ) {
3252 let keystrokes: Vec<Keystroke> = action
3253 .0
3254 .split(' ')
3255 .flat_map(|k| Keystroke::parse(k).log_err())
3256 .map(|k| {
3257 cx.keyboard_mapper()
3258 .map_key_equivalent(k, false)
3259 .inner()
3260 .clone()
3261 })
3262 .collect();
3263 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
3264 }
3265
3266 pub fn send_keystrokes_impl(
3267 &mut self,
3268 keystrokes: Vec<Keystroke>,
3269 window: &mut Window,
3270 cx: &mut Context<Self>,
3271 ) -> Shared<Task<()>> {
3272 let mut state = self.dispatching_keystrokes.borrow_mut();
3273 if !state.dispatched.insert(keystrokes.clone()) {
3274 cx.propagate();
3275 return state.task.clone().unwrap();
3276 }
3277
3278 state.queue.extend(keystrokes);
3279
3280 let keystrokes = self.dispatching_keystrokes.clone();
3281 if state.task.is_none() {
3282 state.task = Some(
3283 window
3284 .spawn(cx, async move |cx| {
3285 // limit to 100 keystrokes to avoid infinite recursion.
3286 for _ in 0..100 {
3287 let keystroke = {
3288 let mut state = keystrokes.borrow_mut();
3289 let Some(keystroke) = state.queue.pop_front() else {
3290 state.dispatched.clear();
3291 state.task.take();
3292 return;
3293 };
3294 keystroke
3295 };
3296 cx.update(|window, cx| {
3297 let focused = window.focused(cx);
3298 window.dispatch_keystroke(keystroke.clone(), cx);
3299 if window.focused(cx) != focused {
3300 // dispatch_keystroke may cause the focus to change.
3301 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3302 // And we need that to happen before the next keystroke to keep vim mode happy...
3303 // (Note that the tests always do this implicitly, so you must manually test with something like:
3304 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3305 // )
3306 window.draw(cx).clear();
3307 }
3308 })
3309 .ok();
3310
3311 // Yield between synthetic keystrokes so deferred focus and
3312 // other effects can settle before dispatching the next key.
3313 yield_now().await;
3314 }
3315
3316 *keystrokes.borrow_mut() = Default::default();
3317 log::error!("over 100 keystrokes passed to send_keystrokes");
3318 })
3319 .shared(),
3320 );
3321 }
3322 state.task.clone().unwrap()
3323 }
3324
3325 fn save_all_internal(
3326 &mut self,
3327 mut save_intent: SaveIntent,
3328 window: &mut Window,
3329 cx: &mut Context<Self>,
3330 ) -> Task<Result<bool>> {
3331 if self.project.read(cx).is_disconnected(cx) {
3332 return Task::ready(Ok(true));
3333 }
3334 let dirty_items = self
3335 .panes
3336 .iter()
3337 .flat_map(|pane| {
3338 pane.read(cx).items().filter_map(|item| {
3339 if item.is_dirty(cx) {
3340 item.tab_content_text(0, cx);
3341 Some((pane.downgrade(), item.boxed_clone()))
3342 } else {
3343 None
3344 }
3345 })
3346 })
3347 .collect::<Vec<_>>();
3348
3349 let project = self.project.clone();
3350 cx.spawn_in(window, async move |workspace, cx| {
3351 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3352 let (serialize_tasks, remaining_dirty_items) =
3353 workspace.update_in(cx, |workspace, window, cx| {
3354 let mut remaining_dirty_items = Vec::new();
3355 let mut serialize_tasks = Vec::new();
3356 for (pane, item) in dirty_items {
3357 if let Some(task) = item
3358 .to_serializable_item_handle(cx)
3359 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3360 {
3361 serialize_tasks.push(task);
3362 } else {
3363 remaining_dirty_items.push((pane, item));
3364 }
3365 }
3366 (serialize_tasks, remaining_dirty_items)
3367 })?;
3368
3369 futures::future::try_join_all(serialize_tasks).await?;
3370
3371 if !remaining_dirty_items.is_empty() {
3372 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3373 }
3374
3375 if remaining_dirty_items.len() > 1 {
3376 let answer = workspace.update_in(cx, |_, window, cx| {
3377 let detail = Pane::file_names_for_prompt(
3378 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3379 cx,
3380 );
3381 window.prompt(
3382 PromptLevel::Warning,
3383 "Do you want to save all changes in the following files?",
3384 Some(&detail),
3385 &["Save all", "Discard all", "Cancel"],
3386 cx,
3387 )
3388 })?;
3389 match answer.await.log_err() {
3390 Some(0) => save_intent = SaveIntent::SaveAll,
3391 Some(1) => save_intent = SaveIntent::Skip,
3392 Some(2) => return Ok(false),
3393 _ => {}
3394 }
3395 }
3396
3397 remaining_dirty_items
3398 } else {
3399 dirty_items
3400 };
3401
3402 for (pane, item) in dirty_items {
3403 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3404 (
3405 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3406 item.project_entry_ids(cx),
3407 )
3408 })?;
3409 if (singleton || !project_entry_ids.is_empty())
3410 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3411 {
3412 return Ok(false);
3413 }
3414 }
3415 Ok(true)
3416 })
3417 }
3418
3419 pub fn open_workspace_for_paths(
3420 &mut self,
3421 // replace_current_window: bool,
3422 mut open_mode: OpenMode,
3423 paths: Vec<PathBuf>,
3424 window: &mut Window,
3425 cx: &mut Context<Self>,
3426 ) -> Task<Result<Entity<Workspace>>> {
3427 let requesting_window = window.window_handle().downcast::<MultiWorkspace>();
3428 let is_remote = self.project.read(cx).is_via_collab();
3429 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3430 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3431
3432 let workspace_is_empty = !is_remote && !has_worktree && !has_dirty_items;
3433 if workspace_is_empty {
3434 open_mode = OpenMode::Activate;
3435 }
3436
3437 let app_state = self.app_state.clone();
3438
3439 cx.spawn(async move |_, cx| {
3440 let OpenResult { workspace, .. } = cx
3441 .update(|cx| {
3442 open_paths(
3443 &paths,
3444 app_state,
3445 OpenOptions {
3446 requesting_window,
3447 open_mode,
3448 ..Default::default()
3449 },
3450 cx,
3451 )
3452 })
3453 .await?;
3454 Ok(workspace)
3455 })
3456 }
3457
3458 #[allow(clippy::type_complexity)]
3459 pub fn open_paths(
3460 &mut self,
3461 mut abs_paths: Vec<PathBuf>,
3462 options: OpenOptions,
3463 pane: Option<WeakEntity<Pane>>,
3464 window: &mut Window,
3465 cx: &mut Context<Self>,
3466 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3467 let fs = self.app_state.fs.clone();
3468
3469 let caller_ordered_abs_paths = abs_paths.clone();
3470
3471 // Sort the paths to ensure we add worktrees for parents before their children.
3472 abs_paths.sort_unstable();
3473 cx.spawn_in(window, async move |this, cx| {
3474 let mut tasks = Vec::with_capacity(abs_paths.len());
3475
3476 for abs_path in &abs_paths {
3477 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3478 OpenVisible::All => Some(true),
3479 OpenVisible::None => Some(false),
3480 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3481 Some(Some(metadata)) => Some(!metadata.is_dir),
3482 Some(None) => Some(true),
3483 None => None,
3484 },
3485 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3486 Some(Some(metadata)) => Some(metadata.is_dir),
3487 Some(None) => Some(false),
3488 None => None,
3489 },
3490 };
3491 let project_path = match visible {
3492 Some(visible) => match this
3493 .update(cx, |this, cx| {
3494 Workspace::project_path_for_path(
3495 this.project.clone(),
3496 abs_path,
3497 visible,
3498 cx,
3499 )
3500 })
3501 .log_err()
3502 {
3503 Some(project_path) => project_path.await.log_err(),
3504 None => None,
3505 },
3506 None => None,
3507 };
3508
3509 let this = this.clone();
3510 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3511 let fs = fs.clone();
3512 let pane = pane.clone();
3513 let task = cx.spawn(async move |cx| {
3514 let (_worktree, project_path) = project_path?;
3515 if fs.is_dir(&abs_path).await {
3516 // Opening a directory should not race to update the active entry.
3517 // We'll select/reveal a deterministic final entry after all paths finish opening.
3518 None
3519 } else {
3520 Some(
3521 this.update_in(cx, |this, window, cx| {
3522 this.open_path(
3523 project_path,
3524 pane,
3525 options.focus.unwrap_or(true),
3526 window,
3527 cx,
3528 )
3529 })
3530 .ok()?
3531 .await,
3532 )
3533 }
3534 });
3535 tasks.push(task);
3536 }
3537
3538 let results = futures::future::join_all(tasks).await;
3539
3540 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3541 let mut winner: Option<(PathBuf, bool)> = None;
3542 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3543 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3544 if !metadata.is_dir {
3545 winner = Some((abs_path, false));
3546 break;
3547 }
3548 if winner.is_none() {
3549 winner = Some((abs_path, true));
3550 }
3551 } else if winner.is_none() {
3552 winner = Some((abs_path, false));
3553 }
3554 }
3555
3556 // Compute the winner entry id on the foreground thread and emit once, after all
3557 // paths finish opening. This avoids races between concurrently-opening paths
3558 // (directories in particular) and makes the resulting project panel selection
3559 // deterministic.
3560 if let Some((winner_abs_path, winner_is_dir)) = winner {
3561 'emit_winner: {
3562 let winner_abs_path: Arc<Path> =
3563 SanitizedPath::new(&winner_abs_path).as_path().into();
3564
3565 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3566 OpenVisible::All => true,
3567 OpenVisible::None => false,
3568 OpenVisible::OnlyFiles => !winner_is_dir,
3569 OpenVisible::OnlyDirectories => winner_is_dir,
3570 };
3571
3572 let Some(worktree_task) = this
3573 .update(cx, |workspace, cx| {
3574 workspace.project.update(cx, |project, cx| {
3575 project.find_or_create_worktree(
3576 winner_abs_path.as_ref(),
3577 visible,
3578 cx,
3579 )
3580 })
3581 })
3582 .ok()
3583 else {
3584 break 'emit_winner;
3585 };
3586
3587 let Ok((worktree, _)) = worktree_task.await else {
3588 break 'emit_winner;
3589 };
3590
3591 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3592 let worktree = worktree.read(cx);
3593 let worktree_abs_path = worktree.abs_path();
3594 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3595 worktree.root_entry()
3596 } else {
3597 winner_abs_path
3598 .strip_prefix(worktree_abs_path.as_ref())
3599 .ok()
3600 .and_then(|relative_path| {
3601 let relative_path =
3602 RelPath::new(relative_path, PathStyle::local())
3603 .log_err()?;
3604 worktree.entry_for_path(&relative_path)
3605 })
3606 }?;
3607 Some(entry.id)
3608 }) else {
3609 break 'emit_winner;
3610 };
3611
3612 this.update(cx, |workspace, cx| {
3613 workspace.project.update(cx, |_, cx| {
3614 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3615 });
3616 })
3617 .ok();
3618 }
3619 }
3620
3621 results
3622 })
3623 }
3624
3625 pub fn open_resolved_path(
3626 &mut self,
3627 path: ResolvedPath,
3628 window: &mut Window,
3629 cx: &mut Context<Self>,
3630 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3631 match path {
3632 ResolvedPath::ProjectPath { project_path, .. } => {
3633 self.open_path(project_path, None, true, window, cx)
3634 }
3635 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3636 PathBuf::from(path),
3637 OpenOptions {
3638 visible: Some(OpenVisible::None),
3639 ..Default::default()
3640 },
3641 window,
3642 cx,
3643 ),
3644 }
3645 }
3646
3647 pub fn absolute_path_of_worktree(
3648 &self,
3649 worktree_id: WorktreeId,
3650 cx: &mut Context<Self>,
3651 ) -> Option<PathBuf> {
3652 self.project
3653 .read(cx)
3654 .worktree_for_id(worktree_id, cx)
3655 // TODO: use `abs_path` or `root_dir`
3656 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3657 }
3658
3659 pub fn add_folder_to_project(
3660 &mut self,
3661 _: &AddFolderToProject,
3662 window: &mut Window,
3663 cx: &mut Context<Self>,
3664 ) {
3665 let project = self.project.read(cx);
3666 if project.is_via_collab() {
3667 self.show_error(
3668 &anyhow!("You cannot add folders to someone else's project"),
3669 cx,
3670 );
3671 return;
3672 }
3673 let paths = self.prompt_for_open_path(
3674 PathPromptOptions {
3675 files: false,
3676 directories: true,
3677 multiple: true,
3678 prompt: None,
3679 },
3680 DirectoryLister::Project(self.project.clone()),
3681 window,
3682 cx,
3683 );
3684 cx.spawn_in(window, async move |this, cx| {
3685 if let Some(paths) = paths.await.log_err().flatten() {
3686 let results = this
3687 .update_in(cx, |this, window, cx| {
3688 this.open_paths(
3689 paths,
3690 OpenOptions {
3691 visible: Some(OpenVisible::All),
3692 ..Default::default()
3693 },
3694 None,
3695 window,
3696 cx,
3697 )
3698 })?
3699 .await;
3700 for result in results.into_iter().flatten() {
3701 result.log_err();
3702 }
3703 }
3704 anyhow::Ok(())
3705 })
3706 .detach_and_log_err(cx);
3707 }
3708
3709 pub fn project_path_for_path(
3710 project: Entity<Project>,
3711 abs_path: &Path,
3712 visible: bool,
3713 cx: &mut App,
3714 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3715 let entry = project.update(cx, |project, cx| {
3716 project.find_or_create_worktree(abs_path, visible, cx)
3717 });
3718 cx.spawn(async move |cx| {
3719 let (worktree, path) = entry.await?;
3720 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3721 Ok((worktree, ProjectPath { worktree_id, path }))
3722 })
3723 }
3724
3725 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3726 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3727 }
3728
3729 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3730 self.items_of_type(cx).max_by_key(|item| item.item_id())
3731 }
3732
3733 pub fn items_of_type<'a, T: Item>(
3734 &'a self,
3735 cx: &'a App,
3736 ) -> impl 'a + Iterator<Item = Entity<T>> {
3737 self.panes
3738 .iter()
3739 .flat_map(|pane| pane.read(cx).items_of_type())
3740 }
3741
3742 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3743 self.active_pane().read(cx).active_item()
3744 }
3745
3746 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3747 let item = self.active_item(cx)?;
3748 item.to_any_view().downcast::<I>().ok()
3749 }
3750
3751 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3752 self.active_item(cx).and_then(|item| item.project_path(cx))
3753 }
3754
3755 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3756 self.recent_navigation_history_iter(cx)
3757 .filter_map(|(path, abs_path)| {
3758 let worktree = self
3759 .project
3760 .read(cx)
3761 .worktree_for_id(path.worktree_id, cx)?;
3762 if worktree.read(cx).is_visible() {
3763 abs_path
3764 } else {
3765 None
3766 }
3767 })
3768 .next()
3769 }
3770
3771 pub fn save_active_item(
3772 &mut self,
3773 save_intent: SaveIntent,
3774 window: &mut Window,
3775 cx: &mut App,
3776 ) -> Task<Result<()>> {
3777 let project = self.project.clone();
3778 let pane = self.active_pane();
3779 let item = pane.read(cx).active_item();
3780 let pane = pane.downgrade();
3781
3782 window.spawn(cx, async move |cx| {
3783 if let Some(item) = item {
3784 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3785 .await
3786 .map(|_| ())
3787 } else {
3788 Ok(())
3789 }
3790 })
3791 }
3792
3793 pub fn close_inactive_items_and_panes(
3794 &mut self,
3795 action: &CloseInactiveTabsAndPanes,
3796 window: &mut Window,
3797 cx: &mut Context<Self>,
3798 ) {
3799 if let Some(task) = self.close_all_internal(
3800 true,
3801 action.save_intent.unwrap_or(SaveIntent::Close),
3802 window,
3803 cx,
3804 ) {
3805 task.detach_and_log_err(cx)
3806 }
3807 }
3808
3809 pub fn close_all_items_and_panes(
3810 &mut self,
3811 action: &CloseAllItemsAndPanes,
3812 window: &mut Window,
3813 cx: &mut Context<Self>,
3814 ) {
3815 if let Some(task) = self.close_all_internal(
3816 false,
3817 action.save_intent.unwrap_or(SaveIntent::Close),
3818 window,
3819 cx,
3820 ) {
3821 task.detach_and_log_err(cx)
3822 }
3823 }
3824
3825 /// Closes the active item across all panes.
3826 pub fn close_item_in_all_panes(
3827 &mut self,
3828 action: &CloseItemInAllPanes,
3829 window: &mut Window,
3830 cx: &mut Context<Self>,
3831 ) {
3832 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3833 return;
3834 };
3835
3836 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3837 let close_pinned = action.close_pinned;
3838
3839 if let Some(project_path) = active_item.project_path(cx) {
3840 self.close_items_with_project_path(
3841 &project_path,
3842 save_intent,
3843 close_pinned,
3844 window,
3845 cx,
3846 );
3847 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3848 let item_id = active_item.item_id();
3849 self.active_pane().update(cx, |pane, cx| {
3850 pane.close_item_by_id(item_id, save_intent, window, cx)
3851 .detach_and_log_err(cx);
3852 });
3853 }
3854 }
3855
3856 /// Closes all items with the given project path across all panes.
3857 pub fn close_items_with_project_path(
3858 &mut self,
3859 project_path: &ProjectPath,
3860 save_intent: SaveIntent,
3861 close_pinned: bool,
3862 window: &mut Window,
3863 cx: &mut Context<Self>,
3864 ) {
3865 let panes = self.panes().to_vec();
3866 for pane in panes {
3867 pane.update(cx, |pane, cx| {
3868 pane.close_items_for_project_path(
3869 project_path,
3870 save_intent,
3871 close_pinned,
3872 window,
3873 cx,
3874 )
3875 .detach_and_log_err(cx);
3876 });
3877 }
3878 }
3879
3880 fn close_all_internal(
3881 &mut self,
3882 retain_active_pane: bool,
3883 save_intent: SaveIntent,
3884 window: &mut Window,
3885 cx: &mut Context<Self>,
3886 ) -> Option<Task<Result<()>>> {
3887 let current_pane = self.active_pane();
3888
3889 let mut tasks = Vec::new();
3890
3891 if retain_active_pane {
3892 let current_pane_close = current_pane.update(cx, |pane, cx| {
3893 pane.close_other_items(
3894 &CloseOtherItems {
3895 save_intent: None,
3896 close_pinned: false,
3897 },
3898 None,
3899 window,
3900 cx,
3901 )
3902 });
3903
3904 tasks.push(current_pane_close);
3905 }
3906
3907 for pane in self.panes() {
3908 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3909 continue;
3910 }
3911
3912 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3913 pane.close_all_items(
3914 &CloseAllItems {
3915 save_intent: Some(save_intent),
3916 close_pinned: false,
3917 },
3918 window,
3919 cx,
3920 )
3921 });
3922
3923 tasks.push(close_pane_items)
3924 }
3925
3926 if tasks.is_empty() {
3927 None
3928 } else {
3929 Some(cx.spawn_in(window, async move |_, _| {
3930 for task in tasks {
3931 task.await?
3932 }
3933 Ok(())
3934 }))
3935 }
3936 }
3937
3938 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3939 self.dock_at_position(position).read(cx).is_open()
3940 }
3941
3942 pub fn toggle_dock(
3943 &mut self,
3944 dock_side: DockPosition,
3945 window: &mut Window,
3946 cx: &mut Context<Self>,
3947 ) {
3948 let mut focus_center = false;
3949 let mut reveal_dock = false;
3950
3951 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3952 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3953
3954 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3955 telemetry::event!(
3956 "Panel Button Clicked",
3957 name = panel.persistent_name(),
3958 toggle_state = !was_visible
3959 );
3960 }
3961 if was_visible {
3962 self.save_open_dock_positions(cx);
3963 }
3964
3965 let dock = self.dock_at_position(dock_side);
3966 dock.update(cx, |dock, cx| {
3967 dock.set_open(!was_visible, window, cx);
3968
3969 if dock.active_panel().is_none() {
3970 let Some(panel_ix) = dock
3971 .first_enabled_panel_idx(cx)
3972 .log_with_level(log::Level::Info)
3973 else {
3974 return;
3975 };
3976 dock.activate_panel(panel_ix, window, cx);
3977 }
3978
3979 if let Some(active_panel) = dock.active_panel() {
3980 if was_visible {
3981 if active_panel
3982 .panel_focus_handle(cx)
3983 .contains_focused(window, cx)
3984 {
3985 focus_center = true;
3986 }
3987 } else {
3988 let focus_handle = &active_panel.panel_focus_handle(cx);
3989 window.focus(focus_handle, cx);
3990 reveal_dock = true;
3991 }
3992 }
3993 });
3994
3995 if reveal_dock {
3996 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3997 }
3998
3999 if focus_center {
4000 self.active_pane
4001 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4002 }
4003
4004 cx.notify();
4005 self.serialize_workspace(window, cx);
4006 }
4007
4008 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
4009 self.all_docks().into_iter().find(|&dock| {
4010 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
4011 })
4012 }
4013
4014 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
4015 if let Some(dock) = self.active_dock(window, cx).cloned() {
4016 self.save_open_dock_positions(cx);
4017 dock.update(cx, |dock, cx| {
4018 dock.set_open(false, window, cx);
4019 });
4020 return true;
4021 }
4022 false
4023 }
4024
4025 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4026 self.save_open_dock_positions(cx);
4027 for dock in self.all_docks() {
4028 dock.update(cx, |dock, cx| {
4029 dock.set_open(false, window, cx);
4030 });
4031 }
4032
4033 cx.focus_self(window);
4034 cx.notify();
4035 self.serialize_workspace(window, cx);
4036 }
4037
4038 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
4039 self.all_docks()
4040 .into_iter()
4041 .filter_map(|dock| {
4042 let dock_ref = dock.read(cx);
4043 if dock_ref.is_open() {
4044 Some(dock_ref.position())
4045 } else {
4046 None
4047 }
4048 })
4049 .collect()
4050 }
4051
4052 /// Saves the positions of currently open docks.
4053 ///
4054 /// Updates `last_open_dock_positions` with positions of all currently open
4055 /// docks, to later be restored by the 'Toggle All Docks' action.
4056 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
4057 let open_dock_positions = self.get_open_dock_positions(cx);
4058 if !open_dock_positions.is_empty() {
4059 self.last_open_dock_positions = open_dock_positions;
4060 }
4061 }
4062
4063 /// Toggles all docks between open and closed states.
4064 ///
4065 /// If any docks are open, closes all and remembers their positions. If all
4066 /// docks are closed, restores the last remembered dock configuration.
4067 fn toggle_all_docks(
4068 &mut self,
4069 _: &ToggleAllDocks,
4070 window: &mut Window,
4071 cx: &mut Context<Self>,
4072 ) {
4073 let open_dock_positions = self.get_open_dock_positions(cx);
4074
4075 if !open_dock_positions.is_empty() {
4076 self.close_all_docks(window, cx);
4077 } else if !self.last_open_dock_positions.is_empty() {
4078 self.restore_last_open_docks(window, cx);
4079 }
4080 }
4081
4082 /// Reopens docks from the most recently remembered configuration.
4083 ///
4084 /// Opens all docks whose positions are stored in `last_open_dock_positions`
4085 /// and clears the stored positions.
4086 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4087 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
4088
4089 for position in positions_to_open {
4090 let dock = self.dock_at_position(position);
4091 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
4092 }
4093
4094 cx.focus_self(window);
4095 cx.notify();
4096 self.serialize_workspace(window, cx);
4097 }
4098
4099 /// Transfer focus to the panel of the given type.
4100 pub fn focus_panel<T: Panel>(
4101 &mut self,
4102 window: &mut Window,
4103 cx: &mut Context<Self>,
4104 ) -> Option<Entity<T>> {
4105 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
4106 panel.to_any().downcast().ok()
4107 }
4108
4109 /// Focus the panel of the given type if it isn't already focused. If it is
4110 /// already focused, then transfer focus back to the workspace center.
4111 /// When the `close_panel_on_toggle` setting is enabled, also closes the
4112 /// panel when transferring focus back to the center.
4113 pub fn toggle_panel_focus<T: Panel>(
4114 &mut self,
4115 window: &mut Window,
4116 cx: &mut Context<Self>,
4117 ) -> bool {
4118 let mut did_focus_panel = false;
4119 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
4120 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
4121 did_focus_panel
4122 });
4123
4124 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
4125 self.close_panel::<T>(window, cx);
4126 }
4127
4128 telemetry::event!(
4129 "Panel Button Clicked",
4130 name = T::persistent_name(),
4131 toggle_state = did_focus_panel
4132 );
4133
4134 did_focus_panel
4135 }
4136
4137 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4138 if let Some(item) = self.active_item(cx) {
4139 item.item_focus_handle(cx).focus(window, cx);
4140 } else {
4141 log::error!("Could not find a focus target when switching focus to the center panes",);
4142 }
4143 }
4144
4145 pub fn activate_panel_for_proto_id(
4146 &mut self,
4147 panel_id: PanelId,
4148 window: &mut Window,
4149 cx: &mut Context<Self>,
4150 ) -> Option<Arc<dyn PanelHandle>> {
4151 let mut panel = None;
4152 for dock in self.all_docks() {
4153 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
4154 panel = dock.update(cx, |dock, cx| {
4155 dock.activate_panel(panel_index, window, cx);
4156 dock.set_open(true, window, cx);
4157 dock.active_panel().cloned()
4158 });
4159 break;
4160 }
4161 }
4162
4163 if panel.is_some() {
4164 cx.notify();
4165 self.serialize_workspace(window, cx);
4166 }
4167
4168 panel
4169 }
4170
4171 /// Focus or unfocus the given panel type, depending on the given callback.
4172 fn focus_or_unfocus_panel<T: Panel>(
4173 &mut self,
4174 window: &mut Window,
4175 cx: &mut Context<Self>,
4176 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
4177 ) -> Option<Arc<dyn PanelHandle>> {
4178 let mut result_panel = None;
4179 let mut serialize = false;
4180 for dock in self.all_docks() {
4181 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4182 let mut focus_center = false;
4183 let panel = dock.update(cx, |dock, cx| {
4184 dock.activate_panel(panel_index, window, cx);
4185
4186 let panel = dock.active_panel().cloned();
4187 if let Some(panel) = panel.as_ref() {
4188 if should_focus(&**panel, window, cx) {
4189 dock.set_open(true, window, cx);
4190 panel.panel_focus_handle(cx).focus(window, cx);
4191 } else {
4192 focus_center = true;
4193 }
4194 }
4195 panel
4196 });
4197
4198 if focus_center {
4199 self.active_pane
4200 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4201 }
4202
4203 result_panel = panel;
4204 serialize = true;
4205 break;
4206 }
4207 }
4208
4209 if serialize {
4210 self.serialize_workspace(window, cx);
4211 }
4212
4213 cx.notify();
4214 result_panel
4215 }
4216
4217 /// Open the panel of the given type
4218 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4219 for dock in self.all_docks() {
4220 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
4221 dock.update(cx, |dock, cx| {
4222 dock.activate_panel(panel_index, window, cx);
4223 dock.set_open(true, window, cx);
4224 });
4225 }
4226 }
4227 }
4228
4229 /// Open the panel of the given type, dismissing any zoomed items that
4230 /// would obscure it (e.g. a zoomed terminal).
4231 pub fn reveal_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4232 let dock_position = self.all_docks().iter().find_map(|dock| {
4233 let dock = dock.read(cx);
4234 dock.panel_index_for_type::<T>().map(|_| dock.position())
4235 });
4236 self.dismiss_zoomed_items_to_reveal(dock_position, window, cx);
4237 self.open_panel::<T>(window, cx);
4238 }
4239
4240 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
4241 for dock in self.all_docks().iter() {
4242 dock.update(cx, |dock, cx| {
4243 if dock.panel::<T>().is_some() {
4244 dock.set_open(false, window, cx)
4245 }
4246 })
4247 }
4248 }
4249
4250 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
4251 self.all_docks()
4252 .iter()
4253 .find_map(|dock| dock.read(cx).panel::<T>())
4254 }
4255
4256 fn dismiss_zoomed_items_to_reveal(
4257 &mut self,
4258 dock_to_reveal: Option<DockPosition>,
4259 window: &mut Window,
4260 cx: &mut Context<Self>,
4261 ) {
4262 // If a center pane is zoomed, unzoom it.
4263 for pane in &self.panes {
4264 if pane != &self.active_pane || dock_to_reveal.is_some() {
4265 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4266 }
4267 }
4268
4269 // If another dock is zoomed, hide it.
4270 let mut focus_center = false;
4271 for dock in self.all_docks() {
4272 dock.update(cx, |dock, cx| {
4273 if Some(dock.position()) != dock_to_reveal
4274 && let Some(panel) = dock.active_panel()
4275 && panel.is_zoomed(window, cx)
4276 {
4277 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
4278 dock.set_open(false, window, cx);
4279 }
4280 });
4281 }
4282
4283 if focus_center {
4284 self.active_pane
4285 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
4286 }
4287
4288 if self.zoomed_position != dock_to_reveal {
4289 self.zoomed = None;
4290 self.zoomed_position = None;
4291 cx.emit(Event::ZoomChanged);
4292 }
4293
4294 cx.notify();
4295 }
4296
4297 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4298 let pane = cx.new(|cx| {
4299 let mut pane = Pane::new(
4300 self.weak_handle(),
4301 self.project.clone(),
4302 self.pane_history_timestamp.clone(),
4303 None,
4304 NewFile.boxed_clone(),
4305 true,
4306 window,
4307 cx,
4308 );
4309 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4310 pane
4311 });
4312 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4313 .detach();
4314 self.panes.push(pane.clone());
4315
4316 window.focus(&pane.focus_handle(cx), cx);
4317
4318 cx.emit(Event::PaneAdded(pane.clone()));
4319 pane
4320 }
4321
4322 pub fn add_item_to_center(
4323 &mut self,
4324 item: Box<dyn ItemHandle>,
4325 window: &mut Window,
4326 cx: &mut Context<Self>,
4327 ) -> bool {
4328 if let Some(center_pane) = self.last_active_center_pane.clone() {
4329 if let Some(center_pane) = center_pane.upgrade() {
4330 center_pane.update(cx, |pane, cx| {
4331 pane.add_item(item, true, true, None, window, cx)
4332 });
4333 true
4334 } else {
4335 false
4336 }
4337 } else {
4338 false
4339 }
4340 }
4341
4342 pub fn add_item_to_active_pane(
4343 &mut self,
4344 item: Box<dyn ItemHandle>,
4345 destination_index: Option<usize>,
4346 focus_item: bool,
4347 window: &mut Window,
4348 cx: &mut App,
4349 ) {
4350 self.add_item(
4351 self.active_pane.clone(),
4352 item,
4353 destination_index,
4354 false,
4355 focus_item,
4356 window,
4357 cx,
4358 )
4359 }
4360
4361 pub fn add_item(
4362 &mut self,
4363 pane: Entity<Pane>,
4364 item: Box<dyn ItemHandle>,
4365 destination_index: Option<usize>,
4366 activate_pane: bool,
4367 focus_item: bool,
4368 window: &mut Window,
4369 cx: &mut App,
4370 ) {
4371 pane.update(cx, |pane, cx| {
4372 pane.add_item(
4373 item,
4374 activate_pane,
4375 focus_item,
4376 destination_index,
4377 window,
4378 cx,
4379 )
4380 });
4381 }
4382
4383 pub fn split_item(
4384 &mut self,
4385 split_direction: SplitDirection,
4386 item: Box<dyn ItemHandle>,
4387 window: &mut Window,
4388 cx: &mut Context<Self>,
4389 ) {
4390 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4391 self.add_item(new_pane, item, None, true, true, window, cx);
4392 }
4393
4394 pub fn open_abs_path(
4395 &mut self,
4396 abs_path: PathBuf,
4397 options: OpenOptions,
4398 window: &mut Window,
4399 cx: &mut Context<Self>,
4400 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4401 cx.spawn_in(window, async move |workspace, cx| {
4402 let open_paths_task_result = workspace
4403 .update_in(cx, |workspace, window, cx| {
4404 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4405 })
4406 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4407 .await;
4408 anyhow::ensure!(
4409 open_paths_task_result.len() == 1,
4410 "open abs path {abs_path:?} task returned incorrect number of results"
4411 );
4412 match open_paths_task_result
4413 .into_iter()
4414 .next()
4415 .expect("ensured single task result")
4416 {
4417 Some(open_result) => {
4418 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4419 }
4420 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4421 }
4422 })
4423 }
4424
4425 pub fn split_abs_path(
4426 &mut self,
4427 abs_path: PathBuf,
4428 visible: bool,
4429 window: &mut Window,
4430 cx: &mut Context<Self>,
4431 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4432 let project_path_task =
4433 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4434 cx.spawn_in(window, async move |this, cx| {
4435 let (_, path) = project_path_task.await?;
4436 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4437 .await
4438 })
4439 }
4440
4441 pub fn open_path(
4442 &mut self,
4443 path: impl Into<ProjectPath>,
4444 pane: Option<WeakEntity<Pane>>,
4445 focus_item: bool,
4446 window: &mut Window,
4447 cx: &mut App,
4448 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4449 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4450 }
4451
4452 pub fn open_path_preview(
4453 &mut self,
4454 path: impl Into<ProjectPath>,
4455 pane: Option<WeakEntity<Pane>>,
4456 focus_item: bool,
4457 allow_preview: bool,
4458 activate: bool,
4459 window: &mut Window,
4460 cx: &mut App,
4461 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4462 let pane = pane.unwrap_or_else(|| {
4463 self.last_active_center_pane.clone().unwrap_or_else(|| {
4464 self.panes
4465 .first()
4466 .expect("There must be an active pane")
4467 .downgrade()
4468 })
4469 });
4470
4471 let project_path = path.into();
4472 let task = self.load_path(project_path.clone(), window, cx);
4473 window.spawn(cx, async move |cx| {
4474 let (project_entry_id, build_item) = task.await?;
4475
4476 pane.update_in(cx, |pane, window, cx| {
4477 pane.open_item(
4478 project_entry_id,
4479 project_path,
4480 focus_item,
4481 allow_preview,
4482 activate,
4483 None,
4484 window,
4485 cx,
4486 build_item,
4487 )
4488 })
4489 })
4490 }
4491
4492 pub fn split_path(
4493 &mut self,
4494 path: impl Into<ProjectPath>,
4495 window: &mut Window,
4496 cx: &mut Context<Self>,
4497 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4498 self.split_path_preview(path, false, None, window, cx)
4499 }
4500
4501 pub fn split_path_preview(
4502 &mut self,
4503 path: impl Into<ProjectPath>,
4504 allow_preview: bool,
4505 split_direction: Option<SplitDirection>,
4506 window: &mut Window,
4507 cx: &mut Context<Self>,
4508 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4509 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4510 self.panes
4511 .first()
4512 .expect("There must be an active pane")
4513 .downgrade()
4514 });
4515
4516 if let Member::Pane(center_pane) = &self.center.root
4517 && center_pane.read(cx).items_len() == 0
4518 {
4519 return self.open_path(path, Some(pane), true, window, cx);
4520 }
4521
4522 let project_path = path.into();
4523 let task = self.load_path(project_path.clone(), window, cx);
4524 cx.spawn_in(window, async move |this, cx| {
4525 let (project_entry_id, build_item) = task.await?;
4526 this.update_in(cx, move |this, window, cx| -> Option<_> {
4527 let pane = pane.upgrade()?;
4528 let new_pane = this.split_pane(
4529 pane,
4530 split_direction.unwrap_or(SplitDirection::Right),
4531 window,
4532 cx,
4533 );
4534 new_pane.update(cx, |new_pane, cx| {
4535 Some(new_pane.open_item(
4536 project_entry_id,
4537 project_path,
4538 true,
4539 allow_preview,
4540 true,
4541 None,
4542 window,
4543 cx,
4544 build_item,
4545 ))
4546 })
4547 })
4548 .map(|option| option.context("pane was dropped"))?
4549 })
4550 }
4551
4552 fn load_path(
4553 &mut self,
4554 path: ProjectPath,
4555 window: &mut Window,
4556 cx: &mut App,
4557 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4558 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4559 registry.open_path(self.project(), &path, window, cx)
4560 }
4561
4562 pub fn find_project_item<T>(
4563 &self,
4564 pane: &Entity<Pane>,
4565 project_item: &Entity<T::Item>,
4566 cx: &App,
4567 ) -> Option<Entity<T>>
4568 where
4569 T: ProjectItem,
4570 {
4571 use project::ProjectItem as _;
4572 let project_item = project_item.read(cx);
4573 let entry_id = project_item.entry_id(cx);
4574 let project_path = project_item.project_path(cx);
4575
4576 let mut item = None;
4577 if let Some(entry_id) = entry_id {
4578 item = pane.read(cx).item_for_entry(entry_id, cx);
4579 }
4580 if item.is_none()
4581 && let Some(project_path) = project_path
4582 {
4583 item = pane.read(cx).item_for_path(project_path, cx);
4584 }
4585
4586 item.and_then(|item| item.downcast::<T>())
4587 }
4588
4589 pub fn is_project_item_open<T>(
4590 &self,
4591 pane: &Entity<Pane>,
4592 project_item: &Entity<T::Item>,
4593 cx: &App,
4594 ) -> bool
4595 where
4596 T: ProjectItem,
4597 {
4598 self.find_project_item::<T>(pane, project_item, cx)
4599 .is_some()
4600 }
4601
4602 pub fn open_project_item<T>(
4603 &mut self,
4604 pane: Entity<Pane>,
4605 project_item: Entity<T::Item>,
4606 activate_pane: bool,
4607 focus_item: bool,
4608 keep_old_preview: bool,
4609 allow_new_preview: bool,
4610 window: &mut Window,
4611 cx: &mut Context<Self>,
4612 ) -> Entity<T>
4613 where
4614 T: ProjectItem,
4615 {
4616 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4617
4618 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4619 if !keep_old_preview
4620 && let Some(old_id) = old_item_id
4621 && old_id != item.item_id()
4622 {
4623 // switching to a different item, so unpreview old active item
4624 pane.update(cx, |pane, _| {
4625 pane.unpreview_item_if_preview(old_id);
4626 });
4627 }
4628
4629 self.activate_item(&item, activate_pane, focus_item, window, cx);
4630 if !allow_new_preview {
4631 pane.update(cx, |pane, _| {
4632 pane.unpreview_item_if_preview(item.item_id());
4633 });
4634 }
4635 return item;
4636 }
4637
4638 let item = pane.update(cx, |pane, cx| {
4639 cx.new(|cx| {
4640 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4641 })
4642 });
4643 let mut destination_index = None;
4644 pane.update(cx, |pane, cx| {
4645 if !keep_old_preview && let Some(old_id) = old_item_id {
4646 pane.unpreview_item_if_preview(old_id);
4647 }
4648 if allow_new_preview {
4649 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4650 }
4651 });
4652
4653 self.add_item(
4654 pane,
4655 Box::new(item.clone()),
4656 destination_index,
4657 activate_pane,
4658 focus_item,
4659 window,
4660 cx,
4661 );
4662 item
4663 }
4664
4665 pub fn open_shared_screen(
4666 &mut self,
4667 peer_id: PeerId,
4668 window: &mut Window,
4669 cx: &mut Context<Self>,
4670 ) {
4671 if let Some(shared_screen) =
4672 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4673 {
4674 self.active_pane.update(cx, |pane, cx| {
4675 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4676 });
4677 }
4678 }
4679
4680 pub fn activate_item(
4681 &mut self,
4682 item: &dyn ItemHandle,
4683 activate_pane: bool,
4684 focus_item: bool,
4685 window: &mut Window,
4686 cx: &mut App,
4687 ) -> bool {
4688 let result = self.panes.iter().find_map(|pane| {
4689 pane.read(cx)
4690 .index_for_item(item)
4691 .map(|ix| (pane.clone(), ix))
4692 });
4693 if let Some((pane, ix)) = result {
4694 pane.update(cx, |pane, cx| {
4695 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4696 });
4697 true
4698 } else {
4699 false
4700 }
4701 }
4702
4703 fn activate_pane_at_index(
4704 &mut self,
4705 action: &ActivatePane,
4706 window: &mut Window,
4707 cx: &mut Context<Self>,
4708 ) {
4709 let panes = self.center.panes();
4710 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4711 window.focus(&pane.focus_handle(cx), cx);
4712 } else {
4713 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4714 .detach();
4715 }
4716 }
4717
4718 fn move_item_to_pane_at_index(
4719 &mut self,
4720 action: &MoveItemToPane,
4721 window: &mut Window,
4722 cx: &mut Context<Self>,
4723 ) {
4724 let panes = self.center.panes();
4725 let destination = match panes.get(action.destination) {
4726 Some(&destination) => destination.clone(),
4727 None => {
4728 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4729 return;
4730 }
4731 let direction = SplitDirection::Right;
4732 let split_off_pane = self
4733 .find_pane_in_direction(direction, cx)
4734 .unwrap_or_else(|| self.active_pane.clone());
4735 let new_pane = self.add_pane(window, cx);
4736 self.center.split(&split_off_pane, &new_pane, direction, cx);
4737 new_pane
4738 }
4739 };
4740
4741 if action.clone {
4742 if self
4743 .active_pane
4744 .read(cx)
4745 .active_item()
4746 .is_some_and(|item| item.can_split(cx))
4747 {
4748 clone_active_item(
4749 self.database_id(),
4750 &self.active_pane,
4751 &destination,
4752 action.focus,
4753 window,
4754 cx,
4755 );
4756 return;
4757 }
4758 }
4759 move_active_item(
4760 &self.active_pane,
4761 &destination,
4762 action.focus,
4763 true,
4764 window,
4765 cx,
4766 )
4767 }
4768
4769 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4770 let panes = self.center.panes();
4771 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4772 let next_ix = (ix + 1) % panes.len();
4773 let next_pane = panes[next_ix].clone();
4774 window.focus(&next_pane.focus_handle(cx), cx);
4775 }
4776 }
4777
4778 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4779 let panes = self.center.panes();
4780 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4781 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4782 let prev_pane = panes[prev_ix].clone();
4783 window.focus(&prev_pane.focus_handle(cx), cx);
4784 }
4785 }
4786
4787 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4788 let last_pane = self.center.last_pane();
4789 window.focus(&last_pane.focus_handle(cx), cx);
4790 }
4791
4792 pub fn activate_pane_in_direction(
4793 &mut self,
4794 direction: SplitDirection,
4795 window: &mut Window,
4796 cx: &mut App,
4797 ) {
4798 use ActivateInDirectionTarget as Target;
4799 enum Origin {
4800 Sidebar,
4801 LeftDock,
4802 RightDock,
4803 BottomDock,
4804 Center,
4805 }
4806
4807 let origin: Origin = if self
4808 .sidebar_focus_handle
4809 .as_ref()
4810 .is_some_and(|h| h.contains_focused(window, cx))
4811 {
4812 Origin::Sidebar
4813 } else {
4814 [
4815 (&self.left_dock, Origin::LeftDock),
4816 (&self.right_dock, Origin::RightDock),
4817 (&self.bottom_dock, Origin::BottomDock),
4818 ]
4819 .into_iter()
4820 .find_map(|(dock, origin)| {
4821 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4822 Some(origin)
4823 } else {
4824 None
4825 }
4826 })
4827 .unwrap_or(Origin::Center)
4828 };
4829
4830 let get_last_active_pane = || {
4831 let pane = self
4832 .last_active_center_pane
4833 .clone()
4834 .unwrap_or_else(|| {
4835 self.panes
4836 .first()
4837 .expect("There must be an active pane")
4838 .downgrade()
4839 })
4840 .upgrade()?;
4841 (pane.read(cx).items_len() != 0).then_some(pane)
4842 };
4843
4844 let try_dock =
4845 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4846
4847 let sidebar_target = self
4848 .sidebar_focus_handle
4849 .as_ref()
4850 .map(|h| Target::Sidebar(h.clone()));
4851
4852 let sidebar_on_right = self
4853 .multi_workspace
4854 .as_ref()
4855 .and_then(|mw| mw.upgrade())
4856 .map_or(false, |mw| {
4857 mw.read(cx).sidebar_side(cx) == SidebarSide::Right
4858 });
4859
4860 let away_from_sidebar = if sidebar_on_right {
4861 SplitDirection::Left
4862 } else {
4863 SplitDirection::Right
4864 };
4865
4866 let (near_dock, far_dock) = if sidebar_on_right {
4867 (&self.right_dock, &self.left_dock)
4868 } else {
4869 (&self.left_dock, &self.right_dock)
4870 };
4871
4872 let target = match (origin, direction) {
4873 (Origin::Sidebar, dir) if dir == away_from_sidebar => try_dock(near_dock)
4874 .or_else(|| get_last_active_pane().map(Target::Pane))
4875 .or_else(|| try_dock(&self.bottom_dock))
4876 .or_else(|| try_dock(far_dock)),
4877
4878 (Origin::Sidebar, _) => None,
4879
4880 // We're in the center, so we first try to go to a different pane,
4881 // otherwise try to go to a dock.
4882 (Origin::Center, direction) => {
4883 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4884 Some(Target::Pane(pane))
4885 } else {
4886 match direction {
4887 SplitDirection::Up => None,
4888 SplitDirection::Down => try_dock(&self.bottom_dock),
4889 SplitDirection::Left => {
4890 let dock_target = try_dock(&self.left_dock);
4891 if sidebar_on_right {
4892 dock_target
4893 } else {
4894 dock_target.or(sidebar_target)
4895 }
4896 }
4897 SplitDirection::Right => {
4898 let dock_target = try_dock(&self.right_dock);
4899 if sidebar_on_right {
4900 dock_target.or(sidebar_target)
4901 } else {
4902 dock_target
4903 }
4904 }
4905 }
4906 }
4907 }
4908
4909 (Origin::LeftDock, SplitDirection::Right) => {
4910 if let Some(last_active_pane) = get_last_active_pane() {
4911 Some(Target::Pane(last_active_pane))
4912 } else {
4913 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4914 }
4915 }
4916
4917 (Origin::LeftDock, SplitDirection::Left) => {
4918 if sidebar_on_right {
4919 None
4920 } else {
4921 sidebar_target
4922 }
4923 }
4924
4925 (Origin::LeftDock, SplitDirection::Down)
4926 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4927
4928 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4929 (Origin::BottomDock, SplitDirection::Left) => {
4930 let dock_target = try_dock(&self.left_dock);
4931 if sidebar_on_right {
4932 dock_target
4933 } else {
4934 dock_target.or(sidebar_target)
4935 }
4936 }
4937 (Origin::BottomDock, SplitDirection::Right) => {
4938 let dock_target = try_dock(&self.right_dock);
4939 if sidebar_on_right {
4940 dock_target.or(sidebar_target)
4941 } else {
4942 dock_target
4943 }
4944 }
4945
4946 (Origin::RightDock, SplitDirection::Left) => {
4947 if let Some(last_active_pane) = get_last_active_pane() {
4948 Some(Target::Pane(last_active_pane))
4949 } else {
4950 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.left_dock))
4951 }
4952 }
4953
4954 (Origin::RightDock, SplitDirection::Right) => {
4955 if sidebar_on_right {
4956 sidebar_target
4957 } else {
4958 None
4959 }
4960 }
4961
4962 _ => None,
4963 };
4964
4965 match target {
4966 Some(ActivateInDirectionTarget::Pane(pane)) => {
4967 let pane = pane.read(cx);
4968 if let Some(item) = pane.active_item() {
4969 item.item_focus_handle(cx).focus(window, cx);
4970 } else {
4971 log::error!(
4972 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4973 );
4974 }
4975 }
4976 Some(ActivateInDirectionTarget::Dock(dock)) => {
4977 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4978 window.defer(cx, move |window, cx| {
4979 let dock = dock.read(cx);
4980 if let Some(panel) = dock.active_panel() {
4981 panel.panel_focus_handle(cx).focus(window, cx);
4982 } else {
4983 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4984 }
4985 })
4986 }
4987 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4988 focus_handle.focus(window, cx);
4989 }
4990 None => {}
4991 }
4992 }
4993
4994 pub fn move_item_to_pane_in_direction(
4995 &mut self,
4996 action: &MoveItemToPaneInDirection,
4997 window: &mut Window,
4998 cx: &mut Context<Self>,
4999 ) {
5000 let destination = match self.find_pane_in_direction(action.direction, cx) {
5001 Some(destination) => destination,
5002 None => {
5003 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
5004 return;
5005 }
5006 let new_pane = self.add_pane(window, cx);
5007 self.center
5008 .split(&self.active_pane, &new_pane, action.direction, cx);
5009 new_pane
5010 }
5011 };
5012
5013 if action.clone {
5014 if self
5015 .active_pane
5016 .read(cx)
5017 .active_item()
5018 .is_some_and(|item| item.can_split(cx))
5019 {
5020 clone_active_item(
5021 self.database_id(),
5022 &self.active_pane,
5023 &destination,
5024 action.focus,
5025 window,
5026 cx,
5027 );
5028 return;
5029 }
5030 }
5031 move_active_item(
5032 &self.active_pane,
5033 &destination,
5034 action.focus,
5035 true,
5036 window,
5037 cx,
5038 );
5039 }
5040
5041 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
5042 self.center.bounding_box_for_pane(pane)
5043 }
5044
5045 pub fn find_pane_in_direction(
5046 &mut self,
5047 direction: SplitDirection,
5048 cx: &App,
5049 ) -> Option<Entity<Pane>> {
5050 self.center
5051 .find_pane_in_direction(&self.active_pane, direction, cx)
5052 .cloned()
5053 }
5054
5055 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
5056 if let Some(to) = self.find_pane_in_direction(direction, cx) {
5057 self.center.swap(&self.active_pane, &to, cx);
5058 cx.notify();
5059 }
5060 }
5061
5062 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
5063 if self
5064 .center
5065 .move_to_border(&self.active_pane, direction, cx)
5066 .unwrap()
5067 {
5068 cx.notify();
5069 }
5070 }
5071
5072 pub fn resize_pane(
5073 &mut self,
5074 axis: gpui::Axis,
5075 amount: Pixels,
5076 window: &mut Window,
5077 cx: &mut Context<Self>,
5078 ) {
5079 let docks = self.all_docks();
5080 let active_dock = docks
5081 .into_iter()
5082 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
5083
5084 if let Some(dock_entity) = active_dock {
5085 let dock = dock_entity.read(cx);
5086 let Some(panel_size) = self.dock_size(&dock, window, cx) else {
5087 return;
5088 };
5089 match dock.position() {
5090 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
5091 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
5092 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
5093 }
5094 } else {
5095 self.center
5096 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
5097 }
5098 cx.notify();
5099 }
5100
5101 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
5102 self.center.reset_pane_sizes(cx);
5103 cx.notify();
5104 }
5105
5106 fn handle_pane_focused(
5107 &mut self,
5108 pane: Entity<Pane>,
5109 window: &mut Window,
5110 cx: &mut Context<Self>,
5111 ) {
5112 // This is explicitly hoisted out of the following check for pane identity as
5113 // terminal panel panes are not registered as a center panes.
5114 self.status_bar.update(cx, |status_bar, cx| {
5115 status_bar.set_active_pane(&pane, window, cx);
5116 });
5117 if self.active_pane != pane {
5118 self.set_active_pane(&pane, window, cx);
5119 }
5120
5121 if self.last_active_center_pane.is_none() {
5122 self.last_active_center_pane = Some(pane.downgrade());
5123 }
5124
5125 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
5126 // This prevents the dock from closing when focus events fire during window activation.
5127 // We also preserve any dock whose active panel itself has focus — this covers
5128 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
5129 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
5130 let dock_read = dock.read(cx);
5131 if let Some(panel) = dock_read.active_panel() {
5132 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
5133 || panel.panel_focus_handle(cx).contains_focused(window, cx)
5134 {
5135 return Some(dock_read.position());
5136 }
5137 }
5138 None
5139 });
5140
5141 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
5142 if pane.read(cx).is_zoomed() {
5143 self.zoomed = Some(pane.downgrade().into());
5144 } else {
5145 self.zoomed = None;
5146 }
5147 self.zoomed_position = None;
5148 cx.emit(Event::ZoomChanged);
5149 self.update_active_view_for_followers(window, cx);
5150 pane.update(cx, |pane, _| {
5151 pane.track_alternate_file_items();
5152 });
5153
5154 cx.notify();
5155 }
5156
5157 fn set_active_pane(
5158 &mut self,
5159 pane: &Entity<Pane>,
5160 window: &mut Window,
5161 cx: &mut Context<Self>,
5162 ) {
5163 self.active_pane = pane.clone();
5164 self.active_item_path_changed(true, window, cx);
5165 self.last_active_center_pane = Some(pane.downgrade());
5166 }
5167
5168 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5169 self.update_active_view_for_followers(window, cx);
5170 }
5171
5172 fn handle_pane_event(
5173 &mut self,
5174 pane: &Entity<Pane>,
5175 event: &pane::Event,
5176 window: &mut Window,
5177 cx: &mut Context<Self>,
5178 ) {
5179 let mut serialize_workspace = true;
5180 match event {
5181 pane::Event::AddItem { item } => {
5182 item.added_to_pane(self, pane.clone(), window, cx);
5183 cx.emit(Event::ItemAdded {
5184 item: item.boxed_clone(),
5185 });
5186 }
5187 pane::Event::Split { direction, mode } => {
5188 match mode {
5189 SplitMode::ClonePane => {
5190 self.split_and_clone(pane.clone(), *direction, window, cx)
5191 .detach();
5192 }
5193 SplitMode::EmptyPane => {
5194 self.split_pane(pane.clone(), *direction, window, cx);
5195 }
5196 SplitMode::MovePane => {
5197 self.split_and_move(pane.clone(), *direction, window, cx);
5198 }
5199 };
5200 }
5201 pane::Event::JoinIntoNext => {
5202 self.join_pane_into_next(pane.clone(), window, cx);
5203 }
5204 pane::Event::JoinAll => {
5205 self.join_all_panes(window, cx);
5206 }
5207 pane::Event::Remove { focus_on_pane } => {
5208 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
5209 }
5210 pane::Event::ActivateItem {
5211 local,
5212 focus_changed,
5213 } => {
5214 window.invalidate_character_coordinates();
5215
5216 pane.update(cx, |pane, _| {
5217 pane.track_alternate_file_items();
5218 });
5219 if *local {
5220 self.unfollow_in_pane(pane, window, cx);
5221 }
5222 serialize_workspace = *focus_changed || pane != self.active_pane();
5223 if pane == self.active_pane() {
5224 self.active_item_path_changed(*focus_changed, window, cx);
5225 self.update_active_view_for_followers(window, cx);
5226 } else if *local {
5227 self.set_active_pane(pane, window, cx);
5228 }
5229 }
5230 pane::Event::UserSavedItem { item, save_intent } => {
5231 cx.emit(Event::UserSavedItem {
5232 pane: pane.downgrade(),
5233 item: item.boxed_clone(),
5234 save_intent: *save_intent,
5235 });
5236 serialize_workspace = false;
5237 }
5238 pane::Event::ChangeItemTitle => {
5239 if *pane == self.active_pane {
5240 self.active_item_path_changed(false, window, cx);
5241 }
5242 serialize_workspace = false;
5243 }
5244 pane::Event::RemovedItem { item } => {
5245 cx.emit(Event::ActiveItemChanged);
5246 self.update_window_edited(window, cx);
5247 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
5248 && entry.get().entity_id() == pane.entity_id()
5249 {
5250 entry.remove();
5251 }
5252 cx.emit(Event::ItemRemoved {
5253 item_id: item.item_id(),
5254 });
5255 }
5256 pane::Event::Focus => {
5257 window.invalidate_character_coordinates();
5258 self.handle_pane_focused(pane.clone(), window, cx);
5259 }
5260 pane::Event::ZoomIn => {
5261 if *pane == self.active_pane {
5262 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
5263 if pane.read(cx).has_focus(window, cx) {
5264 self.zoomed = Some(pane.downgrade().into());
5265 self.zoomed_position = None;
5266 cx.emit(Event::ZoomChanged);
5267 }
5268 cx.notify();
5269 }
5270 }
5271 pane::Event::ZoomOut => {
5272 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
5273 if self.zoomed_position.is_none() {
5274 self.zoomed = None;
5275 cx.emit(Event::ZoomChanged);
5276 }
5277 cx.notify();
5278 }
5279 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
5280 }
5281
5282 if serialize_workspace {
5283 self.serialize_workspace(window, cx);
5284 }
5285 }
5286
5287 pub fn unfollow_in_pane(
5288 &mut self,
5289 pane: &Entity<Pane>,
5290 window: &mut Window,
5291 cx: &mut Context<Workspace>,
5292 ) -> Option<CollaboratorId> {
5293 let leader_id = self.leader_for_pane(pane)?;
5294 self.unfollow(leader_id, window, cx);
5295 Some(leader_id)
5296 }
5297
5298 pub fn split_pane(
5299 &mut self,
5300 pane_to_split: Entity<Pane>,
5301 split_direction: SplitDirection,
5302 window: &mut Window,
5303 cx: &mut Context<Self>,
5304 ) -> Entity<Pane> {
5305 let new_pane = self.add_pane(window, cx);
5306 self.center
5307 .split(&pane_to_split, &new_pane, split_direction, cx);
5308 cx.notify();
5309 new_pane
5310 }
5311
5312 pub fn split_and_move(
5313 &mut self,
5314 pane: Entity<Pane>,
5315 direction: SplitDirection,
5316 window: &mut Window,
5317 cx: &mut Context<Self>,
5318 ) {
5319 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
5320 return;
5321 };
5322 let new_pane = self.add_pane(window, cx);
5323 new_pane.update(cx, |pane, cx| {
5324 pane.add_item(item, true, true, None, window, cx)
5325 });
5326 self.center.split(&pane, &new_pane, direction, cx);
5327 cx.notify();
5328 }
5329
5330 pub fn split_and_clone(
5331 &mut self,
5332 pane: Entity<Pane>,
5333 direction: SplitDirection,
5334 window: &mut Window,
5335 cx: &mut Context<Self>,
5336 ) -> Task<Option<Entity<Pane>>> {
5337 let Some(item) = pane.read(cx).active_item() else {
5338 return Task::ready(None);
5339 };
5340 if !item.can_split(cx) {
5341 return Task::ready(None);
5342 }
5343 let task = item.clone_on_split(self.database_id(), window, cx);
5344 cx.spawn_in(window, async move |this, cx| {
5345 if let Some(clone) = task.await {
5346 this.update_in(cx, |this, window, cx| {
5347 let new_pane = this.add_pane(window, cx);
5348 let nav_history = pane.read(cx).fork_nav_history();
5349 new_pane.update(cx, |pane, cx| {
5350 pane.set_nav_history(nav_history, cx);
5351 pane.add_item(clone, true, true, None, window, cx)
5352 });
5353 this.center.split(&pane, &new_pane, direction, cx);
5354 cx.notify();
5355 new_pane
5356 })
5357 .ok()
5358 } else {
5359 None
5360 }
5361 })
5362 }
5363
5364 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5365 let active_item = self.active_pane.read(cx).active_item();
5366 for pane in &self.panes {
5367 join_pane_into_active(&self.active_pane, pane, window, cx);
5368 }
5369 if let Some(active_item) = active_item {
5370 self.activate_item(active_item.as_ref(), true, true, window, cx);
5371 }
5372 cx.notify();
5373 }
5374
5375 pub fn join_pane_into_next(
5376 &mut self,
5377 pane: Entity<Pane>,
5378 window: &mut Window,
5379 cx: &mut Context<Self>,
5380 ) {
5381 let next_pane = self
5382 .find_pane_in_direction(SplitDirection::Right, cx)
5383 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5384 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5385 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5386 let Some(next_pane) = next_pane else {
5387 return;
5388 };
5389 move_all_items(&pane, &next_pane, window, cx);
5390 cx.notify();
5391 }
5392
5393 fn remove_pane(
5394 &mut self,
5395 pane: Entity<Pane>,
5396 focus_on: Option<Entity<Pane>>,
5397 window: &mut Window,
5398 cx: &mut Context<Self>,
5399 ) {
5400 if self.center.remove(&pane, cx).unwrap() {
5401 self.force_remove_pane(&pane, &focus_on, window, cx);
5402 self.unfollow_in_pane(&pane, window, cx);
5403 self.last_leaders_by_pane.remove(&pane.downgrade());
5404 for removed_item in pane.read(cx).items() {
5405 self.panes_by_item.remove(&removed_item.item_id());
5406 }
5407
5408 cx.notify();
5409 } else {
5410 self.active_item_path_changed(true, window, cx);
5411 }
5412 cx.emit(Event::PaneRemoved);
5413 }
5414
5415 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5416 &mut self.panes
5417 }
5418
5419 pub fn panes(&self) -> &[Entity<Pane>] {
5420 &self.panes
5421 }
5422
5423 pub fn active_pane(&self) -> &Entity<Pane> {
5424 &self.active_pane
5425 }
5426
5427 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5428 for dock in self.all_docks() {
5429 if dock.focus_handle(cx).contains_focused(window, cx)
5430 && let Some(pane) = dock
5431 .read(cx)
5432 .active_panel()
5433 .and_then(|panel| panel.pane(cx))
5434 {
5435 return pane;
5436 }
5437 }
5438 self.active_pane().clone()
5439 }
5440
5441 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5442 self.find_pane_in_direction(SplitDirection::Right, cx)
5443 .unwrap_or_else(|| {
5444 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5445 })
5446 }
5447
5448 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5449 self.pane_for_item_id(handle.item_id())
5450 }
5451
5452 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5453 let weak_pane = self.panes_by_item.get(&item_id)?;
5454 weak_pane.upgrade()
5455 }
5456
5457 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5458 self.panes
5459 .iter()
5460 .find(|pane| pane.entity_id() == entity_id)
5461 .cloned()
5462 }
5463
5464 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5465 self.follower_states.retain(|leader_id, state| {
5466 if *leader_id == CollaboratorId::PeerId(peer_id) {
5467 for item in state.items_by_leader_view_id.values() {
5468 item.view.set_leader_id(None, window, cx);
5469 }
5470 false
5471 } else {
5472 true
5473 }
5474 });
5475 cx.notify();
5476 }
5477
5478 pub fn start_following(
5479 &mut self,
5480 leader_id: impl Into<CollaboratorId>,
5481 window: &mut Window,
5482 cx: &mut Context<Self>,
5483 ) -> Option<Task<Result<()>>> {
5484 let leader_id = leader_id.into();
5485 let pane = self.active_pane().clone();
5486
5487 self.last_leaders_by_pane
5488 .insert(pane.downgrade(), leader_id);
5489 self.unfollow(leader_id, window, cx);
5490 self.unfollow_in_pane(&pane, window, cx);
5491 self.follower_states.insert(
5492 leader_id,
5493 FollowerState {
5494 center_pane: pane.clone(),
5495 dock_pane: None,
5496 active_view_id: None,
5497 items_by_leader_view_id: Default::default(),
5498 },
5499 );
5500 cx.notify();
5501
5502 match leader_id {
5503 CollaboratorId::PeerId(leader_peer_id) => {
5504 let room_id = self.active_call()?.room_id(cx)?;
5505 let project_id = self.project.read(cx).remote_id();
5506 let request = self.app_state.client.request(proto::Follow {
5507 room_id,
5508 project_id,
5509 leader_id: Some(leader_peer_id),
5510 });
5511
5512 Some(cx.spawn_in(window, async move |this, cx| {
5513 let response = request.await?;
5514 this.update(cx, |this, _| {
5515 let state = this
5516 .follower_states
5517 .get_mut(&leader_id)
5518 .context("following interrupted")?;
5519 state.active_view_id = response
5520 .active_view
5521 .as_ref()
5522 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5523 anyhow::Ok(())
5524 })??;
5525 if let Some(view) = response.active_view {
5526 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5527 }
5528 this.update_in(cx, |this, window, cx| {
5529 this.leader_updated(leader_id, window, cx)
5530 })?;
5531 Ok(())
5532 }))
5533 }
5534 CollaboratorId::Agent => {
5535 self.leader_updated(leader_id, window, cx)?;
5536 Some(Task::ready(Ok(())))
5537 }
5538 }
5539 }
5540
5541 pub fn follow_next_collaborator(
5542 &mut self,
5543 _: &FollowNextCollaborator,
5544 window: &mut Window,
5545 cx: &mut Context<Self>,
5546 ) {
5547 let collaborators = self.project.read(cx).collaborators();
5548 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5549 let mut collaborators = collaborators.keys().copied();
5550 for peer_id in collaborators.by_ref() {
5551 if CollaboratorId::PeerId(peer_id) == leader_id {
5552 break;
5553 }
5554 }
5555 collaborators.next().map(CollaboratorId::PeerId)
5556 } else if let Some(last_leader_id) =
5557 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5558 {
5559 match last_leader_id {
5560 CollaboratorId::PeerId(peer_id) => {
5561 if collaborators.contains_key(peer_id) {
5562 Some(*last_leader_id)
5563 } else {
5564 None
5565 }
5566 }
5567 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5568 }
5569 } else {
5570 None
5571 };
5572
5573 let pane = self.active_pane.clone();
5574 let Some(leader_id) = next_leader_id.or_else(|| {
5575 Some(CollaboratorId::PeerId(
5576 collaborators.keys().copied().next()?,
5577 ))
5578 }) else {
5579 return;
5580 };
5581 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5582 return;
5583 }
5584 if let Some(task) = self.start_following(leader_id, window, cx) {
5585 task.detach_and_log_err(cx)
5586 }
5587 }
5588
5589 pub fn follow(
5590 &mut self,
5591 leader_id: impl Into<CollaboratorId>,
5592 window: &mut Window,
5593 cx: &mut Context<Self>,
5594 ) {
5595 let leader_id = leader_id.into();
5596
5597 if let CollaboratorId::PeerId(peer_id) = leader_id {
5598 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5599 return;
5600 };
5601 let Some(remote_participant) =
5602 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5603 else {
5604 return;
5605 };
5606
5607 let project = self.project.read(cx);
5608
5609 let other_project_id = match remote_participant.location {
5610 ParticipantLocation::External => None,
5611 ParticipantLocation::UnsharedProject => None,
5612 ParticipantLocation::SharedProject { project_id } => {
5613 if Some(project_id) == project.remote_id() {
5614 None
5615 } else {
5616 Some(project_id)
5617 }
5618 }
5619 };
5620
5621 // if they are active in another project, follow there.
5622 if let Some(project_id) = other_project_id {
5623 let app_state = self.app_state.clone();
5624 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5625 .detach_and_prompt_err("Failed to join project", window, cx, |error, _, _| {
5626 Some(format!("{error:#}"))
5627 });
5628 }
5629 }
5630
5631 // if you're already following, find the right pane and focus it.
5632 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5633 window.focus(&follower_state.pane().focus_handle(cx), cx);
5634
5635 return;
5636 }
5637
5638 // Otherwise, follow.
5639 if let Some(task) = self.start_following(leader_id, window, cx) {
5640 task.detach_and_log_err(cx)
5641 }
5642 }
5643
5644 pub fn unfollow(
5645 &mut self,
5646 leader_id: impl Into<CollaboratorId>,
5647 window: &mut Window,
5648 cx: &mut Context<Self>,
5649 ) -> Option<()> {
5650 cx.notify();
5651
5652 let leader_id = leader_id.into();
5653 let state = self.follower_states.remove(&leader_id)?;
5654 for (_, item) in state.items_by_leader_view_id {
5655 item.view.set_leader_id(None, window, cx);
5656 }
5657
5658 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5659 let project_id = self.project.read(cx).remote_id();
5660 let room_id = self.active_call()?.room_id(cx)?;
5661 self.app_state
5662 .client
5663 .send(proto::Unfollow {
5664 room_id,
5665 project_id,
5666 leader_id: Some(leader_peer_id),
5667 })
5668 .log_err();
5669 }
5670
5671 Some(())
5672 }
5673
5674 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5675 self.follower_states.contains_key(&id.into())
5676 }
5677
5678 fn active_item_path_changed(
5679 &mut self,
5680 focus_changed: bool,
5681 window: &mut Window,
5682 cx: &mut Context<Self>,
5683 ) {
5684 cx.emit(Event::ActiveItemChanged);
5685 let active_entry = self.active_project_path(cx);
5686 self.project.update(cx, |project, cx| {
5687 project.set_active_path(active_entry.clone(), cx)
5688 });
5689
5690 if focus_changed && let Some(project_path) = &active_entry {
5691 let git_store_entity = self.project.read(cx).git_store().clone();
5692 git_store_entity.update(cx, |git_store, cx| {
5693 git_store.set_active_repo_for_path(project_path, cx);
5694 });
5695 }
5696
5697 self.update_window_title(window, cx);
5698 }
5699
5700 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5701 let project = self.project().read(cx);
5702 let mut title = String::new();
5703
5704 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5705 let name = {
5706 let settings_location = SettingsLocation {
5707 worktree_id: worktree.read(cx).id(),
5708 path: RelPath::empty(),
5709 };
5710
5711 let settings = WorktreeSettings::get(Some(settings_location), cx);
5712 match &settings.project_name {
5713 Some(name) => name.as_str(),
5714 None => worktree.read(cx).root_name_str(),
5715 }
5716 };
5717 if i > 0 {
5718 title.push_str(", ");
5719 }
5720 title.push_str(name);
5721 }
5722
5723 if title.is_empty() {
5724 title = "empty project".to_string();
5725 }
5726
5727 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5728 let filename = path.path.file_name().or_else(|| {
5729 Some(
5730 project
5731 .worktree_for_id(path.worktree_id, cx)?
5732 .read(cx)
5733 .root_name_str(),
5734 )
5735 });
5736
5737 if let Some(filename) = filename {
5738 title.push_str(" — ");
5739 title.push_str(filename.as_ref());
5740 }
5741 }
5742
5743 if project.is_via_collab() {
5744 title.push_str(" ↙");
5745 } else if project.is_shared() {
5746 title.push_str(" ↗");
5747 }
5748
5749 if let Some(last_title) = self.last_window_title.as_ref()
5750 && &title == last_title
5751 {
5752 return;
5753 }
5754 window.set_window_title(&title);
5755 SystemWindowTabController::update_tab_title(
5756 cx,
5757 window.window_handle().window_id(),
5758 SharedString::from(&title),
5759 );
5760 self.last_window_title = Some(title);
5761 }
5762
5763 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5764 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5765 if is_edited != self.window_edited {
5766 self.window_edited = is_edited;
5767 window.set_window_edited(self.window_edited)
5768 }
5769 }
5770
5771 fn update_item_dirty_state(
5772 &mut self,
5773 item: &dyn ItemHandle,
5774 window: &mut Window,
5775 cx: &mut App,
5776 ) {
5777 let is_dirty = item.is_dirty(cx);
5778 let item_id = item.item_id();
5779 let was_dirty = self.dirty_items.contains_key(&item_id);
5780 if is_dirty == was_dirty {
5781 return;
5782 }
5783 if was_dirty {
5784 self.dirty_items.remove(&item_id);
5785 self.update_window_edited(window, cx);
5786 return;
5787 }
5788
5789 let workspace = self.weak_handle();
5790 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5791 return;
5792 };
5793 let on_release_callback = Box::new(move |cx: &mut App| {
5794 window_handle
5795 .update(cx, |_, window, cx| {
5796 workspace
5797 .update(cx, |workspace, cx| {
5798 workspace.dirty_items.remove(&item_id);
5799 workspace.update_window_edited(window, cx)
5800 })
5801 .ok();
5802 })
5803 .ok();
5804 });
5805
5806 let s = item.on_release(cx, on_release_callback);
5807 self.dirty_items.insert(item_id, s);
5808 self.update_window_edited(window, cx);
5809 }
5810
5811 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5812 if self.notifications.is_empty() {
5813 None
5814 } else {
5815 Some(
5816 div()
5817 .absolute()
5818 .right_3()
5819 .bottom_3()
5820 .w_112()
5821 .h_full()
5822 .flex()
5823 .flex_col()
5824 .justify_end()
5825 .gap_2()
5826 .children(
5827 self.notifications
5828 .iter()
5829 .map(|(_, notification)| notification.clone().into_any()),
5830 ),
5831 )
5832 }
5833 }
5834
5835 // RPC handlers
5836
5837 fn active_view_for_follower(
5838 &self,
5839 follower_project_id: Option<u64>,
5840 window: &mut Window,
5841 cx: &mut Context<Self>,
5842 ) -> Option<proto::View> {
5843 let (item, panel_id) = self.active_item_for_followers(window, cx);
5844 let item = item?;
5845 let leader_id = self
5846 .pane_for(&*item)
5847 .and_then(|pane| self.leader_for_pane(&pane));
5848 let leader_peer_id = match leader_id {
5849 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5850 Some(CollaboratorId::Agent) | None => None,
5851 };
5852
5853 let item_handle = item.to_followable_item_handle(cx)?;
5854 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5855 let variant = item_handle.to_state_proto(window, cx)?;
5856
5857 if item_handle.is_project_item(window, cx)
5858 && (follower_project_id.is_none()
5859 || follower_project_id != self.project.read(cx).remote_id())
5860 {
5861 return None;
5862 }
5863
5864 Some(proto::View {
5865 id: id.to_proto(),
5866 leader_id: leader_peer_id,
5867 variant: Some(variant),
5868 panel_id: panel_id.map(|id| id as i32),
5869 })
5870 }
5871
5872 fn handle_follow(
5873 &mut self,
5874 follower_project_id: Option<u64>,
5875 window: &mut Window,
5876 cx: &mut Context<Self>,
5877 ) -> proto::FollowResponse {
5878 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5879
5880 cx.notify();
5881 proto::FollowResponse {
5882 views: active_view.iter().cloned().collect(),
5883 active_view,
5884 }
5885 }
5886
5887 fn handle_update_followers(
5888 &mut self,
5889 leader_id: PeerId,
5890 message: proto::UpdateFollowers,
5891 _window: &mut Window,
5892 _cx: &mut Context<Self>,
5893 ) {
5894 self.leader_updates_tx
5895 .unbounded_send((leader_id, message))
5896 .ok();
5897 }
5898
5899 async fn process_leader_update(
5900 this: &WeakEntity<Self>,
5901 leader_id: PeerId,
5902 update: proto::UpdateFollowers,
5903 cx: &mut AsyncWindowContext,
5904 ) -> Result<()> {
5905 match update.variant.context("invalid update")? {
5906 proto::update_followers::Variant::CreateView(view) => {
5907 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5908 let should_add_view = this.update(cx, |this, _| {
5909 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5910 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5911 } else {
5912 anyhow::Ok(false)
5913 }
5914 })??;
5915
5916 if should_add_view {
5917 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5918 }
5919 }
5920 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5921 let should_add_view = this.update(cx, |this, _| {
5922 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5923 state.active_view_id = update_active_view
5924 .view
5925 .as_ref()
5926 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5927
5928 if state.active_view_id.is_some_and(|view_id| {
5929 !state.items_by_leader_view_id.contains_key(&view_id)
5930 }) {
5931 anyhow::Ok(true)
5932 } else {
5933 anyhow::Ok(false)
5934 }
5935 } else {
5936 anyhow::Ok(false)
5937 }
5938 })??;
5939
5940 if should_add_view && let Some(view) = update_active_view.view {
5941 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5942 }
5943 }
5944 proto::update_followers::Variant::UpdateView(update_view) => {
5945 let variant = update_view.variant.context("missing update view variant")?;
5946 let id = update_view.id.context("missing update view id")?;
5947 let mut tasks = Vec::new();
5948 this.update_in(cx, |this, window, cx| {
5949 let project = this.project.clone();
5950 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5951 let view_id = ViewId::from_proto(id.clone())?;
5952 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5953 tasks.push(item.view.apply_update_proto(
5954 &project,
5955 variant.clone(),
5956 window,
5957 cx,
5958 ));
5959 }
5960 }
5961 anyhow::Ok(())
5962 })??;
5963 try_join_all(tasks).await.log_err();
5964 }
5965 }
5966 this.update_in(cx, |this, window, cx| {
5967 this.leader_updated(leader_id, window, cx)
5968 })?;
5969 Ok(())
5970 }
5971
5972 async fn add_view_from_leader(
5973 this: WeakEntity<Self>,
5974 leader_id: PeerId,
5975 view: &proto::View,
5976 cx: &mut AsyncWindowContext,
5977 ) -> Result<()> {
5978 let this = this.upgrade().context("workspace dropped")?;
5979
5980 let Some(id) = view.id.clone() else {
5981 anyhow::bail!("no id for view");
5982 };
5983 let id = ViewId::from_proto(id)?;
5984 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5985
5986 let pane = this.update(cx, |this, _cx| {
5987 let state = this
5988 .follower_states
5989 .get(&leader_id.into())
5990 .context("stopped following")?;
5991 anyhow::Ok(state.pane().clone())
5992 })?;
5993 let existing_item = pane.update_in(cx, |pane, window, cx| {
5994 let client = this.read(cx).client().clone();
5995 pane.items().find_map(|item| {
5996 let item = item.to_followable_item_handle(cx)?;
5997 if item.remote_id(&client, window, cx) == Some(id) {
5998 Some(item)
5999 } else {
6000 None
6001 }
6002 })
6003 })?;
6004 let item = if let Some(existing_item) = existing_item {
6005 existing_item
6006 } else {
6007 let variant = view.variant.clone();
6008 anyhow::ensure!(variant.is_some(), "missing view variant");
6009
6010 let task = cx.update(|window, cx| {
6011 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
6012 })?;
6013
6014 let Some(task) = task else {
6015 anyhow::bail!(
6016 "failed to construct view from leader (maybe from a different version of zed?)"
6017 );
6018 };
6019
6020 let mut new_item = task.await?;
6021 pane.update_in(cx, |pane, window, cx| {
6022 let mut item_to_remove = None;
6023 for (ix, item) in pane.items().enumerate() {
6024 if let Some(item) = item.to_followable_item_handle(cx) {
6025 match new_item.dedup(item.as_ref(), window, cx) {
6026 Some(item::Dedup::KeepExisting) => {
6027 new_item =
6028 item.boxed_clone().to_followable_item_handle(cx).unwrap();
6029 break;
6030 }
6031 Some(item::Dedup::ReplaceExisting) => {
6032 item_to_remove = Some((ix, item.item_id()));
6033 break;
6034 }
6035 None => {}
6036 }
6037 }
6038 }
6039
6040 if let Some((ix, id)) = item_to_remove {
6041 pane.remove_item(id, false, false, window, cx);
6042 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
6043 }
6044 })?;
6045
6046 new_item
6047 };
6048
6049 this.update_in(cx, |this, window, cx| {
6050 let state = this.follower_states.get_mut(&leader_id.into())?;
6051 item.set_leader_id(Some(leader_id.into()), window, cx);
6052 state.items_by_leader_view_id.insert(
6053 id,
6054 FollowerView {
6055 view: item,
6056 location: panel_id,
6057 },
6058 );
6059
6060 Some(())
6061 })
6062 .context("no follower state")?;
6063
6064 Ok(())
6065 }
6066
6067 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6068 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
6069 return;
6070 };
6071
6072 if let Some(agent_location) = self.project.read(cx).agent_location() {
6073 let buffer_entity_id = agent_location.buffer.entity_id();
6074 let view_id = ViewId {
6075 creator: CollaboratorId::Agent,
6076 id: buffer_entity_id.as_u64(),
6077 };
6078 follower_state.active_view_id = Some(view_id);
6079
6080 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
6081 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
6082 hash_map::Entry::Vacant(entry) => {
6083 let existing_view =
6084 follower_state
6085 .center_pane
6086 .read(cx)
6087 .items()
6088 .find_map(|item| {
6089 let item = item.to_followable_item_handle(cx)?;
6090 if item.buffer_kind(cx) == ItemBufferKind::Singleton
6091 && item.project_item_model_ids(cx).as_slice()
6092 == [buffer_entity_id]
6093 {
6094 Some(item)
6095 } else {
6096 None
6097 }
6098 });
6099 let view = existing_view.or_else(|| {
6100 agent_location.buffer.upgrade().and_then(|buffer| {
6101 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
6102 registry.build_item(buffer, self.project.clone(), None, window, cx)
6103 })?
6104 .to_followable_item_handle(cx)
6105 })
6106 });
6107
6108 view.map(|view| {
6109 entry.insert(FollowerView {
6110 view,
6111 location: None,
6112 })
6113 })
6114 }
6115 };
6116
6117 if let Some(item) = item {
6118 item.view
6119 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
6120 item.view
6121 .update_agent_location(agent_location.position, window, cx);
6122 }
6123 } else {
6124 follower_state.active_view_id = None;
6125 }
6126
6127 self.leader_updated(CollaboratorId::Agent, window, cx);
6128 }
6129
6130 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
6131 let mut is_project_item = true;
6132 let mut update = proto::UpdateActiveView::default();
6133 if window.is_window_active() {
6134 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
6135
6136 if let Some(item) = active_item
6137 && item.item_focus_handle(cx).contains_focused(window, cx)
6138 {
6139 let leader_id = self
6140 .pane_for(&*item)
6141 .and_then(|pane| self.leader_for_pane(&pane));
6142 let leader_peer_id = match leader_id {
6143 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
6144 Some(CollaboratorId::Agent) | None => None,
6145 };
6146
6147 if let Some(item) = item.to_followable_item_handle(cx) {
6148 let id = item
6149 .remote_id(&self.app_state.client, window, cx)
6150 .map(|id| id.to_proto());
6151
6152 if let Some(id) = id
6153 && let Some(variant) = item.to_state_proto(window, cx)
6154 {
6155 let view = Some(proto::View {
6156 id,
6157 leader_id: leader_peer_id,
6158 variant: Some(variant),
6159 panel_id: panel_id.map(|id| id as i32),
6160 });
6161
6162 is_project_item = item.is_project_item(window, cx);
6163 update = proto::UpdateActiveView { view };
6164 };
6165 }
6166 }
6167 }
6168
6169 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
6170 if active_view_id != self.last_active_view_id.as_ref() {
6171 self.last_active_view_id = active_view_id.cloned();
6172 self.update_followers(
6173 is_project_item,
6174 proto::update_followers::Variant::UpdateActiveView(update),
6175 window,
6176 cx,
6177 );
6178 }
6179 }
6180
6181 fn active_item_for_followers(
6182 &self,
6183 window: &mut Window,
6184 cx: &mut App,
6185 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
6186 let mut active_item = None;
6187 let mut panel_id = None;
6188 for dock in self.all_docks() {
6189 if dock.focus_handle(cx).contains_focused(window, cx)
6190 && let Some(panel) = dock.read(cx).active_panel()
6191 && let Some(pane) = panel.pane(cx)
6192 && let Some(item) = pane.read(cx).active_item()
6193 {
6194 active_item = Some(item);
6195 panel_id = panel.remote_id();
6196 break;
6197 }
6198 }
6199
6200 if active_item.is_none() {
6201 active_item = self.active_pane().read(cx).active_item();
6202 }
6203 (active_item, panel_id)
6204 }
6205
6206 fn update_followers(
6207 &self,
6208 project_only: bool,
6209 update: proto::update_followers::Variant,
6210 _: &mut Window,
6211 cx: &mut App,
6212 ) -> Option<()> {
6213 // If this update only applies to for followers in the current project,
6214 // then skip it unless this project is shared. If it applies to all
6215 // followers, regardless of project, then set `project_id` to none,
6216 // indicating that it goes to all followers.
6217 let project_id = if project_only {
6218 Some(self.project.read(cx).remote_id()?)
6219 } else {
6220 None
6221 };
6222 self.app_state().workspace_store.update(cx, |store, cx| {
6223 store.update_followers(project_id, update, cx)
6224 })
6225 }
6226
6227 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
6228 self.follower_states.iter().find_map(|(leader_id, state)| {
6229 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
6230 Some(*leader_id)
6231 } else {
6232 None
6233 }
6234 })
6235 }
6236
6237 fn leader_updated(
6238 &mut self,
6239 leader_id: impl Into<CollaboratorId>,
6240 window: &mut Window,
6241 cx: &mut Context<Self>,
6242 ) -> Option<Box<dyn ItemHandle>> {
6243 cx.notify();
6244
6245 let leader_id = leader_id.into();
6246 let (panel_id, item) = match leader_id {
6247 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
6248 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
6249 };
6250
6251 let state = self.follower_states.get(&leader_id)?;
6252 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
6253 let pane;
6254 if let Some(panel_id) = panel_id {
6255 pane = self
6256 .activate_panel_for_proto_id(panel_id, window, cx)?
6257 .pane(cx)?;
6258 let state = self.follower_states.get_mut(&leader_id)?;
6259 state.dock_pane = Some(pane.clone());
6260 } else {
6261 pane = state.center_pane.clone();
6262 let state = self.follower_states.get_mut(&leader_id)?;
6263 if let Some(dock_pane) = state.dock_pane.take() {
6264 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
6265 }
6266 }
6267
6268 pane.update(cx, |pane, cx| {
6269 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
6270 if let Some(index) = pane.index_for_item(item.as_ref()) {
6271 pane.activate_item(index, false, false, window, cx);
6272 } else {
6273 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
6274 }
6275
6276 if focus_active_item {
6277 pane.focus_active_item(window, cx)
6278 }
6279 });
6280
6281 Some(item)
6282 }
6283
6284 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
6285 let state = self.follower_states.get(&CollaboratorId::Agent)?;
6286 let active_view_id = state.active_view_id?;
6287 Some(
6288 state
6289 .items_by_leader_view_id
6290 .get(&active_view_id)?
6291 .view
6292 .boxed_clone(),
6293 )
6294 }
6295
6296 fn active_item_for_peer(
6297 &self,
6298 peer_id: PeerId,
6299 window: &mut Window,
6300 cx: &mut Context<Self>,
6301 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
6302 let call = self.active_call()?;
6303 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
6304 let leader_in_this_app;
6305 let leader_in_this_project;
6306 match participant.location {
6307 ParticipantLocation::SharedProject { project_id } => {
6308 leader_in_this_app = true;
6309 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
6310 }
6311 ParticipantLocation::UnsharedProject => {
6312 leader_in_this_app = true;
6313 leader_in_this_project = false;
6314 }
6315 ParticipantLocation::External => {
6316 leader_in_this_app = false;
6317 leader_in_this_project = false;
6318 }
6319 };
6320 let state = self.follower_states.get(&peer_id.into())?;
6321 let mut item_to_activate = None;
6322 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
6323 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
6324 && (leader_in_this_project || !item.view.is_project_item(window, cx))
6325 {
6326 item_to_activate = Some((item.location, item.view.boxed_clone()));
6327 }
6328 } else if let Some(shared_screen) =
6329 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
6330 {
6331 item_to_activate = Some((None, Box::new(shared_screen)));
6332 }
6333 item_to_activate
6334 }
6335
6336 fn shared_screen_for_peer(
6337 &self,
6338 peer_id: PeerId,
6339 pane: &Entity<Pane>,
6340 window: &mut Window,
6341 cx: &mut App,
6342 ) -> Option<Entity<SharedScreen>> {
6343 self.active_call()?
6344 .create_shared_screen(peer_id, pane, window, cx)
6345 }
6346
6347 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6348 if window.is_window_active() {
6349 self.update_active_view_for_followers(window, cx);
6350
6351 if let Some(database_id) = self.database_id {
6352 let db = WorkspaceDb::global(cx);
6353 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6354 .detach();
6355 }
6356 } else {
6357 for pane in &self.panes {
6358 pane.update(cx, |pane, cx| {
6359 if let Some(item) = pane.active_item() {
6360 item.workspace_deactivated(window, cx);
6361 }
6362 for item in pane.items() {
6363 if matches!(
6364 item.workspace_settings(cx).autosave,
6365 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6366 ) {
6367 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6368 .detach_and_log_err(cx);
6369 }
6370 }
6371 });
6372 }
6373 }
6374 }
6375
6376 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6377 self.active_call.as_ref().map(|(call, _)| &*call.0)
6378 }
6379
6380 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6381 self.active_call.as_ref().map(|(call, _)| call.clone())
6382 }
6383
6384 fn on_active_call_event(
6385 &mut self,
6386 event: &ActiveCallEvent,
6387 window: &mut Window,
6388 cx: &mut Context<Self>,
6389 ) {
6390 match event {
6391 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6392 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6393 self.leader_updated(participant_id, window, cx);
6394 }
6395 }
6396 }
6397
6398 pub fn database_id(&self) -> Option<WorkspaceId> {
6399 self.database_id
6400 }
6401
6402 #[cfg(any(test, feature = "test-support"))]
6403 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6404 self.database_id = Some(id);
6405 }
6406
6407 pub fn session_id(&self) -> Option<String> {
6408 self.session_id.clone()
6409 }
6410
6411 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6412 let Some(display) = window.display(cx) else {
6413 return Task::ready(());
6414 };
6415 let Ok(display_uuid) = display.uuid() else {
6416 return Task::ready(());
6417 };
6418
6419 let window_bounds = window.inner_window_bounds();
6420 let database_id = self.database_id;
6421 let has_paths = !self.root_paths(cx).is_empty();
6422 let db = WorkspaceDb::global(cx);
6423 let kvp = db::kvp::KeyValueStore::global(cx);
6424
6425 cx.background_executor().spawn(async move {
6426 if !has_paths {
6427 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6428 .await
6429 .log_err();
6430 }
6431 if let Some(database_id) = database_id {
6432 db.set_window_open_status(
6433 database_id,
6434 SerializedWindowBounds(window_bounds),
6435 display_uuid,
6436 )
6437 .await
6438 .log_err();
6439 } else {
6440 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6441 .await
6442 .log_err();
6443 }
6444 })
6445 }
6446
6447 /// Bypass the 200ms serialization throttle and write workspace state to
6448 /// the DB immediately. Returns a task the caller can await to ensure the
6449 /// write completes. Used by the quit handler so the most recent state
6450 /// isn't lost to a pending throttle timer when the process exits.
6451 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6452 self._schedule_serialize_workspace.take();
6453 self._serialize_workspace_task.take();
6454 self.bounds_save_task_queued.take();
6455
6456 let bounds_task = self.save_window_bounds(window, cx);
6457 let serialize_task = self.serialize_workspace_internal(window, cx);
6458 cx.spawn(async move |_| {
6459 bounds_task.await;
6460 serialize_task.await;
6461 })
6462 }
6463
6464 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6465 let project = self.project().read(cx);
6466 project
6467 .visible_worktrees(cx)
6468 .map(|worktree| worktree.read(cx).abs_path())
6469 .collect::<Vec<_>>()
6470 }
6471
6472 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6473 match member {
6474 Member::Axis(PaneAxis { members, .. }) => {
6475 for child in members.iter() {
6476 self.remove_panes(child.clone(), window, cx)
6477 }
6478 }
6479 Member::Pane(pane) => {
6480 self.force_remove_pane(&pane, &None, window, cx);
6481 }
6482 }
6483 }
6484
6485 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6486 self.session_id.take();
6487 self.serialize_workspace_internal(window, cx)
6488 }
6489
6490 fn force_remove_pane(
6491 &mut self,
6492 pane: &Entity<Pane>,
6493 focus_on: &Option<Entity<Pane>>,
6494 window: &mut Window,
6495 cx: &mut Context<Workspace>,
6496 ) {
6497 self.panes.retain(|p| p != pane);
6498 if let Some(focus_on) = focus_on {
6499 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6500 } else if self.active_pane() == pane {
6501 self.panes
6502 .last()
6503 .unwrap()
6504 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6505 }
6506 if self.last_active_center_pane == Some(pane.downgrade()) {
6507 self.last_active_center_pane = None;
6508 }
6509 cx.notify();
6510 }
6511
6512 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6513 if self._schedule_serialize_workspace.is_none() {
6514 self._schedule_serialize_workspace =
6515 Some(cx.spawn_in(window, async move |this, cx| {
6516 cx.background_executor()
6517 .timer(SERIALIZATION_THROTTLE_TIME)
6518 .await;
6519 this.update_in(cx, |this, window, cx| {
6520 this._serialize_workspace_task =
6521 Some(this.serialize_workspace_internal(window, cx));
6522 this._schedule_serialize_workspace.take();
6523 })
6524 .log_err();
6525 }));
6526 }
6527 }
6528
6529 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6530 let Some(database_id) = self.database_id() else {
6531 return Task::ready(());
6532 };
6533
6534 fn serialize_pane_handle(
6535 pane_handle: &Entity<Pane>,
6536 window: &mut Window,
6537 cx: &mut App,
6538 ) -> SerializedPane {
6539 let (items, active, pinned_count) = {
6540 let pane = pane_handle.read(cx);
6541 let active_item_id = pane.active_item().map(|item| item.item_id());
6542 (
6543 pane.items()
6544 .filter_map(|handle| {
6545 let handle = handle.to_serializable_item_handle(cx)?;
6546
6547 Some(SerializedItem {
6548 kind: Arc::from(handle.serialized_item_kind()),
6549 item_id: handle.item_id().as_u64(),
6550 active: Some(handle.item_id()) == active_item_id,
6551 preview: pane.is_active_preview_item(handle.item_id()),
6552 })
6553 })
6554 .collect::<Vec<_>>(),
6555 pane.has_focus(window, cx),
6556 pane.pinned_count(),
6557 )
6558 };
6559
6560 SerializedPane::new(items, active, pinned_count)
6561 }
6562
6563 fn build_serialized_pane_group(
6564 pane_group: &Member,
6565 window: &mut Window,
6566 cx: &mut App,
6567 ) -> SerializedPaneGroup {
6568 match pane_group {
6569 Member::Axis(PaneAxis {
6570 axis,
6571 members,
6572 flexes,
6573 bounding_boxes: _,
6574 }) => SerializedPaneGroup::Group {
6575 axis: SerializedAxis(*axis),
6576 children: members
6577 .iter()
6578 .map(|member| build_serialized_pane_group(member, window, cx))
6579 .collect::<Vec<_>>(),
6580 flexes: Some(flexes.lock().clone()),
6581 },
6582 Member::Pane(pane_handle) => {
6583 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6584 }
6585 }
6586 }
6587
6588 fn build_serialized_docks(
6589 this: &Workspace,
6590 window: &mut Window,
6591 cx: &mut App,
6592 ) -> DockStructure {
6593 this.capture_dock_state(window, cx)
6594 }
6595
6596 match self.workspace_location(cx) {
6597 WorkspaceLocation::Location(location, paths) => {
6598 let breakpoints = self.project.update(cx, |project, cx| {
6599 project
6600 .breakpoint_store()
6601 .read(cx)
6602 .all_source_breakpoints(cx)
6603 });
6604 let user_toolchains = self
6605 .project
6606 .read(cx)
6607 .user_toolchains(cx)
6608 .unwrap_or_default();
6609
6610 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6611 let docks = build_serialized_docks(self, window, cx);
6612 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6613
6614 let serialized_workspace = SerializedWorkspace {
6615 id: database_id,
6616 location,
6617 paths,
6618 center_group,
6619 window_bounds,
6620 display: Default::default(),
6621 docks,
6622 centered_layout: self.centered_layout,
6623 session_id: self.session_id.clone(),
6624 breakpoints,
6625 window_id: Some(window.window_handle().window_id().as_u64()),
6626 user_toolchains,
6627 };
6628
6629 let db = WorkspaceDb::global(cx);
6630 window.spawn(cx, async move |_| {
6631 db.save_workspace(serialized_workspace).await;
6632 })
6633 }
6634 WorkspaceLocation::DetachFromSession => {
6635 let window_bounds = SerializedWindowBounds(window.window_bounds());
6636 let display = window.display(cx).and_then(|d| d.uuid().ok());
6637 // Save dock state for empty local workspaces
6638 let docks = build_serialized_docks(self, window, cx);
6639 let db = WorkspaceDb::global(cx);
6640 let kvp = db::kvp::KeyValueStore::global(cx);
6641 window.spawn(cx, async move |_| {
6642 db.set_window_open_status(
6643 database_id,
6644 window_bounds,
6645 display.unwrap_or_default(),
6646 )
6647 .await
6648 .log_err();
6649 db.set_session_id(database_id, None).await.log_err();
6650 persistence::write_default_dock_state(&kvp, docks)
6651 .await
6652 .log_err();
6653 })
6654 }
6655 WorkspaceLocation::None => {
6656 // Save dock state for empty non-local workspaces
6657 let docks = build_serialized_docks(self, window, cx);
6658 let kvp = db::kvp::KeyValueStore::global(cx);
6659 window.spawn(cx, async move |_| {
6660 persistence::write_default_dock_state(&kvp, docks)
6661 .await
6662 .log_err();
6663 })
6664 }
6665 }
6666 }
6667
6668 fn has_any_items_open(&self, cx: &App) -> bool {
6669 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6670 }
6671
6672 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6673 let paths = PathList::new(&self.root_paths(cx));
6674 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6675 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6676 } else if self.project.read(cx).is_local() {
6677 if !paths.is_empty() || self.has_any_items_open(cx) {
6678 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6679 } else {
6680 WorkspaceLocation::DetachFromSession
6681 }
6682 } else {
6683 WorkspaceLocation::None
6684 }
6685 }
6686
6687 fn update_history(&self, cx: &mut App) {
6688 let Some(id) = self.database_id() else {
6689 return;
6690 };
6691 if !self.project.read(cx).is_local() {
6692 return;
6693 }
6694 if let Some(manager) = HistoryManager::global(cx) {
6695 let paths = PathList::new(&self.root_paths(cx));
6696 manager.update(cx, |this, cx| {
6697 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6698 });
6699 }
6700 }
6701
6702 async fn serialize_items(
6703 this: &WeakEntity<Self>,
6704 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6705 cx: &mut AsyncWindowContext,
6706 ) -> Result<()> {
6707 const CHUNK_SIZE: usize = 200;
6708
6709 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6710
6711 while let Some(items_received) = serializable_items.next().await {
6712 let unique_items =
6713 items_received
6714 .into_iter()
6715 .fold(HashMap::default(), |mut acc, item| {
6716 acc.entry(item.item_id()).or_insert(item);
6717 acc
6718 });
6719
6720 // We use into_iter() here so that the references to the items are moved into
6721 // the tasks and not kept alive while we're sleeping.
6722 for (_, item) in unique_items.into_iter() {
6723 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6724 item.serialize(workspace, false, window, cx)
6725 }) {
6726 cx.background_spawn(async move { task.await.log_err() })
6727 .detach();
6728 }
6729 }
6730
6731 cx.background_executor()
6732 .timer(SERIALIZATION_THROTTLE_TIME)
6733 .await;
6734 }
6735
6736 Ok(())
6737 }
6738
6739 pub(crate) fn enqueue_item_serialization(
6740 &mut self,
6741 item: Box<dyn SerializableItemHandle>,
6742 ) -> Result<()> {
6743 self.serializable_items_tx
6744 .unbounded_send(item)
6745 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6746 }
6747
6748 pub(crate) fn load_workspace(
6749 serialized_workspace: SerializedWorkspace,
6750 paths_to_open: Vec<Option<ProjectPath>>,
6751 window: &mut Window,
6752 cx: &mut Context<Workspace>,
6753 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6754 cx.spawn_in(window, async move |workspace, cx| {
6755 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6756
6757 let mut center_group = None;
6758 let mut center_items = None;
6759
6760 // Traverse the splits tree and add to things
6761 if let Some((group, active_pane, items)) = serialized_workspace
6762 .center_group
6763 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6764 .await
6765 {
6766 center_items = Some(items);
6767 center_group = Some((group, active_pane))
6768 }
6769
6770 let mut items_by_project_path = HashMap::default();
6771 let mut item_ids_by_kind = HashMap::default();
6772 let mut all_deserialized_items = Vec::default();
6773 cx.update(|_, cx| {
6774 for item in center_items.unwrap_or_default().into_iter().flatten() {
6775 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6776 item_ids_by_kind
6777 .entry(serializable_item_handle.serialized_item_kind())
6778 .or_insert(Vec::new())
6779 .push(item.item_id().as_u64() as ItemId);
6780 }
6781
6782 if let Some(project_path) = item.project_path(cx) {
6783 items_by_project_path.insert(project_path, item.clone());
6784 }
6785 all_deserialized_items.push(item);
6786 }
6787 })?;
6788
6789 let opened_items = paths_to_open
6790 .into_iter()
6791 .map(|path_to_open| {
6792 path_to_open
6793 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6794 })
6795 .collect::<Vec<_>>();
6796
6797 // Remove old panes from workspace panes list
6798 workspace.update_in(cx, |workspace, window, cx| {
6799 if let Some((center_group, active_pane)) = center_group {
6800 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6801
6802 // Swap workspace center group
6803 workspace.center = PaneGroup::with_root(center_group);
6804 workspace.center.set_is_center(true);
6805 workspace.center.mark_positions(cx);
6806
6807 if let Some(active_pane) = active_pane {
6808 workspace.set_active_pane(&active_pane, window, cx);
6809 cx.focus_self(window);
6810 } else {
6811 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6812 }
6813 }
6814
6815 let docks = serialized_workspace.docks;
6816
6817 for (dock, serialized_dock) in [
6818 (&mut workspace.right_dock, docks.right),
6819 (&mut workspace.left_dock, docks.left),
6820 (&mut workspace.bottom_dock, docks.bottom),
6821 ]
6822 .iter_mut()
6823 {
6824 dock.update(cx, |dock, cx| {
6825 dock.serialized_dock = Some(serialized_dock.clone());
6826 dock.restore_state(window, cx);
6827 });
6828 }
6829
6830 cx.notify();
6831 })?;
6832
6833 let _ = project
6834 .update(cx, |project, cx| {
6835 project
6836 .breakpoint_store()
6837 .update(cx, |breakpoint_store, cx| {
6838 breakpoint_store
6839 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6840 })
6841 })
6842 .await;
6843
6844 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6845 // after loading the items, we might have different items and in order to avoid
6846 // the database filling up, we delete items that haven't been loaded now.
6847 //
6848 // The items that have been loaded, have been saved after they've been added to the workspace.
6849 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6850 item_ids_by_kind
6851 .into_iter()
6852 .map(|(item_kind, loaded_items)| {
6853 SerializableItemRegistry::cleanup(
6854 item_kind,
6855 serialized_workspace.id,
6856 loaded_items,
6857 window,
6858 cx,
6859 )
6860 .log_err()
6861 })
6862 .collect::<Vec<_>>()
6863 })?;
6864
6865 futures::future::join_all(clean_up_tasks).await;
6866
6867 workspace
6868 .update_in(cx, |workspace, window, cx| {
6869 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6870 workspace.serialize_workspace_internal(window, cx).detach();
6871
6872 // Ensure that we mark the window as edited if we did load dirty items
6873 workspace.update_window_edited(window, cx);
6874 })
6875 .ok();
6876
6877 Ok(opened_items)
6878 })
6879 }
6880
6881 pub fn key_context(&self, cx: &App) -> KeyContext {
6882 let mut context = KeyContext::new_with_defaults();
6883 context.add("Workspace");
6884 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6885 if let Some(status) = self
6886 .debugger_provider
6887 .as_ref()
6888 .and_then(|provider| provider.active_thread_state(cx))
6889 {
6890 match status {
6891 ThreadStatus::Running | ThreadStatus::Stepping => {
6892 context.add("debugger_running");
6893 }
6894 ThreadStatus::Stopped => context.add("debugger_stopped"),
6895 ThreadStatus::Exited | ThreadStatus::Ended => {}
6896 }
6897 }
6898
6899 if self.left_dock.read(cx).is_open() {
6900 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6901 context.set("left_dock", active_panel.panel_key());
6902 }
6903 }
6904
6905 if self.right_dock.read(cx).is_open() {
6906 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6907 context.set("right_dock", active_panel.panel_key());
6908 }
6909 }
6910
6911 if self.bottom_dock.read(cx).is_open() {
6912 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6913 context.set("bottom_dock", active_panel.panel_key());
6914 }
6915 }
6916
6917 context
6918 }
6919
6920 /// Multiworkspace uses this to add workspace action handling to itself
6921 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6922 self.add_workspace_actions_listeners(div, window, cx)
6923 .on_action(cx.listener(
6924 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6925 for action in &action_sequence.0 {
6926 window.dispatch_action(action.boxed_clone(), cx);
6927 }
6928 },
6929 ))
6930 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6931 .on_action(cx.listener(Self::close_all_items_and_panes))
6932 .on_action(cx.listener(Self::close_item_in_all_panes))
6933 .on_action(cx.listener(Self::save_all))
6934 .on_action(cx.listener(Self::send_keystrokes))
6935 .on_action(cx.listener(Self::add_folder_to_project))
6936 .on_action(cx.listener(Self::follow_next_collaborator))
6937 .on_action(cx.listener(Self::activate_pane_at_index))
6938 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6939 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6940 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6941 .on_action(cx.listener(Self::toggle_theme_mode))
6942 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6943 let pane = workspace.active_pane().clone();
6944 workspace.unfollow_in_pane(&pane, window, cx);
6945 }))
6946 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6947 workspace
6948 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6949 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6950 }))
6951 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6952 workspace
6953 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6954 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6955 }))
6956 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6957 workspace
6958 .save_active_item(SaveIntent::SaveAs, window, cx)
6959 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6960 }))
6961 .on_action(
6962 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6963 workspace.activate_previous_pane(window, cx)
6964 }),
6965 )
6966 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6967 workspace.activate_next_pane(window, cx)
6968 }))
6969 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6970 workspace.activate_last_pane(window, cx)
6971 }))
6972 .on_action(
6973 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6974 workspace.activate_next_window(cx)
6975 }),
6976 )
6977 .on_action(
6978 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6979 workspace.activate_previous_window(cx)
6980 }),
6981 )
6982 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6983 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6984 }))
6985 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6986 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6987 }))
6988 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6989 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6990 }))
6991 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6992 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6993 }))
6994 .on_action(cx.listener(
6995 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6996 workspace.move_item_to_pane_in_direction(action, window, cx)
6997 },
6998 ))
6999 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
7000 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
7001 }))
7002 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
7003 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
7004 }))
7005 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
7006 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
7007 }))
7008 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
7009 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
7010 }))
7011 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
7012 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
7013 SplitDirection::Down,
7014 SplitDirection::Up,
7015 SplitDirection::Right,
7016 SplitDirection::Left,
7017 ];
7018 for dir in DIRECTION_PRIORITY {
7019 if workspace.find_pane_in_direction(dir, cx).is_some() {
7020 workspace.swap_pane_in_direction(dir, cx);
7021 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
7022 break;
7023 }
7024 }
7025 }))
7026 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
7027 workspace.move_pane_to_border(SplitDirection::Left, cx)
7028 }))
7029 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
7030 workspace.move_pane_to_border(SplitDirection::Right, cx)
7031 }))
7032 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
7033 workspace.move_pane_to_border(SplitDirection::Up, cx)
7034 }))
7035 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
7036 workspace.move_pane_to_border(SplitDirection::Down, cx)
7037 }))
7038 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
7039 this.toggle_dock(DockPosition::Left, window, cx);
7040 }))
7041 .on_action(cx.listener(
7042 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
7043 workspace.toggle_dock(DockPosition::Right, window, cx);
7044 },
7045 ))
7046 .on_action(cx.listener(
7047 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
7048 workspace.toggle_dock(DockPosition::Bottom, window, cx);
7049 },
7050 ))
7051 .on_action(cx.listener(
7052 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
7053 if !workspace.close_active_dock(window, cx) {
7054 cx.propagate();
7055 }
7056 },
7057 ))
7058 .on_action(
7059 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
7060 workspace.close_all_docks(window, cx);
7061 }),
7062 )
7063 .on_action(cx.listener(Self::toggle_all_docks))
7064 .on_action(cx.listener(
7065 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
7066 workspace.clear_all_notifications(cx);
7067 },
7068 ))
7069 .on_action(cx.listener(
7070 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
7071 workspace.clear_navigation_history(window, cx);
7072 },
7073 ))
7074 .on_action(cx.listener(
7075 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
7076 if let Some((notification_id, _)) = workspace.notifications.pop() {
7077 workspace.suppress_notification(¬ification_id, cx);
7078 }
7079 },
7080 ))
7081 .on_action(cx.listener(
7082 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
7083 workspace.show_worktree_trust_security_modal(true, window, cx);
7084 },
7085 ))
7086 .on_action(
7087 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
7088 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
7089 trusted_worktrees.update(cx, |trusted_worktrees, _| {
7090 trusted_worktrees.clear_trusted_paths()
7091 });
7092 let db = WorkspaceDb::global(cx);
7093 cx.spawn(async move |_, cx| {
7094 if db.clear_trusted_worktrees().await.log_err().is_some() {
7095 cx.update(|cx| reload(cx));
7096 }
7097 })
7098 .detach();
7099 }
7100 }),
7101 )
7102 .on_action(cx.listener(
7103 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
7104 workspace.reopen_closed_item(window, cx).detach();
7105 },
7106 ))
7107 .on_action(cx.listener(
7108 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
7109 for dock in workspace.all_docks() {
7110 if dock.focus_handle(cx).contains_focused(window, cx) {
7111 let panel = dock.read(cx).active_panel().cloned();
7112 if let Some(panel) = panel {
7113 dock.update(cx, |dock, cx| {
7114 dock.set_panel_size_state(
7115 panel.as_ref(),
7116 dock::PanelSizeState::default(),
7117 cx,
7118 );
7119 });
7120 }
7121 return;
7122 }
7123 }
7124 },
7125 ))
7126 .on_action(cx.listener(
7127 |workspace: &mut Workspace, _: &ResetOpenDocksSize, _window, cx| {
7128 for dock in workspace.all_docks() {
7129 let panel = dock.read(cx).visible_panel().cloned();
7130 if let Some(panel) = panel {
7131 dock.update(cx, |dock, cx| {
7132 dock.set_panel_size_state(
7133 panel.as_ref(),
7134 dock::PanelSizeState::default(),
7135 cx,
7136 );
7137 });
7138 }
7139 }
7140 },
7141 ))
7142 .on_action(cx.listener(
7143 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
7144 adjust_active_dock_size_by_px(
7145 px_with_ui_font_fallback(act.px, cx),
7146 workspace,
7147 window,
7148 cx,
7149 );
7150 },
7151 ))
7152 .on_action(cx.listener(
7153 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
7154 adjust_active_dock_size_by_px(
7155 px_with_ui_font_fallback(act.px, cx) * -1.,
7156 workspace,
7157 window,
7158 cx,
7159 );
7160 },
7161 ))
7162 .on_action(cx.listener(
7163 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
7164 adjust_open_docks_size_by_px(
7165 px_with_ui_font_fallback(act.px, cx),
7166 workspace,
7167 window,
7168 cx,
7169 );
7170 },
7171 ))
7172 .on_action(cx.listener(
7173 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
7174 adjust_open_docks_size_by_px(
7175 px_with_ui_font_fallback(act.px, cx) * -1.,
7176 workspace,
7177 window,
7178 cx,
7179 );
7180 },
7181 ))
7182 .on_action(cx.listener(Workspace::toggle_centered_layout))
7183 .on_action(cx.listener(
7184 |workspace: &mut Workspace, action: &pane::ActivateNextItem, window, cx| {
7185 if let Some(active_dock) = workspace.active_dock(window, cx) {
7186 let dock = active_dock.read(cx);
7187 if let Some(active_panel) = dock.active_panel() {
7188 if active_panel.pane(cx).is_none() {
7189 let mut recent_pane: Option<Entity<Pane>> = None;
7190 let mut recent_timestamp = 0;
7191 for pane_handle in workspace.panes() {
7192 let pane = pane_handle.read(cx);
7193 for entry in pane.activation_history() {
7194 if entry.timestamp > recent_timestamp {
7195 recent_timestamp = entry.timestamp;
7196 recent_pane = Some(pane_handle.clone());
7197 }
7198 }
7199 }
7200
7201 if let Some(pane) = recent_pane {
7202 let wrap_around = action.wrap_around;
7203 pane.update(cx, |pane, cx| {
7204 let current_index = pane.active_item_index();
7205 let items_len = pane.items_len();
7206 if items_len > 0 {
7207 let next_index = if current_index + 1 < items_len {
7208 current_index + 1
7209 } else if wrap_around {
7210 0
7211 } else {
7212 return;
7213 };
7214 pane.activate_item(
7215 next_index, false, false, window, cx,
7216 );
7217 }
7218 });
7219 return;
7220 }
7221 }
7222 }
7223 }
7224 cx.propagate();
7225 },
7226 ))
7227 .on_action(cx.listener(
7228 |workspace: &mut Workspace, action: &pane::ActivatePreviousItem, window, cx| {
7229 if let Some(active_dock) = workspace.active_dock(window, cx) {
7230 let dock = active_dock.read(cx);
7231 if let Some(active_panel) = dock.active_panel() {
7232 if active_panel.pane(cx).is_none() {
7233 let mut recent_pane: Option<Entity<Pane>> = None;
7234 let mut recent_timestamp = 0;
7235 for pane_handle in workspace.panes() {
7236 let pane = pane_handle.read(cx);
7237 for entry in pane.activation_history() {
7238 if entry.timestamp > recent_timestamp {
7239 recent_timestamp = entry.timestamp;
7240 recent_pane = Some(pane_handle.clone());
7241 }
7242 }
7243 }
7244
7245 if let Some(pane) = recent_pane {
7246 let wrap_around = action.wrap_around;
7247 pane.update(cx, |pane, cx| {
7248 let current_index = pane.active_item_index();
7249 let items_len = pane.items_len();
7250 if items_len > 0 {
7251 let prev_index = if current_index > 0 {
7252 current_index - 1
7253 } else if wrap_around {
7254 items_len.saturating_sub(1)
7255 } else {
7256 return;
7257 };
7258 pane.activate_item(
7259 prev_index, false, false, window, cx,
7260 );
7261 }
7262 });
7263 return;
7264 }
7265 }
7266 }
7267 }
7268 cx.propagate();
7269 },
7270 ))
7271 .on_action(cx.listener(
7272 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
7273 if let Some(active_dock) = workspace.active_dock(window, cx) {
7274 let dock = active_dock.read(cx);
7275 if let Some(active_panel) = dock.active_panel() {
7276 if active_panel.pane(cx).is_none() {
7277 let active_pane = workspace.active_pane().clone();
7278 active_pane.update(cx, |pane, cx| {
7279 pane.close_active_item(action, window, cx)
7280 .detach_and_log_err(cx);
7281 });
7282 return;
7283 }
7284 }
7285 }
7286 cx.propagate();
7287 },
7288 ))
7289 .on_action(
7290 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
7291 let pane = workspace.active_pane().clone();
7292 if let Some(item) = pane.read(cx).active_item() {
7293 item.toggle_read_only(window, cx);
7294 }
7295 }),
7296 )
7297 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
7298 workspace.focus_center_pane(window, cx);
7299 }))
7300 .on_action(cx.listener(Workspace::cancel))
7301 }
7302
7303 #[cfg(any(test, feature = "test-support"))]
7304 pub fn set_random_database_id(&mut self) {
7305 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
7306 }
7307
7308 #[cfg(any(test, feature = "test-support"))]
7309 pub(crate) fn test_new(
7310 project: Entity<Project>,
7311 window: &mut Window,
7312 cx: &mut Context<Self>,
7313 ) -> Self {
7314 use node_runtime::NodeRuntime;
7315 use session::Session;
7316
7317 let client = project.read(cx).client();
7318 let user_store = project.read(cx).user_store();
7319 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
7320 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
7321 window.activate_window();
7322 let app_state = Arc::new(AppState {
7323 languages: project.read(cx).languages().clone(),
7324 workspace_store,
7325 client,
7326 user_store,
7327 fs: project.read(cx).fs().clone(),
7328 build_window_options: |_, _| Default::default(),
7329 node_runtime: NodeRuntime::unavailable(),
7330 session,
7331 });
7332 let workspace = Self::new(Default::default(), project, app_state, window, cx);
7333 workspace
7334 .active_pane
7335 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
7336 workspace
7337 }
7338
7339 pub fn register_action<A: Action>(
7340 &mut self,
7341 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
7342 ) -> &mut Self {
7343 let callback = Arc::new(callback);
7344
7345 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
7346 let callback = callback.clone();
7347 div.on_action(cx.listener(move |workspace, event, window, cx| {
7348 (callback)(workspace, event, window, cx)
7349 }))
7350 }));
7351 self
7352 }
7353 pub fn register_action_renderer(
7354 &mut self,
7355 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
7356 ) -> &mut Self {
7357 self.workspace_actions.push(Box::new(callback));
7358 self
7359 }
7360
7361 fn add_workspace_actions_listeners(
7362 &self,
7363 mut div: Div,
7364 window: &mut Window,
7365 cx: &mut Context<Self>,
7366 ) -> Div {
7367 for action in self.workspace_actions.iter() {
7368 div = (action)(div, self, window, cx)
7369 }
7370 div
7371 }
7372
7373 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7374 self.modal_layer.read(cx).has_active_modal()
7375 }
7376
7377 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7378 self.modal_layer
7379 .read(cx)
7380 .is_active_modal_command_palette(cx)
7381 }
7382
7383 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7384 self.modal_layer.read(cx).active_modal()
7385 }
7386
7387 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7388 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7389 /// If no modal is active, the new modal will be shown.
7390 ///
7391 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7392 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7393 /// will not be shown.
7394 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7395 where
7396 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7397 {
7398 self.modal_layer.update(cx, |modal_layer, cx| {
7399 modal_layer.toggle_modal(window, cx, build)
7400 })
7401 }
7402
7403 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7404 self.modal_layer
7405 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7406 }
7407
7408 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7409 self.toast_layer
7410 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7411 }
7412
7413 pub fn toggle_centered_layout(
7414 &mut self,
7415 _: &ToggleCenteredLayout,
7416 _: &mut Window,
7417 cx: &mut Context<Self>,
7418 ) {
7419 self.centered_layout = !self.centered_layout;
7420 if let Some(database_id) = self.database_id() {
7421 let db = WorkspaceDb::global(cx);
7422 let centered_layout = self.centered_layout;
7423 cx.background_spawn(async move {
7424 db.set_centered_layout(database_id, centered_layout).await
7425 })
7426 .detach_and_log_err(cx);
7427 }
7428 cx.notify();
7429 }
7430
7431 fn adjust_padding(padding: Option<f32>) -> f32 {
7432 padding
7433 .unwrap_or(CenteredPaddingSettings::default().0)
7434 .clamp(
7435 CenteredPaddingSettings::MIN_PADDING,
7436 CenteredPaddingSettings::MAX_PADDING,
7437 )
7438 }
7439
7440 fn render_dock(
7441 &self,
7442 position: DockPosition,
7443 dock: &Entity<Dock>,
7444 window: &mut Window,
7445 cx: &mut App,
7446 ) -> Option<Div> {
7447 if self.zoomed_position == Some(position) {
7448 return None;
7449 }
7450
7451 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7452 let pane = panel.pane(cx)?;
7453 let follower_states = &self.follower_states;
7454 leader_border_for_pane(follower_states, &pane, window, cx)
7455 });
7456
7457 let mut container = div()
7458 .flex()
7459 .overflow_hidden()
7460 .flex_none()
7461 .child(dock.clone())
7462 .children(leader_border);
7463
7464 // Apply sizing only when the dock is open. When closed the dock is still
7465 // included in the element tree so its focus handle remains mounted — without
7466 // this, toggle_panel_focus cannot focus the panel when the dock is closed.
7467 let dock = dock.read(cx);
7468 if let Some(panel) = dock.visible_panel() {
7469 let size_state = dock.stored_panel_size_state(panel.as_ref());
7470 if position.axis() == Axis::Horizontal {
7471 let use_flexible = panel.has_flexible_size(window, cx);
7472 let flex_grow = if use_flexible {
7473 size_state
7474 .and_then(|state| state.flex)
7475 .or_else(|| self.default_dock_flex(position))
7476 } else {
7477 None
7478 };
7479 if let Some(grow) = flex_grow {
7480 let grow = grow.max(0.001);
7481 let style = container.style();
7482 style.flex_grow = Some(grow);
7483 style.flex_shrink = Some(1.0);
7484 style.flex_basis = Some(relative(0.).into());
7485 } else {
7486 let size = size_state
7487 .and_then(|state| state.size)
7488 .unwrap_or_else(|| panel.default_size(window, cx));
7489 container = container.w(size);
7490 }
7491 } else {
7492 let size = size_state
7493 .and_then(|state| state.size)
7494 .unwrap_or_else(|| panel.default_size(window, cx));
7495 container = container.h(size);
7496 }
7497 }
7498
7499 Some(container)
7500 }
7501
7502 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7503 window
7504 .root::<MultiWorkspace>()
7505 .flatten()
7506 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7507 }
7508
7509 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7510 self.zoomed.as_ref()
7511 }
7512
7513 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7514 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7515 return;
7516 };
7517 let windows = cx.windows();
7518 let next_window =
7519 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7520 || {
7521 windows
7522 .iter()
7523 .cycle()
7524 .skip_while(|window| window.window_id() != current_window_id)
7525 .nth(1)
7526 },
7527 );
7528
7529 if let Some(window) = next_window {
7530 window
7531 .update(cx, |_, window, _| window.activate_window())
7532 .ok();
7533 }
7534 }
7535
7536 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7537 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7538 return;
7539 };
7540 let windows = cx.windows();
7541 let prev_window =
7542 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7543 || {
7544 windows
7545 .iter()
7546 .rev()
7547 .cycle()
7548 .skip_while(|window| window.window_id() != current_window_id)
7549 .nth(1)
7550 },
7551 );
7552
7553 if let Some(window) = prev_window {
7554 window
7555 .update(cx, |_, window, _| window.activate_window())
7556 .ok();
7557 }
7558 }
7559
7560 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7561 if cx.stop_active_drag(window) {
7562 } else if let Some((notification_id, _)) = self.notifications.pop() {
7563 dismiss_app_notification(¬ification_id, cx);
7564 } else {
7565 cx.propagate();
7566 }
7567 }
7568
7569 fn resize_dock(
7570 &mut self,
7571 dock_pos: DockPosition,
7572 new_size: Pixels,
7573 window: &mut Window,
7574 cx: &mut Context<Self>,
7575 ) {
7576 match dock_pos {
7577 DockPosition::Left => self.resize_left_dock(new_size, window, cx),
7578 DockPosition::Right => self.resize_right_dock(new_size, window, cx),
7579 DockPosition::Bottom => self.resize_bottom_dock(new_size, window, cx),
7580 }
7581 }
7582
7583 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7584 let workspace_width = self.bounds.size.width;
7585 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7586
7587 self.right_dock.read_with(cx, |right_dock, cx| {
7588 let right_dock_size = right_dock
7589 .stored_active_panel_size(window, cx)
7590 .unwrap_or(Pixels::ZERO);
7591 if right_dock_size + size > workspace_width {
7592 size = workspace_width - right_dock_size
7593 }
7594 });
7595
7596 let flex_grow = self.dock_flex_for_size(DockPosition::Left, size, window, cx);
7597 self.left_dock.update(cx, |left_dock, cx| {
7598 if WorkspaceSettings::get_global(cx)
7599 .resize_all_panels_in_dock
7600 .contains(&DockPosition::Left)
7601 {
7602 left_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7603 } else {
7604 left_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7605 }
7606 });
7607 }
7608
7609 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7610 let workspace_width = self.bounds.size.width;
7611 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7612 self.left_dock.read_with(cx, |left_dock, cx| {
7613 let left_dock_size = left_dock
7614 .stored_active_panel_size(window, cx)
7615 .unwrap_or(Pixels::ZERO);
7616 if left_dock_size + size > workspace_width {
7617 size = workspace_width - left_dock_size
7618 }
7619 });
7620 let flex_grow = self.dock_flex_for_size(DockPosition::Right, size, window, cx);
7621 self.right_dock.update(cx, |right_dock, cx| {
7622 if WorkspaceSettings::get_global(cx)
7623 .resize_all_panels_in_dock
7624 .contains(&DockPosition::Right)
7625 {
7626 right_dock.resize_all_panels(Some(size), flex_grow, window, cx);
7627 } else {
7628 right_dock.resize_active_panel(Some(size), flex_grow, window, cx);
7629 }
7630 });
7631 }
7632
7633 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7634 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7635 self.bottom_dock.update(cx, |bottom_dock, cx| {
7636 if WorkspaceSettings::get_global(cx)
7637 .resize_all_panels_in_dock
7638 .contains(&DockPosition::Bottom)
7639 {
7640 bottom_dock.resize_all_panels(Some(size), None, window, cx);
7641 } else {
7642 bottom_dock.resize_active_panel(Some(size), None, window, cx);
7643 }
7644 });
7645 }
7646
7647 fn toggle_edit_predictions_all_files(
7648 &mut self,
7649 _: &ToggleEditPrediction,
7650 _window: &mut Window,
7651 cx: &mut Context<Self>,
7652 ) {
7653 let fs = self.project().read(cx).fs().clone();
7654 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7655 update_settings_file(fs, cx, move |file, _| {
7656 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7657 });
7658 }
7659
7660 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7661 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7662 let next_mode = match current_mode {
7663 Some(theme_settings::ThemeAppearanceMode::Light) => {
7664 theme_settings::ThemeAppearanceMode::Dark
7665 }
7666 Some(theme_settings::ThemeAppearanceMode::Dark) => {
7667 theme_settings::ThemeAppearanceMode::Light
7668 }
7669 Some(theme_settings::ThemeAppearanceMode::System) | None => {
7670 match cx.theme().appearance() {
7671 theme::Appearance::Light => theme_settings::ThemeAppearanceMode::Dark,
7672 theme::Appearance::Dark => theme_settings::ThemeAppearanceMode::Light,
7673 }
7674 }
7675 };
7676
7677 let fs = self.project().read(cx).fs().clone();
7678 settings::update_settings_file(fs, cx, move |settings, _cx| {
7679 theme_settings::set_mode(settings, next_mode);
7680 });
7681 }
7682
7683 pub fn show_worktree_trust_security_modal(
7684 &mut self,
7685 toggle: bool,
7686 window: &mut Window,
7687 cx: &mut Context<Self>,
7688 ) {
7689 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7690 if toggle {
7691 security_modal.update(cx, |security_modal, cx| {
7692 security_modal.dismiss(cx);
7693 })
7694 } else {
7695 security_modal.update(cx, |security_modal, cx| {
7696 security_modal.refresh_restricted_paths(cx);
7697 });
7698 }
7699 } else {
7700 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7701 .map(|trusted_worktrees| {
7702 trusted_worktrees
7703 .read(cx)
7704 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7705 })
7706 .unwrap_or(false);
7707 if has_restricted_worktrees {
7708 let project = self.project().read(cx);
7709 let remote_host = project
7710 .remote_connection_options(cx)
7711 .map(RemoteHostLocation::from);
7712 let worktree_store = project.worktree_store().downgrade();
7713 self.toggle_modal(window, cx, |_, cx| {
7714 SecurityModal::new(worktree_store, remote_host, cx)
7715 });
7716 }
7717 }
7718 }
7719}
7720
7721pub trait AnyActiveCall {
7722 fn entity(&self) -> AnyEntity;
7723 fn is_in_room(&self, _: &App) -> bool;
7724 fn room_id(&self, _: &App) -> Option<u64>;
7725 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7726 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7727 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7728 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7729 fn is_sharing_project(&self, _: &App) -> bool;
7730 fn has_remote_participants(&self, _: &App) -> bool;
7731 fn local_participant_is_guest(&self, _: &App) -> bool;
7732 fn client(&self, _: &App) -> Arc<Client>;
7733 fn share_on_join(&self, _: &App) -> bool;
7734 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7735 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7736 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7737 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7738 fn join_project(
7739 &self,
7740 _: u64,
7741 _: Arc<LanguageRegistry>,
7742 _: Arc<dyn Fs>,
7743 _: &mut App,
7744 ) -> Task<Result<Entity<Project>>>;
7745 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7746 fn subscribe(
7747 &self,
7748 _: &mut Window,
7749 _: &mut Context<Workspace>,
7750 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7751 ) -> Subscription;
7752 fn create_shared_screen(
7753 &self,
7754 _: PeerId,
7755 _: &Entity<Pane>,
7756 _: &mut Window,
7757 _: &mut App,
7758 ) -> Option<Entity<SharedScreen>>;
7759}
7760
7761#[derive(Clone)]
7762pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7763impl Global for GlobalAnyActiveCall {}
7764
7765impl GlobalAnyActiveCall {
7766 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7767 cx.try_global()
7768 }
7769
7770 pub(crate) fn global(cx: &App) -> &Self {
7771 cx.global()
7772 }
7773}
7774
7775/// Workspace-local view of a remote participant's location.
7776#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7777pub enum ParticipantLocation {
7778 SharedProject { project_id: u64 },
7779 UnsharedProject,
7780 External,
7781}
7782
7783impl ParticipantLocation {
7784 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7785 match location
7786 .and_then(|l| l.variant)
7787 .context("participant location was not provided")?
7788 {
7789 proto::participant_location::Variant::SharedProject(project) => {
7790 Ok(Self::SharedProject {
7791 project_id: project.id,
7792 })
7793 }
7794 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7795 proto::participant_location::Variant::External(_) => Ok(Self::External),
7796 }
7797 }
7798}
7799/// Workspace-local view of a remote collaborator's state.
7800/// This is the subset of `call::RemoteParticipant` that workspace needs.
7801#[derive(Clone)]
7802pub struct RemoteCollaborator {
7803 pub user: Arc<User>,
7804 pub peer_id: PeerId,
7805 pub location: ParticipantLocation,
7806 pub participant_index: ParticipantIndex,
7807}
7808
7809pub enum ActiveCallEvent {
7810 ParticipantLocationChanged { participant_id: PeerId },
7811 RemoteVideoTracksChanged { participant_id: PeerId },
7812}
7813
7814fn leader_border_for_pane(
7815 follower_states: &HashMap<CollaboratorId, FollowerState>,
7816 pane: &Entity<Pane>,
7817 _: &Window,
7818 cx: &App,
7819) -> Option<Div> {
7820 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7821 if state.pane() == pane {
7822 Some((*leader_id, state))
7823 } else {
7824 None
7825 }
7826 })?;
7827
7828 let mut leader_color = match leader_id {
7829 CollaboratorId::PeerId(leader_peer_id) => {
7830 let leader = GlobalAnyActiveCall::try_global(cx)?
7831 .0
7832 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7833
7834 cx.theme()
7835 .players()
7836 .color_for_participant(leader.participant_index.0)
7837 .cursor
7838 }
7839 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7840 };
7841 leader_color.fade_out(0.3);
7842 Some(
7843 div()
7844 .absolute()
7845 .size_full()
7846 .left_0()
7847 .top_0()
7848 .border_2()
7849 .border_color(leader_color),
7850 )
7851}
7852
7853fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7854 ZED_WINDOW_POSITION
7855 .zip(*ZED_WINDOW_SIZE)
7856 .map(|(position, size)| Bounds {
7857 origin: position,
7858 size,
7859 })
7860}
7861
7862fn open_items(
7863 serialized_workspace: Option<SerializedWorkspace>,
7864 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7865 window: &mut Window,
7866 cx: &mut Context<Workspace>,
7867) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7868 let restored_items = serialized_workspace.map(|serialized_workspace| {
7869 Workspace::load_workspace(
7870 serialized_workspace,
7871 project_paths_to_open
7872 .iter()
7873 .map(|(_, project_path)| project_path)
7874 .cloned()
7875 .collect(),
7876 window,
7877 cx,
7878 )
7879 });
7880
7881 cx.spawn_in(window, async move |workspace, cx| {
7882 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7883
7884 if let Some(restored_items) = restored_items {
7885 let restored_items = restored_items.await?;
7886
7887 let restored_project_paths = restored_items
7888 .iter()
7889 .filter_map(|item| {
7890 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7891 .ok()
7892 .flatten()
7893 })
7894 .collect::<HashSet<_>>();
7895
7896 for restored_item in restored_items {
7897 opened_items.push(restored_item.map(Ok));
7898 }
7899
7900 project_paths_to_open
7901 .iter_mut()
7902 .for_each(|(_, project_path)| {
7903 if let Some(project_path_to_open) = project_path
7904 && restored_project_paths.contains(project_path_to_open)
7905 {
7906 *project_path = None;
7907 }
7908 });
7909 } else {
7910 for _ in 0..project_paths_to_open.len() {
7911 opened_items.push(None);
7912 }
7913 }
7914 assert!(opened_items.len() == project_paths_to_open.len());
7915
7916 let tasks =
7917 project_paths_to_open
7918 .into_iter()
7919 .enumerate()
7920 .map(|(ix, (abs_path, project_path))| {
7921 let workspace = workspace.clone();
7922 cx.spawn(async move |cx| {
7923 let file_project_path = project_path?;
7924 let abs_path_task = workspace.update(cx, |workspace, cx| {
7925 workspace.project().update(cx, |project, cx| {
7926 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7927 })
7928 });
7929
7930 // We only want to open file paths here. If one of the items
7931 // here is a directory, it was already opened further above
7932 // with a `find_or_create_worktree`.
7933 if let Ok(task) = abs_path_task
7934 && task.await.is_none_or(|p| p.is_file())
7935 {
7936 return Some((
7937 ix,
7938 workspace
7939 .update_in(cx, |workspace, window, cx| {
7940 workspace.open_path(
7941 file_project_path,
7942 None,
7943 true,
7944 window,
7945 cx,
7946 )
7947 })
7948 .log_err()?
7949 .await,
7950 ));
7951 }
7952 None
7953 })
7954 });
7955
7956 let tasks = tasks.collect::<Vec<_>>();
7957
7958 let tasks = futures::future::join_all(tasks);
7959 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7960 opened_items[ix] = Some(path_open_result);
7961 }
7962
7963 Ok(opened_items)
7964 })
7965}
7966
7967#[derive(Clone)]
7968enum ActivateInDirectionTarget {
7969 Pane(Entity<Pane>),
7970 Dock(Entity<Dock>),
7971 Sidebar(FocusHandle),
7972}
7973
7974fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7975 window
7976 .update(cx, |multi_workspace, _, cx| {
7977 let workspace = multi_workspace.workspace().clone();
7978 workspace.update(cx, |workspace, cx| {
7979 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7980 struct DatabaseFailedNotification;
7981
7982 workspace.show_notification(
7983 NotificationId::unique::<DatabaseFailedNotification>(),
7984 cx,
7985 |cx| {
7986 cx.new(|cx| {
7987 MessageNotification::new("Failed to load the database file.", cx)
7988 .primary_message("File an Issue")
7989 .primary_icon(IconName::Plus)
7990 .primary_on_click(|window, cx| {
7991 window.dispatch_action(Box::new(FileBugReport), cx)
7992 })
7993 })
7994 },
7995 );
7996 }
7997 });
7998 })
7999 .log_err();
8000}
8001
8002fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
8003 if val == 0 {
8004 ThemeSettings::get_global(cx).ui_font_size(cx)
8005 } else {
8006 px(val as f32)
8007 }
8008}
8009
8010fn adjust_active_dock_size_by_px(
8011 px: Pixels,
8012 workspace: &mut Workspace,
8013 window: &mut Window,
8014 cx: &mut Context<Workspace>,
8015) {
8016 let Some(active_dock) = workspace
8017 .all_docks()
8018 .into_iter()
8019 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
8020 else {
8021 return;
8022 };
8023 let dock = active_dock.read(cx);
8024 let Some(panel_size) = workspace.dock_size(&dock, window, cx) else {
8025 return;
8026 };
8027 workspace.resize_dock(dock.position(), panel_size + px, window, cx);
8028}
8029
8030fn adjust_open_docks_size_by_px(
8031 px: Pixels,
8032 workspace: &mut Workspace,
8033 window: &mut Window,
8034 cx: &mut Context<Workspace>,
8035) {
8036 let docks = workspace
8037 .all_docks()
8038 .into_iter()
8039 .filter_map(|dock_entity| {
8040 let dock = dock_entity.read(cx);
8041 if dock.is_open() {
8042 let dock_pos = dock.position();
8043 let panel_size = workspace.dock_size(&dock, window, cx)?;
8044 Some((dock_pos, panel_size + px))
8045 } else {
8046 None
8047 }
8048 })
8049 .collect::<Vec<_>>();
8050
8051 for (position, new_size) in docks {
8052 workspace.resize_dock(position, new_size, window, cx);
8053 }
8054}
8055
8056impl Focusable for Workspace {
8057 fn focus_handle(&self, cx: &App) -> FocusHandle {
8058 self.active_pane.focus_handle(cx)
8059 }
8060}
8061
8062#[derive(Clone)]
8063struct DraggedDock(DockPosition);
8064
8065impl Render for DraggedDock {
8066 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8067 gpui::Empty
8068 }
8069}
8070
8071impl Render for Workspace {
8072 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8073 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
8074 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
8075 log::info!("Rendered first frame");
8076 }
8077
8078 let centered_layout = self.centered_layout
8079 && self.center.panes().len() == 1
8080 && self.active_item(cx).is_some();
8081 let render_padding = |size| {
8082 (size > 0.0).then(|| {
8083 div()
8084 .h_full()
8085 .w(relative(size))
8086 .bg(cx.theme().colors().editor_background)
8087 .border_color(cx.theme().colors().pane_group_border)
8088 })
8089 };
8090 let paddings = if centered_layout {
8091 let settings = WorkspaceSettings::get_global(cx).centered_layout;
8092 (
8093 render_padding(Self::adjust_padding(
8094 settings.left_padding.map(|padding| padding.0),
8095 )),
8096 render_padding(Self::adjust_padding(
8097 settings.right_padding.map(|padding| padding.0),
8098 )),
8099 )
8100 } else {
8101 (None, None)
8102 };
8103 let ui_font = theme_settings::setup_ui_font(window, cx);
8104
8105 let theme = cx.theme().clone();
8106 let colors = theme.colors();
8107 let notification_entities = self
8108 .notifications
8109 .iter()
8110 .map(|(_, notification)| notification.entity_id())
8111 .collect::<Vec<_>>();
8112 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
8113
8114 div()
8115 .relative()
8116 .size_full()
8117 .flex()
8118 .flex_col()
8119 .font(ui_font)
8120 .gap_0()
8121 .justify_start()
8122 .items_start()
8123 .text_color(colors.text)
8124 .overflow_hidden()
8125 .children(self.titlebar_item.clone())
8126 .on_modifiers_changed(move |_, _, cx| {
8127 for &id in ¬ification_entities {
8128 cx.notify(id);
8129 }
8130 })
8131 .child(
8132 div()
8133 .size_full()
8134 .relative()
8135 .flex_1()
8136 .flex()
8137 .flex_col()
8138 .child(
8139 div()
8140 .id("workspace")
8141 .bg(colors.background)
8142 .relative()
8143 .flex_1()
8144 .w_full()
8145 .flex()
8146 .flex_col()
8147 .overflow_hidden()
8148 .border_t_1()
8149 .border_b_1()
8150 .border_color(colors.border)
8151 .child({
8152 let this = cx.entity();
8153 canvas(
8154 move |bounds, window, cx| {
8155 this.update(cx, |this, cx| {
8156 let bounds_changed = this.bounds != bounds;
8157 this.bounds = bounds;
8158
8159 if bounds_changed {
8160 this.left_dock.update(cx, |dock, cx| {
8161 dock.clamp_panel_size(
8162 bounds.size.width,
8163 window,
8164 cx,
8165 )
8166 });
8167
8168 this.right_dock.update(cx, |dock, cx| {
8169 dock.clamp_panel_size(
8170 bounds.size.width,
8171 window,
8172 cx,
8173 )
8174 });
8175
8176 this.bottom_dock.update(cx, |dock, cx| {
8177 dock.clamp_panel_size(
8178 bounds.size.height,
8179 window,
8180 cx,
8181 )
8182 });
8183 }
8184 })
8185 },
8186 |_, _, _, _| {},
8187 )
8188 .absolute()
8189 .size_full()
8190 })
8191 .when(self.zoomed.is_none(), |this| {
8192 this.on_drag_move(cx.listener(
8193 move |workspace,
8194 e: &DragMoveEvent<DraggedDock>,
8195 window,
8196 cx| {
8197 if workspace.previous_dock_drag_coordinates
8198 != Some(e.event.position)
8199 {
8200 workspace.previous_dock_drag_coordinates =
8201 Some(e.event.position);
8202
8203 match e.drag(cx).0 {
8204 DockPosition::Left => {
8205 workspace.resize_left_dock(
8206 e.event.position.x
8207 - workspace.bounds.left(),
8208 window,
8209 cx,
8210 );
8211 }
8212 DockPosition::Right => {
8213 workspace.resize_right_dock(
8214 workspace.bounds.right()
8215 - e.event.position.x,
8216 window,
8217 cx,
8218 );
8219 }
8220 DockPosition::Bottom => {
8221 workspace.resize_bottom_dock(
8222 workspace.bounds.bottom()
8223 - e.event.position.y,
8224 window,
8225 cx,
8226 );
8227 }
8228 };
8229 workspace.serialize_workspace(window, cx);
8230 }
8231 },
8232 ))
8233
8234 })
8235 .child({
8236 match bottom_dock_layout {
8237 BottomDockLayout::Full => div()
8238 .flex()
8239 .flex_col()
8240 .h_full()
8241 .child(
8242 div()
8243 .flex()
8244 .flex_row()
8245 .flex_1()
8246 .overflow_hidden()
8247 .children(self.render_dock(
8248 DockPosition::Left,
8249 &self.left_dock,
8250 window,
8251 cx,
8252 ))
8253
8254 .child(
8255 div()
8256 .flex()
8257 .flex_col()
8258 .flex_1()
8259 .overflow_hidden()
8260 .child(
8261 h_flex()
8262 .flex_1()
8263 .when_some(
8264 paddings.0,
8265 |this, p| {
8266 this.child(
8267 p.border_r_1(),
8268 )
8269 },
8270 )
8271 .child(self.center.render(
8272 self.zoomed.as_ref(),
8273 &PaneRenderContext {
8274 follower_states:
8275 &self.follower_states,
8276 active_call: self.active_call(),
8277 active_pane: &self.active_pane,
8278 app_state: &self.app_state,
8279 project: &self.project,
8280 workspace: &self.weak_self,
8281 },
8282 window,
8283 cx,
8284 ))
8285 .when_some(
8286 paddings.1,
8287 |this, p| {
8288 this.child(
8289 p.border_l_1(),
8290 )
8291 },
8292 ),
8293 ),
8294 )
8295
8296 .children(self.render_dock(
8297 DockPosition::Right,
8298 &self.right_dock,
8299 window,
8300 cx,
8301 )),
8302 )
8303 .child(div().w_full().children(self.render_dock(
8304 DockPosition::Bottom,
8305 &self.bottom_dock,
8306 window,
8307 cx
8308 ))),
8309
8310 BottomDockLayout::LeftAligned => div()
8311 .flex()
8312 .flex_row()
8313 .h_full()
8314 .child(
8315 div()
8316 .flex()
8317 .flex_col()
8318 .flex_1()
8319 .h_full()
8320 .child(
8321 div()
8322 .flex()
8323 .flex_row()
8324 .flex_1()
8325 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
8326
8327 .child(
8328 div()
8329 .flex()
8330 .flex_col()
8331 .flex_1()
8332 .overflow_hidden()
8333 .child(
8334 h_flex()
8335 .flex_1()
8336 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8337 .child(self.center.render(
8338 self.zoomed.as_ref(),
8339 &PaneRenderContext {
8340 follower_states:
8341 &self.follower_states,
8342 active_call: self.active_call(),
8343 active_pane: &self.active_pane,
8344 app_state: &self.app_state,
8345 project: &self.project,
8346 workspace: &self.weak_self,
8347 },
8348 window,
8349 cx,
8350 ))
8351 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8352 )
8353 )
8354
8355 )
8356 .child(
8357 div()
8358 .w_full()
8359 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8360 ),
8361 )
8362 .children(self.render_dock(
8363 DockPosition::Right,
8364 &self.right_dock,
8365 window,
8366 cx,
8367 )),
8368 BottomDockLayout::RightAligned => div()
8369 .flex()
8370 .flex_row()
8371 .h_full()
8372 .children(self.render_dock(
8373 DockPosition::Left,
8374 &self.left_dock,
8375 window,
8376 cx,
8377 ))
8378
8379 .child(
8380 div()
8381 .flex()
8382 .flex_col()
8383 .flex_1()
8384 .h_full()
8385 .child(
8386 div()
8387 .flex()
8388 .flex_row()
8389 .flex_1()
8390 .child(
8391 div()
8392 .flex()
8393 .flex_col()
8394 .flex_1()
8395 .overflow_hidden()
8396 .child(
8397 h_flex()
8398 .flex_1()
8399 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
8400 .child(self.center.render(
8401 self.zoomed.as_ref(),
8402 &PaneRenderContext {
8403 follower_states:
8404 &self.follower_states,
8405 active_call: self.active_call(),
8406 active_pane: &self.active_pane,
8407 app_state: &self.app_state,
8408 project: &self.project,
8409 workspace: &self.weak_self,
8410 },
8411 window,
8412 cx,
8413 ))
8414 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8415 )
8416 )
8417
8418 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8419 )
8420 .child(
8421 div()
8422 .w_full()
8423 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8424 ),
8425 ),
8426 BottomDockLayout::Contained => div()
8427 .flex()
8428 .flex_row()
8429 .h_full()
8430 .children(self.render_dock(
8431 DockPosition::Left,
8432 &self.left_dock,
8433 window,
8434 cx,
8435 ))
8436
8437 .child(
8438 div()
8439 .flex()
8440 .flex_col()
8441 .flex_1()
8442 .overflow_hidden()
8443 .child(
8444 h_flex()
8445 .flex_1()
8446 .when_some(paddings.0, |this, p| {
8447 this.child(p.border_r_1())
8448 })
8449 .child(self.center.render(
8450 self.zoomed.as_ref(),
8451 &PaneRenderContext {
8452 follower_states:
8453 &self.follower_states,
8454 active_call: self.active_call(),
8455 active_pane: &self.active_pane,
8456 app_state: &self.app_state,
8457 project: &self.project,
8458 workspace: &self.weak_self,
8459 },
8460 window,
8461 cx,
8462 ))
8463 .when_some(paddings.1, |this, p| {
8464 this.child(p.border_l_1())
8465 }),
8466 )
8467 .children(self.render_dock(
8468 DockPosition::Bottom,
8469 &self.bottom_dock,
8470 window,
8471 cx,
8472 )),
8473 )
8474
8475 .children(self.render_dock(
8476 DockPosition::Right,
8477 &self.right_dock,
8478 window,
8479 cx,
8480 )),
8481 }
8482 })
8483 .children(self.zoomed.as_ref().and_then(|view| {
8484 let zoomed_view = view.upgrade()?;
8485 let div = div()
8486 .occlude()
8487 .absolute()
8488 .overflow_hidden()
8489 .border_color(colors.border)
8490 .bg(colors.background)
8491 .child(zoomed_view)
8492 .inset_0()
8493 .shadow_lg();
8494
8495 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8496 return Some(div);
8497 }
8498
8499 Some(match self.zoomed_position {
8500 Some(DockPosition::Left) => div.right_2().border_r_1(),
8501 Some(DockPosition::Right) => div.left_2().border_l_1(),
8502 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8503 None => {
8504 div.top_2().bottom_2().left_2().right_2().border_1()
8505 }
8506 })
8507 }))
8508 .children(self.render_notifications(window, cx)),
8509 )
8510 .when(self.status_bar_visible(cx), |parent| {
8511 parent.child(self.status_bar.clone())
8512 })
8513 .child(self.toast_layer.clone()),
8514 )
8515 }
8516}
8517
8518impl WorkspaceStore {
8519 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8520 Self {
8521 workspaces: Default::default(),
8522 _subscriptions: vec![
8523 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8524 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8525 ],
8526 client,
8527 }
8528 }
8529
8530 pub fn update_followers(
8531 &self,
8532 project_id: Option<u64>,
8533 update: proto::update_followers::Variant,
8534 cx: &App,
8535 ) -> Option<()> {
8536 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8537 let room_id = active_call.0.room_id(cx)?;
8538 self.client
8539 .send(proto::UpdateFollowers {
8540 room_id,
8541 project_id,
8542 variant: Some(update),
8543 })
8544 .log_err()
8545 }
8546
8547 pub async fn handle_follow(
8548 this: Entity<Self>,
8549 envelope: TypedEnvelope<proto::Follow>,
8550 mut cx: AsyncApp,
8551 ) -> Result<proto::FollowResponse> {
8552 this.update(&mut cx, |this, cx| {
8553 let follower = Follower {
8554 project_id: envelope.payload.project_id,
8555 peer_id: envelope.original_sender_id()?,
8556 };
8557
8558 let mut response = proto::FollowResponse::default();
8559
8560 this.workspaces.retain(|(window_handle, weak_workspace)| {
8561 let Some(workspace) = weak_workspace.upgrade() else {
8562 return false;
8563 };
8564 window_handle
8565 .update(cx, |_, window, cx| {
8566 workspace.update(cx, |workspace, cx| {
8567 let handler_response =
8568 workspace.handle_follow(follower.project_id, window, cx);
8569 if let Some(active_view) = handler_response.active_view
8570 && workspace.project.read(cx).remote_id() == follower.project_id
8571 {
8572 response.active_view = Some(active_view)
8573 }
8574 });
8575 })
8576 .is_ok()
8577 });
8578
8579 Ok(response)
8580 })
8581 }
8582
8583 async fn handle_update_followers(
8584 this: Entity<Self>,
8585 envelope: TypedEnvelope<proto::UpdateFollowers>,
8586 mut cx: AsyncApp,
8587 ) -> Result<()> {
8588 let leader_id = envelope.original_sender_id()?;
8589 let update = envelope.payload;
8590
8591 this.update(&mut cx, |this, cx| {
8592 this.workspaces.retain(|(window_handle, weak_workspace)| {
8593 let Some(workspace) = weak_workspace.upgrade() else {
8594 return false;
8595 };
8596 window_handle
8597 .update(cx, |_, window, cx| {
8598 workspace.update(cx, |workspace, cx| {
8599 let project_id = workspace.project.read(cx).remote_id();
8600 if update.project_id != project_id && update.project_id.is_some() {
8601 return;
8602 }
8603 workspace.handle_update_followers(
8604 leader_id,
8605 update.clone(),
8606 window,
8607 cx,
8608 );
8609 });
8610 })
8611 .is_ok()
8612 });
8613 Ok(())
8614 })
8615 }
8616
8617 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8618 self.workspaces.iter().map(|(_, weak)| weak)
8619 }
8620
8621 pub fn workspaces_with_windows(
8622 &self,
8623 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8624 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8625 }
8626}
8627
8628impl ViewId {
8629 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8630 Ok(Self {
8631 creator: message
8632 .creator
8633 .map(CollaboratorId::PeerId)
8634 .context("creator is missing")?,
8635 id: message.id,
8636 })
8637 }
8638
8639 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8640 if let CollaboratorId::PeerId(peer_id) = self.creator {
8641 Some(proto::ViewId {
8642 creator: Some(peer_id),
8643 id: self.id,
8644 })
8645 } else {
8646 None
8647 }
8648 }
8649}
8650
8651impl FollowerState {
8652 fn pane(&self) -> &Entity<Pane> {
8653 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8654 }
8655}
8656
8657pub trait WorkspaceHandle {
8658 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8659}
8660
8661impl WorkspaceHandle for Entity<Workspace> {
8662 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8663 self.read(cx)
8664 .worktrees(cx)
8665 .flat_map(|worktree| {
8666 let worktree_id = worktree.read(cx).id();
8667 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8668 worktree_id,
8669 path: f.path.clone(),
8670 })
8671 })
8672 .collect::<Vec<_>>()
8673 }
8674}
8675
8676pub async fn last_opened_workspace_location(
8677 db: &WorkspaceDb,
8678 fs: &dyn fs::Fs,
8679) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8680 db.last_workspace(fs)
8681 .await
8682 .log_err()
8683 .flatten()
8684 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8685}
8686
8687pub async fn last_session_workspace_locations(
8688 db: &WorkspaceDb,
8689 last_session_id: &str,
8690 last_session_window_stack: Option<Vec<WindowId>>,
8691 fs: &dyn fs::Fs,
8692) -> Option<Vec<SessionWorkspace>> {
8693 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8694 .await
8695 .log_err()
8696}
8697
8698pub async fn restore_multiworkspace(
8699 multi_workspace: SerializedMultiWorkspace,
8700 app_state: Arc<AppState>,
8701 cx: &mut AsyncApp,
8702) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8703 let SerializedMultiWorkspace {
8704 active_workspace,
8705 state,
8706 } = multi_workspace;
8707 let MultiWorkspaceState {
8708 sidebar_open,
8709 project_group_keys,
8710 sidebar_state,
8711 ..
8712 } = state;
8713
8714 let window_handle = if active_workspace.paths.is_empty() {
8715 cx.update(|cx| {
8716 open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx)
8717 })
8718 .await?
8719 } else {
8720 let OpenResult { window, .. } = cx
8721 .update(|cx| {
8722 Workspace::new_local(
8723 active_workspace.paths.paths().to_vec(),
8724 app_state.clone(),
8725 None,
8726 None,
8727 None,
8728 OpenMode::Activate,
8729 cx,
8730 )
8731 })
8732 .await?;
8733 window
8734 };
8735
8736 if !project_group_keys.is_empty() {
8737 let restored_keys: Vec<ProjectGroupKey> =
8738 project_group_keys.into_iter().map(Into::into).collect();
8739 window_handle
8740 .update(cx, |multi_workspace, _window, _cx| {
8741 multi_workspace.restore_project_group_keys(restored_keys);
8742 })
8743 .ok();
8744 }
8745
8746 if sidebar_open {
8747 window_handle
8748 .update(cx, |multi_workspace, _, cx| {
8749 multi_workspace.open_sidebar(cx);
8750 })
8751 .ok();
8752 }
8753
8754 if let Some(sidebar_state) = sidebar_state {
8755 window_handle
8756 .update(cx, |multi_workspace, window, cx| {
8757 if let Some(sidebar) = multi_workspace.sidebar() {
8758 sidebar.restore_serialized_state(&sidebar_state, window, cx);
8759 }
8760 multi_workspace.serialize(cx);
8761 })
8762 .ok();
8763 }
8764
8765 window_handle
8766 .update(cx, |_, window, _cx| {
8767 window.activate_window();
8768 })
8769 .ok();
8770
8771 Ok(window_handle)
8772}
8773
8774actions!(
8775 collab,
8776 [
8777 /// Opens the channel notes for the current call.
8778 ///
8779 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8780 /// channel in the collab panel.
8781 ///
8782 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8783 /// can be copied via "Copy link to section" in the context menu of the channel notes
8784 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8785 OpenChannelNotes,
8786 /// Mutes your microphone.
8787 Mute,
8788 /// Deafens yourself (mute both microphone and speakers).
8789 Deafen,
8790 /// Leaves the current call.
8791 LeaveCall,
8792 /// Shares the current project with collaborators.
8793 ShareProject,
8794 /// Shares your screen with collaborators.
8795 ScreenShare,
8796 /// Copies the current room name and session id for debugging purposes.
8797 CopyRoomId,
8798 ]
8799);
8800
8801/// Opens the channel notes for a specific channel by its ID.
8802#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8803#[action(namespace = collab)]
8804#[serde(deny_unknown_fields)]
8805pub struct OpenChannelNotesById {
8806 pub channel_id: u64,
8807}
8808
8809actions!(
8810 zed,
8811 [
8812 /// Opens the Zed log file.
8813 OpenLog,
8814 /// Reveals the Zed log file in the system file manager.
8815 RevealLogInFileManager
8816 ]
8817);
8818
8819async fn join_channel_internal(
8820 channel_id: ChannelId,
8821 app_state: &Arc<AppState>,
8822 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8823 requesting_workspace: Option<WeakEntity<Workspace>>,
8824 active_call: &dyn AnyActiveCall,
8825 cx: &mut AsyncApp,
8826) -> Result<bool> {
8827 let (should_prompt, already_in_channel) = cx.update(|cx| {
8828 if !active_call.is_in_room(cx) {
8829 return (false, false);
8830 }
8831
8832 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8833 let should_prompt = active_call.is_sharing_project(cx)
8834 && active_call.has_remote_participants(cx)
8835 && !already_in_channel;
8836 (should_prompt, already_in_channel)
8837 });
8838
8839 if already_in_channel {
8840 let task = cx.update(|cx| {
8841 if let Some((project, host)) = active_call.most_active_project(cx) {
8842 Some(join_in_room_project(project, host, app_state.clone(), cx))
8843 } else {
8844 None
8845 }
8846 });
8847 if let Some(task) = task {
8848 task.await?;
8849 }
8850 return anyhow::Ok(true);
8851 }
8852
8853 if should_prompt {
8854 if let Some(multi_workspace) = requesting_window {
8855 let answer = multi_workspace
8856 .update(cx, |_, window, cx| {
8857 window.prompt(
8858 PromptLevel::Warning,
8859 "Do you want to switch channels?",
8860 Some("Leaving this call will unshare your current project."),
8861 &["Yes, Join Channel", "Cancel"],
8862 cx,
8863 )
8864 })?
8865 .await;
8866
8867 if answer == Ok(1) {
8868 return Ok(false);
8869 }
8870 } else {
8871 return Ok(false);
8872 }
8873 }
8874
8875 let client = cx.update(|cx| active_call.client(cx));
8876
8877 let mut client_status = client.status();
8878
8879 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8880 'outer: loop {
8881 let Some(status) = client_status.recv().await else {
8882 anyhow::bail!("error connecting");
8883 };
8884
8885 match status {
8886 Status::Connecting
8887 | Status::Authenticating
8888 | Status::Authenticated
8889 | Status::Reconnecting
8890 | Status::Reauthenticating
8891 | Status::Reauthenticated => continue,
8892 Status::Connected { .. } => break 'outer,
8893 Status::SignedOut | Status::AuthenticationError => {
8894 return Err(ErrorCode::SignedOut.into());
8895 }
8896 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8897 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8898 return Err(ErrorCode::Disconnected.into());
8899 }
8900 }
8901 }
8902
8903 let joined = cx
8904 .update(|cx| active_call.join_channel(channel_id, cx))
8905 .await?;
8906
8907 if !joined {
8908 return anyhow::Ok(true);
8909 }
8910
8911 cx.update(|cx| active_call.room_update_completed(cx)).await;
8912
8913 let task = cx.update(|cx| {
8914 if let Some((project, host)) = active_call.most_active_project(cx) {
8915 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8916 }
8917
8918 // If you are the first to join a channel, see if you should share your project.
8919 if !active_call.has_remote_participants(cx)
8920 && !active_call.local_participant_is_guest(cx)
8921 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8922 {
8923 let project = workspace.update(cx, |workspace, cx| {
8924 let project = workspace.project.read(cx);
8925
8926 if !active_call.share_on_join(cx) {
8927 return None;
8928 }
8929
8930 if (project.is_local() || project.is_via_remote_server())
8931 && project.visible_worktrees(cx).any(|tree| {
8932 tree.read(cx)
8933 .root_entry()
8934 .is_some_and(|entry| entry.is_dir())
8935 })
8936 {
8937 Some(workspace.project.clone())
8938 } else {
8939 None
8940 }
8941 });
8942 if let Some(project) = project {
8943 let share_task = active_call.share_project(project, cx);
8944 return Some(cx.spawn(async move |_cx| -> Result<()> {
8945 share_task.await?;
8946 Ok(())
8947 }));
8948 }
8949 }
8950
8951 None
8952 });
8953 if let Some(task) = task {
8954 task.await?;
8955 return anyhow::Ok(true);
8956 }
8957 anyhow::Ok(false)
8958}
8959
8960pub fn join_channel(
8961 channel_id: ChannelId,
8962 app_state: Arc<AppState>,
8963 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8964 requesting_workspace: Option<WeakEntity<Workspace>>,
8965 cx: &mut App,
8966) -> Task<Result<()>> {
8967 let active_call = GlobalAnyActiveCall::global(cx).clone();
8968 cx.spawn(async move |cx| {
8969 let result = join_channel_internal(
8970 channel_id,
8971 &app_state,
8972 requesting_window,
8973 requesting_workspace,
8974 &*active_call.0,
8975 cx,
8976 )
8977 .await;
8978
8979 // join channel succeeded, and opened a window
8980 if matches!(result, Ok(true)) {
8981 return anyhow::Ok(());
8982 }
8983
8984 // find an existing workspace to focus and show call controls
8985 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8986 if active_window.is_none() {
8987 // no open workspaces, make one to show the error in (blergh)
8988 let OpenResult {
8989 window: window_handle,
8990 ..
8991 } = cx
8992 .update(|cx| {
8993 Workspace::new_local(
8994 vec![],
8995 app_state.clone(),
8996 requesting_window,
8997 None,
8998 None,
8999 OpenMode::Activate,
9000 cx,
9001 )
9002 })
9003 .await?;
9004
9005 window_handle
9006 .update(cx, |_, window, _cx| {
9007 window.activate_window();
9008 })
9009 .ok();
9010
9011 if result.is_ok() {
9012 cx.update(|cx| {
9013 cx.dispatch_action(&OpenChannelNotes);
9014 });
9015 }
9016
9017 active_window = Some(window_handle);
9018 }
9019
9020 if let Err(err) = result {
9021 log::error!("failed to join channel: {}", err);
9022 if let Some(active_window) = active_window {
9023 active_window
9024 .update(cx, |_, window, cx| {
9025 let detail: SharedString = match err.error_code() {
9026 ErrorCode::SignedOut => "Please sign in to continue.".into(),
9027 ErrorCode::UpgradeRequired => concat!(
9028 "Your are running an unsupported version of Zed. ",
9029 "Please update to continue."
9030 )
9031 .into(),
9032 ErrorCode::NoSuchChannel => concat!(
9033 "No matching channel was found. ",
9034 "Please check the link and try again."
9035 )
9036 .into(),
9037 ErrorCode::Forbidden => concat!(
9038 "This channel is private, and you do not have access. ",
9039 "Please ask someone to add you and try again."
9040 )
9041 .into(),
9042 ErrorCode::Disconnected => {
9043 "Please check your internet connection and try again.".into()
9044 }
9045 _ => format!("{}\n\nPlease try again.", err).into(),
9046 };
9047 window.prompt(
9048 PromptLevel::Critical,
9049 "Failed to join channel",
9050 Some(&detail),
9051 &["Ok"],
9052 cx,
9053 )
9054 })?
9055 .await
9056 .ok();
9057 }
9058 }
9059
9060 // return ok, we showed the error to the user.
9061 anyhow::Ok(())
9062 })
9063}
9064
9065pub async fn get_any_active_multi_workspace(
9066 app_state: Arc<AppState>,
9067 mut cx: AsyncApp,
9068) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
9069 // find an existing workspace to focus and show call controls
9070 let active_window = activate_any_workspace_window(&mut cx);
9071 if active_window.is_none() {
9072 cx.update(|cx| {
9073 Workspace::new_local(
9074 vec![],
9075 app_state.clone(),
9076 None,
9077 None,
9078 None,
9079 OpenMode::Activate,
9080 cx,
9081 )
9082 })
9083 .await?;
9084 }
9085 activate_any_workspace_window(&mut cx).context("could not open zed")
9086}
9087
9088fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
9089 cx.update(|cx| {
9090 if let Some(workspace_window) = cx
9091 .active_window()
9092 .and_then(|window| window.downcast::<MultiWorkspace>())
9093 {
9094 return Some(workspace_window);
9095 }
9096
9097 for window in cx.windows() {
9098 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
9099 workspace_window
9100 .update(cx, |_, window, _| window.activate_window())
9101 .ok();
9102 return Some(workspace_window);
9103 }
9104 }
9105 None
9106 })
9107}
9108
9109pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
9110 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
9111}
9112
9113pub fn workspace_windows_for_location(
9114 serialized_location: &SerializedWorkspaceLocation,
9115 cx: &App,
9116) -> Vec<WindowHandle<MultiWorkspace>> {
9117 cx.windows()
9118 .into_iter()
9119 .filter_map(|window| window.downcast::<MultiWorkspace>())
9120 .filter(|multi_workspace| {
9121 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
9122 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
9123 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
9124 }
9125 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
9126 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
9127 a.distro_name == b.distro_name
9128 }
9129 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
9130 a.container_id == b.container_id
9131 }
9132 #[cfg(any(test, feature = "test-support"))]
9133 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
9134 a.id == b.id
9135 }
9136 _ => false,
9137 };
9138
9139 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
9140 multi_workspace.workspaces().any(|workspace| {
9141 match workspace.read(cx).workspace_location(cx) {
9142 WorkspaceLocation::Location(location, _) => {
9143 match (&location, serialized_location) {
9144 (
9145 SerializedWorkspaceLocation::Local,
9146 SerializedWorkspaceLocation::Local,
9147 ) => true,
9148 (
9149 SerializedWorkspaceLocation::Remote(a),
9150 SerializedWorkspaceLocation::Remote(b),
9151 ) => same_host(a, b),
9152 _ => false,
9153 }
9154 }
9155 _ => false,
9156 }
9157 })
9158 })
9159 })
9160 .collect()
9161}
9162
9163pub async fn find_existing_workspace(
9164 abs_paths: &[PathBuf],
9165 open_options: &OpenOptions,
9166 location: &SerializedWorkspaceLocation,
9167 cx: &mut AsyncApp,
9168) -> (
9169 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
9170 OpenVisible,
9171) {
9172 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
9173 let mut open_visible = OpenVisible::All;
9174 let mut best_match = None;
9175
9176 if open_options.open_new_workspace != Some(true) {
9177 cx.update(|cx| {
9178 for window in workspace_windows_for_location(location, cx) {
9179 if let Ok(multi_workspace) = window.read(cx) {
9180 for workspace in multi_workspace.workspaces() {
9181 let project = workspace.read(cx).project.read(cx);
9182 let m = project.visibility_for_paths(
9183 abs_paths,
9184 open_options.open_new_workspace == None,
9185 cx,
9186 );
9187 if m > best_match {
9188 existing = Some((window, workspace.clone()));
9189 best_match = m;
9190 } else if best_match.is_none()
9191 && open_options.open_new_workspace == Some(false)
9192 {
9193 existing = Some((window, workspace.clone()))
9194 }
9195 }
9196 }
9197 }
9198 });
9199
9200 let all_paths_are_files = existing
9201 .as_ref()
9202 .and_then(|(_, target_workspace)| {
9203 cx.update(|cx| {
9204 let workspace = target_workspace.read(cx);
9205 let project = workspace.project.read(cx);
9206 let path_style = workspace.path_style(cx);
9207 Some(!abs_paths.iter().any(|path| {
9208 let path = util::paths::SanitizedPath::new(path);
9209 project.worktrees(cx).any(|worktree| {
9210 let worktree = worktree.read(cx);
9211 let abs_path = worktree.abs_path();
9212 path_style
9213 .strip_prefix(path.as_ref(), abs_path.as_ref())
9214 .and_then(|rel| worktree.entry_for_path(&rel))
9215 .is_some_and(|e| e.is_dir())
9216 })
9217 }))
9218 })
9219 })
9220 .unwrap_or(false);
9221
9222 if open_options.open_new_workspace.is_none()
9223 && existing.is_some()
9224 && open_options.wait
9225 && all_paths_are_files
9226 {
9227 cx.update(|cx| {
9228 let windows = workspace_windows_for_location(location, cx);
9229 let window = cx
9230 .active_window()
9231 .and_then(|window| window.downcast::<MultiWorkspace>())
9232 .filter(|window| windows.contains(window))
9233 .or_else(|| windows.into_iter().next());
9234 if let Some(window) = window {
9235 if let Ok(multi_workspace) = window.read(cx) {
9236 let active_workspace = multi_workspace.workspace().clone();
9237 existing = Some((window, active_workspace));
9238 open_visible = OpenVisible::None;
9239 }
9240 }
9241 });
9242 }
9243 }
9244 (existing, open_visible)
9245}
9246
9247#[derive(Default, Clone)]
9248pub struct OpenOptions {
9249 pub visible: Option<OpenVisible>,
9250 pub focus: Option<bool>,
9251 pub open_new_workspace: Option<bool>,
9252 pub wait: bool,
9253 pub requesting_window: Option<WindowHandle<MultiWorkspace>>,
9254 pub open_mode: OpenMode,
9255 pub env: Option<HashMap<String, String>>,
9256 pub open_in_dev_container: bool,
9257}
9258
9259/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
9260/// or [`Workspace::open_workspace_for_paths`].
9261pub struct OpenResult {
9262 pub window: WindowHandle<MultiWorkspace>,
9263 pub workspace: Entity<Workspace>,
9264 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
9265}
9266
9267/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
9268pub fn open_workspace_by_id(
9269 workspace_id: WorkspaceId,
9270 app_state: Arc<AppState>,
9271 requesting_window: Option<WindowHandle<MultiWorkspace>>,
9272 cx: &mut App,
9273) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
9274 let project_handle = Project::local(
9275 app_state.client.clone(),
9276 app_state.node_runtime.clone(),
9277 app_state.user_store.clone(),
9278 app_state.languages.clone(),
9279 app_state.fs.clone(),
9280 None,
9281 project::LocalProjectFlags {
9282 init_worktree_trust: true,
9283 ..project::LocalProjectFlags::default()
9284 },
9285 cx,
9286 );
9287
9288 let db = WorkspaceDb::global(cx);
9289 let kvp = db::kvp::KeyValueStore::global(cx);
9290 cx.spawn(async move |cx| {
9291 let serialized_workspace = db
9292 .workspace_for_id(workspace_id)
9293 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
9294
9295 let centered_layout = serialized_workspace.centered_layout;
9296
9297 let (window, workspace) = if let Some(window) = requesting_window {
9298 let workspace = window.update(cx, |multi_workspace, window, cx| {
9299 let workspace = cx.new(|cx| {
9300 let mut workspace = Workspace::new(
9301 Some(workspace_id),
9302 project_handle.clone(),
9303 app_state.clone(),
9304 window,
9305 cx,
9306 );
9307 workspace.centered_layout = centered_layout;
9308 workspace
9309 });
9310 multi_workspace.add(workspace.clone(), &*window, cx);
9311 workspace
9312 })?;
9313 (window, workspace)
9314 } else {
9315 let window_bounds_override = window_bounds_env_override();
9316
9317 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
9318 (Some(WindowBounds::Windowed(bounds)), None)
9319 } else if let Some(display) = serialized_workspace.display
9320 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
9321 {
9322 (Some(bounds.0), Some(display))
9323 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
9324 (Some(bounds), Some(display))
9325 } else {
9326 (None, None)
9327 };
9328
9329 let options = cx.update(|cx| {
9330 let mut options = (app_state.build_window_options)(display, cx);
9331 options.window_bounds = window_bounds;
9332 options
9333 });
9334
9335 let window = cx.open_window(options, {
9336 let app_state = app_state.clone();
9337 let project_handle = project_handle.clone();
9338 move |window, cx| {
9339 let workspace = cx.new(|cx| {
9340 let mut workspace = Workspace::new(
9341 Some(workspace_id),
9342 project_handle,
9343 app_state,
9344 window,
9345 cx,
9346 );
9347 workspace.centered_layout = centered_layout;
9348 workspace
9349 });
9350 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9351 }
9352 })?;
9353
9354 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
9355 multi_workspace.workspace().clone()
9356 })?;
9357
9358 (window, workspace)
9359 };
9360
9361 notify_if_database_failed(window, cx);
9362
9363 // Restore items from the serialized workspace
9364 window
9365 .update(cx, |_, window, cx| {
9366 workspace.update(cx, |_workspace, cx| {
9367 open_items(Some(serialized_workspace), vec![], window, cx)
9368 })
9369 })?
9370 .await?;
9371
9372 window.update(cx, |_, window, cx| {
9373 workspace.update(cx, |workspace, cx| {
9374 workspace.serialize_workspace(window, cx);
9375 });
9376 })?;
9377
9378 Ok(window)
9379 })
9380}
9381
9382#[allow(clippy::type_complexity)]
9383pub fn open_paths(
9384 abs_paths: &[PathBuf],
9385 app_state: Arc<AppState>,
9386 mut open_options: OpenOptions,
9387 cx: &mut App,
9388) -> Task<anyhow::Result<OpenResult>> {
9389 let abs_paths = abs_paths.to_vec();
9390 #[cfg(target_os = "windows")]
9391 let wsl_path = abs_paths
9392 .iter()
9393 .find_map(|p| util::paths::WslPath::from_path(p));
9394
9395 cx.spawn(async move |cx| {
9396 let (mut existing, mut open_visible) = find_existing_workspace(
9397 &abs_paths,
9398 &open_options,
9399 &SerializedWorkspaceLocation::Local,
9400 cx,
9401 )
9402 .await;
9403
9404 // Fallback: if no workspace contains the paths and all paths are files,
9405 // prefer an existing local workspace window (active window first).
9406 if open_options.open_new_workspace.is_none() && existing.is_none() {
9407 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9408 let all_metadatas = futures::future::join_all(all_paths)
9409 .await
9410 .into_iter()
9411 .filter_map(|result| result.ok().flatten());
9412
9413 if all_metadatas.into_iter().all(|file| !file.is_dir) {
9414 cx.update(|cx| {
9415 let windows = workspace_windows_for_location(
9416 &SerializedWorkspaceLocation::Local,
9417 cx,
9418 );
9419 let window = cx
9420 .active_window()
9421 .and_then(|window| window.downcast::<MultiWorkspace>())
9422 .filter(|window| windows.contains(window))
9423 .or_else(|| windows.into_iter().next());
9424 if let Some(window) = window {
9425 if let Ok(multi_workspace) = window.read(cx) {
9426 let active_workspace = multi_workspace.workspace().clone();
9427 existing = Some((window, active_workspace));
9428 open_visible = OpenVisible::None;
9429 }
9430 }
9431 });
9432 }
9433 }
9434
9435 // Fallback for directories: when no flag is specified and no existing
9436 // workspace matched, add the directory as a new workspace in the
9437 // active window's MultiWorkspace (instead of opening a new window).
9438 if open_options.open_new_workspace.is_none() && existing.is_none() {
9439 let target_window = cx.update(|cx| {
9440 let windows = workspace_windows_for_location(
9441 &SerializedWorkspaceLocation::Local,
9442 cx,
9443 );
9444 let window = cx
9445 .active_window()
9446 .and_then(|window| window.downcast::<MultiWorkspace>())
9447 .filter(|window| windows.contains(window))
9448 .or_else(|| windows.into_iter().next());
9449 window.filter(|window| {
9450 window.read(cx).is_ok_and(|mw| mw.multi_workspace_enabled(cx))
9451 })
9452 });
9453
9454 if let Some(window) = target_window {
9455 open_options.requesting_window = Some(window);
9456 window
9457 .update(cx, |multi_workspace, _, cx| {
9458 multi_workspace.open_sidebar(cx);
9459 })
9460 .log_err();
9461 }
9462 }
9463
9464 let open_in_dev_container = open_options.open_in_dev_container;
9465
9466 let result = if let Some((existing, target_workspace)) = existing {
9467 let open_task = existing
9468 .update(cx, |multi_workspace, window, cx| {
9469 window.activate_window();
9470 multi_workspace.activate(target_workspace.clone(), window, cx);
9471 target_workspace.update(cx, |workspace, cx| {
9472 if open_in_dev_container {
9473 workspace.set_open_in_dev_container(true);
9474 }
9475 workspace.open_paths(
9476 abs_paths,
9477 OpenOptions {
9478 visible: Some(open_visible),
9479 ..Default::default()
9480 },
9481 None,
9482 window,
9483 cx,
9484 )
9485 })
9486 })?
9487 .await;
9488
9489 _ = existing.update(cx, |multi_workspace, _, cx| {
9490 let workspace = multi_workspace.workspace().clone();
9491 workspace.update(cx, |workspace, cx| {
9492 for item in open_task.iter().flatten() {
9493 if let Err(e) = item {
9494 workspace.show_error(&e, cx);
9495 }
9496 }
9497 });
9498 });
9499
9500 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9501 } else {
9502 let init = if open_in_dev_container {
9503 Some(Box::new(|workspace: &mut Workspace, _window: &mut Window, _cx: &mut Context<Workspace>| {
9504 workspace.set_open_in_dev_container(true);
9505 }) as Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>)
9506 } else {
9507 None
9508 };
9509 let result = cx
9510 .update(move |cx| {
9511 Workspace::new_local(
9512 abs_paths,
9513 app_state.clone(),
9514 open_options.requesting_window,
9515 open_options.env,
9516 init,
9517 open_options.open_mode,
9518 cx,
9519 )
9520 })
9521 .await;
9522
9523 if let Ok(ref result) = result {
9524 result.window
9525 .update(cx, |_, window, _cx| {
9526 window.activate_window();
9527 })
9528 .log_err();
9529 }
9530
9531 result
9532 };
9533
9534 #[cfg(target_os = "windows")]
9535 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9536 && let Ok(ref result) = result
9537 {
9538 result.window
9539 .update(cx, move |multi_workspace, _window, cx| {
9540 struct OpenInWsl;
9541 let workspace = multi_workspace.workspace().clone();
9542 workspace.update(cx, |workspace, cx| {
9543 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9544 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9545 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9546 cx.new(move |cx| {
9547 MessageNotification::new(msg, cx)
9548 .primary_message("Open in WSL")
9549 .primary_icon(IconName::FolderOpen)
9550 .primary_on_click(move |window, cx| {
9551 window.dispatch_action(Box::new(remote::OpenWslPath {
9552 distro: remote::WslConnectionOptions {
9553 distro_name: distro.clone(),
9554 user: None,
9555 },
9556 paths: vec![path.clone().into()],
9557 }), cx)
9558 })
9559 })
9560 });
9561 });
9562 })
9563 .unwrap();
9564 };
9565 result
9566 })
9567}
9568
9569pub fn open_new(
9570 open_options: OpenOptions,
9571 app_state: Arc<AppState>,
9572 cx: &mut App,
9573 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9574) -> Task<anyhow::Result<()>> {
9575 let addition = open_options.open_mode;
9576 let task = Workspace::new_local(
9577 Vec::new(),
9578 app_state,
9579 open_options.requesting_window,
9580 open_options.env,
9581 Some(Box::new(init)),
9582 addition,
9583 cx,
9584 );
9585 cx.spawn(async move |cx| {
9586 let OpenResult { window, .. } = task.await?;
9587 window
9588 .update(cx, |_, window, _cx| {
9589 window.activate_window();
9590 })
9591 .ok();
9592 Ok(())
9593 })
9594}
9595
9596pub fn create_and_open_local_file(
9597 path: &'static Path,
9598 window: &mut Window,
9599 cx: &mut Context<Workspace>,
9600 default_content: impl 'static + Send + FnOnce() -> Rope,
9601) -> Task<Result<Box<dyn ItemHandle>>> {
9602 cx.spawn_in(window, async move |workspace, cx| {
9603 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9604 if !fs.is_file(path).await {
9605 fs.create_file(path, Default::default()).await?;
9606 fs.save(path, &default_content(), Default::default())
9607 .await?;
9608 }
9609
9610 workspace
9611 .update_in(cx, |workspace, window, cx| {
9612 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9613 let path = workspace
9614 .project
9615 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9616 cx.spawn_in(window, async move |workspace, cx| {
9617 let path = path.await?;
9618
9619 let path = fs.canonicalize(&path).await.unwrap_or(path);
9620
9621 let mut items = workspace
9622 .update_in(cx, |workspace, window, cx| {
9623 workspace.open_paths(
9624 vec![path.to_path_buf()],
9625 OpenOptions {
9626 visible: Some(OpenVisible::None),
9627 ..Default::default()
9628 },
9629 None,
9630 window,
9631 cx,
9632 )
9633 })?
9634 .await;
9635 let item = items.pop().flatten();
9636 item.with_context(|| format!("path {path:?} is not a file"))?
9637 })
9638 })
9639 })?
9640 .await?
9641 .await
9642 })
9643}
9644
9645pub fn open_remote_project_with_new_connection(
9646 window: WindowHandle<MultiWorkspace>,
9647 remote_connection: Arc<dyn RemoteConnection>,
9648 cancel_rx: oneshot::Receiver<()>,
9649 delegate: Arc<dyn RemoteClientDelegate>,
9650 app_state: Arc<AppState>,
9651 paths: Vec<PathBuf>,
9652 cx: &mut App,
9653) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9654 cx.spawn(async move |cx| {
9655 let (workspace_id, serialized_workspace) =
9656 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9657 .await?;
9658
9659 let session = match cx
9660 .update(|cx| {
9661 remote::RemoteClient::new(
9662 ConnectionIdentifier::Workspace(workspace_id.0),
9663 remote_connection,
9664 cancel_rx,
9665 delegate,
9666 cx,
9667 )
9668 })
9669 .await?
9670 {
9671 Some(result) => result,
9672 None => return Ok(Vec::new()),
9673 };
9674
9675 let project = cx.update(|cx| {
9676 project::Project::remote(
9677 session,
9678 app_state.client.clone(),
9679 app_state.node_runtime.clone(),
9680 app_state.user_store.clone(),
9681 app_state.languages.clone(),
9682 app_state.fs.clone(),
9683 true,
9684 cx,
9685 )
9686 });
9687
9688 open_remote_project_inner(
9689 project,
9690 paths,
9691 workspace_id,
9692 serialized_workspace,
9693 app_state,
9694 window,
9695 cx,
9696 )
9697 .await
9698 })
9699}
9700
9701pub fn open_remote_project_with_existing_connection(
9702 connection_options: RemoteConnectionOptions,
9703 project: Entity<Project>,
9704 paths: Vec<PathBuf>,
9705 app_state: Arc<AppState>,
9706 window: WindowHandle<MultiWorkspace>,
9707 cx: &mut AsyncApp,
9708) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9709 cx.spawn(async move |cx| {
9710 let (workspace_id, serialized_workspace) =
9711 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9712
9713 open_remote_project_inner(
9714 project,
9715 paths,
9716 workspace_id,
9717 serialized_workspace,
9718 app_state,
9719 window,
9720 cx,
9721 )
9722 .await
9723 })
9724}
9725
9726async fn open_remote_project_inner(
9727 project: Entity<Project>,
9728 paths: Vec<PathBuf>,
9729 workspace_id: WorkspaceId,
9730 serialized_workspace: Option<SerializedWorkspace>,
9731 app_state: Arc<AppState>,
9732 window: WindowHandle<MultiWorkspace>,
9733 cx: &mut AsyncApp,
9734) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9735 let db = cx.update(|cx| WorkspaceDb::global(cx));
9736 let toolchains = db.toolchains(workspace_id).await?;
9737 for (toolchain, worktree_path, path) in toolchains {
9738 project
9739 .update(cx, |this, cx| {
9740 let Some(worktree_id) =
9741 this.find_worktree(&worktree_path, cx)
9742 .and_then(|(worktree, rel_path)| {
9743 if rel_path.is_empty() {
9744 Some(worktree.read(cx).id())
9745 } else {
9746 None
9747 }
9748 })
9749 else {
9750 return Task::ready(None);
9751 };
9752
9753 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9754 })
9755 .await;
9756 }
9757 let mut project_paths_to_open = vec![];
9758 let mut project_path_errors = vec![];
9759
9760 for path in paths {
9761 let result = cx
9762 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9763 .await;
9764 match result {
9765 Ok((_, project_path)) => {
9766 project_paths_to_open.push((path.clone(), Some(project_path)));
9767 }
9768 Err(error) => {
9769 project_path_errors.push(error);
9770 }
9771 };
9772 }
9773
9774 if project_paths_to_open.is_empty() {
9775 return Err(project_path_errors.pop().context("no paths given")?);
9776 }
9777
9778 let workspace = window.update(cx, |multi_workspace, window, cx| {
9779 telemetry::event!("SSH Project Opened");
9780
9781 let new_workspace = cx.new(|cx| {
9782 let mut workspace =
9783 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9784 workspace.update_history(cx);
9785
9786 if let Some(ref serialized) = serialized_workspace {
9787 workspace.centered_layout = serialized.centered_layout;
9788 }
9789
9790 workspace
9791 });
9792
9793 multi_workspace.activate(new_workspace.clone(), window, cx);
9794 new_workspace
9795 })?;
9796
9797 let items = window
9798 .update(cx, |_, window, cx| {
9799 window.activate_window();
9800 workspace.update(cx, |_workspace, cx| {
9801 open_items(serialized_workspace, project_paths_to_open, window, cx)
9802 })
9803 })?
9804 .await?;
9805
9806 workspace.update(cx, |workspace, cx| {
9807 for error in project_path_errors {
9808 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9809 if let Some(path) = error.error_tag("path") {
9810 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9811 }
9812 } else {
9813 workspace.show_error(&error, cx)
9814 }
9815 }
9816 });
9817
9818 Ok(items.into_iter().map(|item| item?.ok()).collect())
9819}
9820
9821fn deserialize_remote_project(
9822 connection_options: RemoteConnectionOptions,
9823 paths: Vec<PathBuf>,
9824 cx: &AsyncApp,
9825) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9826 let db = cx.update(|cx| WorkspaceDb::global(cx));
9827 cx.background_spawn(async move {
9828 let remote_connection_id = db
9829 .get_or_create_remote_connection(connection_options)
9830 .await?;
9831
9832 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9833
9834 let workspace_id = if let Some(workspace_id) =
9835 serialized_workspace.as_ref().map(|workspace| workspace.id)
9836 {
9837 workspace_id
9838 } else {
9839 db.next_id().await?
9840 };
9841
9842 Ok((workspace_id, serialized_workspace))
9843 })
9844}
9845
9846pub fn join_in_room_project(
9847 project_id: u64,
9848 follow_user_id: u64,
9849 app_state: Arc<AppState>,
9850 cx: &mut App,
9851) -> Task<Result<()>> {
9852 let windows = cx.windows();
9853 cx.spawn(async move |cx| {
9854 let existing_window_and_workspace: Option<(
9855 WindowHandle<MultiWorkspace>,
9856 Entity<Workspace>,
9857 )> = windows.into_iter().find_map(|window_handle| {
9858 window_handle
9859 .downcast::<MultiWorkspace>()
9860 .and_then(|window_handle| {
9861 window_handle
9862 .update(cx, |multi_workspace, _window, cx| {
9863 for workspace in multi_workspace.workspaces() {
9864 if workspace.read(cx).project().read(cx).remote_id()
9865 == Some(project_id)
9866 {
9867 return Some((window_handle, workspace.clone()));
9868 }
9869 }
9870 None
9871 })
9872 .unwrap_or(None)
9873 })
9874 });
9875
9876 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9877 existing_window_and_workspace
9878 {
9879 existing_window
9880 .update(cx, |multi_workspace, window, cx| {
9881 multi_workspace.activate(target_workspace, window, cx);
9882 })
9883 .ok();
9884 existing_window
9885 } else {
9886 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9887 let project = cx
9888 .update(|cx| {
9889 active_call.0.join_project(
9890 project_id,
9891 app_state.languages.clone(),
9892 app_state.fs.clone(),
9893 cx,
9894 )
9895 })
9896 .await?;
9897
9898 let window_bounds_override = window_bounds_env_override();
9899 cx.update(|cx| {
9900 let mut options = (app_state.build_window_options)(None, cx);
9901 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9902 cx.open_window(options, |window, cx| {
9903 let workspace = cx.new(|cx| {
9904 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9905 });
9906 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9907 })
9908 })?
9909 };
9910
9911 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9912 cx.activate(true);
9913 window.activate_window();
9914
9915 // We set the active workspace above, so this is the correct workspace.
9916 let workspace = multi_workspace.workspace().clone();
9917 workspace.update(cx, |workspace, cx| {
9918 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9919 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9920 .or_else(|| {
9921 // If we couldn't follow the given user, follow the host instead.
9922 let collaborator = workspace
9923 .project()
9924 .read(cx)
9925 .collaborators()
9926 .values()
9927 .find(|collaborator| collaborator.is_host)?;
9928 Some(collaborator.peer_id)
9929 });
9930
9931 if let Some(follow_peer_id) = follow_peer_id {
9932 workspace.follow(follow_peer_id, window, cx);
9933 }
9934 });
9935 })?;
9936
9937 anyhow::Ok(())
9938 })
9939}
9940
9941pub fn reload(cx: &mut App) {
9942 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9943 let mut workspace_windows = cx
9944 .windows()
9945 .into_iter()
9946 .filter_map(|window| window.downcast::<MultiWorkspace>())
9947 .collect::<Vec<_>>();
9948
9949 // If multiple windows have unsaved changes, and need a save prompt,
9950 // prompt in the active window before switching to a different window.
9951 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9952
9953 let mut prompt = None;
9954 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9955 prompt = window
9956 .update(cx, |_, window, cx| {
9957 window.prompt(
9958 PromptLevel::Info,
9959 "Are you sure you want to restart?",
9960 None,
9961 &["Restart", "Cancel"],
9962 cx,
9963 )
9964 })
9965 .ok();
9966 }
9967
9968 cx.spawn(async move |cx| {
9969 if let Some(prompt) = prompt {
9970 let answer = prompt.await?;
9971 if answer != 0 {
9972 return anyhow::Ok(());
9973 }
9974 }
9975
9976 // If the user cancels any save prompt, then keep the app open.
9977 for window in workspace_windows {
9978 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9979 let workspace = multi_workspace.workspace().clone();
9980 workspace.update(cx, |workspace, cx| {
9981 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9982 })
9983 }) && !should_close.await?
9984 {
9985 return anyhow::Ok(());
9986 }
9987 }
9988 cx.update(|cx| cx.restart());
9989 anyhow::Ok(())
9990 })
9991 .detach_and_log_err(cx);
9992}
9993
9994fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9995 let mut parts = value.split(',');
9996 let x: usize = parts.next()?.parse().ok()?;
9997 let y: usize = parts.next()?.parse().ok()?;
9998 Some(point(px(x as f32), px(y as f32)))
9999}
10000
10001fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
10002 let mut parts = value.split(',');
10003 let width: usize = parts.next()?.parse().ok()?;
10004 let height: usize = parts.next()?.parse().ok()?;
10005 Some(size(px(width as f32), px(height as f32)))
10006}
10007
10008/// Add client-side decorations (rounded corners, shadows, resize handling) when
10009/// appropriate.
10010///
10011/// The `border_radius_tiling` parameter allows overriding which corners get
10012/// rounded, independently of the actual window tiling state. This is used
10013/// specifically for the workspace switcher sidebar: when the sidebar is open,
10014/// we want square corners on the left (so the sidebar appears flush with the
10015/// window edge) but we still need the shadow padding for proper visual
10016/// appearance. Unlike actual window tiling, this only affects border radius -
10017/// not padding or shadows.
10018pub fn client_side_decorations(
10019 element: impl IntoElement,
10020 window: &mut Window,
10021 cx: &mut App,
10022 border_radius_tiling: Tiling,
10023) -> Stateful<Div> {
10024 const BORDER_SIZE: Pixels = px(1.0);
10025 let decorations = window.window_decorations();
10026 let tiling = match decorations {
10027 Decorations::Server => Tiling::default(),
10028 Decorations::Client { tiling } => tiling,
10029 };
10030
10031 match decorations {
10032 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
10033 Decorations::Server => window.set_client_inset(px(0.0)),
10034 }
10035
10036 struct GlobalResizeEdge(ResizeEdge);
10037 impl Global for GlobalResizeEdge {}
10038
10039 div()
10040 .id("window-backdrop")
10041 .bg(transparent_black())
10042 .map(|div| match decorations {
10043 Decorations::Server => div,
10044 Decorations::Client { .. } => div
10045 .when(
10046 !(tiling.top
10047 || tiling.right
10048 || border_radius_tiling.top
10049 || border_radius_tiling.right),
10050 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10051 )
10052 .when(
10053 !(tiling.top
10054 || tiling.left
10055 || border_radius_tiling.top
10056 || border_radius_tiling.left),
10057 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10058 )
10059 .when(
10060 !(tiling.bottom
10061 || tiling.right
10062 || border_radius_tiling.bottom
10063 || border_radius_tiling.right),
10064 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10065 )
10066 .when(
10067 !(tiling.bottom
10068 || tiling.left
10069 || border_radius_tiling.bottom
10070 || border_radius_tiling.left),
10071 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10072 )
10073 .when(!tiling.top, |div| {
10074 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
10075 })
10076 .when(!tiling.bottom, |div| {
10077 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
10078 })
10079 .when(!tiling.left, |div| {
10080 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
10081 })
10082 .when(!tiling.right, |div| {
10083 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
10084 })
10085 .on_mouse_move(move |e, window, cx| {
10086 let size = window.window_bounds().get_bounds().size;
10087 let pos = e.position;
10088
10089 let new_edge =
10090 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
10091
10092 let edge = cx.try_global::<GlobalResizeEdge>();
10093 if new_edge != edge.map(|edge| edge.0) {
10094 window
10095 .window_handle()
10096 .update(cx, |workspace, _, cx| {
10097 cx.notify(workspace.entity_id());
10098 })
10099 .ok();
10100 }
10101 })
10102 .on_mouse_down(MouseButton::Left, move |e, window, _| {
10103 let size = window.window_bounds().get_bounds().size;
10104 let pos = e.position;
10105
10106 let edge = match resize_edge(
10107 pos,
10108 theme::CLIENT_SIDE_DECORATION_SHADOW,
10109 size,
10110 tiling,
10111 ) {
10112 Some(value) => value,
10113 None => return,
10114 };
10115
10116 window.start_window_resize(edge);
10117 }),
10118 })
10119 .size_full()
10120 .child(
10121 div()
10122 .cursor(CursorStyle::Arrow)
10123 .map(|div| match decorations {
10124 Decorations::Server => div,
10125 Decorations::Client { .. } => div
10126 .border_color(cx.theme().colors().border)
10127 .when(
10128 !(tiling.top
10129 || tiling.right
10130 || border_radius_tiling.top
10131 || border_radius_tiling.right),
10132 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10133 )
10134 .when(
10135 !(tiling.top
10136 || tiling.left
10137 || border_radius_tiling.top
10138 || border_radius_tiling.left),
10139 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10140 )
10141 .when(
10142 !(tiling.bottom
10143 || tiling.right
10144 || border_radius_tiling.bottom
10145 || border_radius_tiling.right),
10146 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10147 )
10148 .when(
10149 !(tiling.bottom
10150 || tiling.left
10151 || border_radius_tiling.bottom
10152 || border_radius_tiling.left),
10153 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
10154 )
10155 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
10156 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
10157 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
10158 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
10159 .when(!tiling.is_tiled(), |div| {
10160 div.shadow(vec![gpui::BoxShadow {
10161 color: Hsla {
10162 h: 0.,
10163 s: 0.,
10164 l: 0.,
10165 a: 0.4,
10166 },
10167 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
10168 spread_radius: px(0.),
10169 offset: point(px(0.0), px(0.0)),
10170 }])
10171 }),
10172 })
10173 .on_mouse_move(|_e, _, cx| {
10174 cx.stop_propagation();
10175 })
10176 .size_full()
10177 .child(element),
10178 )
10179 .map(|div| match decorations {
10180 Decorations::Server => div,
10181 Decorations::Client { tiling, .. } => div.child(
10182 canvas(
10183 |_bounds, window, _| {
10184 window.insert_hitbox(
10185 Bounds::new(
10186 point(px(0.0), px(0.0)),
10187 window.window_bounds().get_bounds().size,
10188 ),
10189 HitboxBehavior::Normal,
10190 )
10191 },
10192 move |_bounds, hitbox, window, cx| {
10193 let mouse = window.mouse_position();
10194 let size = window.window_bounds().get_bounds().size;
10195 let Some(edge) =
10196 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
10197 else {
10198 return;
10199 };
10200 cx.set_global(GlobalResizeEdge(edge));
10201 window.set_cursor_style(
10202 match edge {
10203 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
10204 ResizeEdge::Left | ResizeEdge::Right => {
10205 CursorStyle::ResizeLeftRight
10206 }
10207 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
10208 CursorStyle::ResizeUpLeftDownRight
10209 }
10210 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
10211 CursorStyle::ResizeUpRightDownLeft
10212 }
10213 },
10214 &hitbox,
10215 );
10216 },
10217 )
10218 .size_full()
10219 .absolute(),
10220 ),
10221 })
10222}
10223
10224fn resize_edge(
10225 pos: Point<Pixels>,
10226 shadow_size: Pixels,
10227 window_size: Size<Pixels>,
10228 tiling: Tiling,
10229) -> Option<ResizeEdge> {
10230 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
10231 if bounds.contains(&pos) {
10232 return None;
10233 }
10234
10235 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
10236 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
10237 if !tiling.top && top_left_bounds.contains(&pos) {
10238 return Some(ResizeEdge::TopLeft);
10239 }
10240
10241 let top_right_bounds = Bounds::new(
10242 Point::new(window_size.width - corner_size.width, px(0.)),
10243 corner_size,
10244 );
10245 if !tiling.top && top_right_bounds.contains(&pos) {
10246 return Some(ResizeEdge::TopRight);
10247 }
10248
10249 let bottom_left_bounds = Bounds::new(
10250 Point::new(px(0.), window_size.height - corner_size.height),
10251 corner_size,
10252 );
10253 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
10254 return Some(ResizeEdge::BottomLeft);
10255 }
10256
10257 let bottom_right_bounds = Bounds::new(
10258 Point::new(
10259 window_size.width - corner_size.width,
10260 window_size.height - corner_size.height,
10261 ),
10262 corner_size,
10263 );
10264 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
10265 return Some(ResizeEdge::BottomRight);
10266 }
10267
10268 if !tiling.top && pos.y < shadow_size {
10269 Some(ResizeEdge::Top)
10270 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
10271 Some(ResizeEdge::Bottom)
10272 } else if !tiling.left && pos.x < shadow_size {
10273 Some(ResizeEdge::Left)
10274 } else if !tiling.right && pos.x > window_size.width - shadow_size {
10275 Some(ResizeEdge::Right)
10276 } else {
10277 None
10278 }
10279}
10280
10281fn join_pane_into_active(
10282 active_pane: &Entity<Pane>,
10283 pane: &Entity<Pane>,
10284 window: &mut Window,
10285 cx: &mut App,
10286) {
10287 if pane == active_pane {
10288 } else if pane.read(cx).items_len() == 0 {
10289 pane.update(cx, |_, cx| {
10290 cx.emit(pane::Event::Remove {
10291 focus_on_pane: None,
10292 });
10293 })
10294 } else {
10295 move_all_items(pane, active_pane, window, cx);
10296 }
10297}
10298
10299fn move_all_items(
10300 from_pane: &Entity<Pane>,
10301 to_pane: &Entity<Pane>,
10302 window: &mut Window,
10303 cx: &mut App,
10304) {
10305 let destination_is_different = from_pane != to_pane;
10306 let mut moved_items = 0;
10307 for (item_ix, item_handle) in from_pane
10308 .read(cx)
10309 .items()
10310 .enumerate()
10311 .map(|(ix, item)| (ix, item.clone()))
10312 .collect::<Vec<_>>()
10313 {
10314 let ix = item_ix - moved_items;
10315 if destination_is_different {
10316 // Close item from previous pane
10317 from_pane.update(cx, |source, cx| {
10318 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
10319 });
10320 moved_items += 1;
10321 }
10322
10323 // This automatically removes duplicate items in the pane
10324 to_pane.update(cx, |destination, cx| {
10325 destination.add_item(item_handle, true, true, None, window, cx);
10326 window.focus(&destination.focus_handle(cx), cx)
10327 });
10328 }
10329}
10330
10331pub fn move_item(
10332 source: &Entity<Pane>,
10333 destination: &Entity<Pane>,
10334 item_id_to_move: EntityId,
10335 destination_index: usize,
10336 activate: bool,
10337 window: &mut Window,
10338 cx: &mut App,
10339) {
10340 let Some((item_ix, item_handle)) = source
10341 .read(cx)
10342 .items()
10343 .enumerate()
10344 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
10345 .map(|(ix, item)| (ix, item.clone()))
10346 else {
10347 // Tab was closed during drag
10348 return;
10349 };
10350
10351 if source != destination {
10352 // Close item from previous pane
10353 source.update(cx, |source, cx| {
10354 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
10355 });
10356 }
10357
10358 // This automatically removes duplicate items in the pane
10359 destination.update(cx, |destination, cx| {
10360 destination.add_item_inner(
10361 item_handle,
10362 activate,
10363 activate,
10364 activate,
10365 Some(destination_index),
10366 window,
10367 cx,
10368 );
10369 if activate {
10370 window.focus(&destination.focus_handle(cx), cx)
10371 }
10372 });
10373}
10374
10375pub fn move_active_item(
10376 source: &Entity<Pane>,
10377 destination: &Entity<Pane>,
10378 focus_destination: bool,
10379 close_if_empty: bool,
10380 window: &mut Window,
10381 cx: &mut App,
10382) {
10383 if source == destination {
10384 return;
10385 }
10386 let Some(active_item) = source.read(cx).active_item() else {
10387 return;
10388 };
10389 source.update(cx, |source_pane, cx| {
10390 let item_id = active_item.item_id();
10391 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
10392 destination.update(cx, |target_pane, cx| {
10393 target_pane.add_item(
10394 active_item,
10395 focus_destination,
10396 focus_destination,
10397 Some(target_pane.items_len()),
10398 window,
10399 cx,
10400 );
10401 });
10402 });
10403}
10404
10405pub fn clone_active_item(
10406 workspace_id: Option<WorkspaceId>,
10407 source: &Entity<Pane>,
10408 destination: &Entity<Pane>,
10409 focus_destination: bool,
10410 window: &mut Window,
10411 cx: &mut App,
10412) {
10413 if source == destination {
10414 return;
10415 }
10416 let Some(active_item) = source.read(cx).active_item() else {
10417 return;
10418 };
10419 if !active_item.can_split(cx) {
10420 return;
10421 }
10422 let destination = destination.downgrade();
10423 let task = active_item.clone_on_split(workspace_id, window, cx);
10424 window
10425 .spawn(cx, async move |cx| {
10426 let Some(clone) = task.await else {
10427 return;
10428 };
10429 destination
10430 .update_in(cx, |target_pane, window, cx| {
10431 target_pane.add_item(
10432 clone,
10433 focus_destination,
10434 focus_destination,
10435 Some(target_pane.items_len()),
10436 window,
10437 cx,
10438 );
10439 })
10440 .log_err();
10441 })
10442 .detach();
10443}
10444
10445#[derive(Debug)]
10446pub struct WorkspacePosition {
10447 pub window_bounds: Option<WindowBounds>,
10448 pub display: Option<Uuid>,
10449 pub centered_layout: bool,
10450}
10451
10452pub fn remote_workspace_position_from_db(
10453 connection_options: RemoteConnectionOptions,
10454 paths_to_open: &[PathBuf],
10455 cx: &App,
10456) -> Task<Result<WorkspacePosition>> {
10457 let paths = paths_to_open.to_vec();
10458 let db = WorkspaceDb::global(cx);
10459 let kvp = db::kvp::KeyValueStore::global(cx);
10460
10461 cx.background_spawn(async move {
10462 let remote_connection_id = db
10463 .get_or_create_remote_connection(connection_options)
10464 .await
10465 .context("fetching serialized ssh project")?;
10466 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10467
10468 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10469 (Some(WindowBounds::Windowed(bounds)), None)
10470 } else {
10471 let restorable_bounds = serialized_workspace
10472 .as_ref()
10473 .and_then(|workspace| {
10474 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10475 })
10476 .or_else(|| persistence::read_default_window_bounds(&kvp));
10477
10478 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10479 (Some(serialized_bounds), Some(serialized_display))
10480 } else {
10481 (None, None)
10482 }
10483 };
10484
10485 let centered_layout = serialized_workspace
10486 .as_ref()
10487 .map(|w| w.centered_layout)
10488 .unwrap_or(false);
10489
10490 Ok(WorkspacePosition {
10491 window_bounds,
10492 display,
10493 centered_layout,
10494 })
10495 })
10496}
10497
10498pub fn with_active_or_new_workspace(
10499 cx: &mut App,
10500 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10501) {
10502 match cx
10503 .active_window()
10504 .and_then(|w| w.downcast::<MultiWorkspace>())
10505 {
10506 Some(multi_workspace) => {
10507 cx.defer(move |cx| {
10508 multi_workspace
10509 .update(cx, |multi_workspace, window, cx| {
10510 let workspace = multi_workspace.workspace().clone();
10511 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10512 })
10513 .log_err();
10514 });
10515 }
10516 None => {
10517 let app_state = AppState::global(cx);
10518 open_new(
10519 OpenOptions::default(),
10520 app_state,
10521 cx,
10522 move |workspace, window, cx| f(workspace, window, cx),
10523 )
10524 .detach_and_log_err(cx);
10525 }
10526 }
10527}
10528
10529/// Reads a panel's pixel size from its legacy KVP format and deletes the legacy
10530/// key. This migration path only runs once per panel per workspace.
10531fn load_legacy_panel_size(
10532 panel_key: &str,
10533 dock_position: DockPosition,
10534 workspace: &Workspace,
10535 cx: &mut App,
10536) -> Option<Pixels> {
10537 #[derive(Deserialize)]
10538 struct LegacyPanelState {
10539 #[serde(default)]
10540 width: Option<Pixels>,
10541 #[serde(default)]
10542 height: Option<Pixels>,
10543 }
10544
10545 let workspace_id = workspace
10546 .database_id()
10547 .map(|id| i64::from(id).to_string())
10548 .or_else(|| workspace.session_id())?;
10549
10550 let legacy_key = match panel_key {
10551 "ProjectPanel" => {
10552 format!("{}-{:?}", "ProjectPanel", workspace_id)
10553 }
10554 "OutlinePanel" => {
10555 format!("{}-{:?}", "OutlinePanel", workspace_id)
10556 }
10557 "GitPanel" => {
10558 format!("{}-{:?}", "GitPanel", workspace_id)
10559 }
10560 "TerminalPanel" => {
10561 format!("{:?}-{:?}", "TerminalPanel", workspace_id)
10562 }
10563 _ => return None,
10564 };
10565
10566 let kvp = db::kvp::KeyValueStore::global(cx);
10567 let json = kvp.read_kvp(&legacy_key).log_err().flatten()?;
10568 let state = serde_json::from_str::<LegacyPanelState>(&json).log_err()?;
10569 let size = match dock_position {
10570 DockPosition::Bottom => state.height,
10571 DockPosition::Left | DockPosition::Right => state.width,
10572 }?;
10573
10574 cx.background_spawn(async move { kvp.delete_kvp(legacy_key).await })
10575 .detach_and_log_err(cx);
10576
10577 Some(size)
10578}
10579
10580#[cfg(test)]
10581mod tests {
10582 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10583
10584 use super::*;
10585 use crate::{
10586 dock::{PanelEvent, test::TestPanel},
10587 item::{
10588 ItemBufferKind, ItemEvent,
10589 test::{TestItem, TestProjectItem},
10590 },
10591 };
10592 use fs::FakeFs;
10593 use gpui::{
10594 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10595 UpdateGlobal, VisualTestContext, px,
10596 };
10597 use project::{Project, ProjectEntryId};
10598 use serde_json::json;
10599 use settings::SettingsStore;
10600 use util::path;
10601 use util::rel_path::rel_path;
10602
10603 #[gpui::test]
10604 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10605 init_test(cx);
10606
10607 let fs = FakeFs::new(cx.executor());
10608 let project = Project::test(fs, [], cx).await;
10609 let (workspace, cx) =
10610 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10611
10612 // Adding an item with no ambiguity renders the tab without detail.
10613 let item1 = cx.new(|cx| {
10614 let mut item = TestItem::new(cx);
10615 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10616 item
10617 });
10618 workspace.update_in(cx, |workspace, window, cx| {
10619 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10620 });
10621 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10622
10623 // Adding an item that creates ambiguity increases the level of detail on
10624 // both tabs.
10625 let item2 = cx.new_window_entity(|_window, cx| {
10626 let mut item = TestItem::new(cx);
10627 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10628 item
10629 });
10630 workspace.update_in(cx, |workspace, window, cx| {
10631 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10632 });
10633 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10634 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10635
10636 // Adding an item that creates ambiguity increases the level of detail only
10637 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10638 // we stop at the highest detail available.
10639 let item3 = cx.new(|cx| {
10640 let mut item = TestItem::new(cx);
10641 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10642 item
10643 });
10644 workspace.update_in(cx, |workspace, window, cx| {
10645 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10646 });
10647 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10648 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10649 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10650 }
10651
10652 #[gpui::test]
10653 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10654 init_test(cx);
10655
10656 let fs = FakeFs::new(cx.executor());
10657 fs.insert_tree(
10658 "/root1",
10659 json!({
10660 "one.txt": "",
10661 "two.txt": "",
10662 }),
10663 )
10664 .await;
10665 fs.insert_tree(
10666 "/root2",
10667 json!({
10668 "three.txt": "",
10669 }),
10670 )
10671 .await;
10672
10673 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10674 let (workspace, cx) =
10675 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10676 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10677 let worktree_id = project.update(cx, |project, cx| {
10678 project.worktrees(cx).next().unwrap().read(cx).id()
10679 });
10680
10681 let item1 = cx.new(|cx| {
10682 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10683 });
10684 let item2 = cx.new(|cx| {
10685 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10686 });
10687
10688 // Add an item to an empty pane
10689 workspace.update_in(cx, |workspace, window, cx| {
10690 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10691 });
10692 project.update(cx, |project, cx| {
10693 assert_eq!(
10694 project.active_entry(),
10695 project
10696 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10697 .map(|e| e.id)
10698 );
10699 });
10700 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10701
10702 // Add a second item to a non-empty pane
10703 workspace.update_in(cx, |workspace, window, cx| {
10704 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10705 });
10706 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10707 project.update(cx, |project, cx| {
10708 assert_eq!(
10709 project.active_entry(),
10710 project
10711 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10712 .map(|e| e.id)
10713 );
10714 });
10715
10716 // Close the active item
10717 pane.update_in(cx, |pane, window, cx| {
10718 pane.close_active_item(&Default::default(), window, cx)
10719 })
10720 .await
10721 .unwrap();
10722 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10723 project.update(cx, |project, cx| {
10724 assert_eq!(
10725 project.active_entry(),
10726 project
10727 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10728 .map(|e| e.id)
10729 );
10730 });
10731
10732 // Add a project folder
10733 project
10734 .update(cx, |project, cx| {
10735 project.find_or_create_worktree("root2", true, cx)
10736 })
10737 .await
10738 .unwrap();
10739 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10740
10741 // Remove a project folder
10742 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10743 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10744 }
10745
10746 #[gpui::test]
10747 async fn test_close_window(cx: &mut TestAppContext) {
10748 init_test(cx);
10749
10750 let fs = FakeFs::new(cx.executor());
10751 fs.insert_tree("/root", json!({ "one": "" })).await;
10752
10753 let project = Project::test(fs, ["root".as_ref()], cx).await;
10754 let (workspace, cx) =
10755 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10756
10757 // When there are no dirty items, there's nothing to do.
10758 let item1 = cx.new(TestItem::new);
10759 workspace.update_in(cx, |w, window, cx| {
10760 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10761 });
10762 let task = workspace.update_in(cx, |w, window, cx| {
10763 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10764 });
10765 assert!(task.await.unwrap());
10766
10767 // When there are dirty untitled items, prompt to save each one. If the user
10768 // cancels any prompt, then abort.
10769 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10770 let item3 = cx.new(|cx| {
10771 TestItem::new(cx)
10772 .with_dirty(true)
10773 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10774 });
10775 workspace.update_in(cx, |w, window, cx| {
10776 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10777 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10778 });
10779 let task = workspace.update_in(cx, |w, window, cx| {
10780 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10781 });
10782 cx.executor().run_until_parked();
10783 cx.simulate_prompt_answer("Cancel"); // cancel save all
10784 cx.executor().run_until_parked();
10785 assert!(!cx.has_pending_prompt());
10786 assert!(!task.await.unwrap());
10787 }
10788
10789 #[gpui::test]
10790 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10791 init_test(cx);
10792
10793 let fs = FakeFs::new(cx.executor());
10794 fs.insert_tree("/root", json!({ "one": "" })).await;
10795
10796 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10797 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10798 let multi_workspace_handle =
10799 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10800 cx.run_until_parked();
10801
10802 multi_workspace_handle
10803 .update(cx, |mw, _window, cx| {
10804 mw.open_sidebar(cx);
10805 })
10806 .unwrap();
10807
10808 let workspace_a = multi_workspace_handle
10809 .read_with(cx, |mw, _| mw.workspace().clone())
10810 .unwrap();
10811
10812 let workspace_b = multi_workspace_handle
10813 .update(cx, |mw, window, cx| {
10814 mw.test_add_workspace(project_b, window, cx)
10815 })
10816 .unwrap();
10817
10818 // Activate workspace A
10819 multi_workspace_handle
10820 .update(cx, |mw, window, cx| {
10821 let workspace = mw.workspaces().next().unwrap().clone();
10822 mw.activate(workspace, window, cx);
10823 })
10824 .unwrap();
10825
10826 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10827
10828 // Workspace A has a clean item
10829 let item_a = cx.new(TestItem::new);
10830 workspace_a.update_in(cx, |w, window, cx| {
10831 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10832 });
10833
10834 // Workspace B has a dirty item
10835 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10836 workspace_b.update_in(cx, |w, window, cx| {
10837 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10838 });
10839
10840 // Verify workspace A is active
10841 multi_workspace_handle
10842 .read_with(cx, |mw, _| {
10843 assert_eq!(mw.workspace(), &workspace_a);
10844 })
10845 .unwrap();
10846
10847 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10848 multi_workspace_handle
10849 .update(cx, |mw, window, cx| {
10850 mw.close_window(&CloseWindow, window, cx);
10851 })
10852 .unwrap();
10853 cx.run_until_parked();
10854
10855 // Workspace B should now be active since it has dirty items that need attention
10856 multi_workspace_handle
10857 .read_with(cx, |mw, _| {
10858 assert_eq!(
10859 mw.workspace(),
10860 &workspace_b,
10861 "workspace B should be activated when it prompts"
10862 );
10863 })
10864 .unwrap();
10865
10866 // User cancels the save prompt from workspace B
10867 cx.simulate_prompt_answer("Cancel");
10868 cx.run_until_parked();
10869
10870 // Window should still exist because workspace B's close was cancelled
10871 assert!(
10872 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10873 "window should still exist after cancelling one workspace's close"
10874 );
10875 }
10876
10877 #[gpui::test]
10878 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10879 init_test(cx);
10880
10881 // Register TestItem as a serializable item
10882 cx.update(|cx| {
10883 register_serializable_item::<TestItem>(cx);
10884 });
10885
10886 let fs = FakeFs::new(cx.executor());
10887 fs.insert_tree("/root", json!({ "one": "" })).await;
10888
10889 let project = Project::test(fs, ["root".as_ref()], cx).await;
10890 let (workspace, cx) =
10891 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10892
10893 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10894 let item1 = cx.new(|cx| {
10895 TestItem::new(cx)
10896 .with_dirty(true)
10897 .with_serialize(|| Some(Task::ready(Ok(()))))
10898 });
10899 let item2 = cx.new(|cx| {
10900 TestItem::new(cx)
10901 .with_dirty(true)
10902 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10903 .with_serialize(|| Some(Task::ready(Ok(()))))
10904 });
10905 workspace.update_in(cx, |w, window, cx| {
10906 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10907 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10908 });
10909 let task = workspace.update_in(cx, |w, window, cx| {
10910 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10911 });
10912 assert!(task.await.unwrap());
10913 }
10914
10915 #[gpui::test]
10916 async fn test_close_pane_items(cx: &mut TestAppContext) {
10917 init_test(cx);
10918
10919 let fs = FakeFs::new(cx.executor());
10920
10921 let project = Project::test(fs, None, cx).await;
10922 let (workspace, cx) =
10923 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10924
10925 let item1 = cx.new(|cx| {
10926 TestItem::new(cx)
10927 .with_dirty(true)
10928 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10929 });
10930 let item2 = cx.new(|cx| {
10931 TestItem::new(cx)
10932 .with_dirty(true)
10933 .with_conflict(true)
10934 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10935 });
10936 let item3 = cx.new(|cx| {
10937 TestItem::new(cx)
10938 .with_dirty(true)
10939 .with_conflict(true)
10940 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10941 });
10942 let item4 = cx.new(|cx| {
10943 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10944 let project_item = TestProjectItem::new_untitled(cx);
10945 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10946 project_item
10947 }])
10948 });
10949 let pane = workspace.update_in(cx, |workspace, window, cx| {
10950 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10951 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10952 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10953 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10954 workspace.active_pane().clone()
10955 });
10956
10957 let close_items = pane.update_in(cx, |pane, window, cx| {
10958 pane.activate_item(1, true, true, window, cx);
10959 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10960 let item1_id = item1.item_id();
10961 let item3_id = item3.item_id();
10962 let item4_id = item4.item_id();
10963 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10964 [item1_id, item3_id, item4_id].contains(&id)
10965 })
10966 });
10967 cx.executor().run_until_parked();
10968
10969 assert!(cx.has_pending_prompt());
10970 cx.simulate_prompt_answer("Save all");
10971
10972 cx.executor().run_until_parked();
10973
10974 // Item 1 is saved. There's a prompt to save item 3.
10975 pane.update(cx, |pane, cx| {
10976 assert_eq!(item1.read(cx).save_count, 1);
10977 assert_eq!(item1.read(cx).save_as_count, 0);
10978 assert_eq!(item1.read(cx).reload_count, 0);
10979 assert_eq!(pane.items_len(), 3);
10980 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10981 });
10982 assert!(cx.has_pending_prompt());
10983
10984 // Cancel saving item 3.
10985 cx.simulate_prompt_answer("Discard");
10986 cx.executor().run_until_parked();
10987
10988 // Item 3 is reloaded. There's a prompt to save item 4.
10989 pane.update(cx, |pane, cx| {
10990 assert_eq!(item3.read(cx).save_count, 0);
10991 assert_eq!(item3.read(cx).save_as_count, 0);
10992 assert_eq!(item3.read(cx).reload_count, 1);
10993 assert_eq!(pane.items_len(), 2);
10994 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10995 });
10996
10997 // There's a prompt for a path for item 4.
10998 cx.simulate_new_path_selection(|_| Some(Default::default()));
10999 close_items.await.unwrap();
11000
11001 // The requested items are closed.
11002 pane.update(cx, |pane, cx| {
11003 assert_eq!(item4.read(cx).save_count, 0);
11004 assert_eq!(item4.read(cx).save_as_count, 1);
11005 assert_eq!(item4.read(cx).reload_count, 0);
11006 assert_eq!(pane.items_len(), 1);
11007 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
11008 });
11009 }
11010
11011 #[gpui::test]
11012 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
11013 init_test(cx);
11014
11015 let fs = FakeFs::new(cx.executor());
11016 let project = Project::test(fs, [], cx).await;
11017 let (workspace, cx) =
11018 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11019
11020 // Create several workspace items with single project entries, and two
11021 // workspace items with multiple project entries.
11022 let single_entry_items = (0..=4)
11023 .map(|project_entry_id| {
11024 cx.new(|cx| {
11025 TestItem::new(cx)
11026 .with_dirty(true)
11027 .with_project_items(&[dirty_project_item(
11028 project_entry_id,
11029 &format!("{project_entry_id}.txt"),
11030 cx,
11031 )])
11032 })
11033 })
11034 .collect::<Vec<_>>();
11035 let item_2_3 = cx.new(|cx| {
11036 TestItem::new(cx)
11037 .with_dirty(true)
11038 .with_buffer_kind(ItemBufferKind::Multibuffer)
11039 .with_project_items(&[
11040 single_entry_items[2].read(cx).project_items[0].clone(),
11041 single_entry_items[3].read(cx).project_items[0].clone(),
11042 ])
11043 });
11044 let item_3_4 = cx.new(|cx| {
11045 TestItem::new(cx)
11046 .with_dirty(true)
11047 .with_buffer_kind(ItemBufferKind::Multibuffer)
11048 .with_project_items(&[
11049 single_entry_items[3].read(cx).project_items[0].clone(),
11050 single_entry_items[4].read(cx).project_items[0].clone(),
11051 ])
11052 });
11053
11054 // Create two panes that contain the following project entries:
11055 // left pane:
11056 // multi-entry items: (2, 3)
11057 // single-entry items: 0, 2, 3, 4
11058 // right pane:
11059 // single-entry items: 4, 1
11060 // multi-entry items: (3, 4)
11061 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
11062 let left_pane = workspace.active_pane().clone();
11063 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
11064 workspace.add_item_to_active_pane(
11065 single_entry_items[0].boxed_clone(),
11066 None,
11067 true,
11068 window,
11069 cx,
11070 );
11071 workspace.add_item_to_active_pane(
11072 single_entry_items[2].boxed_clone(),
11073 None,
11074 true,
11075 window,
11076 cx,
11077 );
11078 workspace.add_item_to_active_pane(
11079 single_entry_items[3].boxed_clone(),
11080 None,
11081 true,
11082 window,
11083 cx,
11084 );
11085 workspace.add_item_to_active_pane(
11086 single_entry_items[4].boxed_clone(),
11087 None,
11088 true,
11089 window,
11090 cx,
11091 );
11092
11093 let right_pane =
11094 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
11095
11096 let boxed_clone = single_entry_items[1].boxed_clone();
11097 let right_pane = window.spawn(cx, async move |cx| {
11098 right_pane.await.inspect(|right_pane| {
11099 right_pane
11100 .update_in(cx, |pane, window, cx| {
11101 pane.add_item(boxed_clone, true, true, None, window, cx);
11102 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
11103 })
11104 .unwrap();
11105 })
11106 });
11107
11108 (left_pane, right_pane)
11109 });
11110 let right_pane = right_pane.await.unwrap();
11111 cx.focus(&right_pane);
11112
11113 let close = right_pane.update_in(cx, |pane, window, cx| {
11114 pane.close_all_items(&CloseAllItems::default(), window, cx)
11115 .unwrap()
11116 });
11117 cx.executor().run_until_parked();
11118
11119 let msg = cx.pending_prompt().unwrap().0;
11120 assert!(msg.contains("1.txt"));
11121 assert!(!msg.contains("2.txt"));
11122 assert!(!msg.contains("3.txt"));
11123 assert!(!msg.contains("4.txt"));
11124
11125 // With best-effort close, cancelling item 1 keeps it open but items 4
11126 // and (3,4) still close since their entries exist in left pane.
11127 cx.simulate_prompt_answer("Cancel");
11128 close.await;
11129
11130 right_pane.read_with(cx, |pane, _| {
11131 assert_eq!(pane.items_len(), 1);
11132 });
11133
11134 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
11135 left_pane
11136 .update_in(cx, |left_pane, window, cx| {
11137 left_pane.close_item_by_id(
11138 single_entry_items[3].entity_id(),
11139 SaveIntent::Skip,
11140 window,
11141 cx,
11142 )
11143 })
11144 .await
11145 .unwrap();
11146
11147 let close = left_pane.update_in(cx, |pane, window, cx| {
11148 pane.close_all_items(&CloseAllItems::default(), window, cx)
11149 .unwrap()
11150 });
11151 cx.executor().run_until_parked();
11152
11153 let details = cx.pending_prompt().unwrap().1;
11154 assert!(details.contains("0.txt"));
11155 assert!(details.contains("3.txt"));
11156 assert!(details.contains("4.txt"));
11157 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
11158 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
11159 // assert!(!details.contains("2.txt"));
11160
11161 cx.simulate_prompt_answer("Save all");
11162 cx.executor().run_until_parked();
11163 close.await;
11164
11165 left_pane.read_with(cx, |pane, _| {
11166 assert_eq!(pane.items_len(), 0);
11167 });
11168 }
11169
11170 #[gpui::test]
11171 async fn test_autosave(cx: &mut gpui::TestAppContext) {
11172 init_test(cx);
11173
11174 let fs = FakeFs::new(cx.executor());
11175 let project = Project::test(fs, [], cx).await;
11176 let (workspace, cx) =
11177 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11178 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11179
11180 let item = cx.new(|cx| {
11181 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11182 });
11183 let item_id = item.entity_id();
11184 workspace.update_in(cx, |workspace, window, cx| {
11185 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11186 });
11187
11188 // Autosave on window change.
11189 item.update(cx, |item, cx| {
11190 SettingsStore::update_global(cx, |settings, cx| {
11191 settings.update_user_settings(cx, |settings| {
11192 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
11193 })
11194 });
11195 item.is_dirty = true;
11196 });
11197
11198 // Deactivating the window saves the file.
11199 cx.deactivate_window();
11200 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11201
11202 // Re-activating the window doesn't save the file.
11203 cx.update(|window, _| window.activate_window());
11204 cx.executor().run_until_parked();
11205 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11206
11207 // Autosave on focus change.
11208 item.update_in(cx, |item, window, cx| {
11209 cx.focus_self(window);
11210 SettingsStore::update_global(cx, |settings, cx| {
11211 settings.update_user_settings(cx, |settings| {
11212 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11213 })
11214 });
11215 item.is_dirty = true;
11216 });
11217 // Blurring the item saves the file.
11218 item.update_in(cx, |_, window, _| window.blur());
11219 cx.executor().run_until_parked();
11220 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
11221
11222 // Deactivating the window still saves the file.
11223 item.update_in(cx, |item, window, cx| {
11224 cx.focus_self(window);
11225 item.is_dirty = true;
11226 });
11227 cx.deactivate_window();
11228 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
11229
11230 // Autosave after delay.
11231 item.update(cx, |item, cx| {
11232 SettingsStore::update_global(cx, |settings, cx| {
11233 settings.update_user_settings(cx, |settings| {
11234 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
11235 milliseconds: 500.into(),
11236 });
11237 })
11238 });
11239 item.is_dirty = true;
11240 cx.emit(ItemEvent::Edit);
11241 });
11242
11243 // Delay hasn't fully expired, so the file is still dirty and unsaved.
11244 cx.executor().advance_clock(Duration::from_millis(250));
11245 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
11246
11247 // After delay expires, the file is saved.
11248 cx.executor().advance_clock(Duration::from_millis(250));
11249 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11250
11251 // Autosave after delay, should save earlier than delay if tab is closed
11252 item.update(cx, |item, cx| {
11253 item.is_dirty = true;
11254 cx.emit(ItemEvent::Edit);
11255 });
11256 cx.executor().advance_clock(Duration::from_millis(250));
11257 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
11258
11259 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
11260 pane.update_in(cx, |pane, window, cx| {
11261 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11262 })
11263 .await
11264 .unwrap();
11265 assert!(!cx.has_pending_prompt());
11266 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11267
11268 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11269 workspace.update_in(cx, |workspace, window, cx| {
11270 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11271 });
11272 item.update_in(cx, |item, _window, cx| {
11273 item.is_dirty = true;
11274 for project_item in &mut item.project_items {
11275 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11276 }
11277 });
11278 cx.run_until_parked();
11279 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
11280
11281 // Autosave on focus change, ensuring closing the tab counts as such.
11282 item.update(cx, |item, cx| {
11283 SettingsStore::update_global(cx, |settings, cx| {
11284 settings.update_user_settings(cx, |settings| {
11285 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11286 })
11287 });
11288 item.is_dirty = true;
11289 for project_item in &mut item.project_items {
11290 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
11291 }
11292 });
11293
11294 pane.update_in(cx, |pane, window, cx| {
11295 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11296 })
11297 .await
11298 .unwrap();
11299 assert!(!cx.has_pending_prompt());
11300 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11301
11302 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
11303 workspace.update_in(cx, |workspace, window, cx| {
11304 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11305 });
11306 item.update_in(cx, |item, window, cx| {
11307 item.project_items[0].update(cx, |item, _| {
11308 item.entry_id = None;
11309 });
11310 item.is_dirty = true;
11311 window.blur();
11312 });
11313 cx.run_until_parked();
11314 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11315
11316 // Ensure autosave is prevented for deleted files also when closing the buffer.
11317 let _close_items = pane.update_in(cx, |pane, window, cx| {
11318 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
11319 });
11320 cx.run_until_parked();
11321 assert!(cx.has_pending_prompt());
11322 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
11323 }
11324
11325 #[gpui::test]
11326 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
11327 init_test(cx);
11328
11329 let fs = FakeFs::new(cx.executor());
11330 let project = Project::test(fs, [], cx).await;
11331 let (workspace, cx) =
11332 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11333
11334 // Create a multibuffer-like item with two child focus handles,
11335 // simulating individual buffer editors within a multibuffer.
11336 let item = cx.new(|cx| {
11337 TestItem::new(cx)
11338 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11339 .with_child_focus_handles(2, cx)
11340 });
11341 workspace.update_in(cx, |workspace, window, cx| {
11342 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11343 });
11344
11345 // Set autosave to OnFocusChange and focus the first child handle,
11346 // simulating the user's cursor being inside one of the multibuffer's excerpts.
11347 item.update_in(cx, |item, window, cx| {
11348 SettingsStore::update_global(cx, |settings, cx| {
11349 settings.update_user_settings(cx, |settings| {
11350 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
11351 })
11352 });
11353 item.is_dirty = true;
11354 window.focus(&item.child_focus_handles[0], cx);
11355 });
11356 cx.executor().run_until_parked();
11357 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
11358
11359 // Moving focus from one child to another within the same item should
11360 // NOT trigger autosave — focus is still within the item's focus hierarchy.
11361 item.update_in(cx, |item, window, cx| {
11362 window.focus(&item.child_focus_handles[1], cx);
11363 });
11364 cx.executor().run_until_parked();
11365 item.read_with(cx, |item, _| {
11366 assert_eq!(
11367 item.save_count, 0,
11368 "Switching focus between children within the same item should not autosave"
11369 );
11370 });
11371
11372 // Blurring the item saves the file. This is the core regression scenario:
11373 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
11374 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
11375 // the leaf is always a child focus handle, so `on_blur` never detected
11376 // focus leaving the item.
11377 item.update_in(cx, |_, window, _| window.blur());
11378 cx.executor().run_until_parked();
11379 item.read_with(cx, |item, _| {
11380 assert_eq!(
11381 item.save_count, 1,
11382 "Blurring should trigger autosave when focus was on a child of the item"
11383 );
11384 });
11385
11386 // Deactivating the window should also trigger autosave when a child of
11387 // the multibuffer item currently owns focus.
11388 item.update_in(cx, |item, window, cx| {
11389 item.is_dirty = true;
11390 window.focus(&item.child_focus_handles[0], cx);
11391 });
11392 cx.executor().run_until_parked();
11393 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
11394
11395 cx.deactivate_window();
11396 item.read_with(cx, |item, _| {
11397 assert_eq!(
11398 item.save_count, 2,
11399 "Deactivating window should trigger autosave when focus was on a child"
11400 );
11401 });
11402 }
11403
11404 #[gpui::test]
11405 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
11406 init_test(cx);
11407
11408 let fs = FakeFs::new(cx.executor());
11409
11410 let project = Project::test(fs, [], cx).await;
11411 let (workspace, cx) =
11412 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11413
11414 let item = cx.new(|cx| {
11415 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11416 });
11417 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11418 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
11419 let toolbar_notify_count = Rc::new(RefCell::new(0));
11420
11421 workspace.update_in(cx, |workspace, window, cx| {
11422 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
11423 let toolbar_notification_count = toolbar_notify_count.clone();
11424 cx.observe_in(&toolbar, window, move |_, _, _, _| {
11425 *toolbar_notification_count.borrow_mut() += 1
11426 })
11427 .detach();
11428 });
11429
11430 pane.read_with(cx, |pane, _| {
11431 assert!(!pane.can_navigate_backward());
11432 assert!(!pane.can_navigate_forward());
11433 });
11434
11435 item.update_in(cx, |item, _, cx| {
11436 item.set_state("one".to_string(), cx);
11437 });
11438
11439 // Toolbar must be notified to re-render the navigation buttons
11440 assert_eq!(*toolbar_notify_count.borrow(), 1);
11441
11442 pane.read_with(cx, |pane, _| {
11443 assert!(pane.can_navigate_backward());
11444 assert!(!pane.can_navigate_forward());
11445 });
11446
11447 workspace
11448 .update_in(cx, |workspace, window, cx| {
11449 workspace.go_back(pane.downgrade(), window, cx)
11450 })
11451 .await
11452 .unwrap();
11453
11454 assert_eq!(*toolbar_notify_count.borrow(), 2);
11455 pane.read_with(cx, |pane, _| {
11456 assert!(!pane.can_navigate_backward());
11457 assert!(pane.can_navigate_forward());
11458 });
11459 }
11460
11461 /// Tests that the navigation history deduplicates entries for the same item.
11462 ///
11463 /// When navigating back and forth between items (e.g., A -> B -> A -> B -> A -> B -> C),
11464 /// the navigation history deduplicates by keeping only the most recent visit to each item,
11465 /// resulting in [A, B, C] instead of [A, B, A, B, A, B, C]. This ensures that Go Back (Ctrl-O)
11466 /// navigates through unique items efficiently: C -> B -> A, rather than bouncing between
11467 /// repeated entries: C -> B -> A -> B -> A -> B -> A.
11468 ///
11469 /// This behavior prevents the navigation history from growing unnecessarily large and provides
11470 /// a better user experience by eliminating redundant navigation steps when jumping between files.
11471 #[gpui::test]
11472 async fn test_navigation_history_deduplication(cx: &mut gpui::TestAppContext) {
11473 init_test(cx);
11474
11475 let fs = FakeFs::new(cx.executor());
11476 let project = Project::test(fs, [], cx).await;
11477 let (workspace, cx) =
11478 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11479
11480 let item_a = cx.new(|cx| {
11481 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "a.txt", cx)])
11482 });
11483 let item_b = cx.new(|cx| {
11484 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "b.txt", cx)])
11485 });
11486 let item_c = cx.new(|cx| {
11487 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "c.txt", cx)])
11488 });
11489
11490 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11491
11492 workspace.update_in(cx, |workspace, window, cx| {
11493 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx);
11494 workspace.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx);
11495 workspace.add_item_to_active_pane(Box::new(item_c.clone()), None, true, window, cx);
11496 });
11497
11498 workspace.update_in(cx, |workspace, window, cx| {
11499 workspace.activate_item(&item_a, false, false, window, cx);
11500 });
11501 cx.run_until_parked();
11502
11503 workspace.update_in(cx, |workspace, window, cx| {
11504 workspace.activate_item(&item_b, false, false, window, cx);
11505 });
11506 cx.run_until_parked();
11507
11508 workspace.update_in(cx, |workspace, window, cx| {
11509 workspace.activate_item(&item_a, false, false, window, cx);
11510 });
11511 cx.run_until_parked();
11512
11513 workspace.update_in(cx, |workspace, window, cx| {
11514 workspace.activate_item(&item_b, false, false, window, cx);
11515 });
11516 cx.run_until_parked();
11517
11518 workspace.update_in(cx, |workspace, window, cx| {
11519 workspace.activate_item(&item_a, false, false, window, cx);
11520 });
11521 cx.run_until_parked();
11522
11523 workspace.update_in(cx, |workspace, window, cx| {
11524 workspace.activate_item(&item_b, false, false, window, cx);
11525 });
11526 cx.run_until_parked();
11527
11528 workspace.update_in(cx, |workspace, window, cx| {
11529 workspace.activate_item(&item_c, false, false, window, cx);
11530 });
11531 cx.run_until_parked();
11532
11533 let backward_count = pane.read_with(cx, |pane, cx| {
11534 let mut count = 0;
11535 pane.nav_history().for_each_entry(cx, &mut |_, _| {
11536 count += 1;
11537 });
11538 count
11539 });
11540 assert!(
11541 backward_count <= 4,
11542 "Should have at most 4 entries, got {}",
11543 backward_count
11544 );
11545
11546 workspace
11547 .update_in(cx, |workspace, window, cx| {
11548 workspace.go_back(pane.downgrade(), window, cx)
11549 })
11550 .await
11551 .unwrap();
11552
11553 let active_item = workspace.read_with(cx, |workspace, cx| {
11554 workspace.active_item(cx).unwrap().item_id()
11555 });
11556 assert_eq!(
11557 active_item,
11558 item_b.entity_id(),
11559 "After first go_back, should be at item B"
11560 );
11561
11562 workspace
11563 .update_in(cx, |workspace, window, cx| {
11564 workspace.go_back(pane.downgrade(), window, cx)
11565 })
11566 .await
11567 .unwrap();
11568
11569 let active_item = workspace.read_with(cx, |workspace, cx| {
11570 workspace.active_item(cx).unwrap().item_id()
11571 });
11572 assert_eq!(
11573 active_item,
11574 item_a.entity_id(),
11575 "After second go_back, should be at item A"
11576 );
11577
11578 pane.read_with(cx, |pane, _| {
11579 assert!(pane.can_navigate_forward(), "Should be able to go forward");
11580 });
11581 }
11582
11583 #[gpui::test]
11584 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
11585 init_test(cx);
11586 let fs = FakeFs::new(cx.executor());
11587 let project = Project::test(fs, [], cx).await;
11588 let (multi_workspace, cx) =
11589 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11590 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11591
11592 workspace.update_in(cx, |workspace, window, cx| {
11593 let first_item = cx.new(|cx| {
11594 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
11595 });
11596 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
11597 workspace.split_pane(
11598 workspace.active_pane().clone(),
11599 SplitDirection::Right,
11600 window,
11601 cx,
11602 );
11603 workspace.split_pane(
11604 workspace.active_pane().clone(),
11605 SplitDirection::Right,
11606 window,
11607 cx,
11608 );
11609 });
11610
11611 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11612 let panes = workspace.center.panes();
11613 assert!(panes.len() >= 2);
11614 (
11615 panes.first().expect("at least one pane").entity_id(),
11616 panes.last().expect("at least one pane").entity_id(),
11617 )
11618 });
11619
11620 workspace.update_in(cx, |workspace, window, cx| {
11621 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11622 });
11623 workspace.update(cx, |workspace, _| {
11624 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11625 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11626 });
11627
11628 cx.dispatch_action(ActivateLastPane);
11629
11630 workspace.update(cx, |workspace, _| {
11631 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11632 });
11633 }
11634
11635 #[gpui::test]
11636 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11637 init_test(cx);
11638 let fs = FakeFs::new(cx.executor());
11639
11640 let project = Project::test(fs, [], cx).await;
11641 let (workspace, cx) =
11642 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11643
11644 let panel = workspace.update_in(cx, |workspace, window, cx| {
11645 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11646 workspace.add_panel(panel.clone(), window, cx);
11647
11648 workspace
11649 .right_dock()
11650 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11651
11652 panel
11653 });
11654
11655 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11656 pane.update_in(cx, |pane, window, cx| {
11657 let item = cx.new(TestItem::new);
11658 pane.add_item(Box::new(item), true, true, None, window, cx);
11659 });
11660
11661 // Transfer focus from center to panel
11662 workspace.update_in(cx, |workspace, window, cx| {
11663 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11664 });
11665
11666 workspace.update_in(cx, |workspace, window, cx| {
11667 assert!(workspace.right_dock().read(cx).is_open());
11668 assert!(!panel.is_zoomed(window, cx));
11669 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11670 });
11671
11672 // Transfer focus from panel to center
11673 workspace.update_in(cx, |workspace, window, cx| {
11674 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11675 });
11676
11677 workspace.update_in(cx, |workspace, window, cx| {
11678 assert!(workspace.right_dock().read(cx).is_open());
11679 assert!(!panel.is_zoomed(window, cx));
11680 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11681 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11682 });
11683
11684 // Close the dock
11685 workspace.update_in(cx, |workspace, window, cx| {
11686 workspace.toggle_dock(DockPosition::Right, window, cx);
11687 });
11688
11689 workspace.update_in(cx, |workspace, window, cx| {
11690 assert!(!workspace.right_dock().read(cx).is_open());
11691 assert!(!panel.is_zoomed(window, cx));
11692 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11693 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11694 });
11695
11696 // Open the dock
11697 workspace.update_in(cx, |workspace, window, cx| {
11698 workspace.toggle_dock(DockPosition::Right, window, cx);
11699 });
11700
11701 workspace.update_in(cx, |workspace, window, cx| {
11702 assert!(workspace.right_dock().read(cx).is_open());
11703 assert!(!panel.is_zoomed(window, cx));
11704 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11705 });
11706
11707 // Focus and zoom panel
11708 panel.update_in(cx, |panel, window, cx| {
11709 cx.focus_self(window);
11710 panel.set_zoomed(true, window, cx)
11711 });
11712
11713 workspace.update_in(cx, |workspace, window, cx| {
11714 assert!(workspace.right_dock().read(cx).is_open());
11715 assert!(panel.is_zoomed(window, cx));
11716 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11717 });
11718
11719 // Transfer focus to the center closes the dock
11720 workspace.update_in(cx, |workspace, window, cx| {
11721 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11722 });
11723
11724 workspace.update_in(cx, |workspace, window, cx| {
11725 assert!(!workspace.right_dock().read(cx).is_open());
11726 assert!(panel.is_zoomed(window, cx));
11727 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11728 });
11729
11730 // Transferring focus back to the panel keeps it zoomed
11731 workspace.update_in(cx, |workspace, window, cx| {
11732 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11733 });
11734
11735 workspace.update_in(cx, |workspace, window, cx| {
11736 assert!(workspace.right_dock().read(cx).is_open());
11737 assert!(panel.is_zoomed(window, cx));
11738 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11739 });
11740
11741 // Close the dock while it is zoomed
11742 workspace.update_in(cx, |workspace, window, cx| {
11743 workspace.toggle_dock(DockPosition::Right, window, cx)
11744 });
11745
11746 workspace.update_in(cx, |workspace, window, cx| {
11747 assert!(!workspace.right_dock().read(cx).is_open());
11748 assert!(panel.is_zoomed(window, cx));
11749 assert!(workspace.zoomed.is_none());
11750 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11751 });
11752
11753 // Opening the dock, when it's zoomed, retains focus
11754 workspace.update_in(cx, |workspace, window, cx| {
11755 workspace.toggle_dock(DockPosition::Right, window, cx)
11756 });
11757
11758 workspace.update_in(cx, |workspace, window, cx| {
11759 assert!(workspace.right_dock().read(cx).is_open());
11760 assert!(panel.is_zoomed(window, cx));
11761 assert!(workspace.zoomed.is_some());
11762 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11763 });
11764
11765 // Unzoom and close the panel, zoom the active pane.
11766 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11767 workspace.update_in(cx, |workspace, window, cx| {
11768 workspace.toggle_dock(DockPosition::Right, window, cx)
11769 });
11770 pane.update_in(cx, |pane, window, cx| {
11771 pane.toggle_zoom(&Default::default(), window, cx)
11772 });
11773
11774 // Opening a dock unzooms the pane.
11775 workspace.update_in(cx, |workspace, window, cx| {
11776 workspace.toggle_dock(DockPosition::Right, window, cx)
11777 });
11778 workspace.update_in(cx, |workspace, window, cx| {
11779 let pane = pane.read(cx);
11780 assert!(!pane.is_zoomed());
11781 assert!(!pane.focus_handle(cx).is_focused(window));
11782 assert!(workspace.right_dock().read(cx).is_open());
11783 assert!(workspace.zoomed.is_none());
11784 });
11785 }
11786
11787 #[gpui::test]
11788 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11789 init_test(cx);
11790 let fs = FakeFs::new(cx.executor());
11791
11792 let project = Project::test(fs, [], cx).await;
11793 let (workspace, cx) =
11794 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11795
11796 let panel = workspace.update_in(cx, |workspace, window, cx| {
11797 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11798 workspace.add_panel(panel.clone(), window, cx);
11799 panel
11800 });
11801
11802 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11803 pane.update_in(cx, |pane, window, cx| {
11804 let item = cx.new(TestItem::new);
11805 pane.add_item(Box::new(item), true, true, None, window, cx);
11806 });
11807
11808 // Enable close_panel_on_toggle
11809 cx.update_global(|store: &mut SettingsStore, cx| {
11810 store.update_user_settings(cx, |settings| {
11811 settings.workspace.close_panel_on_toggle = Some(true);
11812 });
11813 });
11814
11815 // Panel starts closed. Toggling should open and focus it.
11816 workspace.update_in(cx, |workspace, window, cx| {
11817 assert!(!workspace.right_dock().read(cx).is_open());
11818 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11819 });
11820
11821 workspace.update_in(cx, |workspace, window, cx| {
11822 assert!(
11823 workspace.right_dock().read(cx).is_open(),
11824 "Dock should be open after toggling from center"
11825 );
11826 assert!(
11827 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11828 "Panel should be focused after toggling from center"
11829 );
11830 });
11831
11832 // Panel is open and focused. Toggling should close the panel and
11833 // return focus to the center.
11834 workspace.update_in(cx, |workspace, window, cx| {
11835 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11836 });
11837
11838 workspace.update_in(cx, |workspace, window, cx| {
11839 assert!(
11840 !workspace.right_dock().read(cx).is_open(),
11841 "Dock should be closed after toggling from focused panel"
11842 );
11843 assert!(
11844 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11845 "Panel should not be focused after toggling from focused panel"
11846 );
11847 });
11848
11849 // Open the dock and focus something else so the panel is open but not
11850 // focused. Toggling should focus the panel (not close it).
11851 workspace.update_in(cx, |workspace, window, cx| {
11852 workspace
11853 .right_dock()
11854 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11855 window.focus(&pane.read(cx).focus_handle(cx), cx);
11856 });
11857
11858 workspace.update_in(cx, |workspace, window, cx| {
11859 assert!(workspace.right_dock().read(cx).is_open());
11860 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11861 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11862 });
11863
11864 workspace.update_in(cx, |workspace, window, cx| {
11865 assert!(
11866 workspace.right_dock().read(cx).is_open(),
11867 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11868 );
11869 assert!(
11870 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11871 "Panel should be focused after toggling an open-but-unfocused panel"
11872 );
11873 });
11874
11875 // Now disable the setting and verify the original behavior: toggling
11876 // from a focused panel moves focus to center but leaves the dock open.
11877 cx.update_global(|store: &mut SettingsStore, cx| {
11878 store.update_user_settings(cx, |settings| {
11879 settings.workspace.close_panel_on_toggle = Some(false);
11880 });
11881 });
11882
11883 workspace.update_in(cx, |workspace, window, cx| {
11884 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11885 });
11886
11887 workspace.update_in(cx, |workspace, window, cx| {
11888 assert!(
11889 workspace.right_dock().read(cx).is_open(),
11890 "Dock should remain open when setting is disabled"
11891 );
11892 assert!(
11893 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11894 "Panel should not be focused after toggling with setting disabled"
11895 );
11896 });
11897 }
11898
11899 #[gpui::test]
11900 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11901 init_test(cx);
11902 let fs = FakeFs::new(cx.executor());
11903
11904 let project = Project::test(fs, [], cx).await;
11905 let (workspace, cx) =
11906 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11907
11908 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11909 workspace.active_pane().clone()
11910 });
11911
11912 // Add an item to the pane so it can be zoomed
11913 workspace.update_in(cx, |workspace, window, cx| {
11914 let item = cx.new(TestItem::new);
11915 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11916 });
11917
11918 // Initially not zoomed
11919 workspace.update_in(cx, |workspace, _window, cx| {
11920 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11921 assert!(
11922 workspace.zoomed.is_none(),
11923 "Workspace should track no zoomed pane"
11924 );
11925 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11926 });
11927
11928 // Zoom In
11929 pane.update_in(cx, |pane, window, cx| {
11930 pane.zoom_in(&crate::ZoomIn, window, cx);
11931 });
11932
11933 workspace.update_in(cx, |workspace, window, cx| {
11934 assert!(
11935 pane.read(cx).is_zoomed(),
11936 "Pane should be zoomed after ZoomIn"
11937 );
11938 assert!(
11939 workspace.zoomed.is_some(),
11940 "Workspace should track the zoomed pane"
11941 );
11942 assert!(
11943 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11944 "ZoomIn should focus the pane"
11945 );
11946 });
11947
11948 // Zoom In again is a no-op
11949 pane.update_in(cx, |pane, window, cx| {
11950 pane.zoom_in(&crate::ZoomIn, window, cx);
11951 });
11952
11953 workspace.update_in(cx, |workspace, window, cx| {
11954 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11955 assert!(
11956 workspace.zoomed.is_some(),
11957 "Workspace still tracks zoomed pane"
11958 );
11959 assert!(
11960 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11961 "Pane remains focused after repeated ZoomIn"
11962 );
11963 });
11964
11965 // Zoom Out
11966 pane.update_in(cx, |pane, window, cx| {
11967 pane.zoom_out(&crate::ZoomOut, window, cx);
11968 });
11969
11970 workspace.update_in(cx, |workspace, _window, cx| {
11971 assert!(
11972 !pane.read(cx).is_zoomed(),
11973 "Pane should unzoom after ZoomOut"
11974 );
11975 assert!(
11976 workspace.zoomed.is_none(),
11977 "Workspace clears zoom tracking after ZoomOut"
11978 );
11979 });
11980
11981 // Zoom Out again is a no-op
11982 pane.update_in(cx, |pane, window, cx| {
11983 pane.zoom_out(&crate::ZoomOut, window, cx);
11984 });
11985
11986 workspace.update_in(cx, |workspace, _window, cx| {
11987 assert!(
11988 !pane.read(cx).is_zoomed(),
11989 "Second ZoomOut keeps pane unzoomed"
11990 );
11991 assert!(
11992 workspace.zoomed.is_none(),
11993 "Workspace remains without zoomed pane"
11994 );
11995 });
11996 }
11997
11998 #[gpui::test]
11999 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
12000 init_test(cx);
12001 let fs = FakeFs::new(cx.executor());
12002
12003 let project = Project::test(fs, [], cx).await;
12004 let (workspace, cx) =
12005 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12006 workspace.update_in(cx, |workspace, window, cx| {
12007 // Open two docks
12008 let left_dock = workspace.dock_at_position(DockPosition::Left);
12009 let right_dock = workspace.dock_at_position(DockPosition::Right);
12010
12011 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12012 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12013
12014 assert!(left_dock.read(cx).is_open());
12015 assert!(right_dock.read(cx).is_open());
12016 });
12017
12018 workspace.update_in(cx, |workspace, window, cx| {
12019 // Toggle all docks - should close both
12020 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12021
12022 let left_dock = workspace.dock_at_position(DockPosition::Left);
12023 let right_dock = workspace.dock_at_position(DockPosition::Right);
12024 assert!(!left_dock.read(cx).is_open());
12025 assert!(!right_dock.read(cx).is_open());
12026 });
12027
12028 workspace.update_in(cx, |workspace, window, cx| {
12029 // Toggle again - should reopen both
12030 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12031
12032 let left_dock = workspace.dock_at_position(DockPosition::Left);
12033 let right_dock = workspace.dock_at_position(DockPosition::Right);
12034 assert!(left_dock.read(cx).is_open());
12035 assert!(right_dock.read(cx).is_open());
12036 });
12037 }
12038
12039 #[gpui::test]
12040 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
12041 init_test(cx);
12042 let fs = FakeFs::new(cx.executor());
12043
12044 let project = Project::test(fs, [], cx).await;
12045 let (workspace, cx) =
12046 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12047 workspace.update_in(cx, |workspace, window, cx| {
12048 // Open two docks
12049 let left_dock = workspace.dock_at_position(DockPosition::Left);
12050 let right_dock = workspace.dock_at_position(DockPosition::Right);
12051
12052 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12053 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
12054
12055 assert!(left_dock.read(cx).is_open());
12056 assert!(right_dock.read(cx).is_open());
12057 });
12058
12059 workspace.update_in(cx, |workspace, window, cx| {
12060 // Close them manually
12061 workspace.toggle_dock(DockPosition::Left, window, cx);
12062 workspace.toggle_dock(DockPosition::Right, window, cx);
12063
12064 let left_dock = workspace.dock_at_position(DockPosition::Left);
12065 let right_dock = workspace.dock_at_position(DockPosition::Right);
12066 assert!(!left_dock.read(cx).is_open());
12067 assert!(!right_dock.read(cx).is_open());
12068 });
12069
12070 workspace.update_in(cx, |workspace, window, cx| {
12071 // Toggle all docks - only last closed (right dock) should reopen
12072 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12073
12074 let left_dock = workspace.dock_at_position(DockPosition::Left);
12075 let right_dock = workspace.dock_at_position(DockPosition::Right);
12076 assert!(!left_dock.read(cx).is_open());
12077 assert!(right_dock.read(cx).is_open());
12078 });
12079 }
12080
12081 #[gpui::test]
12082 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
12083 init_test(cx);
12084 let fs = FakeFs::new(cx.executor());
12085 let project = Project::test(fs, [], cx).await;
12086 let (multi_workspace, cx) =
12087 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12088 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12089
12090 // Open two docks (left and right) with one panel each
12091 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
12092 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12093 workspace.add_panel(left_panel.clone(), window, cx);
12094
12095 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12096 workspace.add_panel(right_panel.clone(), window, cx);
12097
12098 workspace.toggle_dock(DockPosition::Left, window, cx);
12099 workspace.toggle_dock(DockPosition::Right, window, cx);
12100
12101 // Verify initial state
12102 assert!(
12103 workspace.left_dock().read(cx).is_open(),
12104 "Left dock should be open"
12105 );
12106 assert_eq!(
12107 workspace
12108 .left_dock()
12109 .read(cx)
12110 .visible_panel()
12111 .unwrap()
12112 .panel_id(),
12113 left_panel.panel_id(),
12114 "Left panel should be visible in left dock"
12115 );
12116 assert!(
12117 workspace.right_dock().read(cx).is_open(),
12118 "Right dock should be open"
12119 );
12120 assert_eq!(
12121 workspace
12122 .right_dock()
12123 .read(cx)
12124 .visible_panel()
12125 .unwrap()
12126 .panel_id(),
12127 right_panel.panel_id(),
12128 "Right panel should be visible in right dock"
12129 );
12130 assert!(
12131 !workspace.bottom_dock().read(cx).is_open(),
12132 "Bottom dock should be closed"
12133 );
12134
12135 (left_panel, right_panel)
12136 });
12137
12138 // Focus the left panel and move it to the next position (bottom dock)
12139 workspace.update_in(cx, |workspace, window, cx| {
12140 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
12141 assert!(
12142 left_panel.read(cx).focus_handle(cx).is_focused(window),
12143 "Left panel should be focused"
12144 );
12145 });
12146
12147 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12148
12149 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
12150 workspace.update(cx, |workspace, cx| {
12151 assert!(
12152 !workspace.left_dock().read(cx).is_open(),
12153 "Left dock should be closed"
12154 );
12155 assert!(
12156 workspace.bottom_dock().read(cx).is_open(),
12157 "Bottom dock should now be open"
12158 );
12159 assert_eq!(
12160 left_panel.read(cx).position,
12161 DockPosition::Bottom,
12162 "Left panel should now be in the bottom dock"
12163 );
12164 assert_eq!(
12165 workspace
12166 .bottom_dock()
12167 .read(cx)
12168 .visible_panel()
12169 .unwrap()
12170 .panel_id(),
12171 left_panel.panel_id(),
12172 "Left panel should be the visible panel in the bottom dock"
12173 );
12174 });
12175
12176 // Toggle all docks off
12177 workspace.update_in(cx, |workspace, window, cx| {
12178 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12179 assert!(
12180 !workspace.left_dock().read(cx).is_open(),
12181 "Left dock should be closed"
12182 );
12183 assert!(
12184 !workspace.right_dock().read(cx).is_open(),
12185 "Right dock should be closed"
12186 );
12187 assert!(
12188 !workspace.bottom_dock().read(cx).is_open(),
12189 "Bottom dock should be closed"
12190 );
12191 });
12192
12193 // Toggle all docks back on and verify positions are restored
12194 workspace.update_in(cx, |workspace, window, cx| {
12195 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
12196 assert!(
12197 !workspace.left_dock().read(cx).is_open(),
12198 "Left dock should remain closed"
12199 );
12200 assert!(
12201 workspace.right_dock().read(cx).is_open(),
12202 "Right dock should remain open"
12203 );
12204 assert!(
12205 workspace.bottom_dock().read(cx).is_open(),
12206 "Bottom dock should remain open"
12207 );
12208 assert_eq!(
12209 left_panel.read(cx).position,
12210 DockPosition::Bottom,
12211 "Left panel should remain in the bottom dock"
12212 );
12213 assert_eq!(
12214 right_panel.read(cx).position,
12215 DockPosition::Right,
12216 "Right panel should remain in the right dock"
12217 );
12218 assert_eq!(
12219 workspace
12220 .bottom_dock()
12221 .read(cx)
12222 .visible_panel()
12223 .unwrap()
12224 .panel_id(),
12225 left_panel.panel_id(),
12226 "Left panel should be the visible panel in the right dock"
12227 );
12228 });
12229 }
12230
12231 #[gpui::test]
12232 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
12233 init_test(cx);
12234
12235 let fs = FakeFs::new(cx.executor());
12236
12237 let project = Project::test(fs, None, cx).await;
12238 let (workspace, cx) =
12239 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12240
12241 // Let's arrange the panes like this:
12242 //
12243 // +-----------------------+
12244 // | top |
12245 // +------+--------+-------+
12246 // | left | center | right |
12247 // +------+--------+-------+
12248 // | bottom |
12249 // +-----------------------+
12250
12251 let top_item = cx.new(|cx| {
12252 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
12253 });
12254 let bottom_item = cx.new(|cx| {
12255 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
12256 });
12257 let left_item = cx.new(|cx| {
12258 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
12259 });
12260 let right_item = cx.new(|cx| {
12261 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
12262 });
12263 let center_item = cx.new(|cx| {
12264 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
12265 });
12266
12267 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12268 let top_pane_id = workspace.active_pane().entity_id();
12269 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
12270 workspace.split_pane(
12271 workspace.active_pane().clone(),
12272 SplitDirection::Down,
12273 window,
12274 cx,
12275 );
12276 top_pane_id
12277 });
12278 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12279 let bottom_pane_id = workspace.active_pane().entity_id();
12280 workspace.add_item_to_active_pane(
12281 Box::new(bottom_item.clone()),
12282 None,
12283 false,
12284 window,
12285 cx,
12286 );
12287 workspace.split_pane(
12288 workspace.active_pane().clone(),
12289 SplitDirection::Up,
12290 window,
12291 cx,
12292 );
12293 bottom_pane_id
12294 });
12295 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12296 let left_pane_id = workspace.active_pane().entity_id();
12297 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
12298 workspace.split_pane(
12299 workspace.active_pane().clone(),
12300 SplitDirection::Right,
12301 window,
12302 cx,
12303 );
12304 left_pane_id
12305 });
12306 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12307 let right_pane_id = workspace.active_pane().entity_id();
12308 workspace.add_item_to_active_pane(
12309 Box::new(right_item.clone()),
12310 None,
12311 false,
12312 window,
12313 cx,
12314 );
12315 workspace.split_pane(
12316 workspace.active_pane().clone(),
12317 SplitDirection::Left,
12318 window,
12319 cx,
12320 );
12321 right_pane_id
12322 });
12323 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
12324 let center_pane_id = workspace.active_pane().entity_id();
12325 workspace.add_item_to_active_pane(
12326 Box::new(center_item.clone()),
12327 None,
12328 false,
12329 window,
12330 cx,
12331 );
12332 center_pane_id
12333 });
12334 cx.executor().run_until_parked();
12335
12336 workspace.update_in(cx, |workspace, window, cx| {
12337 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
12338
12339 // Join into next from center pane into right
12340 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12341 });
12342
12343 workspace.update_in(cx, |workspace, window, cx| {
12344 let active_pane = workspace.active_pane();
12345 assert_eq!(right_pane_id, active_pane.entity_id());
12346 assert_eq!(2, active_pane.read(cx).items_len());
12347 let item_ids_in_pane =
12348 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12349 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12350 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12351
12352 // Join into next from right pane into bottom
12353 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12354 });
12355
12356 workspace.update_in(cx, |workspace, window, cx| {
12357 let active_pane = workspace.active_pane();
12358 assert_eq!(bottom_pane_id, active_pane.entity_id());
12359 assert_eq!(3, active_pane.read(cx).items_len());
12360 let item_ids_in_pane =
12361 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12362 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12363 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12364 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12365
12366 // Join into next from bottom pane into left
12367 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12368 });
12369
12370 workspace.update_in(cx, |workspace, window, cx| {
12371 let active_pane = workspace.active_pane();
12372 assert_eq!(left_pane_id, active_pane.entity_id());
12373 assert_eq!(4, active_pane.read(cx).items_len());
12374 let item_ids_in_pane =
12375 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12376 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12377 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12378 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12379 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12380
12381 // Join into next from left pane into top
12382 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
12383 });
12384
12385 workspace.update_in(cx, |workspace, window, cx| {
12386 let active_pane = workspace.active_pane();
12387 assert_eq!(top_pane_id, active_pane.entity_id());
12388 assert_eq!(5, active_pane.read(cx).items_len());
12389 let item_ids_in_pane =
12390 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
12391 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
12392 assert!(item_ids_in_pane.contains(&right_item.item_id()));
12393 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
12394 assert!(item_ids_in_pane.contains(&left_item.item_id()));
12395 assert!(item_ids_in_pane.contains(&top_item.item_id()));
12396
12397 // Single pane left: no-op
12398 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
12399 });
12400
12401 workspace.update(cx, |workspace, _cx| {
12402 let active_pane = workspace.active_pane();
12403 assert_eq!(top_pane_id, active_pane.entity_id());
12404 });
12405 }
12406
12407 fn add_an_item_to_active_pane(
12408 cx: &mut VisualTestContext,
12409 workspace: &Entity<Workspace>,
12410 item_id: u64,
12411 ) -> Entity<TestItem> {
12412 let item = cx.new(|cx| {
12413 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
12414 item_id,
12415 "item{item_id}.txt",
12416 cx,
12417 )])
12418 });
12419 workspace.update_in(cx, |workspace, window, cx| {
12420 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
12421 });
12422 item
12423 }
12424
12425 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
12426 workspace.update_in(cx, |workspace, window, cx| {
12427 workspace.split_pane(
12428 workspace.active_pane().clone(),
12429 SplitDirection::Right,
12430 window,
12431 cx,
12432 )
12433 })
12434 }
12435
12436 #[gpui::test]
12437 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
12438 init_test(cx);
12439 let fs = FakeFs::new(cx.executor());
12440 let project = Project::test(fs, None, cx).await;
12441 let (workspace, cx) =
12442 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12443
12444 add_an_item_to_active_pane(cx, &workspace, 1);
12445 split_pane(cx, &workspace);
12446 add_an_item_to_active_pane(cx, &workspace, 2);
12447 split_pane(cx, &workspace); // empty pane
12448 split_pane(cx, &workspace);
12449 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
12450
12451 cx.executor().run_until_parked();
12452
12453 workspace.update(cx, |workspace, cx| {
12454 let num_panes = workspace.panes().len();
12455 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12456 let active_item = workspace
12457 .active_pane()
12458 .read(cx)
12459 .active_item()
12460 .expect("item is in focus");
12461
12462 assert_eq!(num_panes, 4);
12463 assert_eq!(num_items_in_current_pane, 1);
12464 assert_eq!(active_item.item_id(), last_item.item_id());
12465 });
12466
12467 workspace.update_in(cx, |workspace, window, cx| {
12468 workspace.join_all_panes(window, cx);
12469 });
12470
12471 workspace.update(cx, |workspace, cx| {
12472 let num_panes = workspace.panes().len();
12473 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
12474 let active_item = workspace
12475 .active_pane()
12476 .read(cx)
12477 .active_item()
12478 .expect("item is in focus");
12479
12480 assert_eq!(num_panes, 1);
12481 assert_eq!(num_items_in_current_pane, 3);
12482 assert_eq!(active_item.item_id(), last_item.item_id());
12483 });
12484 }
12485
12486 #[gpui::test]
12487 async fn test_flexible_dock_sizing(cx: &mut gpui::TestAppContext) {
12488 init_test(cx);
12489 let fs = FakeFs::new(cx.executor());
12490
12491 let project = Project::test(fs, [], cx).await;
12492 let (multi_workspace, cx) =
12493 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12494 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12495
12496 workspace.update(cx, |workspace, _cx| {
12497 workspace.bounds.size.width = px(800.);
12498 });
12499
12500 workspace.update_in(cx, |workspace, window, cx| {
12501 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12502 workspace.add_panel(panel, window, cx);
12503 workspace.toggle_dock(DockPosition::Right, window, cx);
12504 });
12505
12506 let (panel, resized_width, ratio_basis_width) =
12507 workspace.update_in(cx, |workspace, window, cx| {
12508 let item = cx.new(|cx| {
12509 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12510 });
12511 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12512
12513 let dock = workspace.right_dock().read(cx);
12514 let workspace_width = workspace.bounds.size.width;
12515 let initial_width = workspace
12516 .dock_size(&dock, window, cx)
12517 .expect("flexible dock should have an initial width");
12518
12519 assert_eq!(initial_width, workspace_width / 2.);
12520
12521 workspace.resize_right_dock(px(300.), window, cx);
12522
12523 let dock = workspace.right_dock().read(cx);
12524 let resized_width = workspace
12525 .dock_size(&dock, window, cx)
12526 .expect("flexible dock should keep its resized width");
12527
12528 assert_eq!(resized_width, px(300.));
12529
12530 let panel = workspace
12531 .right_dock()
12532 .read(cx)
12533 .visible_panel()
12534 .expect("flexible dock should have a visible panel")
12535 .panel_id();
12536
12537 (panel, resized_width, workspace_width)
12538 });
12539
12540 workspace.update_in(cx, |workspace, window, cx| {
12541 workspace.toggle_dock(DockPosition::Right, window, cx);
12542 workspace.toggle_dock(DockPosition::Right, window, cx);
12543
12544 let dock = workspace.right_dock().read(cx);
12545 let reopened_width = workspace
12546 .dock_size(&dock, window, cx)
12547 .expect("flexible dock should restore when reopened");
12548
12549 assert_eq!(reopened_width, resized_width);
12550
12551 let right_dock = workspace.right_dock().read(cx);
12552 let flexible_panel = right_dock
12553 .visible_panel()
12554 .expect("flexible dock should still have a visible panel");
12555 assert_eq!(flexible_panel.panel_id(), panel);
12556 assert_eq!(
12557 right_dock
12558 .stored_panel_size_state(flexible_panel.as_ref())
12559 .and_then(|size_state| size_state.flex),
12560 Some(
12561 resized_width.to_f64() as f32
12562 / (workspace.bounds.size.width - resized_width).to_f64() as f32
12563 )
12564 );
12565 });
12566
12567 workspace.update_in(cx, |workspace, window, cx| {
12568 workspace.split_pane(
12569 workspace.active_pane().clone(),
12570 SplitDirection::Right,
12571 window,
12572 cx,
12573 );
12574
12575 let dock = workspace.right_dock().read(cx);
12576 let split_width = workspace
12577 .dock_size(&dock, window, cx)
12578 .expect("flexible dock should keep its user-resized proportion");
12579
12580 assert_eq!(split_width, px(300.));
12581
12582 workspace.bounds.size.width = px(1600.);
12583
12584 let dock = workspace.right_dock().read(cx);
12585 let resized_window_width = workspace
12586 .dock_size(&dock, window, cx)
12587 .expect("flexible dock should preserve proportional size on window resize");
12588
12589 assert_eq!(
12590 resized_window_width,
12591 workspace.bounds.size.width
12592 * (resized_width.to_f64() as f32 / ratio_basis_width.to_f64() as f32)
12593 );
12594 });
12595 }
12596
12597 #[gpui::test]
12598 async fn test_panel_size_state_persistence(cx: &mut gpui::TestAppContext) {
12599 init_test(cx);
12600 let fs = FakeFs::new(cx.executor());
12601
12602 // Fixed-width panel: pixel size is persisted to KVP and restored on re-add.
12603 {
12604 let project = Project::test(fs.clone(), [], cx).await;
12605 let (multi_workspace, cx) =
12606 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12607 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12608
12609 workspace.update(cx, |workspace, _cx| {
12610 workspace.set_random_database_id();
12611 workspace.bounds.size.width = px(800.);
12612 });
12613
12614 let panel = workspace.update_in(cx, |workspace, window, cx| {
12615 let panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12616 workspace.add_panel(panel.clone(), window, cx);
12617 workspace.toggle_dock(DockPosition::Left, window, cx);
12618 panel
12619 });
12620
12621 workspace.update_in(cx, |workspace, window, cx| {
12622 workspace.resize_left_dock(px(350.), window, cx);
12623 });
12624
12625 cx.run_until_parked();
12626
12627 let persisted = workspace.read_with(cx, |workspace, cx| {
12628 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12629 });
12630 assert_eq!(
12631 persisted.and_then(|s| s.size),
12632 Some(px(350.)),
12633 "fixed-width panel size should be persisted to KVP"
12634 );
12635
12636 // Remove the panel and re-add a fresh instance with the same key.
12637 // The new instance should have its size state restored from KVP.
12638 workspace.update_in(cx, |workspace, window, cx| {
12639 workspace.remove_panel(&panel, window, cx);
12640 });
12641
12642 workspace.update_in(cx, |workspace, window, cx| {
12643 let new_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12644 workspace.add_panel(new_panel, window, cx);
12645
12646 let left_dock = workspace.left_dock().read(cx);
12647 let size_state = left_dock
12648 .panel::<TestPanel>()
12649 .and_then(|p| left_dock.stored_panel_size_state(&p));
12650 assert_eq!(
12651 size_state.and_then(|s| s.size),
12652 Some(px(350.)),
12653 "re-added fixed-width panel should restore persisted size from KVP"
12654 );
12655 });
12656 }
12657
12658 // Flexible panel: both pixel size and ratio are persisted and restored.
12659 {
12660 let project = Project::test(fs.clone(), [], cx).await;
12661 let (multi_workspace, cx) =
12662 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12663 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12664
12665 workspace.update(cx, |workspace, _cx| {
12666 workspace.set_random_database_id();
12667 workspace.bounds.size.width = px(800.);
12668 });
12669
12670 let panel = workspace.update_in(cx, |workspace, window, cx| {
12671 let item = cx.new(|cx| {
12672 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12673 });
12674 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12675
12676 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12677 workspace.add_panel(panel.clone(), window, cx);
12678 workspace.toggle_dock(DockPosition::Right, window, cx);
12679 panel
12680 });
12681
12682 workspace.update_in(cx, |workspace, window, cx| {
12683 workspace.resize_right_dock(px(300.), window, cx);
12684 });
12685
12686 cx.run_until_parked();
12687
12688 let persisted = workspace
12689 .read_with(cx, |workspace, cx| {
12690 workspace.persisted_panel_size_state(TestPanel::panel_key(), cx)
12691 })
12692 .expect("flexible panel state should be persisted to KVP");
12693 assert_eq!(
12694 persisted.size, None,
12695 "flexible panel should not persist a redundant pixel size"
12696 );
12697 let original_ratio = persisted.flex.expect("panel's flex should be persisted");
12698
12699 // Remove the panel and re-add: both size and ratio should be restored.
12700 workspace.update_in(cx, |workspace, window, cx| {
12701 workspace.remove_panel(&panel, window, cx);
12702 });
12703
12704 workspace.update_in(cx, |workspace, window, cx| {
12705 let new_panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Right, 100, cx));
12706 workspace.add_panel(new_panel, window, cx);
12707
12708 let right_dock = workspace.right_dock().read(cx);
12709 let size_state = right_dock
12710 .panel::<TestPanel>()
12711 .and_then(|p| right_dock.stored_panel_size_state(&p))
12712 .expect("re-added flexible panel should have restored size state from KVP");
12713 assert_eq!(
12714 size_state.size, None,
12715 "re-added flexible panel should not have a persisted pixel size"
12716 );
12717 assert_eq!(
12718 size_state.flex,
12719 Some(original_ratio),
12720 "re-added flexible panel should restore persisted flex"
12721 );
12722 });
12723 }
12724 }
12725
12726 #[gpui::test]
12727 async fn test_flexible_panel_left_dock_sizing(cx: &mut gpui::TestAppContext) {
12728 init_test(cx);
12729 let fs = FakeFs::new(cx.executor());
12730
12731 let project = Project::test(fs, [], cx).await;
12732 let (multi_workspace, cx) =
12733 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12734 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12735
12736 workspace.update(cx, |workspace, _cx| {
12737 workspace.bounds.size.width = px(900.);
12738 });
12739
12740 // Step 1: Add a tab to the center pane then open a flexible panel in the left
12741 // dock. With one full-width center pane the default ratio is 0.5, so the panel
12742 // and the center pane each take half the workspace width.
12743 workspace.update_in(cx, |workspace, window, cx| {
12744 let item = cx.new(|cx| {
12745 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
12746 });
12747 workspace.add_item_to_active_pane(Box::new(item), None, true, window, cx);
12748
12749 let panel = cx.new(|cx| TestPanel::new_flexible(DockPosition::Left, 100, cx));
12750 workspace.add_panel(panel, window, cx);
12751 workspace.toggle_dock(DockPosition::Left, window, cx);
12752
12753 let left_dock = workspace.left_dock().read(cx);
12754 let left_width = workspace
12755 .dock_size(&left_dock, window, cx)
12756 .expect("left dock should have an active panel");
12757
12758 assert_eq!(
12759 left_width,
12760 workspace.bounds.size.width / 2.,
12761 "flexible left panel should split evenly with the center pane"
12762 );
12763 });
12764
12765 // Step 2: Split the center pane vertically (top/bottom). Vertical splits do not
12766 // change horizontal width fractions, so the flexible panel stays at the same
12767 // width as each half of the split.
12768 workspace.update_in(cx, |workspace, window, cx| {
12769 workspace.split_pane(
12770 workspace.active_pane().clone(),
12771 SplitDirection::Down,
12772 window,
12773 cx,
12774 );
12775
12776 let left_dock = workspace.left_dock().read(cx);
12777 let left_width = workspace
12778 .dock_size(&left_dock, window, cx)
12779 .expect("left dock should still have an active panel after vertical split");
12780
12781 assert_eq!(
12782 left_width,
12783 workspace.bounds.size.width / 2.,
12784 "flexible left panel width should match each vertically-split pane"
12785 );
12786 });
12787
12788 // Step 3: Open a fixed-width panel in the right dock. The right dock's default
12789 // size reduces the available width, so the flexible left panel and the center
12790 // panes all shrink proportionally to accommodate it.
12791 workspace.update_in(cx, |workspace, window, cx| {
12792 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 200, cx));
12793 workspace.add_panel(panel, window, cx);
12794 workspace.toggle_dock(DockPosition::Right, window, cx);
12795
12796 let right_dock = workspace.right_dock().read(cx);
12797 let right_width = workspace
12798 .dock_size(&right_dock, window, cx)
12799 .expect("right dock should have an active panel");
12800
12801 let left_dock = workspace.left_dock().read(cx);
12802 let left_width = workspace
12803 .dock_size(&left_dock, window, cx)
12804 .expect("left dock should still have an active panel");
12805
12806 let available_width = workspace.bounds.size.width - right_width;
12807 assert_eq!(
12808 left_width,
12809 available_width / 2.,
12810 "flexible left panel should shrink proportionally as the right dock takes space"
12811 );
12812 });
12813
12814 // Step 4: Toggle the right dock's panel to flexible. Now both docks use
12815 // flex sizing and the workspace width is divided among left-flex, center
12816 // (implicit flex 1.0), and right-flex.
12817 workspace.update_in(cx, |workspace, window, cx| {
12818 let right_dock = workspace.right_dock().clone();
12819 let right_panel = right_dock
12820 .read(cx)
12821 .visible_panel()
12822 .expect("right dock should have a visible panel")
12823 .clone();
12824 workspace.toggle_dock_panel_flexible_size(
12825 &right_dock,
12826 right_panel.as_ref(),
12827 window,
12828 cx,
12829 );
12830
12831 let right_dock = right_dock.read(cx);
12832 let right_panel = right_dock
12833 .visible_panel()
12834 .expect("right dock should still have a visible panel");
12835 assert!(
12836 right_panel.has_flexible_size(window, cx),
12837 "right panel should now be flexible"
12838 );
12839
12840 let right_size_state = right_dock
12841 .stored_panel_size_state(right_panel.as_ref())
12842 .expect("right panel should have a stored size state after toggling");
12843 let right_flex = right_size_state
12844 .flex
12845 .expect("right panel should have a flex value after toggling");
12846
12847 let left_dock = workspace.left_dock().read(cx);
12848 let left_width = workspace
12849 .dock_size(&left_dock, window, cx)
12850 .expect("left dock should still have an active panel");
12851 let right_width = workspace
12852 .dock_size(&right_dock, window, cx)
12853 .expect("right dock should still have an active panel");
12854
12855 let left_flex = workspace
12856 .default_dock_flex(DockPosition::Left)
12857 .expect("left dock should have a default flex");
12858
12859 let total_flex = left_flex + 1.0 + right_flex;
12860 let expected_left = left_flex / total_flex * workspace.bounds.size.width;
12861 let expected_right = right_flex / total_flex * workspace.bounds.size.width;
12862 assert_eq!(
12863 left_width, expected_left,
12864 "flexible left panel should share workspace width via flex ratios"
12865 );
12866 assert_eq!(
12867 right_width, expected_right,
12868 "flexible right panel should share workspace width via flex ratios"
12869 );
12870 });
12871 }
12872
12873 struct TestModal(FocusHandle);
12874
12875 impl TestModal {
12876 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
12877 Self(cx.focus_handle())
12878 }
12879 }
12880
12881 impl EventEmitter<DismissEvent> for TestModal {}
12882
12883 impl Focusable for TestModal {
12884 fn focus_handle(&self, _cx: &App) -> FocusHandle {
12885 self.0.clone()
12886 }
12887 }
12888
12889 impl ModalView for TestModal {}
12890
12891 impl Render for TestModal {
12892 fn render(
12893 &mut self,
12894 _window: &mut Window,
12895 _cx: &mut Context<TestModal>,
12896 ) -> impl IntoElement {
12897 div().track_focus(&self.0)
12898 }
12899 }
12900
12901 #[gpui::test]
12902 async fn test_panels(cx: &mut gpui::TestAppContext) {
12903 init_test(cx);
12904 let fs = FakeFs::new(cx.executor());
12905
12906 let project = Project::test(fs, [], cx).await;
12907 let (multi_workspace, cx) =
12908 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12909 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12910
12911 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
12912 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
12913 workspace.add_panel(panel_1.clone(), window, cx);
12914 workspace.toggle_dock(DockPosition::Left, window, cx);
12915 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
12916 workspace.add_panel(panel_2.clone(), window, cx);
12917 workspace.toggle_dock(DockPosition::Right, window, cx);
12918
12919 let left_dock = workspace.left_dock();
12920 assert_eq!(
12921 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12922 panel_1.panel_id()
12923 );
12924 assert_eq!(
12925 workspace.dock_size(&left_dock.read(cx), window, cx),
12926 Some(px(300.))
12927 );
12928
12929 workspace.resize_left_dock(px(1337.), window, cx);
12930 assert_eq!(
12931 workspace
12932 .right_dock()
12933 .read(cx)
12934 .visible_panel()
12935 .unwrap()
12936 .panel_id(),
12937 panel_2.panel_id(),
12938 );
12939
12940 (panel_1, panel_2)
12941 });
12942
12943 // Move panel_1 to the right
12944 panel_1.update_in(cx, |panel_1, window, cx| {
12945 panel_1.set_position(DockPosition::Right, window, cx)
12946 });
12947
12948 workspace.update_in(cx, |workspace, window, cx| {
12949 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
12950 // Since it was the only panel on the left, the left dock should now be closed.
12951 assert!(!workspace.left_dock().read(cx).is_open());
12952 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
12953 let right_dock = workspace.right_dock();
12954 assert_eq!(
12955 right_dock.read(cx).visible_panel().unwrap().panel_id(),
12956 panel_1.panel_id()
12957 );
12958 assert_eq!(
12959 right_dock
12960 .read(cx)
12961 .active_panel_size()
12962 .unwrap()
12963 .size
12964 .unwrap(),
12965 px(1337.)
12966 );
12967
12968 // Now we move panel_2 to the left
12969 panel_2.set_position(DockPosition::Left, window, cx);
12970 });
12971
12972 workspace.update(cx, |workspace, cx| {
12973 // Since panel_2 was not visible on the right, we don't open the left dock.
12974 assert!(!workspace.left_dock().read(cx).is_open());
12975 // And the right dock is unaffected in its displaying of panel_1
12976 assert!(workspace.right_dock().read(cx).is_open());
12977 assert_eq!(
12978 workspace
12979 .right_dock()
12980 .read(cx)
12981 .visible_panel()
12982 .unwrap()
12983 .panel_id(),
12984 panel_1.panel_id(),
12985 );
12986 });
12987
12988 // Move panel_1 back to the left
12989 panel_1.update_in(cx, |panel_1, window, cx| {
12990 panel_1.set_position(DockPosition::Left, window, cx)
12991 });
12992
12993 workspace.update_in(cx, |workspace, window, cx| {
12994 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12995 let left_dock = workspace.left_dock();
12996 assert!(left_dock.read(cx).is_open());
12997 assert_eq!(
12998 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12999 panel_1.panel_id()
13000 );
13001 assert_eq!(
13002 workspace.dock_size(&left_dock.read(cx), window, cx),
13003 Some(px(1337.))
13004 );
13005 // And the right dock should be closed as it no longer has any panels.
13006 assert!(!workspace.right_dock().read(cx).is_open());
13007
13008 // Now we move panel_1 to the bottom
13009 panel_1.set_position(DockPosition::Bottom, window, cx);
13010 });
13011
13012 workspace.update_in(cx, |workspace, window, cx| {
13013 // Since panel_1 was visible on the left, we close the left dock.
13014 assert!(!workspace.left_dock().read(cx).is_open());
13015 // The bottom dock is sized based on the panel's default size,
13016 // since the panel orientation changed from vertical to horizontal.
13017 let bottom_dock = workspace.bottom_dock();
13018 assert_eq!(
13019 workspace.dock_size(&bottom_dock.read(cx), window, cx),
13020 Some(px(300.))
13021 );
13022 // Close bottom dock and move panel_1 back to the left.
13023 bottom_dock.update(cx, |bottom_dock, cx| {
13024 bottom_dock.set_open(false, window, cx)
13025 });
13026 panel_1.set_position(DockPosition::Left, window, cx);
13027 });
13028
13029 // Emit activated event on panel 1
13030 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
13031
13032 // Now the left dock is open and panel_1 is active and focused.
13033 workspace.update_in(cx, |workspace, window, cx| {
13034 let left_dock = workspace.left_dock();
13035 assert!(left_dock.read(cx).is_open());
13036 assert_eq!(
13037 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13038 panel_1.panel_id(),
13039 );
13040 assert!(panel_1.focus_handle(cx).is_focused(window));
13041 });
13042
13043 // Emit closed event on panel 2, which is not active
13044 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13045
13046 // Wo don't close the left dock, because panel_2 wasn't the active panel
13047 workspace.update(cx, |workspace, cx| {
13048 let left_dock = workspace.left_dock();
13049 assert!(left_dock.read(cx).is_open());
13050 assert_eq!(
13051 left_dock.read(cx).visible_panel().unwrap().panel_id(),
13052 panel_1.panel_id(),
13053 );
13054 });
13055
13056 // Emitting a ZoomIn event shows the panel as zoomed.
13057 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
13058 workspace.read_with(cx, |workspace, _| {
13059 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13060 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
13061 });
13062
13063 // Move panel to another dock while it is zoomed
13064 panel_1.update_in(cx, |panel, window, cx| {
13065 panel.set_position(DockPosition::Right, window, cx)
13066 });
13067 workspace.read_with(cx, |workspace, _| {
13068 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13069
13070 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13071 });
13072
13073 // This is a helper for getting a:
13074 // - valid focus on an element,
13075 // - that isn't a part of the panes and panels system of the Workspace,
13076 // - and doesn't trigger the 'on_focus_lost' API.
13077 let focus_other_view = {
13078 let workspace = workspace.clone();
13079 move |cx: &mut VisualTestContext| {
13080 workspace.update_in(cx, |workspace, window, cx| {
13081 if workspace.active_modal::<TestModal>(cx).is_some() {
13082 workspace.toggle_modal(window, cx, TestModal::new);
13083 workspace.toggle_modal(window, cx, TestModal::new);
13084 } else {
13085 workspace.toggle_modal(window, cx, TestModal::new);
13086 }
13087 })
13088 }
13089 };
13090
13091 // If focus is transferred to another view that's not a panel or another pane, we still show
13092 // the panel as zoomed.
13093 focus_other_view(cx);
13094 workspace.read_with(cx, |workspace, _| {
13095 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13096 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13097 });
13098
13099 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
13100 workspace.update_in(cx, |_workspace, window, cx| {
13101 cx.focus_self(window);
13102 });
13103 workspace.read_with(cx, |workspace, _| {
13104 assert_eq!(workspace.zoomed, None);
13105 assert_eq!(workspace.zoomed_position, None);
13106 });
13107
13108 // If focus is transferred again to another view that's not a panel or a pane, we won't
13109 // show the panel as zoomed because it wasn't zoomed before.
13110 focus_other_view(cx);
13111 workspace.read_with(cx, |workspace, _| {
13112 assert_eq!(workspace.zoomed, None);
13113 assert_eq!(workspace.zoomed_position, None);
13114 });
13115
13116 // When the panel is activated, it is zoomed again.
13117 cx.dispatch_action(ToggleRightDock);
13118 workspace.read_with(cx, |workspace, _| {
13119 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
13120 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
13121 });
13122
13123 // Emitting a ZoomOut event unzooms the panel.
13124 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
13125 workspace.read_with(cx, |workspace, _| {
13126 assert_eq!(workspace.zoomed, None);
13127 assert_eq!(workspace.zoomed_position, None);
13128 });
13129
13130 // Emit closed event on panel 1, which is active
13131 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
13132
13133 // Now the left dock is closed, because panel_1 was the active panel
13134 workspace.update(cx, |workspace, cx| {
13135 let right_dock = workspace.right_dock();
13136 assert!(!right_dock.read(cx).is_open());
13137 });
13138 }
13139
13140 #[gpui::test]
13141 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
13142 init_test(cx);
13143
13144 let fs = FakeFs::new(cx.background_executor.clone());
13145 let project = Project::test(fs, [], cx).await;
13146 let (workspace, cx) =
13147 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13148 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13149
13150 let dirty_regular_buffer = cx.new(|cx| {
13151 TestItem::new(cx)
13152 .with_dirty(true)
13153 .with_label("1.txt")
13154 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13155 });
13156 let dirty_regular_buffer_2 = cx.new(|cx| {
13157 TestItem::new(cx)
13158 .with_dirty(true)
13159 .with_label("2.txt")
13160 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13161 });
13162 let dirty_multi_buffer_with_both = cx.new(|cx| {
13163 TestItem::new(cx)
13164 .with_dirty(true)
13165 .with_buffer_kind(ItemBufferKind::Multibuffer)
13166 .with_label("Fake Project Search")
13167 .with_project_items(&[
13168 dirty_regular_buffer.read(cx).project_items[0].clone(),
13169 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13170 ])
13171 });
13172 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13173 workspace.update_in(cx, |workspace, window, cx| {
13174 workspace.add_item(
13175 pane.clone(),
13176 Box::new(dirty_regular_buffer.clone()),
13177 None,
13178 false,
13179 false,
13180 window,
13181 cx,
13182 );
13183 workspace.add_item(
13184 pane.clone(),
13185 Box::new(dirty_regular_buffer_2.clone()),
13186 None,
13187 false,
13188 false,
13189 window,
13190 cx,
13191 );
13192 workspace.add_item(
13193 pane.clone(),
13194 Box::new(dirty_multi_buffer_with_both.clone()),
13195 None,
13196 false,
13197 false,
13198 window,
13199 cx,
13200 );
13201 });
13202
13203 pane.update_in(cx, |pane, window, cx| {
13204 pane.activate_item(2, true, true, window, cx);
13205 assert_eq!(
13206 pane.active_item().unwrap().item_id(),
13207 multi_buffer_with_both_files_id,
13208 "Should select the multi buffer in the pane"
13209 );
13210 });
13211 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13212 pane.close_other_items(
13213 &CloseOtherItems {
13214 save_intent: Some(SaveIntent::Save),
13215 close_pinned: true,
13216 },
13217 None,
13218 window,
13219 cx,
13220 )
13221 });
13222 cx.background_executor.run_until_parked();
13223 assert!(!cx.has_pending_prompt());
13224 close_all_but_multi_buffer_task
13225 .await
13226 .expect("Closing all buffers but the multi buffer failed");
13227 pane.update(cx, |pane, cx| {
13228 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
13229 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
13230 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
13231 assert_eq!(pane.items_len(), 1);
13232 assert_eq!(
13233 pane.active_item().unwrap().item_id(),
13234 multi_buffer_with_both_files_id,
13235 "Should have only the multi buffer left in the pane"
13236 );
13237 assert!(
13238 dirty_multi_buffer_with_both.read(cx).is_dirty,
13239 "The multi buffer containing the unsaved buffer should still be dirty"
13240 );
13241 });
13242
13243 dirty_regular_buffer.update(cx, |buffer, cx| {
13244 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
13245 });
13246
13247 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13248 pane.close_active_item(
13249 &CloseActiveItem {
13250 save_intent: Some(SaveIntent::Close),
13251 close_pinned: false,
13252 },
13253 window,
13254 cx,
13255 )
13256 });
13257 cx.background_executor.run_until_parked();
13258 assert!(
13259 cx.has_pending_prompt(),
13260 "Dirty multi buffer should prompt a save dialog"
13261 );
13262 cx.simulate_prompt_answer("Save");
13263 cx.background_executor.run_until_parked();
13264 close_multi_buffer_task
13265 .await
13266 .expect("Closing the multi buffer failed");
13267 pane.update(cx, |pane, cx| {
13268 assert_eq!(
13269 dirty_multi_buffer_with_both.read(cx).save_count,
13270 1,
13271 "Multi buffer item should get be saved"
13272 );
13273 // Test impl does not save inner items, so we do not assert them
13274 assert_eq!(
13275 pane.items_len(),
13276 0,
13277 "No more items should be left in the pane"
13278 );
13279 assert!(pane.active_item().is_none());
13280 });
13281 }
13282
13283 #[gpui::test]
13284 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
13285 cx: &mut TestAppContext,
13286 ) {
13287 init_test(cx);
13288
13289 let fs = FakeFs::new(cx.background_executor.clone());
13290 let project = Project::test(fs, [], cx).await;
13291 let (workspace, cx) =
13292 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13293 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13294
13295 let dirty_regular_buffer = cx.new(|cx| {
13296 TestItem::new(cx)
13297 .with_dirty(true)
13298 .with_label("1.txt")
13299 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13300 });
13301 let dirty_regular_buffer_2 = cx.new(|cx| {
13302 TestItem::new(cx)
13303 .with_dirty(true)
13304 .with_label("2.txt")
13305 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13306 });
13307 let clear_regular_buffer = cx.new(|cx| {
13308 TestItem::new(cx)
13309 .with_label("3.txt")
13310 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13311 });
13312
13313 let dirty_multi_buffer_with_both = cx.new(|cx| {
13314 TestItem::new(cx)
13315 .with_dirty(true)
13316 .with_buffer_kind(ItemBufferKind::Multibuffer)
13317 .with_label("Fake Project Search")
13318 .with_project_items(&[
13319 dirty_regular_buffer.read(cx).project_items[0].clone(),
13320 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13321 clear_regular_buffer.read(cx).project_items[0].clone(),
13322 ])
13323 });
13324 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
13325 workspace.update_in(cx, |workspace, window, cx| {
13326 workspace.add_item(
13327 pane.clone(),
13328 Box::new(dirty_regular_buffer.clone()),
13329 None,
13330 false,
13331 false,
13332 window,
13333 cx,
13334 );
13335 workspace.add_item(
13336 pane.clone(),
13337 Box::new(dirty_multi_buffer_with_both.clone()),
13338 None,
13339 false,
13340 false,
13341 window,
13342 cx,
13343 );
13344 });
13345
13346 pane.update_in(cx, |pane, window, cx| {
13347 pane.activate_item(1, true, true, window, cx);
13348 assert_eq!(
13349 pane.active_item().unwrap().item_id(),
13350 multi_buffer_with_both_files_id,
13351 "Should select the multi buffer in the pane"
13352 );
13353 });
13354 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13355 pane.close_active_item(
13356 &CloseActiveItem {
13357 save_intent: None,
13358 close_pinned: false,
13359 },
13360 window,
13361 cx,
13362 )
13363 });
13364 cx.background_executor.run_until_parked();
13365 assert!(
13366 cx.has_pending_prompt(),
13367 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
13368 );
13369 }
13370
13371 /// Tests that when `close_on_file_delete` is enabled, files are automatically
13372 /// closed when they are deleted from disk.
13373 #[gpui::test]
13374 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
13375 init_test(cx);
13376
13377 // Enable the close_on_disk_deletion setting
13378 cx.update_global(|store: &mut SettingsStore, cx| {
13379 store.update_user_settings(cx, |settings| {
13380 settings.workspace.close_on_file_delete = Some(true);
13381 });
13382 });
13383
13384 let fs = FakeFs::new(cx.background_executor.clone());
13385 let project = Project::test(fs, [], cx).await;
13386 let (workspace, cx) =
13387 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13388 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13389
13390 // Create a test item that simulates a file
13391 let item = cx.new(|cx| {
13392 TestItem::new(cx)
13393 .with_label("test.txt")
13394 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13395 });
13396
13397 // Add item to workspace
13398 workspace.update_in(cx, |workspace, window, cx| {
13399 workspace.add_item(
13400 pane.clone(),
13401 Box::new(item.clone()),
13402 None,
13403 false,
13404 false,
13405 window,
13406 cx,
13407 );
13408 });
13409
13410 // Verify the item is in the pane
13411 pane.read_with(cx, |pane, _| {
13412 assert_eq!(pane.items().count(), 1);
13413 });
13414
13415 // Simulate file deletion by setting the item's deleted state
13416 item.update(cx, |item, _| {
13417 item.set_has_deleted_file(true);
13418 });
13419
13420 // Emit UpdateTab event to trigger the close behavior
13421 cx.run_until_parked();
13422 item.update(cx, |_, cx| {
13423 cx.emit(ItemEvent::UpdateTab);
13424 });
13425
13426 // Allow the close operation to complete
13427 cx.run_until_parked();
13428
13429 // Verify the item was automatically closed
13430 pane.read_with(cx, |pane, _| {
13431 assert_eq!(
13432 pane.items().count(),
13433 0,
13434 "Item should be automatically closed when file is deleted"
13435 );
13436 });
13437 }
13438
13439 /// Tests that when `close_on_file_delete` is disabled (default), files remain
13440 /// open with a strikethrough when they are deleted from disk.
13441 #[gpui::test]
13442 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
13443 init_test(cx);
13444
13445 // Ensure close_on_disk_deletion is disabled (default)
13446 cx.update_global(|store: &mut SettingsStore, cx| {
13447 store.update_user_settings(cx, |settings| {
13448 settings.workspace.close_on_file_delete = Some(false);
13449 });
13450 });
13451
13452 let fs = FakeFs::new(cx.background_executor.clone());
13453 let project = Project::test(fs, [], cx).await;
13454 let (workspace, cx) =
13455 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13456 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13457
13458 // Create a test item that simulates a file
13459 let item = cx.new(|cx| {
13460 TestItem::new(cx)
13461 .with_label("test.txt")
13462 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13463 });
13464
13465 // Add item to workspace
13466 workspace.update_in(cx, |workspace, window, cx| {
13467 workspace.add_item(
13468 pane.clone(),
13469 Box::new(item.clone()),
13470 None,
13471 false,
13472 false,
13473 window,
13474 cx,
13475 );
13476 });
13477
13478 // Verify the item is in the pane
13479 pane.read_with(cx, |pane, _| {
13480 assert_eq!(pane.items().count(), 1);
13481 });
13482
13483 // Simulate file deletion
13484 item.update(cx, |item, _| {
13485 item.set_has_deleted_file(true);
13486 });
13487
13488 // Emit UpdateTab event
13489 cx.run_until_parked();
13490 item.update(cx, |_, cx| {
13491 cx.emit(ItemEvent::UpdateTab);
13492 });
13493
13494 // Allow any potential close operation to complete
13495 cx.run_until_parked();
13496
13497 // Verify the item remains open (with strikethrough)
13498 pane.read_with(cx, |pane, _| {
13499 assert_eq!(
13500 pane.items().count(),
13501 1,
13502 "Item should remain open when close_on_disk_deletion is disabled"
13503 );
13504 });
13505
13506 // Verify the item shows as deleted
13507 item.read_with(cx, |item, _| {
13508 assert!(
13509 item.has_deleted_file,
13510 "Item should be marked as having deleted file"
13511 );
13512 });
13513 }
13514
13515 /// Tests that dirty files are not automatically closed when deleted from disk,
13516 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
13517 /// unsaved changes without being prompted.
13518 #[gpui::test]
13519 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
13520 init_test(cx);
13521
13522 // Enable the close_on_file_delete setting
13523 cx.update_global(|store: &mut SettingsStore, cx| {
13524 store.update_user_settings(cx, |settings| {
13525 settings.workspace.close_on_file_delete = Some(true);
13526 });
13527 });
13528
13529 let fs = FakeFs::new(cx.background_executor.clone());
13530 let project = Project::test(fs, [], cx).await;
13531 let (workspace, cx) =
13532 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13533 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13534
13535 // Create a dirty test item
13536 let item = cx.new(|cx| {
13537 TestItem::new(cx)
13538 .with_dirty(true)
13539 .with_label("test.txt")
13540 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13541 });
13542
13543 // Add item to workspace
13544 workspace.update_in(cx, |workspace, window, cx| {
13545 workspace.add_item(
13546 pane.clone(),
13547 Box::new(item.clone()),
13548 None,
13549 false,
13550 false,
13551 window,
13552 cx,
13553 );
13554 });
13555
13556 // Simulate file deletion
13557 item.update(cx, |item, _| {
13558 item.set_has_deleted_file(true);
13559 });
13560
13561 // Emit UpdateTab event to trigger the close behavior
13562 cx.run_until_parked();
13563 item.update(cx, |_, cx| {
13564 cx.emit(ItemEvent::UpdateTab);
13565 });
13566
13567 // Allow any potential close operation to complete
13568 cx.run_until_parked();
13569
13570 // Verify the item remains open (dirty files are not auto-closed)
13571 pane.read_with(cx, |pane, _| {
13572 assert_eq!(
13573 pane.items().count(),
13574 1,
13575 "Dirty items should not be automatically closed even when file is deleted"
13576 );
13577 });
13578
13579 // Verify the item is marked as deleted and still dirty
13580 item.read_with(cx, |item, _| {
13581 assert!(
13582 item.has_deleted_file,
13583 "Item should be marked as having deleted file"
13584 );
13585 assert!(item.is_dirty, "Item should still be dirty");
13586 });
13587 }
13588
13589 /// Tests that navigation history is cleaned up when files are auto-closed
13590 /// due to deletion from disk.
13591 #[gpui::test]
13592 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
13593 init_test(cx);
13594
13595 // Enable the close_on_file_delete setting
13596 cx.update_global(|store: &mut SettingsStore, cx| {
13597 store.update_user_settings(cx, |settings| {
13598 settings.workspace.close_on_file_delete = Some(true);
13599 });
13600 });
13601
13602 let fs = FakeFs::new(cx.background_executor.clone());
13603 let project = Project::test(fs, [], cx).await;
13604 let (workspace, cx) =
13605 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13606 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13607
13608 // Create test items
13609 let item1 = cx.new(|cx| {
13610 TestItem::new(cx)
13611 .with_label("test1.txt")
13612 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
13613 });
13614 let item1_id = item1.item_id();
13615
13616 let item2 = cx.new(|cx| {
13617 TestItem::new(cx)
13618 .with_label("test2.txt")
13619 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
13620 });
13621
13622 // Add items to workspace
13623 workspace.update_in(cx, |workspace, window, cx| {
13624 workspace.add_item(
13625 pane.clone(),
13626 Box::new(item1.clone()),
13627 None,
13628 false,
13629 false,
13630 window,
13631 cx,
13632 );
13633 workspace.add_item(
13634 pane.clone(),
13635 Box::new(item2.clone()),
13636 None,
13637 false,
13638 false,
13639 window,
13640 cx,
13641 );
13642 });
13643
13644 // Activate item1 to ensure it gets navigation entries
13645 pane.update_in(cx, |pane, window, cx| {
13646 pane.activate_item(0, true, true, window, cx);
13647 });
13648
13649 // Switch to item2 and back to create navigation history
13650 pane.update_in(cx, |pane, window, cx| {
13651 pane.activate_item(1, true, true, window, cx);
13652 });
13653 cx.run_until_parked();
13654
13655 pane.update_in(cx, |pane, window, cx| {
13656 pane.activate_item(0, true, true, window, cx);
13657 });
13658 cx.run_until_parked();
13659
13660 // Simulate file deletion for item1
13661 item1.update(cx, |item, _| {
13662 item.set_has_deleted_file(true);
13663 });
13664
13665 // Emit UpdateTab event to trigger the close behavior
13666 item1.update(cx, |_, cx| {
13667 cx.emit(ItemEvent::UpdateTab);
13668 });
13669 cx.run_until_parked();
13670
13671 // Verify item1 was closed
13672 pane.read_with(cx, |pane, _| {
13673 assert_eq!(
13674 pane.items().count(),
13675 1,
13676 "Should have 1 item remaining after auto-close"
13677 );
13678 });
13679
13680 // Check navigation history after close
13681 let has_item = pane.read_with(cx, |pane, cx| {
13682 let mut has_item = false;
13683 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
13684 if entry.item.id() == item1_id {
13685 has_item = true;
13686 }
13687 });
13688 has_item
13689 });
13690
13691 assert!(
13692 !has_item,
13693 "Navigation history should not contain closed item entries"
13694 );
13695 }
13696
13697 #[gpui::test]
13698 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
13699 cx: &mut TestAppContext,
13700 ) {
13701 init_test(cx);
13702
13703 let fs = FakeFs::new(cx.background_executor.clone());
13704 let project = Project::test(fs, [], cx).await;
13705 let (workspace, cx) =
13706 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13707 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13708
13709 let dirty_regular_buffer = cx.new(|cx| {
13710 TestItem::new(cx)
13711 .with_dirty(true)
13712 .with_label("1.txt")
13713 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
13714 });
13715 let dirty_regular_buffer_2 = cx.new(|cx| {
13716 TestItem::new(cx)
13717 .with_dirty(true)
13718 .with_label("2.txt")
13719 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
13720 });
13721 let clear_regular_buffer = cx.new(|cx| {
13722 TestItem::new(cx)
13723 .with_label("3.txt")
13724 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
13725 });
13726
13727 let dirty_multi_buffer = cx.new(|cx| {
13728 TestItem::new(cx)
13729 .with_dirty(true)
13730 .with_buffer_kind(ItemBufferKind::Multibuffer)
13731 .with_label("Fake Project Search")
13732 .with_project_items(&[
13733 dirty_regular_buffer.read(cx).project_items[0].clone(),
13734 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
13735 clear_regular_buffer.read(cx).project_items[0].clone(),
13736 ])
13737 });
13738 workspace.update_in(cx, |workspace, window, cx| {
13739 workspace.add_item(
13740 pane.clone(),
13741 Box::new(dirty_regular_buffer.clone()),
13742 None,
13743 false,
13744 false,
13745 window,
13746 cx,
13747 );
13748 workspace.add_item(
13749 pane.clone(),
13750 Box::new(dirty_regular_buffer_2.clone()),
13751 None,
13752 false,
13753 false,
13754 window,
13755 cx,
13756 );
13757 workspace.add_item(
13758 pane.clone(),
13759 Box::new(dirty_multi_buffer.clone()),
13760 None,
13761 false,
13762 false,
13763 window,
13764 cx,
13765 );
13766 });
13767
13768 pane.update_in(cx, |pane, window, cx| {
13769 pane.activate_item(2, true, true, window, cx);
13770 assert_eq!(
13771 pane.active_item().unwrap().item_id(),
13772 dirty_multi_buffer.item_id(),
13773 "Should select the multi buffer in the pane"
13774 );
13775 });
13776 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
13777 pane.close_active_item(
13778 &CloseActiveItem {
13779 save_intent: None,
13780 close_pinned: false,
13781 },
13782 window,
13783 cx,
13784 )
13785 });
13786 cx.background_executor.run_until_parked();
13787 assert!(
13788 !cx.has_pending_prompt(),
13789 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
13790 );
13791 close_multi_buffer_task
13792 .await
13793 .expect("Closing multi buffer failed");
13794 pane.update(cx, |pane, cx| {
13795 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
13796 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
13797 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
13798 assert_eq!(
13799 pane.items()
13800 .map(|item| item.item_id())
13801 .sorted()
13802 .collect::<Vec<_>>(),
13803 vec![
13804 dirty_regular_buffer.item_id(),
13805 dirty_regular_buffer_2.item_id(),
13806 ],
13807 "Should have no multi buffer left in the pane"
13808 );
13809 assert!(dirty_regular_buffer.read(cx).is_dirty);
13810 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
13811 });
13812 }
13813
13814 #[gpui::test]
13815 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
13816 init_test(cx);
13817 let fs = FakeFs::new(cx.executor());
13818 let project = Project::test(fs, [], cx).await;
13819 let (multi_workspace, cx) =
13820 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13821 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13822
13823 // Add a new panel to the right dock, opening the dock and setting the
13824 // focus to the new panel.
13825 let panel = workspace.update_in(cx, |workspace, window, cx| {
13826 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13827 workspace.add_panel(panel.clone(), window, cx);
13828
13829 workspace
13830 .right_dock()
13831 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13832
13833 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13834
13835 panel
13836 });
13837
13838 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13839 // panel to the next valid position which, in this case, is the left
13840 // dock.
13841 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13842 workspace.update(cx, |workspace, cx| {
13843 assert!(workspace.left_dock().read(cx).is_open());
13844 assert_eq!(panel.read(cx).position, DockPosition::Left);
13845 });
13846
13847 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
13848 // panel to the next valid position which, in this case, is the bottom
13849 // dock.
13850 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13851 workspace.update(cx, |workspace, cx| {
13852 assert!(workspace.bottom_dock().read(cx).is_open());
13853 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
13854 });
13855
13856 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
13857 // around moving the panel to its initial position, the right dock.
13858 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13859 workspace.update(cx, |workspace, cx| {
13860 assert!(workspace.right_dock().read(cx).is_open());
13861 assert_eq!(panel.read(cx).position, DockPosition::Right);
13862 });
13863
13864 // Remove focus from the panel, ensuring that, if the panel is not
13865 // focused, the `MoveFocusedPanelToNextPosition` action does not update
13866 // the panel's position, so the panel is still in the right dock.
13867 workspace.update_in(cx, |workspace, window, cx| {
13868 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13869 });
13870
13871 cx.dispatch_action(MoveFocusedPanelToNextPosition);
13872 workspace.update(cx, |workspace, cx| {
13873 assert!(workspace.right_dock().read(cx).is_open());
13874 assert_eq!(panel.read(cx).position, DockPosition::Right);
13875 });
13876 }
13877
13878 #[gpui::test]
13879 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
13880 init_test(cx);
13881
13882 let fs = FakeFs::new(cx.executor());
13883 let project = Project::test(fs, [], cx).await;
13884 let (workspace, cx) =
13885 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13886
13887 let item_1 = cx.new(|cx| {
13888 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13889 });
13890 workspace.update_in(cx, |workspace, window, cx| {
13891 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13892 workspace.move_item_to_pane_in_direction(
13893 &MoveItemToPaneInDirection {
13894 direction: SplitDirection::Right,
13895 focus: true,
13896 clone: false,
13897 },
13898 window,
13899 cx,
13900 );
13901 workspace.move_item_to_pane_at_index(
13902 &MoveItemToPane {
13903 destination: 3,
13904 focus: true,
13905 clone: false,
13906 },
13907 window,
13908 cx,
13909 );
13910
13911 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
13912 assert_eq!(
13913 pane_items_paths(&workspace.active_pane, cx),
13914 vec!["first.txt".to_string()],
13915 "Single item was not moved anywhere"
13916 );
13917 });
13918
13919 let item_2 = cx.new(|cx| {
13920 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
13921 });
13922 workspace.update_in(cx, |workspace, window, cx| {
13923 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
13924 assert_eq!(
13925 pane_items_paths(&workspace.panes[0], cx),
13926 vec!["first.txt".to_string(), "second.txt".to_string()],
13927 );
13928 workspace.move_item_to_pane_in_direction(
13929 &MoveItemToPaneInDirection {
13930 direction: SplitDirection::Right,
13931 focus: true,
13932 clone: false,
13933 },
13934 window,
13935 cx,
13936 );
13937
13938 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
13939 assert_eq!(
13940 pane_items_paths(&workspace.panes[0], cx),
13941 vec!["first.txt".to_string()],
13942 "After moving, one item should be left in the original pane"
13943 );
13944 assert_eq!(
13945 pane_items_paths(&workspace.panes[1], cx),
13946 vec!["second.txt".to_string()],
13947 "New item should have been moved to the new pane"
13948 );
13949 });
13950
13951 let item_3 = cx.new(|cx| {
13952 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
13953 });
13954 workspace.update_in(cx, |workspace, window, cx| {
13955 let original_pane = workspace.panes[0].clone();
13956 workspace.set_active_pane(&original_pane, window, cx);
13957 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
13958 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
13959 assert_eq!(
13960 pane_items_paths(&workspace.active_pane, cx),
13961 vec!["first.txt".to_string(), "third.txt".to_string()],
13962 "New pane should be ready to move one item out"
13963 );
13964
13965 workspace.move_item_to_pane_at_index(
13966 &MoveItemToPane {
13967 destination: 3,
13968 focus: true,
13969 clone: false,
13970 },
13971 window,
13972 cx,
13973 );
13974 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
13975 assert_eq!(
13976 pane_items_paths(&workspace.active_pane, cx),
13977 vec!["first.txt".to_string()],
13978 "After moving, one item should be left in the original pane"
13979 );
13980 assert_eq!(
13981 pane_items_paths(&workspace.panes[1], cx),
13982 vec!["second.txt".to_string()],
13983 "Previously created pane should be unchanged"
13984 );
13985 assert_eq!(
13986 pane_items_paths(&workspace.panes[2], cx),
13987 vec!["third.txt".to_string()],
13988 "New item should have been moved to the new pane"
13989 );
13990 });
13991 }
13992
13993 #[gpui::test]
13994 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13995 init_test(cx);
13996
13997 let fs = FakeFs::new(cx.executor());
13998 let project = Project::test(fs, [], cx).await;
13999 let (workspace, cx) =
14000 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14001
14002 let item_1 = cx.new(|cx| {
14003 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
14004 });
14005 workspace.update_in(cx, |workspace, window, cx| {
14006 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
14007 workspace.move_item_to_pane_in_direction(
14008 &MoveItemToPaneInDirection {
14009 direction: SplitDirection::Right,
14010 focus: true,
14011 clone: true,
14012 },
14013 window,
14014 cx,
14015 );
14016 });
14017 cx.run_until_parked();
14018 workspace.update_in(cx, |workspace, window, cx| {
14019 workspace.move_item_to_pane_at_index(
14020 &MoveItemToPane {
14021 destination: 3,
14022 focus: true,
14023 clone: true,
14024 },
14025 window,
14026 cx,
14027 );
14028 });
14029 cx.run_until_parked();
14030
14031 workspace.update(cx, |workspace, cx| {
14032 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
14033 for pane in workspace.panes() {
14034 assert_eq!(
14035 pane_items_paths(pane, cx),
14036 vec!["first.txt".to_string()],
14037 "Single item exists in all panes"
14038 );
14039 }
14040 });
14041
14042 // verify that the active pane has been updated after waiting for the
14043 // pane focus event to fire and resolve
14044 workspace.read_with(cx, |workspace, _app| {
14045 assert_eq!(
14046 workspace.active_pane(),
14047 &workspace.panes[2],
14048 "The third pane should be the active one: {:?}",
14049 workspace.panes
14050 );
14051 })
14052 }
14053
14054 #[gpui::test]
14055 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
14056 init_test(cx);
14057
14058 let fs = FakeFs::new(cx.executor());
14059 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
14060
14061 let project = Project::test(fs, ["root".as_ref()], cx).await;
14062 let (workspace, cx) =
14063 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14064
14065 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14066 // Add item to pane A with project path
14067 let item_a = cx.new(|cx| {
14068 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14069 });
14070 workspace.update_in(cx, |workspace, window, cx| {
14071 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
14072 });
14073
14074 // Split to create pane B
14075 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
14076 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
14077 });
14078
14079 // Add item with SAME project path to pane B, and pin it
14080 let item_b = cx.new(|cx| {
14081 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14082 });
14083 pane_b.update_in(cx, |pane, window, cx| {
14084 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14085 pane.set_pinned_count(1);
14086 });
14087
14088 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
14089 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
14090
14091 // close_pinned: false should only close the unpinned copy
14092 workspace.update_in(cx, |workspace, window, cx| {
14093 workspace.close_item_in_all_panes(
14094 &CloseItemInAllPanes {
14095 save_intent: Some(SaveIntent::Close),
14096 close_pinned: false,
14097 },
14098 window,
14099 cx,
14100 )
14101 });
14102 cx.executor().run_until_parked();
14103
14104 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
14105 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14106 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
14107 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
14108
14109 // Split again, seeing as closing the previous item also closed its
14110 // pane, so only pane remains, which does not allow us to properly test
14111 // that both items close when `close_pinned: true`.
14112 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
14113 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
14114 });
14115
14116 // Add an item with the same project path to pane C so that
14117 // close_item_in_all_panes can determine what to close across all panes
14118 // (it reads the active item from the active pane, and split_pane
14119 // creates an empty pane).
14120 let item_c = cx.new(|cx| {
14121 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
14122 });
14123 pane_c.update_in(cx, |pane, window, cx| {
14124 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
14125 });
14126
14127 // close_pinned: true should close the pinned copy too
14128 workspace.update_in(cx, |workspace, window, cx| {
14129 let panes_count = workspace.panes().len();
14130 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
14131
14132 workspace.close_item_in_all_panes(
14133 &CloseItemInAllPanes {
14134 save_intent: Some(SaveIntent::Close),
14135 close_pinned: true,
14136 },
14137 window,
14138 cx,
14139 )
14140 });
14141 cx.executor().run_until_parked();
14142
14143 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
14144 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
14145 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
14146 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
14147 }
14148
14149 mod register_project_item_tests {
14150
14151 use super::*;
14152
14153 // View
14154 struct TestPngItemView {
14155 focus_handle: FocusHandle,
14156 }
14157 // Model
14158 struct TestPngItem {}
14159
14160 impl project::ProjectItem for TestPngItem {
14161 fn try_open(
14162 _project: &Entity<Project>,
14163 path: &ProjectPath,
14164 cx: &mut App,
14165 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14166 if path.path.extension().unwrap() == "png" {
14167 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
14168 } else {
14169 None
14170 }
14171 }
14172
14173 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14174 None
14175 }
14176
14177 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14178 None
14179 }
14180
14181 fn is_dirty(&self) -> bool {
14182 false
14183 }
14184 }
14185
14186 impl Item for TestPngItemView {
14187 type Event = ();
14188 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14189 "".into()
14190 }
14191 }
14192 impl EventEmitter<()> for TestPngItemView {}
14193 impl Focusable for TestPngItemView {
14194 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14195 self.focus_handle.clone()
14196 }
14197 }
14198
14199 impl Render for TestPngItemView {
14200 fn render(
14201 &mut self,
14202 _window: &mut Window,
14203 _cx: &mut Context<Self>,
14204 ) -> impl IntoElement {
14205 Empty
14206 }
14207 }
14208
14209 impl ProjectItem for TestPngItemView {
14210 type Item = TestPngItem;
14211
14212 fn for_project_item(
14213 _project: Entity<Project>,
14214 _pane: Option<&Pane>,
14215 _item: Entity<Self::Item>,
14216 _: &mut Window,
14217 cx: &mut Context<Self>,
14218 ) -> Self
14219 where
14220 Self: Sized,
14221 {
14222 Self {
14223 focus_handle: cx.focus_handle(),
14224 }
14225 }
14226 }
14227
14228 // View
14229 struct TestIpynbItemView {
14230 focus_handle: FocusHandle,
14231 }
14232 // Model
14233 struct TestIpynbItem {}
14234
14235 impl project::ProjectItem for TestIpynbItem {
14236 fn try_open(
14237 _project: &Entity<Project>,
14238 path: &ProjectPath,
14239 cx: &mut App,
14240 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
14241 if path.path.extension().unwrap() == "ipynb" {
14242 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
14243 } else {
14244 None
14245 }
14246 }
14247
14248 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
14249 None
14250 }
14251
14252 fn project_path(&self, _: &App) -> Option<ProjectPath> {
14253 None
14254 }
14255
14256 fn is_dirty(&self) -> bool {
14257 false
14258 }
14259 }
14260
14261 impl Item for TestIpynbItemView {
14262 type Event = ();
14263 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14264 "".into()
14265 }
14266 }
14267 impl EventEmitter<()> for TestIpynbItemView {}
14268 impl Focusable for TestIpynbItemView {
14269 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14270 self.focus_handle.clone()
14271 }
14272 }
14273
14274 impl Render for TestIpynbItemView {
14275 fn render(
14276 &mut self,
14277 _window: &mut Window,
14278 _cx: &mut Context<Self>,
14279 ) -> impl IntoElement {
14280 Empty
14281 }
14282 }
14283
14284 impl ProjectItem for TestIpynbItemView {
14285 type Item = TestIpynbItem;
14286
14287 fn for_project_item(
14288 _project: Entity<Project>,
14289 _pane: Option<&Pane>,
14290 _item: Entity<Self::Item>,
14291 _: &mut Window,
14292 cx: &mut Context<Self>,
14293 ) -> Self
14294 where
14295 Self: Sized,
14296 {
14297 Self {
14298 focus_handle: cx.focus_handle(),
14299 }
14300 }
14301 }
14302
14303 struct TestAlternatePngItemView {
14304 focus_handle: FocusHandle,
14305 }
14306
14307 impl Item for TestAlternatePngItemView {
14308 type Event = ();
14309 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
14310 "".into()
14311 }
14312 }
14313
14314 impl EventEmitter<()> for TestAlternatePngItemView {}
14315 impl Focusable for TestAlternatePngItemView {
14316 fn focus_handle(&self, _cx: &App) -> FocusHandle {
14317 self.focus_handle.clone()
14318 }
14319 }
14320
14321 impl Render for TestAlternatePngItemView {
14322 fn render(
14323 &mut self,
14324 _window: &mut Window,
14325 _cx: &mut Context<Self>,
14326 ) -> impl IntoElement {
14327 Empty
14328 }
14329 }
14330
14331 impl ProjectItem for TestAlternatePngItemView {
14332 type Item = TestPngItem;
14333
14334 fn for_project_item(
14335 _project: Entity<Project>,
14336 _pane: Option<&Pane>,
14337 _item: Entity<Self::Item>,
14338 _: &mut Window,
14339 cx: &mut Context<Self>,
14340 ) -> Self
14341 where
14342 Self: Sized,
14343 {
14344 Self {
14345 focus_handle: cx.focus_handle(),
14346 }
14347 }
14348 }
14349
14350 #[gpui::test]
14351 async fn test_register_project_item(cx: &mut TestAppContext) {
14352 init_test(cx);
14353
14354 cx.update(|cx| {
14355 register_project_item::<TestPngItemView>(cx);
14356 register_project_item::<TestIpynbItemView>(cx);
14357 });
14358
14359 let fs = FakeFs::new(cx.executor());
14360 fs.insert_tree(
14361 "/root1",
14362 json!({
14363 "one.png": "BINARYDATAHERE",
14364 "two.ipynb": "{ totally a notebook }",
14365 "three.txt": "editing text, sure why not?"
14366 }),
14367 )
14368 .await;
14369
14370 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14371 let (workspace, cx) =
14372 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14373
14374 let worktree_id = project.update(cx, |project, cx| {
14375 project.worktrees(cx).next().unwrap().read(cx).id()
14376 });
14377
14378 let handle = workspace
14379 .update_in(cx, |workspace, window, cx| {
14380 let project_path = (worktree_id, rel_path("one.png"));
14381 workspace.open_path(project_path, None, true, window, cx)
14382 })
14383 .await
14384 .unwrap();
14385
14386 // Now we can check if the handle we got back errored or not
14387 assert_eq!(
14388 handle.to_any_view().entity_type(),
14389 TypeId::of::<TestPngItemView>()
14390 );
14391
14392 let handle = workspace
14393 .update_in(cx, |workspace, window, cx| {
14394 let project_path = (worktree_id, rel_path("two.ipynb"));
14395 workspace.open_path(project_path, None, true, window, cx)
14396 })
14397 .await
14398 .unwrap();
14399
14400 assert_eq!(
14401 handle.to_any_view().entity_type(),
14402 TypeId::of::<TestIpynbItemView>()
14403 );
14404
14405 let handle = workspace
14406 .update_in(cx, |workspace, window, cx| {
14407 let project_path = (worktree_id, rel_path("three.txt"));
14408 workspace.open_path(project_path, None, true, window, cx)
14409 })
14410 .await;
14411 assert!(handle.is_err());
14412 }
14413
14414 #[gpui::test]
14415 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
14416 init_test(cx);
14417
14418 cx.update(|cx| {
14419 register_project_item::<TestPngItemView>(cx);
14420 register_project_item::<TestAlternatePngItemView>(cx);
14421 });
14422
14423 let fs = FakeFs::new(cx.executor());
14424 fs.insert_tree(
14425 "/root1",
14426 json!({
14427 "one.png": "BINARYDATAHERE",
14428 "two.ipynb": "{ totally a notebook }",
14429 "three.txt": "editing text, sure why not?"
14430 }),
14431 )
14432 .await;
14433 let project = Project::test(fs, ["root1".as_ref()], cx).await;
14434 let (workspace, cx) =
14435 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14436 let worktree_id = project.update(cx, |project, cx| {
14437 project.worktrees(cx).next().unwrap().read(cx).id()
14438 });
14439
14440 let handle = workspace
14441 .update_in(cx, |workspace, window, cx| {
14442 let project_path = (worktree_id, rel_path("one.png"));
14443 workspace.open_path(project_path, None, true, window, cx)
14444 })
14445 .await
14446 .unwrap();
14447
14448 // This _must_ be the second item registered
14449 assert_eq!(
14450 handle.to_any_view().entity_type(),
14451 TypeId::of::<TestAlternatePngItemView>()
14452 );
14453
14454 let handle = workspace
14455 .update_in(cx, |workspace, window, cx| {
14456 let project_path = (worktree_id, rel_path("three.txt"));
14457 workspace.open_path(project_path, None, true, window, cx)
14458 })
14459 .await;
14460 assert!(handle.is_err());
14461 }
14462 }
14463
14464 #[gpui::test]
14465 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
14466 init_test(cx);
14467
14468 let fs = FakeFs::new(cx.executor());
14469 let project = Project::test(fs, [], cx).await;
14470 let (workspace, _cx) =
14471 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14472
14473 // Test with status bar shown (default)
14474 workspace.read_with(cx, |workspace, cx| {
14475 let visible = workspace.status_bar_visible(cx);
14476 assert!(visible, "Status bar should be visible by default");
14477 });
14478
14479 // Test with status bar hidden
14480 cx.update_global(|store: &mut SettingsStore, cx| {
14481 store.update_user_settings(cx, |settings| {
14482 settings.status_bar.get_or_insert_default().show = Some(false);
14483 });
14484 });
14485
14486 workspace.read_with(cx, |workspace, cx| {
14487 let visible = workspace.status_bar_visible(cx);
14488 assert!(!visible, "Status bar should be hidden when show is false");
14489 });
14490
14491 // Test with status bar shown explicitly
14492 cx.update_global(|store: &mut SettingsStore, cx| {
14493 store.update_user_settings(cx, |settings| {
14494 settings.status_bar.get_or_insert_default().show = Some(true);
14495 });
14496 });
14497
14498 workspace.read_with(cx, |workspace, cx| {
14499 let visible = workspace.status_bar_visible(cx);
14500 assert!(visible, "Status bar should be visible when show is true");
14501 });
14502 }
14503
14504 #[gpui::test]
14505 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
14506 init_test(cx);
14507
14508 let fs = FakeFs::new(cx.executor());
14509 let project = Project::test(fs, [], cx).await;
14510 let (multi_workspace, cx) =
14511 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
14512 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
14513 let panel = workspace.update_in(cx, |workspace, window, cx| {
14514 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14515 workspace.add_panel(panel.clone(), window, cx);
14516
14517 workspace
14518 .right_dock()
14519 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
14520
14521 panel
14522 });
14523
14524 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14525 let item_a = cx.new(TestItem::new);
14526 let item_b = cx.new(TestItem::new);
14527 let item_a_id = item_a.entity_id();
14528 let item_b_id = item_b.entity_id();
14529
14530 pane.update_in(cx, |pane, window, cx| {
14531 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
14532 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
14533 });
14534
14535 pane.read_with(cx, |pane, _| {
14536 assert_eq!(pane.items_len(), 2);
14537 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
14538 });
14539
14540 workspace.update_in(cx, |workspace, window, cx| {
14541 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14542 });
14543
14544 workspace.update_in(cx, |_, window, cx| {
14545 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14546 });
14547
14548 // Assert that the `pane::CloseActiveItem` action is handled at the
14549 // workspace level when one of the dock panels is focused and, in that
14550 // case, the center pane's active item is closed but the focus is not
14551 // moved.
14552 cx.dispatch_action(pane::CloseActiveItem::default());
14553 cx.run_until_parked();
14554
14555 pane.read_with(cx, |pane, _| {
14556 assert_eq!(pane.items_len(), 1);
14557 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
14558 });
14559
14560 workspace.update_in(cx, |workspace, window, cx| {
14561 assert!(workspace.right_dock().read(cx).is_open());
14562 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14563 });
14564 }
14565
14566 #[gpui::test]
14567 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
14568 init_test(cx);
14569 let fs = FakeFs::new(cx.executor());
14570
14571 let project_a = Project::test(fs.clone(), [], cx).await;
14572 let project_b = Project::test(fs, [], cx).await;
14573
14574 let multi_workspace_handle =
14575 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
14576 cx.run_until_parked();
14577
14578 multi_workspace_handle
14579 .update(cx, |mw, _window, cx| {
14580 mw.open_sidebar(cx);
14581 })
14582 .unwrap();
14583
14584 let workspace_a = multi_workspace_handle
14585 .read_with(cx, |mw, _| mw.workspace().clone())
14586 .unwrap();
14587
14588 let _workspace_b = multi_workspace_handle
14589 .update(cx, |mw, window, cx| {
14590 mw.test_add_workspace(project_b, window, cx)
14591 })
14592 .unwrap();
14593
14594 // Switch to workspace A
14595 multi_workspace_handle
14596 .update(cx, |mw, window, cx| {
14597 let workspace = mw.workspaces().next().unwrap().clone();
14598 mw.activate(workspace, window, cx);
14599 })
14600 .unwrap();
14601
14602 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
14603
14604 // Add a panel to workspace A's right dock and open the dock
14605 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
14606 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14607 workspace.add_panel(panel.clone(), window, cx);
14608 workspace
14609 .right_dock()
14610 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14611 panel
14612 });
14613
14614 // Focus the panel through the workspace (matching existing test pattern)
14615 workspace_a.update_in(cx, |workspace, window, cx| {
14616 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14617 });
14618
14619 // Zoom the panel
14620 panel.update_in(cx, |panel, window, cx| {
14621 panel.set_zoomed(true, window, cx);
14622 });
14623
14624 // Verify the panel is zoomed and the dock is open
14625 workspace_a.update_in(cx, |workspace, window, cx| {
14626 assert!(
14627 workspace.right_dock().read(cx).is_open(),
14628 "dock should be open before switch"
14629 );
14630 assert!(
14631 panel.is_zoomed(window, cx),
14632 "panel should be zoomed before switch"
14633 );
14634 assert!(
14635 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
14636 "panel should be focused before switch"
14637 );
14638 });
14639
14640 // Switch to workspace B
14641 multi_workspace_handle
14642 .update(cx, |mw, window, cx| {
14643 let workspace = mw.workspaces().nth(1).unwrap().clone();
14644 mw.activate(workspace, window, cx);
14645 })
14646 .unwrap();
14647 cx.run_until_parked();
14648
14649 // Switch back to workspace A
14650 multi_workspace_handle
14651 .update(cx, |mw, window, cx| {
14652 let workspace = mw.workspaces().next().unwrap().clone();
14653 mw.activate(workspace, window, cx);
14654 })
14655 .unwrap();
14656 cx.run_until_parked();
14657
14658 // Verify the panel is still zoomed and the dock is still open
14659 workspace_a.update_in(cx, |workspace, window, cx| {
14660 assert!(
14661 workspace.right_dock().read(cx).is_open(),
14662 "dock should still be open after switching back"
14663 );
14664 assert!(
14665 panel.is_zoomed(window, cx),
14666 "panel should still be zoomed after switching back"
14667 );
14668 });
14669 }
14670
14671 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
14672 pane.read(cx)
14673 .items()
14674 .flat_map(|item| {
14675 item.project_paths(cx)
14676 .into_iter()
14677 .map(|path| path.path.display(PathStyle::local()).into_owned())
14678 })
14679 .collect()
14680 }
14681
14682 pub fn init_test(cx: &mut TestAppContext) {
14683 cx.update(|cx| {
14684 let settings_store = SettingsStore::test(cx);
14685 cx.set_global(settings_store);
14686 cx.set_global(db::AppDatabase::test_new());
14687 theme_settings::init(theme::LoadThemes::JustBase, cx);
14688 });
14689 }
14690
14691 #[gpui::test]
14692 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
14693 use settings::{ThemeName, ThemeSelection};
14694 use theme::SystemAppearance;
14695 use zed_actions::theme::ToggleMode;
14696
14697 init_test(cx);
14698
14699 let fs = FakeFs::new(cx.executor());
14700 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
14701
14702 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
14703 .await;
14704
14705 // Build a test project and workspace view so the test can invoke
14706 // the workspace action handler the same way the UI would.
14707 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
14708 let (workspace, cx) =
14709 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
14710
14711 // Seed the settings file with a plain static light theme so the
14712 // first toggle always starts from a known persisted state.
14713 workspace.update_in(cx, |_workspace, _window, cx| {
14714 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
14715 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
14716 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
14717 });
14718 });
14719 cx.executor().advance_clock(Duration::from_millis(200));
14720 cx.run_until_parked();
14721
14722 // Confirm the initial persisted settings contain the static theme
14723 // we just wrote before any toggling happens.
14724 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14725 assert!(settings_text.contains(r#""theme": "One Light""#));
14726
14727 // Toggle once. This should migrate the persisted theme settings
14728 // into light/dark slots and enable system mode.
14729 workspace.update_in(cx, |workspace, window, cx| {
14730 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14731 });
14732 cx.executor().advance_clock(Duration::from_millis(200));
14733 cx.run_until_parked();
14734
14735 // 1. Static -> Dynamic
14736 // this assertion checks theme changed from static to dynamic.
14737 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14738 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
14739 assert_eq!(
14740 parsed["theme"],
14741 serde_json::json!({
14742 "mode": "system",
14743 "light": "One Light",
14744 "dark": "One Dark"
14745 })
14746 );
14747
14748 // 2. Toggle again, suppose it will change the mode to light
14749 workspace.update_in(cx, |workspace, window, cx| {
14750 workspace.toggle_theme_mode(&ToggleMode, window, cx);
14751 });
14752 cx.executor().advance_clock(Duration::from_millis(200));
14753 cx.run_until_parked();
14754
14755 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
14756 assert!(settings_text.contains(r#""mode": "light""#));
14757 }
14758
14759 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
14760 let item = TestProjectItem::new(id, path, cx);
14761 item.update(cx, |item, _| {
14762 item.is_dirty = true;
14763 });
14764 item
14765 }
14766
14767 #[gpui::test]
14768 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
14769 cx: &mut gpui::TestAppContext,
14770 ) {
14771 init_test(cx);
14772 let fs = FakeFs::new(cx.executor());
14773
14774 let project = Project::test(fs, [], cx).await;
14775 let (workspace, cx) =
14776 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14777
14778 let panel = workspace.update_in(cx, |workspace, window, cx| {
14779 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
14780 workspace.add_panel(panel.clone(), window, cx);
14781 workspace
14782 .right_dock()
14783 .update(cx, |dock, cx| dock.set_open(true, window, cx));
14784 panel
14785 });
14786
14787 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
14788 pane.update_in(cx, |pane, window, cx| {
14789 let item = cx.new(TestItem::new);
14790 pane.add_item(Box::new(item), true, true, None, window, cx);
14791 });
14792
14793 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
14794 // mirrors the real-world flow and avoids side effects from directly
14795 // focusing the panel while the center pane is active.
14796 workspace.update_in(cx, |workspace, window, cx| {
14797 workspace.toggle_panel_focus::<TestPanel>(window, cx);
14798 });
14799
14800 panel.update_in(cx, |panel, window, cx| {
14801 panel.set_zoomed(true, window, cx);
14802 });
14803
14804 workspace.update_in(cx, |workspace, window, cx| {
14805 assert!(workspace.right_dock().read(cx).is_open());
14806 assert!(panel.is_zoomed(window, cx));
14807 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
14808 });
14809
14810 // Simulate a spurious pane::Event::Focus on the center pane while the
14811 // panel still has focus. This mirrors what happens during macOS window
14812 // activation: the center pane fires a focus event even though actual
14813 // focus remains on the dock panel.
14814 pane.update_in(cx, |_, _, cx| {
14815 cx.emit(pane::Event::Focus);
14816 });
14817
14818 // The dock must remain open because the panel had focus at the time the
14819 // event was processed. Before the fix, dock_to_preserve was None for
14820 // panels that don't implement pane(), causing the dock to close.
14821 workspace.update_in(cx, |workspace, window, cx| {
14822 assert!(
14823 workspace.right_dock().read(cx).is_open(),
14824 "Dock should stay open when its zoomed panel (without pane()) still has focus"
14825 );
14826 assert!(panel.is_zoomed(window, cx));
14827 });
14828 }
14829
14830 #[gpui::test]
14831 async fn test_panels_stay_open_after_position_change_and_settings_update(
14832 cx: &mut gpui::TestAppContext,
14833 ) {
14834 init_test(cx);
14835 let fs = FakeFs::new(cx.executor());
14836 let project = Project::test(fs, [], cx).await;
14837 let (workspace, cx) =
14838 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
14839
14840 // Add two panels to the left dock and open it.
14841 let (panel_a, panel_b) = workspace.update_in(cx, |workspace, window, cx| {
14842 let panel_a = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
14843 let panel_b = cx.new(|cx| TestPanel::new(DockPosition::Left, 101, cx));
14844 workspace.add_panel(panel_a.clone(), window, cx);
14845 workspace.add_panel(panel_b.clone(), window, cx);
14846 workspace.left_dock().update(cx, |dock, cx| {
14847 dock.set_open(true, window, cx);
14848 dock.activate_panel(0, window, cx);
14849 });
14850 (panel_a, panel_b)
14851 });
14852
14853 workspace.update_in(cx, |workspace, _, cx| {
14854 assert!(workspace.left_dock().read(cx).is_open());
14855 });
14856
14857 // Simulate a feature flag changing default dock positions: both panels
14858 // move from Left to Right.
14859 workspace.update_in(cx, |_workspace, _window, cx| {
14860 panel_a.update(cx, |p, _cx| p.position = DockPosition::Right);
14861 panel_b.update(cx, |p, _cx| p.position = DockPosition::Right);
14862 cx.update_global::<SettingsStore, _>(|_, _| {});
14863 });
14864
14865 // Both panels should now be in the right dock.
14866 workspace.update_in(cx, |workspace, _, cx| {
14867 let right_dock = workspace.right_dock().read(cx);
14868 assert_eq!(right_dock.panels_len(), 2);
14869 });
14870
14871 // Open the right dock and activate panel_b (simulating the user
14872 // opening the panel after it moved).
14873 workspace.update_in(cx, |workspace, window, cx| {
14874 workspace.right_dock().update(cx, |dock, cx| {
14875 dock.set_open(true, window, cx);
14876 dock.activate_panel(1, window, cx);
14877 });
14878 });
14879
14880 // Now trigger another SettingsStore change
14881 workspace.update_in(cx, |_workspace, _window, cx| {
14882 cx.update_global::<SettingsStore, _>(|_, _| {});
14883 });
14884
14885 workspace.update_in(cx, |workspace, _, cx| {
14886 assert!(
14887 workspace.right_dock().read(cx).is_open(),
14888 "Right dock should still be open after a settings change"
14889 );
14890 assert_eq!(
14891 workspace.right_dock().read(cx).panels_len(),
14892 2,
14893 "Both panels should still be in the right dock"
14894 );
14895 });
14896 }
14897}