1pub mod dock;
2pub mod history_manager;
3pub mod invalid_item_view;
4pub mod item;
5mod modal_layer;
6mod multi_workspace;
7pub mod notifications;
8pub mod pane;
9pub mod pane_group;
10pub mod path_list {
11 pub use util::path_list::{PathList, SerializedPathList};
12}
13mod persistence;
14pub mod searchable;
15mod security_modal;
16pub mod shared_screen;
17use db::smol::future::yield_now;
18pub use shared_screen::SharedScreen;
19mod status_bar;
20pub mod tasks;
21mod theme_preview;
22mod toast_layer;
23mod toolbar;
24pub mod welcome;
25mod workspace_settings;
26
27pub use crate::notifications::NotificationFrame;
28pub use dock::Panel;
29pub use multi_workspace::{
30 CloseWorkspaceSidebar, DraggedSidebar, FocusWorkspaceSidebar, MultiWorkspace,
31 MultiWorkspaceEvent, NextWorkspace, PreviousWorkspace, Sidebar, SidebarHandle,
32 ToggleWorkspaceSidebar,
33};
34pub use path_list::{PathList, SerializedPathList};
35pub use toast_layer::{ToastAction, ToastLayer, ToastView};
36
37use anyhow::{Context as _, Result, anyhow};
38use client::{
39 ChannelId, Client, ErrorExt, ParticipantIndex, Status, TypedEnvelope, User, UserStore,
40 proto::{self, ErrorCode, PanelId, PeerId},
41};
42use collections::{HashMap, HashSet, hash_map};
43use dock::{Dock, DockPosition, PanelButtons, PanelHandle, RESIZE_HANDLE_SIZE};
44use fs::Fs;
45use futures::{
46 Future, FutureExt, StreamExt,
47 channel::{
48 mpsc::{self, UnboundedReceiver, UnboundedSender},
49 oneshot,
50 },
51 future::{Shared, try_join_all},
52};
53use gpui::{
54 Action, AnyEntity, AnyView, AnyWeakView, App, AsyncApp, AsyncWindowContext, Bounds, Context,
55 CursorStyle, Decorations, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle,
56 Focusable, Global, HitboxBehavior, Hsla, KeyContext, Keystroke, ManagedView, MouseButton,
57 PathPromptOptions, Point, PromptLevel, Render, ResizeEdge, Size, Stateful, Subscription,
58 SystemWindowTabController, Task, Tiling, WeakEntity, WindowBounds, WindowHandle, WindowId,
59 WindowOptions, actions, canvas, point, relative, size, transparent_black,
60};
61pub use history_manager::*;
62pub use item::{
63 FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, PreviewTabsSettings,
64 ProjectItem, SerializableItem, SerializableItemHandle, WeakItemHandle,
65};
66use itertools::Itertools;
67use language::{Buffer, LanguageRegistry, Rope, language_settings::all_language_settings};
68pub use modal_layer::*;
69use node_runtime::NodeRuntime;
70use notifications::{
71 DetachAndPromptErr, Notifications, dismiss_app_notification,
72 simple_message_notification::MessageNotification,
73};
74pub use pane::*;
75pub use pane_group::{
76 ActivePaneDecorator, HANDLE_HITBOX_SIZE, Member, PaneAxis, PaneGroup, PaneRenderContext,
77 SplitDirection,
78};
79use persistence::{SerializedWindowBounds, model::SerializedWorkspace};
80pub use persistence::{
81 WorkspaceDb, delete_unloaded_items,
82 model::{
83 DockStructure, ItemId, SerializedMultiWorkspace, SerializedWorkspaceLocation,
84 SessionWorkspace,
85 },
86 read_serialized_multi_workspaces, resolve_worktree_workspaces,
87};
88use postage::stream::Stream;
89use project::{
90 DirectoryLister, Project, ProjectEntryId, ProjectPath, ResolvedPath, Worktree, WorktreeId,
91 WorktreeSettings,
92 debugger::{breakpoint_store::BreakpointStoreEvent, session::ThreadStatus},
93 project_settings::ProjectSettings,
94 toolchain_store::ToolchainStoreEvent,
95 trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
96};
97use remote::{
98 RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions,
99 remote_client::ConnectionIdentifier,
100};
101use schemars::JsonSchema;
102use serde::Deserialize;
103use session::AppSession;
104use settings::{
105 CenteredPaddingSettings, Settings, SettingsLocation, SettingsStore, update_settings_file,
106};
107
108use sqlez::{
109 bindable::{Bind, Column, StaticColumnCount},
110 statement::Statement,
111};
112use status_bar::StatusBar;
113pub use status_bar::StatusItemView;
114use std::{
115 any::TypeId,
116 borrow::Cow,
117 cell::RefCell,
118 cmp,
119 collections::VecDeque,
120 env,
121 hash::Hash,
122 path::{Path, PathBuf},
123 process::ExitStatus,
124 rc::Rc,
125 sync::{
126 Arc, LazyLock, Weak,
127 atomic::{AtomicBool, AtomicUsize},
128 },
129 time::Duration,
130};
131use task::{DebugScenario, SharedTaskContext, SpawnInTerminal};
132use theme::{ActiveTheme, GlobalTheme, SystemAppearance, ThemeSettings};
133pub use toolbar::{
134 PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
135};
136pub use ui;
137use ui::{Window, prelude::*};
138use util::{
139 ResultExt, TryFutureExt,
140 paths::{PathStyle, SanitizedPath},
141 rel_path::RelPath,
142 serde::default_true,
143};
144use uuid::Uuid;
145pub use workspace_settings::{
146 AutosaveSetting, BottomDockLayout, RestoreOnStartupBehavior, StatusBarSettings, TabBarSettings,
147 WorkspaceSettings,
148};
149use zed_actions::{Spawn, feedback::FileBugReport, theme::ToggleMode};
150
151use crate::{item::ItemBufferKind, notifications::NotificationId};
152use crate::{
153 persistence::{
154 SerializedAxis,
155 model::{DockData, SerializedItem, SerializedPane, SerializedPaneGroup},
156 },
157 security_modal::SecurityModal,
158};
159
160pub const SERIALIZATION_THROTTLE_TIME: Duration = Duration::from_millis(200);
161
162static ZED_WINDOW_SIZE: LazyLock<Option<Size<Pixels>>> = LazyLock::new(|| {
163 env::var("ZED_WINDOW_SIZE")
164 .ok()
165 .as_deref()
166 .and_then(parse_pixel_size_env_var)
167});
168
169static ZED_WINDOW_POSITION: LazyLock<Option<Point<Pixels>>> = LazyLock::new(|| {
170 env::var("ZED_WINDOW_POSITION")
171 .ok()
172 .as_deref()
173 .and_then(parse_pixel_position_env_var)
174});
175
176pub trait TerminalProvider {
177 fn spawn(
178 &self,
179 task: SpawnInTerminal,
180 window: &mut Window,
181 cx: &mut App,
182 ) -> Task<Option<Result<ExitStatus>>>;
183}
184
185pub trait DebuggerProvider {
186 // `active_buffer` is used to resolve build task's name against language-specific tasks.
187 fn start_session(
188 &self,
189 definition: DebugScenario,
190 task_context: SharedTaskContext,
191 active_buffer: Option<Entity<Buffer>>,
192 worktree_id: Option<WorktreeId>,
193 window: &mut Window,
194 cx: &mut App,
195 );
196
197 fn spawn_task_or_modal(
198 &self,
199 workspace: &mut Workspace,
200 action: &Spawn,
201 window: &mut Window,
202 cx: &mut Context<Workspace>,
203 );
204
205 fn task_scheduled(&self, cx: &mut App);
206 fn debug_scenario_scheduled(&self, cx: &mut App);
207 fn debug_scenario_scheduled_last(&self, cx: &App) -> bool;
208
209 fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus>;
210}
211
212/// Opens a file or directory.
213#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
214#[action(namespace = workspace)]
215pub struct Open {
216 /// When true, opens in a new window. When false, adds to the current
217 /// window as a new workspace (multi-workspace).
218 #[serde(default = "Open::default_create_new_window")]
219 pub create_new_window: bool,
220}
221
222impl Open {
223 pub const DEFAULT: Self = Self {
224 create_new_window: true,
225 };
226
227 /// Used by `#[serde(default)]` on the `create_new_window` field so that
228 /// the serde default and `Open::DEFAULT` stay in sync.
229 fn default_create_new_window() -> bool {
230 Self::DEFAULT.create_new_window
231 }
232}
233
234impl Default for Open {
235 fn default() -> Self {
236 Self::DEFAULT
237 }
238}
239
240actions!(
241 workspace,
242 [
243 /// Activates the next pane in the workspace.
244 ActivateNextPane,
245 /// Activates the previous pane in the workspace.
246 ActivatePreviousPane,
247 /// Activates the last pane in the workspace.
248 ActivateLastPane,
249 /// Switches to the next window.
250 ActivateNextWindow,
251 /// Switches to the previous window.
252 ActivatePreviousWindow,
253 /// Adds a folder to the current project.
254 AddFolderToProject,
255 /// Clears all notifications.
256 ClearAllNotifications,
257 /// Clears all navigation history, including forward/backward navigation, recently opened files, and recently closed tabs. **This action is irreversible**.
258 ClearNavigationHistory,
259 /// Closes the active dock.
260 CloseActiveDock,
261 /// Closes all docks.
262 CloseAllDocks,
263 /// Toggles all docks.
264 ToggleAllDocks,
265 /// Closes the current window.
266 CloseWindow,
267 /// Closes the current project.
268 CloseProject,
269 /// Opens the feedback dialog.
270 Feedback,
271 /// Follows the next collaborator in the session.
272 FollowNextCollaborator,
273 /// Moves the focused panel to the next position.
274 MoveFocusedPanelToNextPosition,
275 /// Creates a new file.
276 NewFile,
277 /// Creates a new file in a vertical split.
278 NewFileSplitVertical,
279 /// Creates a new file in a horizontal split.
280 NewFileSplitHorizontal,
281 /// Opens a new search.
282 NewSearch,
283 /// Opens a new window.
284 NewWindow,
285 /// Opens multiple files.
286 OpenFiles,
287 /// Opens the current location in terminal.
288 OpenInTerminal,
289 /// Opens the component preview.
290 OpenComponentPreview,
291 /// Reloads the active item.
292 ReloadActiveItem,
293 /// Resets the active dock to its default size.
294 ResetActiveDockSize,
295 /// Resets all open docks to their default sizes.
296 ResetOpenDocksSize,
297 /// Reloads the application
298 Reload,
299 /// Saves the current file with a new name.
300 SaveAs,
301 /// Saves without formatting.
302 SaveWithoutFormat,
303 /// Shuts down all debug adapters.
304 ShutdownDebugAdapters,
305 /// Suppresses the current notification.
306 SuppressNotification,
307 /// Toggles the bottom dock.
308 ToggleBottomDock,
309 /// Toggles centered layout mode.
310 ToggleCenteredLayout,
311 /// Toggles edit prediction feature globally for all files.
312 ToggleEditPrediction,
313 /// Toggles the left dock.
314 ToggleLeftDock,
315 /// Toggles the right dock.
316 ToggleRightDock,
317 /// Toggles zoom on the active pane.
318 ToggleZoom,
319 /// Toggles read-only mode for the active item (if supported by that item).
320 ToggleReadOnlyFile,
321 /// Zooms in on the active pane.
322 ZoomIn,
323 /// Zooms out of the active pane.
324 ZoomOut,
325 /// If any worktrees are in restricted mode, shows a modal with possible actions.
326 /// If the modal is shown already, closes it without trusting any worktree.
327 ToggleWorktreeSecurity,
328 /// Clears all trusted worktrees, placing them in restricted mode on next open.
329 /// Requires restart to take effect on already opened projects.
330 ClearTrustedWorktrees,
331 /// Stops following a collaborator.
332 Unfollow,
333 /// Restores the banner.
334 RestoreBanner,
335 /// Toggles expansion of the selected item.
336 ToggleExpandItem,
337 ]
338);
339
340/// Activates a specific pane by its index.
341#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
342#[action(namespace = workspace)]
343pub struct ActivatePane(pub usize);
344
345/// Moves an item to a specific pane by index.
346#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
347#[action(namespace = workspace)]
348#[serde(deny_unknown_fields)]
349pub struct MoveItemToPane {
350 #[serde(default = "default_1")]
351 pub destination: usize,
352 #[serde(default = "default_true")]
353 pub focus: bool,
354 #[serde(default)]
355 pub clone: bool,
356}
357
358fn default_1() -> usize {
359 1
360}
361
362/// Moves an item to a pane in the specified direction.
363#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
364#[action(namespace = workspace)]
365#[serde(deny_unknown_fields)]
366pub struct MoveItemToPaneInDirection {
367 #[serde(default = "default_right")]
368 pub direction: SplitDirection,
369 #[serde(default = "default_true")]
370 pub focus: bool,
371 #[serde(default)]
372 pub clone: bool,
373}
374
375/// Creates a new file in a split of the desired direction.
376#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
377#[action(namespace = workspace)]
378#[serde(deny_unknown_fields)]
379pub struct NewFileSplit(pub SplitDirection);
380
381fn default_right() -> SplitDirection {
382 SplitDirection::Right
383}
384
385/// Saves all open files in the workspace.
386#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
387#[action(namespace = workspace)]
388#[serde(deny_unknown_fields)]
389pub struct SaveAll {
390 #[serde(default)]
391 pub save_intent: Option<SaveIntent>,
392}
393
394/// Saves the current file with the specified options.
395#[derive(Clone, PartialEq, Debug, Deserialize, JsonSchema, Action)]
396#[action(namespace = workspace)]
397#[serde(deny_unknown_fields)]
398pub struct Save {
399 #[serde(default)]
400 pub save_intent: Option<SaveIntent>,
401}
402
403/// Moves Focus to the central panes in the workspace.
404#[derive(Clone, Debug, PartialEq, Eq, Action)]
405#[action(namespace = workspace)]
406pub struct FocusCenterPane;
407
408/// Closes all items and panes in the workspace.
409#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
410#[action(namespace = workspace)]
411#[serde(deny_unknown_fields)]
412pub struct CloseAllItemsAndPanes {
413 #[serde(default)]
414 pub save_intent: Option<SaveIntent>,
415}
416
417/// Closes all inactive tabs and panes in the workspace.
418#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
419#[action(namespace = workspace)]
420#[serde(deny_unknown_fields)]
421pub struct CloseInactiveTabsAndPanes {
422 #[serde(default)]
423 pub save_intent: Option<SaveIntent>,
424}
425
426/// Closes the active item across all panes.
427#[derive(Clone, PartialEq, Debug, Deserialize, Default, JsonSchema, Action)]
428#[action(namespace = workspace)]
429#[serde(deny_unknown_fields)]
430pub struct CloseItemInAllPanes {
431 #[serde(default)]
432 pub save_intent: Option<SaveIntent>,
433 #[serde(default)]
434 pub close_pinned: bool,
435}
436
437/// Sends a sequence of keystrokes to the active element.
438#[derive(Clone, Deserialize, PartialEq, JsonSchema, Action)]
439#[action(namespace = workspace)]
440pub struct SendKeystrokes(pub String);
441
442actions!(
443 project_symbols,
444 [
445 /// Toggles the project symbols search.
446 #[action(name = "Toggle")]
447 ToggleProjectSymbols
448 ]
449);
450
451/// Toggles the file finder interface.
452#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
453#[action(namespace = file_finder, name = "Toggle")]
454#[serde(deny_unknown_fields)]
455pub struct ToggleFileFinder {
456 #[serde(default)]
457 pub separate_history: bool,
458}
459
460/// Opens a new terminal in the center.
461#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
462#[action(namespace = workspace)]
463#[serde(deny_unknown_fields)]
464pub struct NewCenterTerminal {
465 /// If true, creates a local terminal even in remote projects.
466 #[serde(default)]
467 pub local: bool,
468}
469
470/// Opens a new terminal.
471#[derive(Default, PartialEq, Eq, Clone, Deserialize, JsonSchema, Action)]
472#[action(namespace = workspace)]
473#[serde(deny_unknown_fields)]
474pub struct NewTerminal {
475 /// If true, creates a local terminal even in remote projects.
476 #[serde(default)]
477 pub local: bool,
478}
479
480/// Increases size of a currently focused dock by a given amount of pixels.
481#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
482#[action(namespace = workspace)]
483#[serde(deny_unknown_fields)]
484pub struct IncreaseActiveDockSize {
485 /// For 0px parameter, uses UI font size value.
486 #[serde(default)]
487 pub px: u32,
488}
489
490/// Decreases size of a currently focused dock by a given amount of pixels.
491#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
492#[action(namespace = workspace)]
493#[serde(deny_unknown_fields)]
494pub struct DecreaseActiveDockSize {
495 /// For 0px parameter, uses UI font size value.
496 #[serde(default)]
497 pub px: u32,
498}
499
500/// Increases size of all currently visible docks uniformly, by a given amount of pixels.
501#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
502#[action(namespace = workspace)]
503#[serde(deny_unknown_fields)]
504pub struct IncreaseOpenDocksSize {
505 /// For 0px parameter, uses UI font size value.
506 #[serde(default)]
507 pub px: u32,
508}
509
510/// Decreases size of all currently visible docks uniformly, by a given amount of pixels.
511#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
512#[action(namespace = workspace)]
513#[serde(deny_unknown_fields)]
514pub struct DecreaseOpenDocksSize {
515 /// For 0px parameter, uses UI font size value.
516 #[serde(default)]
517 pub px: u32,
518}
519
520actions!(
521 workspace,
522 [
523 /// Activates the pane to the left.
524 ActivatePaneLeft,
525 /// Activates the pane to the right.
526 ActivatePaneRight,
527 /// Activates the pane above.
528 ActivatePaneUp,
529 /// Activates the pane below.
530 ActivatePaneDown,
531 /// Swaps the current pane with the one to the left.
532 SwapPaneLeft,
533 /// Swaps the current pane with the one to the right.
534 SwapPaneRight,
535 /// Swaps the current pane with the one above.
536 SwapPaneUp,
537 /// Swaps the current pane with the one below.
538 SwapPaneDown,
539 // Swaps the current pane with the first available adjacent pane (searching in order: below, above, right, left) and activates that pane.
540 SwapPaneAdjacent,
541 /// Move the current pane to be at the far left.
542 MovePaneLeft,
543 /// Move the current pane to be at the far right.
544 MovePaneRight,
545 /// Move the current pane to be at the very top.
546 MovePaneUp,
547 /// Move the current pane to be at the very bottom.
548 MovePaneDown,
549 ]
550);
551
552#[derive(PartialEq, Eq, Debug)]
553pub enum CloseIntent {
554 /// Quit the program entirely.
555 Quit,
556 /// Close a window.
557 CloseWindow,
558 /// Replace the workspace in an existing window.
559 ReplaceWindow,
560}
561
562#[derive(Clone)]
563pub struct Toast {
564 id: NotificationId,
565 msg: Cow<'static, str>,
566 autohide: bool,
567 on_click: Option<(Cow<'static, str>, Arc<dyn Fn(&mut Window, &mut App)>)>,
568}
569
570impl Toast {
571 pub fn new<I: Into<Cow<'static, str>>>(id: NotificationId, msg: I) -> Self {
572 Toast {
573 id,
574 msg: msg.into(),
575 on_click: None,
576 autohide: false,
577 }
578 }
579
580 pub fn on_click<F, M>(mut self, message: M, on_click: F) -> Self
581 where
582 M: Into<Cow<'static, str>>,
583 F: Fn(&mut Window, &mut App) + 'static,
584 {
585 self.on_click = Some((message.into(), Arc::new(on_click)));
586 self
587 }
588
589 pub fn autohide(mut self) -> Self {
590 self.autohide = true;
591 self
592 }
593}
594
595impl PartialEq for Toast {
596 fn eq(&self, other: &Self) -> bool {
597 self.id == other.id
598 && self.msg == other.msg
599 && self.on_click.is_some() == other.on_click.is_some()
600 }
601}
602
603/// Opens a new terminal with the specified working directory.
604#[derive(Debug, Default, Clone, Deserialize, PartialEq, JsonSchema, Action)]
605#[action(namespace = workspace)]
606#[serde(deny_unknown_fields)]
607pub struct OpenTerminal {
608 pub working_directory: PathBuf,
609 /// If true, creates a local terminal even in remote projects.
610 #[serde(default)]
611 pub local: bool,
612}
613
614#[derive(
615 Clone,
616 Copy,
617 Debug,
618 Default,
619 Hash,
620 PartialEq,
621 Eq,
622 PartialOrd,
623 Ord,
624 serde::Serialize,
625 serde::Deserialize,
626)]
627pub struct WorkspaceId(i64);
628
629impl WorkspaceId {
630 pub fn from_i64(value: i64) -> Self {
631 Self(value)
632 }
633}
634
635impl StaticColumnCount for WorkspaceId {}
636impl Bind for WorkspaceId {
637 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
638 self.0.bind(statement, start_index)
639 }
640}
641impl Column for WorkspaceId {
642 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
643 i64::column(statement, start_index)
644 .map(|(i, next_index)| (Self(i), next_index))
645 .with_context(|| format!("Failed to read WorkspaceId at index {start_index}"))
646 }
647}
648impl From<WorkspaceId> for i64 {
649 fn from(val: WorkspaceId) -> Self {
650 val.0
651 }
652}
653
654fn prompt_and_open_paths(app_state: Arc<AppState>, options: PathPromptOptions, cx: &mut App) {
655 if let Some(workspace_window) = local_workspace_windows(cx).into_iter().next() {
656 workspace_window
657 .update(cx, |multi_workspace, window, cx| {
658 let workspace = multi_workspace.workspace().clone();
659 workspace.update(cx, |workspace, cx| {
660 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
661 });
662 })
663 .ok();
664 } else {
665 let task = Workspace::new_local(Vec::new(), app_state.clone(), None, None, None, true, cx);
666 cx.spawn(async move |cx| {
667 let OpenResult { window, .. } = task.await?;
668 window.update(cx, |multi_workspace, window, cx| {
669 window.activate_window();
670 let workspace = multi_workspace.workspace().clone();
671 workspace.update(cx, |workspace, cx| {
672 prompt_for_open_path_and_open(workspace, app_state, options, true, window, cx);
673 });
674 })?;
675 anyhow::Ok(())
676 })
677 .detach_and_log_err(cx);
678 }
679}
680
681pub fn prompt_for_open_path_and_open(
682 workspace: &mut Workspace,
683 app_state: Arc<AppState>,
684 options: PathPromptOptions,
685 create_new_window: bool,
686 window: &mut Window,
687 cx: &mut Context<Workspace>,
688) {
689 let paths = workspace.prompt_for_open_path(
690 options,
691 DirectoryLister::Local(workspace.project().clone(), app_state.fs.clone()),
692 window,
693 cx,
694 );
695 let multi_workspace_handle = window.window_handle().downcast::<MultiWorkspace>();
696 cx.spawn_in(window, async move |this, cx| {
697 let Some(paths) = paths.await.log_err().flatten() else {
698 return;
699 };
700 if !create_new_window {
701 if let Some(handle) = multi_workspace_handle {
702 if let Some(task) = handle
703 .update(cx, |multi_workspace, window, cx| {
704 multi_workspace.open_project(paths, window, cx)
705 })
706 .log_err()
707 {
708 task.await.log_err();
709 }
710 return;
711 }
712 }
713 if let Some(task) = this
714 .update_in(cx, |this, window, cx| {
715 this.open_workspace_for_paths(false, paths, window, cx)
716 })
717 .log_err()
718 {
719 task.await.log_err();
720 }
721 })
722 .detach();
723}
724
725pub fn init(app_state: Arc<AppState>, cx: &mut App) {
726 component::init();
727 theme_preview::init(cx);
728 toast_layer::init(cx);
729 history_manager::init(app_state.fs.clone(), cx);
730
731 cx.on_action(|_: &CloseWindow, cx| Workspace::close_global(cx))
732 .on_action(|_: &Reload, cx| reload(cx))
733 .on_action({
734 let app_state = Arc::downgrade(&app_state);
735 move |_: &Open, cx: &mut App| {
736 if let Some(app_state) = app_state.upgrade() {
737 prompt_and_open_paths(
738 app_state,
739 PathPromptOptions {
740 files: true,
741 directories: true,
742 multiple: true,
743 prompt: None,
744 },
745 cx,
746 );
747 }
748 }
749 })
750 .on_action({
751 let app_state = Arc::downgrade(&app_state);
752 move |_: &OpenFiles, cx: &mut App| {
753 let directories = cx.can_select_mixed_files_and_dirs();
754 if let Some(app_state) = app_state.upgrade() {
755 prompt_and_open_paths(
756 app_state,
757 PathPromptOptions {
758 files: true,
759 directories,
760 multiple: true,
761 prompt: None,
762 },
763 cx,
764 );
765 }
766 }
767 });
768}
769
770type BuildProjectItemFn =
771 fn(AnyEntity, Entity<Project>, Option<&Pane>, &mut Window, &mut App) -> Box<dyn ItemHandle>;
772
773type BuildProjectItemForPathFn =
774 fn(
775 &Entity<Project>,
776 &ProjectPath,
777 &mut Window,
778 &mut App,
779 ) -> Option<Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>>>;
780
781#[derive(Clone, Default)]
782struct ProjectItemRegistry {
783 build_project_item_fns_by_type: HashMap<TypeId, BuildProjectItemFn>,
784 build_project_item_for_path_fns: Vec<BuildProjectItemForPathFn>,
785}
786
787impl ProjectItemRegistry {
788 fn register<T: ProjectItem>(&mut self) {
789 self.build_project_item_fns_by_type.insert(
790 TypeId::of::<T::Item>(),
791 |item, project, pane, window, cx| {
792 let item = item.downcast().unwrap();
793 Box::new(cx.new(|cx| T::for_project_item(project, pane, item, window, cx)))
794 as Box<dyn ItemHandle>
795 },
796 );
797 self.build_project_item_for_path_fns
798 .push(|project, project_path, window, cx| {
799 let project_path = project_path.clone();
800 let is_file = project
801 .read(cx)
802 .entry_for_path(&project_path, cx)
803 .is_some_and(|entry| entry.is_file());
804 let entry_abs_path = project.read(cx).absolute_path(&project_path, cx);
805 let is_local = project.read(cx).is_local();
806 let project_item =
807 <T::Item as project::ProjectItem>::try_open(project, &project_path, cx)?;
808 let project = project.clone();
809 Some(window.spawn(cx, async move |cx| {
810 match project_item.await.with_context(|| {
811 format!(
812 "opening project path {:?}",
813 entry_abs_path.as_deref().unwrap_or(&project_path.path.as_std_path())
814 )
815 }) {
816 Ok(project_item) => {
817 let project_item = project_item;
818 let project_entry_id: Option<ProjectEntryId> =
819 project_item.read_with(cx, project::ProjectItem::entry_id);
820 let build_workspace_item = Box::new(
821 |pane: &mut Pane, window: &mut Window, cx: &mut Context<Pane>| {
822 Box::new(cx.new(|cx| {
823 T::for_project_item(
824 project,
825 Some(pane),
826 project_item,
827 window,
828 cx,
829 )
830 })) as Box<dyn ItemHandle>
831 },
832 ) as Box<_>;
833 Ok((project_entry_id, build_workspace_item))
834 }
835 Err(e) => {
836 log::warn!("Failed to open a project item: {e:#}");
837 if e.error_code() == ErrorCode::Internal {
838 if let Some(abs_path) =
839 entry_abs_path.as_deref().filter(|_| is_file)
840 {
841 if let Some(broken_project_item_view) =
842 cx.update(|window, cx| {
843 T::for_broken_project_item(
844 abs_path, is_local, &e, window, cx,
845 )
846 })?
847 {
848 let build_workspace_item = Box::new(
849 move |_: &mut Pane, _: &mut Window, cx: &mut Context<Pane>| {
850 cx.new(|_| broken_project_item_view).boxed_clone()
851 },
852 )
853 as Box<_>;
854 return Ok((None, build_workspace_item));
855 }
856 }
857 }
858 Err(e)
859 }
860 }
861 }))
862 });
863 }
864
865 fn open_path(
866 &self,
867 project: &Entity<Project>,
868 path: &ProjectPath,
869 window: &mut Window,
870 cx: &mut App,
871 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
872 let Some(open_project_item) = self
873 .build_project_item_for_path_fns
874 .iter()
875 .rev()
876 .find_map(|open_project_item| open_project_item(project, path, window, cx))
877 else {
878 return Task::ready(Err(anyhow!("cannot open file {:?}", path.path)));
879 };
880 open_project_item
881 }
882
883 fn build_item<T: project::ProjectItem>(
884 &self,
885 item: Entity<T>,
886 project: Entity<Project>,
887 pane: Option<&Pane>,
888 window: &mut Window,
889 cx: &mut App,
890 ) -> Option<Box<dyn ItemHandle>> {
891 let build = self
892 .build_project_item_fns_by_type
893 .get(&TypeId::of::<T>())?;
894 Some(build(item.into_any(), project, pane, window, cx))
895 }
896}
897
898type WorkspaceItemBuilder =
899 Box<dyn FnOnce(&mut Pane, &mut Window, &mut Context<Pane>) -> Box<dyn ItemHandle>>;
900
901impl Global for ProjectItemRegistry {}
902
903/// Registers a [ProjectItem] for the app. When opening a file, all the registered
904/// items will get a chance to open the file, starting from the project item that
905/// was added last.
906pub fn register_project_item<I: ProjectItem>(cx: &mut App) {
907 cx.default_global::<ProjectItemRegistry>().register::<I>();
908}
909
910#[derive(Default)]
911pub struct FollowableViewRegistry(HashMap<TypeId, FollowableViewDescriptor>);
912
913struct FollowableViewDescriptor {
914 from_state_proto: fn(
915 Entity<Workspace>,
916 ViewId,
917 &mut Option<proto::view::Variant>,
918 &mut Window,
919 &mut App,
920 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>,
921 to_followable_view: fn(&AnyView) -> Box<dyn FollowableItemHandle>,
922}
923
924impl Global for FollowableViewRegistry {}
925
926impl FollowableViewRegistry {
927 pub fn register<I: FollowableItem>(cx: &mut App) {
928 cx.default_global::<Self>().0.insert(
929 TypeId::of::<I>(),
930 FollowableViewDescriptor {
931 from_state_proto: |workspace, id, state, window, cx| {
932 I::from_state_proto(workspace, id, state, window, cx).map(|task| {
933 cx.foreground_executor()
934 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
935 })
936 },
937 to_followable_view: |view| Box::new(view.clone().downcast::<I>().unwrap()),
938 },
939 );
940 }
941
942 pub fn from_state_proto(
943 workspace: Entity<Workspace>,
944 view_id: ViewId,
945 mut state: Option<proto::view::Variant>,
946 window: &mut Window,
947 cx: &mut App,
948 ) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>> {
949 cx.update_default_global(|this: &mut Self, cx| {
950 this.0.values().find_map(|descriptor| {
951 (descriptor.from_state_proto)(workspace.clone(), view_id, &mut state, window, cx)
952 })
953 })
954 }
955
956 pub fn to_followable_view(
957 view: impl Into<AnyView>,
958 cx: &App,
959 ) -> Option<Box<dyn FollowableItemHandle>> {
960 let this = cx.try_global::<Self>()?;
961 let view = view.into();
962 let descriptor = this.0.get(&view.entity_type())?;
963 Some((descriptor.to_followable_view)(&view))
964 }
965}
966
967#[derive(Copy, Clone)]
968struct SerializableItemDescriptor {
969 deserialize: fn(
970 Entity<Project>,
971 WeakEntity<Workspace>,
972 WorkspaceId,
973 ItemId,
974 &mut Window,
975 &mut Context<Pane>,
976 ) -> Task<Result<Box<dyn ItemHandle>>>,
977 cleanup: fn(WorkspaceId, Vec<ItemId>, &mut Window, &mut App) -> Task<Result<()>>,
978 view_to_serializable_item: fn(AnyView) -> Box<dyn SerializableItemHandle>,
979}
980
981#[derive(Default)]
982struct SerializableItemRegistry {
983 descriptors_by_kind: HashMap<Arc<str>, SerializableItemDescriptor>,
984 descriptors_by_type: HashMap<TypeId, SerializableItemDescriptor>,
985}
986
987impl Global for SerializableItemRegistry {}
988
989impl SerializableItemRegistry {
990 fn deserialize(
991 item_kind: &str,
992 project: Entity<Project>,
993 workspace: WeakEntity<Workspace>,
994 workspace_id: WorkspaceId,
995 item_item: ItemId,
996 window: &mut Window,
997 cx: &mut Context<Pane>,
998 ) -> Task<Result<Box<dyn ItemHandle>>> {
999 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1000 return Task::ready(Err(anyhow!(
1001 "cannot deserialize {}, descriptor not found",
1002 item_kind
1003 )));
1004 };
1005
1006 (descriptor.deserialize)(project, workspace, workspace_id, item_item, window, cx)
1007 }
1008
1009 fn cleanup(
1010 item_kind: &str,
1011 workspace_id: WorkspaceId,
1012 loaded_items: Vec<ItemId>,
1013 window: &mut Window,
1014 cx: &mut App,
1015 ) -> Task<Result<()>> {
1016 let Some(descriptor) = Self::descriptor(item_kind, cx) else {
1017 return Task::ready(Err(anyhow!(
1018 "cannot cleanup {}, descriptor not found",
1019 item_kind
1020 )));
1021 };
1022
1023 (descriptor.cleanup)(workspace_id, loaded_items, window, cx)
1024 }
1025
1026 fn view_to_serializable_item_handle(
1027 view: AnyView,
1028 cx: &App,
1029 ) -> Option<Box<dyn SerializableItemHandle>> {
1030 let this = cx.try_global::<Self>()?;
1031 let descriptor = this.descriptors_by_type.get(&view.entity_type())?;
1032 Some((descriptor.view_to_serializable_item)(view))
1033 }
1034
1035 fn descriptor(item_kind: &str, cx: &App) -> Option<SerializableItemDescriptor> {
1036 let this = cx.try_global::<Self>()?;
1037 this.descriptors_by_kind.get(item_kind).copied()
1038 }
1039}
1040
1041pub fn register_serializable_item<I: SerializableItem>(cx: &mut App) {
1042 let serialized_item_kind = I::serialized_item_kind();
1043
1044 let registry = cx.default_global::<SerializableItemRegistry>();
1045 let descriptor = SerializableItemDescriptor {
1046 deserialize: |project, workspace, workspace_id, item_id, window, cx| {
1047 let task = I::deserialize(project, workspace, workspace_id, item_id, window, cx);
1048 cx.foreground_executor()
1049 .spawn(async { Ok(Box::new(task.await?) as Box<_>) })
1050 },
1051 cleanup: |workspace_id, loaded_items, window, cx| {
1052 I::cleanup(workspace_id, loaded_items, window, cx)
1053 },
1054 view_to_serializable_item: |view| Box::new(view.downcast::<I>().unwrap()),
1055 };
1056 registry
1057 .descriptors_by_kind
1058 .insert(Arc::from(serialized_item_kind), descriptor);
1059 registry
1060 .descriptors_by_type
1061 .insert(TypeId::of::<I>(), descriptor);
1062}
1063
1064pub struct AppState {
1065 pub languages: Arc<LanguageRegistry>,
1066 pub client: Arc<Client>,
1067 pub user_store: Entity<UserStore>,
1068 pub workspace_store: Entity<WorkspaceStore>,
1069 pub fs: Arc<dyn fs::Fs>,
1070 pub build_window_options: fn(Option<Uuid>, &mut App) -> WindowOptions,
1071 pub node_runtime: NodeRuntime,
1072 pub session: Entity<AppSession>,
1073}
1074
1075struct GlobalAppState(Weak<AppState>);
1076
1077impl Global for GlobalAppState {}
1078
1079pub struct WorkspaceStore {
1080 workspaces: HashSet<(gpui::AnyWindowHandle, WeakEntity<Workspace>)>,
1081 client: Arc<Client>,
1082 _subscriptions: Vec<client::Subscription>,
1083}
1084
1085#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]
1086pub enum CollaboratorId {
1087 PeerId(PeerId),
1088 Agent,
1089}
1090
1091impl From<PeerId> for CollaboratorId {
1092 fn from(peer_id: PeerId) -> Self {
1093 CollaboratorId::PeerId(peer_id)
1094 }
1095}
1096
1097impl From<&PeerId> for CollaboratorId {
1098 fn from(peer_id: &PeerId) -> Self {
1099 CollaboratorId::PeerId(*peer_id)
1100 }
1101}
1102
1103#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
1104struct Follower {
1105 project_id: Option<u64>,
1106 peer_id: PeerId,
1107}
1108
1109impl AppState {
1110 #[track_caller]
1111 pub fn global(cx: &App) -> Weak<Self> {
1112 cx.global::<GlobalAppState>().0.clone()
1113 }
1114 pub fn try_global(cx: &App) -> Option<Weak<Self>> {
1115 cx.try_global::<GlobalAppState>()
1116 .map(|state| state.0.clone())
1117 }
1118 pub fn set_global(state: Weak<AppState>, cx: &mut App) {
1119 cx.set_global(GlobalAppState(state));
1120 }
1121
1122 #[cfg(any(test, feature = "test-support"))]
1123 pub fn test(cx: &mut App) -> Arc<Self> {
1124 use fs::Fs;
1125 use node_runtime::NodeRuntime;
1126 use session::Session;
1127 use settings::SettingsStore;
1128
1129 if !cx.has_global::<SettingsStore>() {
1130 let settings_store = SettingsStore::test(cx);
1131 cx.set_global(settings_store);
1132 }
1133
1134 let fs = fs::FakeFs::new(cx.background_executor().clone());
1135 <dyn Fs>::set_global(fs.clone(), cx);
1136 let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
1137 let clock = Arc::new(clock::FakeSystemClock::new());
1138 let http_client = http_client::FakeHttpClient::with_404_response();
1139 let client = Client::new(clock, http_client, cx);
1140 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
1141 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1142 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
1143
1144 theme::init(theme::LoadThemes::JustBase, cx);
1145 client::init(&client, cx);
1146
1147 Arc::new(Self {
1148 client,
1149 fs,
1150 languages,
1151 user_store,
1152 workspace_store,
1153 node_runtime: NodeRuntime::unavailable(),
1154 build_window_options: |_, _| Default::default(),
1155 session,
1156 })
1157 }
1158}
1159
1160struct DelayedDebouncedEditAction {
1161 task: Option<Task<()>>,
1162 cancel_channel: Option<oneshot::Sender<()>>,
1163}
1164
1165impl DelayedDebouncedEditAction {
1166 fn new() -> DelayedDebouncedEditAction {
1167 DelayedDebouncedEditAction {
1168 task: None,
1169 cancel_channel: None,
1170 }
1171 }
1172
1173 fn fire_new<F>(
1174 &mut self,
1175 delay: Duration,
1176 window: &mut Window,
1177 cx: &mut Context<Workspace>,
1178 func: F,
1179 ) where
1180 F: 'static
1181 + Send
1182 + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> Task<Result<()>>,
1183 {
1184 if let Some(channel) = self.cancel_channel.take() {
1185 _ = channel.send(());
1186 }
1187
1188 let (sender, mut receiver) = oneshot::channel::<()>();
1189 self.cancel_channel = Some(sender);
1190
1191 let previous_task = self.task.take();
1192 self.task = Some(cx.spawn_in(window, async move |workspace, cx| {
1193 let mut timer = cx.background_executor().timer(delay).fuse();
1194 if let Some(previous_task) = previous_task {
1195 previous_task.await;
1196 }
1197
1198 futures::select_biased! {
1199 _ = receiver => return,
1200 _ = timer => {}
1201 }
1202
1203 if let Some(result) = workspace
1204 .update_in(cx, |workspace, window, cx| (func)(workspace, window, cx))
1205 .log_err()
1206 {
1207 result.await.log_err();
1208 }
1209 }));
1210 }
1211}
1212
1213pub enum Event {
1214 PaneAdded(Entity<Pane>),
1215 PaneRemoved,
1216 ItemAdded {
1217 item: Box<dyn ItemHandle>,
1218 },
1219 ActiveItemChanged,
1220 ItemRemoved {
1221 item_id: EntityId,
1222 },
1223 UserSavedItem {
1224 pane: WeakEntity<Pane>,
1225 item: Box<dyn WeakItemHandle>,
1226 save_intent: SaveIntent,
1227 },
1228 ContactRequestedJoin(u64),
1229 WorkspaceCreated(WeakEntity<Workspace>),
1230 OpenBundledFile {
1231 text: Cow<'static, str>,
1232 title: &'static str,
1233 language: &'static str,
1234 },
1235 ZoomChanged,
1236 ModalOpened,
1237 Activate,
1238 PanelAdded(AnyView),
1239}
1240
1241#[derive(Debug, Clone)]
1242pub enum OpenVisible {
1243 All,
1244 None,
1245 OnlyFiles,
1246 OnlyDirectories,
1247}
1248
1249enum WorkspaceLocation {
1250 // Valid local paths or SSH project to serialize
1251 Location(SerializedWorkspaceLocation, PathList),
1252 // No valid location found hence clear session id
1253 DetachFromSession,
1254 // No valid location found to serialize
1255 None,
1256}
1257
1258type PromptForNewPath = Box<
1259 dyn Fn(
1260 &mut Workspace,
1261 DirectoryLister,
1262 Option<String>,
1263 &mut Window,
1264 &mut Context<Workspace>,
1265 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1266>;
1267
1268type PromptForOpenPath = Box<
1269 dyn Fn(
1270 &mut Workspace,
1271 DirectoryLister,
1272 &mut Window,
1273 &mut Context<Workspace>,
1274 ) -> oneshot::Receiver<Option<Vec<PathBuf>>>,
1275>;
1276
1277#[derive(Default)]
1278struct DispatchingKeystrokes {
1279 dispatched: HashSet<Vec<Keystroke>>,
1280 queue: VecDeque<Keystroke>,
1281 task: Option<Shared<Task<()>>>,
1282}
1283
1284/// Collects everything project-related for a certain window opened.
1285/// In some way, is a counterpart of a window, as the [`WindowHandle`] could be downcast into `Workspace`.
1286///
1287/// A `Workspace` usually consists of 1 or more projects, a central pane group, 3 docks and a status bar.
1288/// The `Workspace` owns everybody's state and serves as a default, "global context",
1289/// that can be used to register a global action to be triggered from any place in the window.
1290pub struct Workspace {
1291 weak_self: WeakEntity<Self>,
1292 workspace_actions: Vec<Box<dyn Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div>>,
1293 zoomed: Option<AnyWeakView>,
1294 previous_dock_drag_coordinates: Option<Point<Pixels>>,
1295 zoomed_position: Option<DockPosition>,
1296 center: PaneGroup,
1297 left_dock: Entity<Dock>,
1298 bottom_dock: Entity<Dock>,
1299 right_dock: Entity<Dock>,
1300 panes: Vec<Entity<Pane>>,
1301 active_worktree_override: Option<WorktreeId>,
1302 panes_by_item: HashMap<EntityId, WeakEntity<Pane>>,
1303 active_pane: Entity<Pane>,
1304 last_active_center_pane: Option<WeakEntity<Pane>>,
1305 last_active_view_id: Option<proto::ViewId>,
1306 status_bar: Entity<StatusBar>,
1307 pub(crate) modal_layer: Entity<ModalLayer>,
1308 toast_layer: Entity<ToastLayer>,
1309 titlebar_item: Option<AnyView>,
1310 notifications: Notifications,
1311 suppressed_notifications: HashSet<NotificationId>,
1312 project: Entity<Project>,
1313 follower_states: HashMap<CollaboratorId, FollowerState>,
1314 last_leaders_by_pane: HashMap<WeakEntity<Pane>, CollaboratorId>,
1315 window_edited: bool,
1316 last_window_title: Option<String>,
1317 dirty_items: HashMap<EntityId, Subscription>,
1318 active_call: Option<(GlobalAnyActiveCall, Vec<Subscription>)>,
1319 leader_updates_tx: mpsc::UnboundedSender<(PeerId, proto::UpdateFollowers)>,
1320 database_id: Option<WorkspaceId>,
1321 app_state: Arc<AppState>,
1322 dispatching_keystrokes: Rc<RefCell<DispatchingKeystrokes>>,
1323 _subscriptions: Vec<Subscription>,
1324 _apply_leader_updates: Task<Result<()>>,
1325 _observe_current_user: Task<Result<()>>,
1326 _schedule_serialize_workspace: Option<Task<()>>,
1327 _serialize_workspace_task: Option<Task<()>>,
1328 _schedule_serialize_ssh_paths: Option<Task<()>>,
1329 pane_history_timestamp: Arc<AtomicUsize>,
1330 bounds: Bounds<Pixels>,
1331 pub centered_layout: bool,
1332 bounds_save_task_queued: Option<Task<()>>,
1333 on_prompt_for_new_path: Option<PromptForNewPath>,
1334 on_prompt_for_open_path: Option<PromptForOpenPath>,
1335 terminal_provider: Option<Box<dyn TerminalProvider>>,
1336 debugger_provider: Option<Arc<dyn DebuggerProvider>>,
1337 serializable_items_tx: UnboundedSender<Box<dyn SerializableItemHandle>>,
1338 _items_serializer: Task<Result<()>>,
1339 session_id: Option<String>,
1340 scheduled_tasks: Vec<Task<()>>,
1341 last_open_dock_positions: Vec<DockPosition>,
1342 removing: bool,
1343 _panels_task: Option<Task<Result<()>>>,
1344 sidebar_focus_handle: Option<FocusHandle>,
1345}
1346
1347impl EventEmitter<Event> for Workspace {}
1348
1349#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1350pub struct ViewId {
1351 pub creator: CollaboratorId,
1352 pub id: u64,
1353}
1354
1355pub struct FollowerState {
1356 center_pane: Entity<Pane>,
1357 dock_pane: Option<Entity<Pane>>,
1358 active_view_id: Option<ViewId>,
1359 items_by_leader_view_id: HashMap<ViewId, FollowerView>,
1360}
1361
1362struct FollowerView {
1363 view: Box<dyn FollowableItemHandle>,
1364 location: Option<proto::PanelId>,
1365}
1366
1367impl Workspace {
1368 pub fn new(
1369 workspace_id: Option<WorkspaceId>,
1370 project: Entity<Project>,
1371 app_state: Arc<AppState>,
1372 window: &mut Window,
1373 cx: &mut Context<Self>,
1374 ) -> Self {
1375 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1376 cx.subscribe(&trusted_worktrees, |_, worktrees_store, e, cx| {
1377 if let TrustedWorktreesEvent::Trusted(..) = e {
1378 // Do not persist auto trusted worktrees
1379 if !ProjectSettings::get_global(cx).session.trust_all_worktrees {
1380 worktrees_store.update(cx, |worktrees_store, cx| {
1381 worktrees_store.schedule_serialization(
1382 cx,
1383 |new_trusted_worktrees, cx| {
1384 let timeout =
1385 cx.background_executor().timer(SERIALIZATION_THROTTLE_TIME);
1386 let db = WorkspaceDb::global(cx);
1387 cx.background_spawn(async move {
1388 timeout.await;
1389 db.save_trusted_worktrees(new_trusted_worktrees)
1390 .await
1391 .log_err();
1392 })
1393 },
1394 )
1395 });
1396 }
1397 }
1398 })
1399 .detach();
1400
1401 cx.observe_global::<SettingsStore>(|_, cx| {
1402 if ProjectSettings::get_global(cx).session.trust_all_worktrees {
1403 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
1404 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
1405 trusted_worktrees.auto_trust_all(cx);
1406 })
1407 }
1408 }
1409 })
1410 .detach();
1411 }
1412
1413 cx.subscribe_in(&project, window, move |this, _, event, window, cx| {
1414 match event {
1415 project::Event::RemoteIdChanged(_) => {
1416 this.update_window_title(window, cx);
1417 }
1418
1419 project::Event::CollaboratorLeft(peer_id) => {
1420 this.collaborator_left(*peer_id, window, cx);
1421 }
1422
1423 &project::Event::WorktreeRemoved(_) => {
1424 this.update_window_title(window, cx);
1425 this.serialize_workspace(window, cx);
1426 this.update_history(cx);
1427 }
1428
1429 &project::Event::WorktreeAdded(id) => {
1430 this.update_window_title(window, cx);
1431 if this
1432 .project()
1433 .read(cx)
1434 .worktree_for_id(id, cx)
1435 .is_some_and(|wt| wt.read(cx).is_visible())
1436 {
1437 this.serialize_workspace(window, cx);
1438 this.update_history(cx);
1439 }
1440 }
1441 project::Event::WorktreeUpdatedEntries(..) => {
1442 this.update_window_title(window, cx);
1443 this.serialize_workspace(window, cx);
1444 }
1445
1446 project::Event::DisconnectedFromHost => {
1447 this.update_window_edited(window, cx);
1448 let leaders_to_unfollow =
1449 this.follower_states.keys().copied().collect::<Vec<_>>();
1450 for leader_id in leaders_to_unfollow {
1451 this.unfollow(leader_id, window, cx);
1452 }
1453 }
1454
1455 project::Event::DisconnectedFromRemote {
1456 server_not_running: _,
1457 } => {
1458 this.update_window_edited(window, cx);
1459 }
1460
1461 project::Event::Closed => {
1462 window.remove_window();
1463 }
1464
1465 project::Event::DeletedEntry(_, entry_id) => {
1466 for pane in this.panes.iter() {
1467 pane.update(cx, |pane, cx| {
1468 pane.handle_deleted_project_item(*entry_id, window, cx)
1469 });
1470 }
1471 }
1472
1473 project::Event::Toast {
1474 notification_id,
1475 message,
1476 link,
1477 } => this.show_notification(
1478 NotificationId::named(notification_id.clone()),
1479 cx,
1480 |cx| {
1481 let mut notification = MessageNotification::new(message.clone(), cx);
1482 if let Some(link) = link {
1483 notification = notification
1484 .more_info_message(link.label)
1485 .more_info_url(link.url);
1486 }
1487
1488 cx.new(|_| notification)
1489 },
1490 ),
1491
1492 project::Event::HideToast { notification_id } => {
1493 this.dismiss_notification(&NotificationId::named(notification_id.clone()), cx)
1494 }
1495
1496 project::Event::LanguageServerPrompt(request) => {
1497 struct LanguageServerPrompt;
1498
1499 this.show_notification(
1500 NotificationId::composite::<LanguageServerPrompt>(request.id),
1501 cx,
1502 |cx| {
1503 cx.new(|cx| {
1504 notifications::LanguageServerPrompt::new(request.clone(), cx)
1505 })
1506 },
1507 );
1508 }
1509
1510 project::Event::AgentLocationChanged => {
1511 this.handle_agent_location_changed(window, cx)
1512 }
1513
1514 _ => {}
1515 }
1516 cx.notify()
1517 })
1518 .detach();
1519
1520 cx.subscribe_in(
1521 &project.read(cx).breakpoint_store(),
1522 window,
1523 |workspace, _, event, window, cx| match event {
1524 BreakpointStoreEvent::BreakpointsUpdated(_, _)
1525 | BreakpointStoreEvent::BreakpointsCleared(_) => {
1526 workspace.serialize_workspace(window, cx);
1527 }
1528 BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
1529 },
1530 )
1531 .detach();
1532 if let Some(toolchain_store) = project.read(cx).toolchain_store() {
1533 cx.subscribe_in(
1534 &toolchain_store,
1535 window,
1536 |workspace, _, event, window, cx| match event {
1537 ToolchainStoreEvent::CustomToolchainsModified => {
1538 workspace.serialize_workspace(window, cx);
1539 }
1540 _ => {}
1541 },
1542 )
1543 .detach();
1544 }
1545
1546 cx.on_focus_lost(window, |this, window, cx| {
1547 let focus_handle = this.focus_handle(cx);
1548 window.focus(&focus_handle, cx);
1549 })
1550 .detach();
1551
1552 let weak_handle = cx.entity().downgrade();
1553 let pane_history_timestamp = Arc::new(AtomicUsize::new(0));
1554
1555 let center_pane = cx.new(|cx| {
1556 let mut center_pane = Pane::new(
1557 weak_handle.clone(),
1558 project.clone(),
1559 pane_history_timestamp.clone(),
1560 None,
1561 NewFile.boxed_clone(),
1562 true,
1563 window,
1564 cx,
1565 );
1566 center_pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
1567 center_pane.set_should_display_welcome_page(true);
1568 center_pane
1569 });
1570 cx.subscribe_in(¢er_pane, window, Self::handle_pane_event)
1571 .detach();
1572
1573 window.focus(¢er_pane.focus_handle(cx), cx);
1574
1575 cx.emit(Event::PaneAdded(center_pane.clone()));
1576
1577 let any_window_handle = window.window_handle();
1578 app_state.workspace_store.update(cx, |store, _| {
1579 store
1580 .workspaces
1581 .insert((any_window_handle, weak_handle.clone()));
1582 });
1583
1584 let mut current_user = app_state.user_store.read(cx).watch_current_user();
1585 let mut connection_status = app_state.client.status();
1586 let _observe_current_user = cx.spawn_in(window, async move |this, cx| {
1587 current_user.next().await;
1588 connection_status.next().await;
1589 let mut stream =
1590 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
1591
1592 while stream.recv().await.is_some() {
1593 this.update(cx, |_, cx| cx.notify())?;
1594 }
1595 anyhow::Ok(())
1596 });
1597
1598 // All leader updates are enqueued and then processed in a single task, so
1599 // that each asynchronous operation can be run in order.
1600 let (leader_updates_tx, mut leader_updates_rx) =
1601 mpsc::unbounded::<(PeerId, proto::UpdateFollowers)>();
1602 let _apply_leader_updates = cx.spawn_in(window, async move |this, cx| {
1603 while let Some((leader_id, update)) = leader_updates_rx.next().await {
1604 Self::process_leader_update(&this, leader_id, update, cx)
1605 .await
1606 .log_err();
1607 }
1608
1609 Ok(())
1610 });
1611
1612 cx.emit(Event::WorkspaceCreated(weak_handle.clone()));
1613 let modal_layer = cx.new(|_| ModalLayer::new());
1614 let toast_layer = cx.new(|_| ToastLayer::new());
1615 cx.subscribe(
1616 &modal_layer,
1617 |_, _, _: &modal_layer::ModalOpenedEvent, cx| {
1618 cx.emit(Event::ModalOpened);
1619 },
1620 )
1621 .detach();
1622
1623 let left_dock = Dock::new(DockPosition::Left, modal_layer.clone(), window, cx);
1624 let bottom_dock = Dock::new(DockPosition::Bottom, modal_layer.clone(), window, cx);
1625 let right_dock = Dock::new(DockPosition::Right, modal_layer.clone(), window, cx);
1626 let left_dock_buttons = cx.new(|cx| PanelButtons::new(left_dock.clone(), cx));
1627 let bottom_dock_buttons = cx.new(|cx| PanelButtons::new(bottom_dock.clone(), cx));
1628 let right_dock_buttons = cx.new(|cx| PanelButtons::new(right_dock.clone(), cx));
1629 let status_bar = cx.new(|cx| {
1630 let mut status_bar = StatusBar::new(¢er_pane.clone(), window, cx);
1631 status_bar.add_left_item(left_dock_buttons, window, cx);
1632 status_bar.add_right_item(right_dock_buttons, window, cx);
1633 status_bar.add_right_item(bottom_dock_buttons, window, cx);
1634 status_bar
1635 });
1636
1637 let session_id = app_state.session.read(cx).id().to_owned();
1638
1639 let mut active_call = None;
1640 if let Some(call) = GlobalAnyActiveCall::try_global(cx).cloned() {
1641 let subscriptions =
1642 vec![
1643 call.0
1644 .subscribe(window, cx, Box::new(Self::on_active_call_event)),
1645 ];
1646 active_call = Some((call, subscriptions));
1647 }
1648
1649 let (serializable_items_tx, serializable_items_rx) =
1650 mpsc::unbounded::<Box<dyn SerializableItemHandle>>();
1651 let _items_serializer = cx.spawn_in(window, async move |this, cx| {
1652 Self::serialize_items(&this, serializable_items_rx, cx).await
1653 });
1654
1655 let subscriptions = vec![
1656 cx.observe_window_activation(window, Self::on_window_activation_changed),
1657 cx.observe_window_bounds(window, move |this, window, cx| {
1658 if this.bounds_save_task_queued.is_some() {
1659 return;
1660 }
1661 this.bounds_save_task_queued = Some(cx.spawn_in(window, async move |this, cx| {
1662 cx.background_executor()
1663 .timer(Duration::from_millis(100))
1664 .await;
1665 this.update_in(cx, |this, window, cx| {
1666 this.save_window_bounds(window, cx).detach();
1667 this.bounds_save_task_queued.take();
1668 })
1669 .ok();
1670 }));
1671 cx.notify();
1672 }),
1673 cx.observe_window_appearance(window, |_, window, cx| {
1674 let window_appearance = window.appearance();
1675
1676 *SystemAppearance::global_mut(cx) = SystemAppearance(window_appearance.into());
1677
1678 GlobalTheme::reload_theme(cx);
1679 GlobalTheme::reload_icon_theme(cx);
1680 }),
1681 cx.on_release({
1682 let weak_handle = weak_handle.clone();
1683 move |this, cx| {
1684 this.app_state.workspace_store.update(cx, move |store, _| {
1685 store.workspaces.retain(|(_, weak)| weak != &weak_handle);
1686 })
1687 }
1688 }),
1689 ];
1690
1691 cx.defer_in(window, move |this, window, cx| {
1692 this.update_window_title(window, cx);
1693 this.show_initial_notifications(cx);
1694 });
1695
1696 let mut center = PaneGroup::new(center_pane.clone());
1697 center.set_is_center(true);
1698 center.mark_positions(cx);
1699
1700 Workspace {
1701 weak_self: weak_handle.clone(),
1702 zoomed: None,
1703 zoomed_position: None,
1704 previous_dock_drag_coordinates: None,
1705 center,
1706 panes: vec![center_pane.clone()],
1707 panes_by_item: Default::default(),
1708 active_pane: center_pane.clone(),
1709 last_active_center_pane: Some(center_pane.downgrade()),
1710 last_active_view_id: None,
1711 status_bar,
1712 modal_layer,
1713 toast_layer,
1714 titlebar_item: None,
1715 active_worktree_override: None,
1716 notifications: Notifications::default(),
1717 suppressed_notifications: HashSet::default(),
1718 left_dock,
1719 bottom_dock,
1720 right_dock,
1721 _panels_task: None,
1722 project: project.clone(),
1723 follower_states: Default::default(),
1724 last_leaders_by_pane: Default::default(),
1725 dispatching_keystrokes: Default::default(),
1726 window_edited: false,
1727 last_window_title: None,
1728 dirty_items: Default::default(),
1729 active_call,
1730 database_id: workspace_id,
1731 app_state,
1732 _observe_current_user,
1733 _apply_leader_updates,
1734 _schedule_serialize_workspace: None,
1735 _serialize_workspace_task: None,
1736 _schedule_serialize_ssh_paths: None,
1737 leader_updates_tx,
1738 _subscriptions: subscriptions,
1739 pane_history_timestamp,
1740 workspace_actions: Default::default(),
1741 // This data will be incorrect, but it will be overwritten by the time it needs to be used.
1742 bounds: Default::default(),
1743 centered_layout: false,
1744 bounds_save_task_queued: None,
1745 on_prompt_for_new_path: None,
1746 on_prompt_for_open_path: None,
1747 terminal_provider: None,
1748 debugger_provider: None,
1749 serializable_items_tx,
1750 _items_serializer,
1751 session_id: Some(session_id),
1752
1753 scheduled_tasks: Vec::new(),
1754 last_open_dock_positions: Vec::new(),
1755 removing: false,
1756 sidebar_focus_handle: None,
1757 }
1758 }
1759
1760 pub fn new_local(
1761 abs_paths: Vec<PathBuf>,
1762 app_state: Arc<AppState>,
1763 requesting_window: Option<WindowHandle<MultiWorkspace>>,
1764 env: Option<HashMap<String, String>>,
1765 init: Option<Box<dyn FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send>>,
1766 activate: bool,
1767 cx: &mut App,
1768 ) -> Task<anyhow::Result<OpenResult>> {
1769 let project_handle = Project::local(
1770 app_state.client.clone(),
1771 app_state.node_runtime.clone(),
1772 app_state.user_store.clone(),
1773 app_state.languages.clone(),
1774 app_state.fs.clone(),
1775 env,
1776 Default::default(),
1777 cx,
1778 );
1779
1780 let db = WorkspaceDb::global(cx);
1781 let kvp = db::kvp::KeyValueStore::global(cx);
1782 cx.spawn(async move |cx| {
1783 let mut paths_to_open = Vec::with_capacity(abs_paths.len());
1784 for path in abs_paths.into_iter() {
1785 if let Some(canonical) = app_state.fs.canonicalize(&path).await.ok() {
1786 paths_to_open.push(canonical)
1787 } else {
1788 paths_to_open.push(path)
1789 }
1790 }
1791
1792 let serialized_workspace = db.workspace_for_roots(paths_to_open.as_slice());
1793
1794 if let Some(paths) = serialized_workspace.as_ref().map(|ws| &ws.paths) {
1795 paths_to_open = paths.ordered_paths().cloned().collect();
1796 if !paths.is_lexicographically_ordered() {
1797 project_handle.update(cx, |project, cx| {
1798 project.set_worktrees_reordered(true, cx);
1799 });
1800 }
1801 }
1802
1803 // Get project paths for all of the abs_paths
1804 let mut project_paths: Vec<(PathBuf, Option<ProjectPath>)> =
1805 Vec::with_capacity(paths_to_open.len());
1806
1807 for path in paths_to_open.into_iter() {
1808 if let Some((_, project_entry)) = cx
1809 .update(|cx| {
1810 Workspace::project_path_for_path(project_handle.clone(), &path, true, cx)
1811 })
1812 .await
1813 .log_err()
1814 {
1815 project_paths.push((path, Some(project_entry)));
1816 } else {
1817 project_paths.push((path, None));
1818 }
1819 }
1820
1821 let workspace_id = if let Some(serialized_workspace) = serialized_workspace.as_ref() {
1822 serialized_workspace.id
1823 } else {
1824 db.next_id().await.unwrap_or_else(|_| Default::default())
1825 };
1826
1827 let toolchains = db.toolchains(workspace_id).await?;
1828
1829 for (toolchain, worktree_path, path) in toolchains {
1830 let toolchain_path = PathBuf::from(toolchain.path.clone().to_string());
1831 let Some(worktree_id) = project_handle.read_with(cx, |this, cx| {
1832 this.find_worktree(&worktree_path, cx)
1833 .and_then(|(worktree, rel_path)| {
1834 if rel_path.is_empty() {
1835 Some(worktree.read(cx).id())
1836 } else {
1837 None
1838 }
1839 })
1840 }) else {
1841 // We did not find a worktree with a given path, but that's whatever.
1842 continue;
1843 };
1844 if !app_state.fs.is_file(toolchain_path.as_path()).await {
1845 continue;
1846 }
1847
1848 project_handle
1849 .update(cx, |this, cx| {
1850 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
1851 })
1852 .await;
1853 }
1854 if let Some(workspace) = serialized_workspace.as_ref() {
1855 project_handle.update(cx, |this, cx| {
1856 for (scope, toolchains) in &workspace.user_toolchains {
1857 for toolchain in toolchains {
1858 this.add_toolchain(toolchain.clone(), scope.clone(), cx);
1859 }
1860 }
1861 });
1862 }
1863
1864 let (window, workspace): (WindowHandle<MultiWorkspace>, Entity<Workspace>) =
1865 if let Some(window) = requesting_window {
1866 let centered_layout = serialized_workspace
1867 .as_ref()
1868 .map(|w| w.centered_layout)
1869 .unwrap_or(false);
1870
1871 let workspace = window.update(cx, |multi_workspace, window, cx| {
1872 let workspace = cx.new(|cx| {
1873 let mut workspace = Workspace::new(
1874 Some(workspace_id),
1875 project_handle.clone(),
1876 app_state.clone(),
1877 window,
1878 cx,
1879 );
1880
1881 workspace.centered_layout = centered_layout;
1882
1883 // Call init callback to add items before window renders
1884 if let Some(init) = init {
1885 init(&mut workspace, window, cx);
1886 }
1887
1888 workspace
1889 });
1890 if activate {
1891 multi_workspace.activate(workspace.clone(), cx);
1892 } else {
1893 multi_workspace.add_workspace(workspace.clone(), cx);
1894 }
1895 workspace
1896 })?;
1897 (window, workspace)
1898 } else {
1899 let window_bounds_override = window_bounds_env_override();
1900
1901 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
1902 (Some(WindowBounds::Windowed(bounds)), None)
1903 } else if let Some(workspace) = serialized_workspace.as_ref()
1904 && let Some(display) = workspace.display
1905 && let Some(bounds) = workspace.window_bounds.as_ref()
1906 {
1907 // Reopening an existing workspace - restore its saved bounds
1908 (Some(bounds.0), Some(display))
1909 } else if let Some((display, bounds)) =
1910 persistence::read_default_window_bounds(&kvp)
1911 {
1912 // New or empty workspace - use the last known window bounds
1913 (Some(bounds), Some(display))
1914 } else {
1915 // New window - let GPUI's default_bounds() handle cascading
1916 (None, None)
1917 };
1918
1919 // Use the serialized workspace to construct the new window
1920 let mut options = cx.update(|cx| (app_state.build_window_options)(display, cx));
1921 options.window_bounds = window_bounds;
1922 let centered_layout = serialized_workspace
1923 .as_ref()
1924 .map(|w| w.centered_layout)
1925 .unwrap_or(false);
1926 let window = cx.open_window(options, {
1927 let app_state = app_state.clone();
1928 let project_handle = project_handle.clone();
1929 move |window, cx| {
1930 let workspace = cx.new(|cx| {
1931 let mut workspace = Workspace::new(
1932 Some(workspace_id),
1933 project_handle,
1934 app_state,
1935 window,
1936 cx,
1937 );
1938 workspace.centered_layout = centered_layout;
1939
1940 // Call init callback to add items before window renders
1941 if let Some(init) = init {
1942 init(&mut workspace, window, cx);
1943 }
1944
1945 workspace
1946 });
1947 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
1948 }
1949 })?;
1950 let workspace =
1951 window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
1952 multi_workspace.workspace().clone()
1953 })?;
1954 (window, workspace)
1955 };
1956
1957 notify_if_database_failed(window, cx);
1958 // Check if this is an empty workspace (no paths to open)
1959 // An empty workspace is one where project_paths is empty
1960 let is_empty_workspace = project_paths.is_empty();
1961 // Check if serialized workspace has paths before it's moved
1962 let serialized_workspace_has_paths = serialized_workspace
1963 .as_ref()
1964 .map(|ws| !ws.paths.is_empty())
1965 .unwrap_or(false);
1966
1967 let opened_items = window
1968 .update(cx, |_, window, cx| {
1969 workspace.update(cx, |_workspace: &mut Workspace, cx| {
1970 open_items(serialized_workspace, project_paths, window, cx)
1971 })
1972 })?
1973 .await
1974 .unwrap_or_default();
1975
1976 // Restore default dock state for empty workspaces
1977 // Only restore if:
1978 // 1. This is an empty workspace (no paths), AND
1979 // 2. The serialized workspace either doesn't exist or has no paths
1980 if is_empty_workspace && !serialized_workspace_has_paths {
1981 if let Some(default_docks) = persistence::read_default_dock_state(&kvp) {
1982 window
1983 .update(cx, |_, window, cx| {
1984 workspace.update(cx, |workspace, cx| {
1985 for (dock, serialized_dock) in [
1986 (&workspace.right_dock, &default_docks.right),
1987 (&workspace.left_dock, &default_docks.left),
1988 (&workspace.bottom_dock, &default_docks.bottom),
1989 ] {
1990 dock.update(cx, |dock, cx| {
1991 dock.serialized_dock = Some(serialized_dock.clone());
1992 dock.restore_state(window, cx);
1993 });
1994 }
1995 cx.notify();
1996 });
1997 })
1998 .log_err();
1999 }
2000 }
2001
2002 window
2003 .update(cx, |_, _window, cx| {
2004 workspace.update(cx, |this: &mut Workspace, cx| {
2005 this.update_history(cx);
2006 });
2007 })
2008 .log_err();
2009 Ok(OpenResult {
2010 window,
2011 workspace,
2012 opened_items,
2013 })
2014 })
2015 }
2016
2017 pub fn weak_handle(&self) -> WeakEntity<Self> {
2018 self.weak_self.clone()
2019 }
2020
2021 pub fn left_dock(&self) -> &Entity<Dock> {
2022 &self.left_dock
2023 }
2024
2025 pub fn bottom_dock(&self) -> &Entity<Dock> {
2026 &self.bottom_dock
2027 }
2028
2029 pub fn set_bottom_dock_layout(
2030 &mut self,
2031 layout: BottomDockLayout,
2032 window: &mut Window,
2033 cx: &mut Context<Self>,
2034 ) {
2035 let fs = self.project().read(cx).fs();
2036 settings::update_settings_file(fs.clone(), cx, move |content, _cx| {
2037 content.workspace.bottom_dock_layout = Some(layout);
2038 });
2039
2040 cx.notify();
2041 self.serialize_workspace(window, cx);
2042 }
2043
2044 pub fn right_dock(&self) -> &Entity<Dock> {
2045 &self.right_dock
2046 }
2047
2048 pub fn all_docks(&self) -> [&Entity<Dock>; 3] {
2049 [&self.left_dock, &self.bottom_dock, &self.right_dock]
2050 }
2051
2052 pub fn capture_dock_state(&self, _window: &Window, cx: &App) -> DockStructure {
2053 let left_dock = self.left_dock.read(cx);
2054 let left_visible = left_dock.is_open();
2055 let left_active_panel = left_dock
2056 .active_panel()
2057 .map(|panel| panel.persistent_name().to_string());
2058 // `zoomed_position` is kept in sync with individual panel zoom state
2059 // by the dock code in `Dock::new` and `Dock::add_panel`.
2060 let left_dock_zoom = self.zoomed_position == Some(DockPosition::Left);
2061
2062 let right_dock = self.right_dock.read(cx);
2063 let right_visible = right_dock.is_open();
2064 let right_active_panel = right_dock
2065 .active_panel()
2066 .map(|panel| panel.persistent_name().to_string());
2067 let right_dock_zoom = self.zoomed_position == Some(DockPosition::Right);
2068
2069 let bottom_dock = self.bottom_dock.read(cx);
2070 let bottom_visible = bottom_dock.is_open();
2071 let bottom_active_panel = bottom_dock
2072 .active_panel()
2073 .map(|panel| panel.persistent_name().to_string());
2074 let bottom_dock_zoom = self.zoomed_position == Some(DockPosition::Bottom);
2075
2076 DockStructure {
2077 left: DockData {
2078 visible: left_visible,
2079 active_panel: left_active_panel,
2080 zoom: left_dock_zoom,
2081 },
2082 right: DockData {
2083 visible: right_visible,
2084 active_panel: right_active_panel,
2085 zoom: right_dock_zoom,
2086 },
2087 bottom: DockData {
2088 visible: bottom_visible,
2089 active_panel: bottom_active_panel,
2090 zoom: bottom_dock_zoom,
2091 },
2092 }
2093 }
2094
2095 pub fn set_dock_structure(
2096 &self,
2097 docks: DockStructure,
2098 window: &mut Window,
2099 cx: &mut Context<Self>,
2100 ) {
2101 for (dock, data) in [
2102 (&self.left_dock, docks.left),
2103 (&self.bottom_dock, docks.bottom),
2104 (&self.right_dock, docks.right),
2105 ] {
2106 dock.update(cx, |dock, cx| {
2107 dock.serialized_dock = Some(data);
2108 dock.restore_state(window, cx);
2109 });
2110 }
2111 }
2112
2113 pub fn open_item_abs_paths(&self, cx: &App) -> Vec<PathBuf> {
2114 self.items(cx)
2115 .filter_map(|item| {
2116 let project_path = item.project_path(cx)?;
2117 self.project.read(cx).absolute_path(&project_path, cx)
2118 })
2119 .collect()
2120 }
2121
2122 pub fn dock_at_position(&self, position: DockPosition) -> &Entity<Dock> {
2123 match position {
2124 DockPosition::Left => &self.left_dock,
2125 DockPosition::Bottom => &self.bottom_dock,
2126 DockPosition::Right => &self.right_dock,
2127 }
2128 }
2129
2130 pub fn is_edited(&self) -> bool {
2131 self.window_edited
2132 }
2133
2134 pub fn add_panel<T: Panel>(
2135 &mut self,
2136 panel: Entity<T>,
2137 window: &mut Window,
2138 cx: &mut Context<Self>,
2139 ) {
2140 let focus_handle = panel.panel_focus_handle(cx);
2141 cx.on_focus_in(&focus_handle, window, Self::handle_panel_focused)
2142 .detach();
2143
2144 let dock_position = panel.position(window, cx);
2145 let dock = self.dock_at_position(dock_position);
2146 let any_panel = panel.to_any();
2147
2148 dock.update(cx, |dock, cx| {
2149 dock.add_panel(panel, self.weak_self.clone(), window, cx)
2150 });
2151
2152 cx.emit(Event::PanelAdded(any_panel));
2153 }
2154
2155 pub fn remove_panel<T: Panel>(
2156 &mut self,
2157 panel: &Entity<T>,
2158 window: &mut Window,
2159 cx: &mut Context<Self>,
2160 ) {
2161 for dock in [&self.left_dock, &self.bottom_dock, &self.right_dock] {
2162 dock.update(cx, |dock, cx| dock.remove_panel(panel, window, cx));
2163 }
2164 }
2165
2166 pub fn status_bar(&self) -> &Entity<StatusBar> {
2167 &self.status_bar
2168 }
2169
2170 pub fn set_workspace_sidebar_open(
2171 &self,
2172 open: bool,
2173 has_notifications: bool,
2174 show_toggle: bool,
2175 cx: &mut App,
2176 ) {
2177 self.status_bar.update(cx, |status_bar, cx| {
2178 status_bar.set_workspace_sidebar_open(open, cx);
2179 status_bar.set_sidebar_has_notifications(has_notifications, cx);
2180 status_bar.set_show_sidebar_toggle(show_toggle, cx);
2181 });
2182 }
2183
2184 pub fn set_sidebar_focus_handle(&mut self, handle: Option<FocusHandle>) {
2185 self.sidebar_focus_handle = handle;
2186 }
2187
2188 pub fn status_bar_visible(&self, cx: &App) -> bool {
2189 StatusBarSettings::get_global(cx).show
2190 }
2191
2192 pub fn app_state(&self) -> &Arc<AppState> {
2193 &self.app_state
2194 }
2195
2196 pub fn set_panels_task(&mut self, task: Task<Result<()>>) {
2197 self._panels_task = Some(task);
2198 }
2199
2200 pub fn take_panels_task(&mut self) -> Option<Task<Result<()>>> {
2201 self._panels_task.take()
2202 }
2203
2204 pub fn user_store(&self) -> &Entity<UserStore> {
2205 &self.app_state.user_store
2206 }
2207
2208 pub fn project(&self) -> &Entity<Project> {
2209 &self.project
2210 }
2211
2212 pub fn path_style(&self, cx: &App) -> PathStyle {
2213 self.project.read(cx).path_style(cx)
2214 }
2215
2216 pub fn recently_activated_items(&self, cx: &App) -> HashMap<EntityId, usize> {
2217 let mut history: HashMap<EntityId, usize> = HashMap::default();
2218
2219 for pane_handle in &self.panes {
2220 let pane = pane_handle.read(cx);
2221
2222 for entry in pane.activation_history() {
2223 history.insert(
2224 entry.entity_id,
2225 history
2226 .get(&entry.entity_id)
2227 .cloned()
2228 .unwrap_or(0)
2229 .max(entry.timestamp),
2230 );
2231 }
2232 }
2233
2234 history
2235 }
2236
2237 pub fn recent_active_item_by_type<T: 'static>(&self, cx: &App) -> Option<Entity<T>> {
2238 let mut recent_item: Option<Entity<T>> = None;
2239 let mut recent_timestamp = 0;
2240 for pane_handle in &self.panes {
2241 let pane = pane_handle.read(cx);
2242 let item_map: HashMap<EntityId, &Box<dyn ItemHandle>> =
2243 pane.items().map(|item| (item.item_id(), item)).collect();
2244 for entry in pane.activation_history() {
2245 if entry.timestamp > recent_timestamp
2246 && let Some(&item) = item_map.get(&entry.entity_id)
2247 && let Some(typed_item) = item.act_as::<T>(cx)
2248 {
2249 recent_timestamp = entry.timestamp;
2250 recent_item = Some(typed_item);
2251 }
2252 }
2253 }
2254 recent_item
2255 }
2256
2257 pub fn recent_navigation_history_iter(
2258 &self,
2259 cx: &App,
2260 ) -> impl Iterator<Item = (ProjectPath, Option<PathBuf>)> + use<> {
2261 let mut abs_paths_opened: HashMap<PathBuf, HashSet<ProjectPath>> = HashMap::default();
2262 let mut history: HashMap<ProjectPath, (Option<PathBuf>, usize)> = HashMap::default();
2263
2264 for pane in &self.panes {
2265 let pane = pane.read(cx);
2266
2267 pane.nav_history()
2268 .for_each_entry(cx, &mut |entry, (project_path, fs_path)| {
2269 if let Some(fs_path) = &fs_path {
2270 abs_paths_opened
2271 .entry(fs_path.clone())
2272 .or_default()
2273 .insert(project_path.clone());
2274 }
2275 let timestamp = entry.timestamp;
2276 match history.entry(project_path) {
2277 hash_map::Entry::Occupied(mut entry) => {
2278 let (_, old_timestamp) = entry.get();
2279 if ×tamp > old_timestamp {
2280 entry.insert((fs_path, timestamp));
2281 }
2282 }
2283 hash_map::Entry::Vacant(entry) => {
2284 entry.insert((fs_path, timestamp));
2285 }
2286 }
2287 });
2288
2289 if let Some(item) = pane.active_item()
2290 && let Some(project_path) = item.project_path(cx)
2291 {
2292 let fs_path = self.project.read(cx).absolute_path(&project_path, cx);
2293
2294 if let Some(fs_path) = &fs_path {
2295 abs_paths_opened
2296 .entry(fs_path.clone())
2297 .or_default()
2298 .insert(project_path.clone());
2299 }
2300
2301 history.insert(project_path, (fs_path, std::usize::MAX));
2302 }
2303 }
2304
2305 history
2306 .into_iter()
2307 .sorted_by_key(|(_, (_, order))| *order)
2308 .map(|(project_path, (fs_path, _))| (project_path, fs_path))
2309 .rev()
2310 .filter(move |(history_path, abs_path)| {
2311 let latest_project_path_opened = abs_path
2312 .as_ref()
2313 .and_then(|abs_path| abs_paths_opened.get(abs_path))
2314 .and_then(|project_paths| {
2315 project_paths
2316 .iter()
2317 .max_by(|b1, b2| b1.worktree_id.cmp(&b2.worktree_id))
2318 });
2319
2320 latest_project_path_opened.is_none_or(|path| path == history_path)
2321 })
2322 }
2323
2324 pub fn recent_navigation_history(
2325 &self,
2326 limit: Option<usize>,
2327 cx: &App,
2328 ) -> Vec<(ProjectPath, Option<PathBuf>)> {
2329 self.recent_navigation_history_iter(cx)
2330 .take(limit.unwrap_or(usize::MAX))
2331 .collect()
2332 }
2333
2334 pub fn clear_navigation_history(&mut self, _window: &mut Window, cx: &mut Context<Workspace>) {
2335 for pane in &self.panes {
2336 pane.update(cx, |pane, cx| pane.nav_history_mut().clear(cx));
2337 }
2338 }
2339
2340 fn navigate_history(
2341 &mut self,
2342 pane: WeakEntity<Pane>,
2343 mode: NavigationMode,
2344 window: &mut Window,
2345 cx: &mut Context<Workspace>,
2346 ) -> Task<Result<()>> {
2347 self.navigate_history_impl(
2348 pane,
2349 mode,
2350 window,
2351 &mut |history, cx| history.pop(mode, cx),
2352 cx,
2353 )
2354 }
2355
2356 fn navigate_tag_history(
2357 &mut self,
2358 pane: WeakEntity<Pane>,
2359 mode: TagNavigationMode,
2360 window: &mut Window,
2361 cx: &mut Context<Workspace>,
2362 ) -> Task<Result<()>> {
2363 self.navigate_history_impl(
2364 pane,
2365 NavigationMode::Normal,
2366 window,
2367 &mut |history, _cx| history.pop_tag(mode),
2368 cx,
2369 )
2370 }
2371
2372 fn navigate_history_impl(
2373 &mut self,
2374 pane: WeakEntity<Pane>,
2375 mode: NavigationMode,
2376 window: &mut Window,
2377 cb: &mut dyn FnMut(&mut NavHistory, &mut App) -> Option<NavigationEntry>,
2378 cx: &mut Context<Workspace>,
2379 ) -> Task<Result<()>> {
2380 let to_load = if let Some(pane) = pane.upgrade() {
2381 pane.update(cx, |pane, cx| {
2382 window.focus(&pane.focus_handle(cx), cx);
2383 loop {
2384 // Retrieve the weak item handle from the history.
2385 let entry = cb(pane.nav_history_mut(), cx)?;
2386
2387 // If the item is still present in this pane, then activate it.
2388 if let Some(index) = entry
2389 .item
2390 .upgrade()
2391 .and_then(|v| pane.index_for_item(v.as_ref()))
2392 {
2393 let prev_active_item_index = pane.active_item_index();
2394 pane.nav_history_mut().set_mode(mode);
2395 pane.activate_item(index, true, true, window, cx);
2396 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2397
2398 let mut navigated = prev_active_item_index != pane.active_item_index();
2399 if let Some(data) = entry.data {
2400 navigated |= pane.active_item()?.navigate(data, window, cx);
2401 }
2402
2403 if navigated {
2404 break None;
2405 }
2406 } else {
2407 // If the item is no longer present in this pane, then retrieve its
2408 // path info in order to reopen it.
2409 break pane
2410 .nav_history()
2411 .path_for_item(entry.item.id())
2412 .map(|(project_path, abs_path)| (project_path, abs_path, entry));
2413 }
2414 }
2415 })
2416 } else {
2417 None
2418 };
2419
2420 if let Some((project_path, abs_path, entry)) = to_load {
2421 // If the item was no longer present, then load it again from its previous path, first try the local path
2422 let open_by_project_path = self.load_path(project_path.clone(), window, cx);
2423
2424 cx.spawn_in(window, async move |workspace, cx| {
2425 let open_by_project_path = open_by_project_path.await;
2426 let mut navigated = false;
2427 match open_by_project_path
2428 .with_context(|| format!("Navigating to {project_path:?}"))
2429 {
2430 Ok((project_entry_id, build_item)) => {
2431 let prev_active_item_id = pane.update(cx, |pane, _| {
2432 pane.nav_history_mut().set_mode(mode);
2433 pane.active_item().map(|p| p.item_id())
2434 })?;
2435
2436 pane.update_in(cx, |pane, window, cx| {
2437 let item = pane.open_item(
2438 project_entry_id,
2439 project_path,
2440 true,
2441 entry.is_preview,
2442 true,
2443 None,
2444 window, cx,
2445 build_item,
2446 );
2447 navigated |= Some(item.item_id()) != prev_active_item_id;
2448 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2449 if let Some(data) = entry.data {
2450 navigated |= item.navigate(data, window, cx);
2451 }
2452 })?;
2453 }
2454 Err(open_by_project_path_e) => {
2455 // Fall back to opening by abs path, in case an external file was opened and closed,
2456 // and its worktree is now dropped
2457 if let Some(abs_path) = abs_path {
2458 let prev_active_item_id = pane.update(cx, |pane, _| {
2459 pane.nav_history_mut().set_mode(mode);
2460 pane.active_item().map(|p| p.item_id())
2461 })?;
2462 let open_by_abs_path = workspace.update_in(cx, |workspace, window, cx| {
2463 workspace.open_abs_path(abs_path.clone(), OpenOptions { visible: Some(OpenVisible::None), ..Default::default() }, window, cx)
2464 })?;
2465 match open_by_abs_path
2466 .await
2467 .with_context(|| format!("Navigating to {abs_path:?}"))
2468 {
2469 Ok(item) => {
2470 pane.update_in(cx, |pane, window, cx| {
2471 navigated |= Some(item.item_id()) != prev_active_item_id;
2472 pane.nav_history_mut().set_mode(NavigationMode::Normal);
2473 if let Some(data) = entry.data {
2474 navigated |= item.navigate(data, window, cx);
2475 }
2476 })?;
2477 }
2478 Err(open_by_abs_path_e) => {
2479 log::error!("Failed to navigate history: {open_by_project_path_e:#} and {open_by_abs_path_e:#}");
2480 }
2481 }
2482 }
2483 }
2484 }
2485
2486 if !navigated {
2487 workspace
2488 .update_in(cx, |workspace, window, cx| {
2489 Self::navigate_history(workspace, pane, mode, window, cx)
2490 })?
2491 .await?;
2492 }
2493
2494 Ok(())
2495 })
2496 } else {
2497 Task::ready(Ok(()))
2498 }
2499 }
2500
2501 pub fn go_back(
2502 &mut self,
2503 pane: WeakEntity<Pane>,
2504 window: &mut Window,
2505 cx: &mut Context<Workspace>,
2506 ) -> Task<Result<()>> {
2507 self.navigate_history(pane, NavigationMode::GoingBack, window, cx)
2508 }
2509
2510 pub fn go_forward(
2511 &mut self,
2512 pane: WeakEntity<Pane>,
2513 window: &mut Window,
2514 cx: &mut Context<Workspace>,
2515 ) -> Task<Result<()>> {
2516 self.navigate_history(pane, NavigationMode::GoingForward, window, cx)
2517 }
2518
2519 pub fn reopen_closed_item(
2520 &mut self,
2521 window: &mut Window,
2522 cx: &mut Context<Workspace>,
2523 ) -> Task<Result<()>> {
2524 self.navigate_history(
2525 self.active_pane().downgrade(),
2526 NavigationMode::ReopeningClosedItem,
2527 window,
2528 cx,
2529 )
2530 }
2531
2532 pub fn client(&self) -> &Arc<Client> {
2533 &self.app_state.client
2534 }
2535
2536 pub fn set_titlebar_item(&mut self, item: AnyView, _: &mut Window, cx: &mut Context<Self>) {
2537 self.titlebar_item = Some(item);
2538 cx.notify();
2539 }
2540
2541 pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) {
2542 self.on_prompt_for_new_path = Some(prompt)
2543 }
2544
2545 pub fn set_prompt_for_open_path(&mut self, prompt: PromptForOpenPath) {
2546 self.on_prompt_for_open_path = Some(prompt)
2547 }
2548
2549 pub fn set_terminal_provider(&mut self, provider: impl TerminalProvider + 'static) {
2550 self.terminal_provider = Some(Box::new(provider));
2551 }
2552
2553 pub fn set_debugger_provider(&mut self, provider: impl DebuggerProvider + 'static) {
2554 self.debugger_provider = Some(Arc::new(provider));
2555 }
2556
2557 pub fn debugger_provider(&self) -> Option<Arc<dyn DebuggerProvider>> {
2558 self.debugger_provider.clone()
2559 }
2560
2561 pub fn prompt_for_open_path(
2562 &mut self,
2563 path_prompt_options: PathPromptOptions,
2564 lister: DirectoryLister,
2565 window: &mut Window,
2566 cx: &mut Context<Self>,
2567 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2568 if !lister.is_local(cx) || !WorkspaceSettings::get_global(cx).use_system_path_prompts {
2569 let prompt = self.on_prompt_for_open_path.take().unwrap();
2570 let rx = prompt(self, lister, window, cx);
2571 self.on_prompt_for_open_path = Some(prompt);
2572 rx
2573 } else {
2574 let (tx, rx) = oneshot::channel();
2575 let abs_path = cx.prompt_for_paths(path_prompt_options);
2576
2577 cx.spawn_in(window, async move |workspace, cx| {
2578 let Ok(result) = abs_path.await else {
2579 return Ok(());
2580 };
2581
2582 match result {
2583 Ok(result) => {
2584 tx.send(result).ok();
2585 }
2586 Err(err) => {
2587 let rx = workspace.update_in(cx, |workspace, window, cx| {
2588 workspace.show_portal_error(err.to_string(), cx);
2589 let prompt = workspace.on_prompt_for_open_path.take().unwrap();
2590 let rx = prompt(workspace, lister, window, cx);
2591 workspace.on_prompt_for_open_path = Some(prompt);
2592 rx
2593 })?;
2594 if let Ok(path) = rx.await {
2595 tx.send(path).ok();
2596 }
2597 }
2598 };
2599 anyhow::Ok(())
2600 })
2601 .detach();
2602
2603 rx
2604 }
2605 }
2606
2607 pub fn prompt_for_new_path(
2608 &mut self,
2609 lister: DirectoryLister,
2610 suggested_name: Option<String>,
2611 window: &mut Window,
2612 cx: &mut Context<Self>,
2613 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
2614 if self.project.read(cx).is_via_collab()
2615 || self.project.read(cx).is_via_remote_server()
2616 || !WorkspaceSettings::get_global(cx).use_system_path_prompts
2617 {
2618 let prompt = self.on_prompt_for_new_path.take().unwrap();
2619 let rx = prompt(self, lister, suggested_name, window, cx);
2620 self.on_prompt_for_new_path = Some(prompt);
2621 return rx;
2622 }
2623
2624 let (tx, rx) = oneshot::channel();
2625 cx.spawn_in(window, async move |workspace, cx| {
2626 let abs_path = workspace.update(cx, |workspace, cx| {
2627 let relative_to = workspace
2628 .most_recent_active_path(cx)
2629 .and_then(|p| p.parent().map(|p| p.to_path_buf()))
2630 .or_else(|| {
2631 let project = workspace.project.read(cx);
2632 project.visible_worktrees(cx).find_map(|worktree| {
2633 Some(worktree.read(cx).as_local()?.abs_path().to_path_buf())
2634 })
2635 })
2636 .or_else(std::env::home_dir)
2637 .unwrap_or_else(|| PathBuf::from(""));
2638 cx.prompt_for_new_path(&relative_to, suggested_name.as_deref())
2639 })?;
2640 let abs_path = match abs_path.await? {
2641 Ok(path) => path,
2642 Err(err) => {
2643 let rx = workspace.update_in(cx, |workspace, window, cx| {
2644 workspace.show_portal_error(err.to_string(), cx);
2645
2646 let prompt = workspace.on_prompt_for_new_path.take().unwrap();
2647 let rx = prompt(workspace, lister, suggested_name, window, cx);
2648 workspace.on_prompt_for_new_path = Some(prompt);
2649 rx
2650 })?;
2651 if let Ok(path) = rx.await {
2652 tx.send(path).ok();
2653 }
2654 return anyhow::Ok(());
2655 }
2656 };
2657
2658 tx.send(abs_path.map(|path| vec![path])).ok();
2659 anyhow::Ok(())
2660 })
2661 .detach();
2662
2663 rx
2664 }
2665
2666 pub fn titlebar_item(&self) -> Option<AnyView> {
2667 self.titlebar_item.clone()
2668 }
2669
2670 /// Returns the worktree override set by the user (e.g., via the project dropdown).
2671 /// When set, git-related operations should use this worktree instead of deriving
2672 /// the active worktree from the focused file.
2673 pub fn active_worktree_override(&self) -> Option<WorktreeId> {
2674 self.active_worktree_override
2675 }
2676
2677 pub fn set_active_worktree_override(
2678 &mut self,
2679 worktree_id: Option<WorktreeId>,
2680 cx: &mut Context<Self>,
2681 ) {
2682 self.active_worktree_override = worktree_id;
2683 cx.notify();
2684 }
2685
2686 pub fn clear_active_worktree_override(&mut self, cx: &mut Context<Self>) {
2687 self.active_worktree_override = None;
2688 cx.notify();
2689 }
2690
2691 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2692 ///
2693 /// If the given workspace has a local project, then it will be passed
2694 /// to the callback. Otherwise, a new empty window will be created.
2695 pub fn with_local_workspace<T, F>(
2696 &mut self,
2697 window: &mut Window,
2698 cx: &mut Context<Self>,
2699 callback: F,
2700 ) -> Task<Result<T>>
2701 where
2702 T: 'static,
2703 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2704 {
2705 if self.project.read(cx).is_local() {
2706 Task::ready(Ok(callback(self, window, cx)))
2707 } else {
2708 let env = self.project.read(cx).cli_environment(cx);
2709 let task = Self::new_local(
2710 Vec::new(),
2711 self.app_state.clone(),
2712 None,
2713 env,
2714 None,
2715 true,
2716 cx,
2717 );
2718 cx.spawn_in(window, async move |_vh, cx| {
2719 let OpenResult {
2720 window: multi_workspace_window,
2721 ..
2722 } = task.await?;
2723 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2724 let workspace = multi_workspace.workspace().clone();
2725 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2726 })
2727 })
2728 }
2729 }
2730
2731 /// Call the given callback with a workspace whose project is local or remote via WSL (allowing host access).
2732 ///
2733 /// If the given workspace has a local project, then it will be passed
2734 /// to the callback. Otherwise, a new empty window will be created.
2735 pub fn with_local_or_wsl_workspace<T, F>(
2736 &mut self,
2737 window: &mut Window,
2738 cx: &mut Context<Self>,
2739 callback: F,
2740 ) -> Task<Result<T>>
2741 where
2742 T: 'static,
2743 F: 'static + FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) -> T,
2744 {
2745 let project = self.project.read(cx);
2746 if project.is_local() || project.is_via_wsl_with_host_interop(cx) {
2747 Task::ready(Ok(callback(self, window, cx)))
2748 } else {
2749 let env = self.project.read(cx).cli_environment(cx);
2750 let task = Self::new_local(
2751 Vec::new(),
2752 self.app_state.clone(),
2753 None,
2754 env,
2755 None,
2756 true,
2757 cx,
2758 );
2759 cx.spawn_in(window, async move |_vh, cx| {
2760 let OpenResult {
2761 window: multi_workspace_window,
2762 ..
2763 } = task.await?;
2764 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
2765 let workspace = multi_workspace.workspace().clone();
2766 workspace.update(cx, |workspace, cx| callback(workspace, window, cx))
2767 })
2768 })
2769 }
2770 }
2771
2772 pub fn worktrees<'a>(&self, cx: &'a App) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2773 self.project.read(cx).worktrees(cx)
2774 }
2775
2776 pub fn visible_worktrees<'a>(
2777 &self,
2778 cx: &'a App,
2779 ) -> impl 'a + Iterator<Item = Entity<Worktree>> {
2780 self.project.read(cx).visible_worktrees(cx)
2781 }
2782
2783 #[cfg(any(test, feature = "test-support"))]
2784 pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
2785 let futures = self
2786 .worktrees(cx)
2787 .filter_map(|worktree| worktree.read(cx).as_local())
2788 .map(|worktree| worktree.scan_complete())
2789 .collect::<Vec<_>>();
2790 async move {
2791 for future in futures {
2792 future.await;
2793 }
2794 }
2795 }
2796
2797 pub fn close_global(cx: &mut App) {
2798 cx.defer(|cx| {
2799 cx.windows().iter().find(|window| {
2800 window
2801 .update(cx, |_, window, _| {
2802 if window.is_window_active() {
2803 //This can only get called when the window's project connection has been lost
2804 //so we don't need to prompt the user for anything and instead just close the window
2805 window.remove_window();
2806 true
2807 } else {
2808 false
2809 }
2810 })
2811 .unwrap_or(false)
2812 });
2813 });
2814 }
2815
2816 pub fn move_focused_panel_to_next_position(
2817 &mut self,
2818 _: &MoveFocusedPanelToNextPosition,
2819 window: &mut Window,
2820 cx: &mut Context<Self>,
2821 ) {
2822 let docks = self.all_docks();
2823 let active_dock = docks
2824 .into_iter()
2825 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
2826
2827 if let Some(dock) = active_dock {
2828 dock.update(cx, |dock, cx| {
2829 let active_panel = dock
2830 .active_panel()
2831 .filter(|panel| panel.panel_focus_handle(cx).contains_focused(window, cx));
2832
2833 if let Some(panel) = active_panel {
2834 panel.move_to_next_position(window, cx);
2835 }
2836 })
2837 }
2838 }
2839
2840 pub fn prepare_to_close(
2841 &mut self,
2842 close_intent: CloseIntent,
2843 window: &mut Window,
2844 cx: &mut Context<Self>,
2845 ) -> Task<Result<bool>> {
2846 let active_call = self.active_global_call();
2847
2848 cx.spawn_in(window, async move |this, cx| {
2849 this.update(cx, |this, _| {
2850 if close_intent == CloseIntent::CloseWindow {
2851 this.removing = true;
2852 }
2853 })?;
2854
2855 let workspace_count = cx.update(|_window, cx| {
2856 cx.windows()
2857 .iter()
2858 .filter(|window| window.downcast::<MultiWorkspace>().is_some())
2859 .count()
2860 })?;
2861
2862 #[cfg(target_os = "macos")]
2863 let save_last_workspace = false;
2864
2865 // On Linux and Windows, closing the last window should restore the last workspace.
2866 #[cfg(not(target_os = "macos"))]
2867 let save_last_workspace = {
2868 let remaining_workspaces = cx.update(|_window, cx| {
2869 cx.windows()
2870 .iter()
2871 .filter_map(|window| window.downcast::<MultiWorkspace>())
2872 .filter_map(|multi_workspace| {
2873 multi_workspace
2874 .update(cx, |multi_workspace, _, cx| {
2875 multi_workspace.workspace().read(cx).removing
2876 })
2877 .ok()
2878 })
2879 .filter(|removing| !removing)
2880 .count()
2881 })?;
2882
2883 close_intent != CloseIntent::ReplaceWindow && remaining_workspaces == 0
2884 };
2885
2886 if let Some(active_call) = active_call
2887 && workspace_count == 1
2888 && cx
2889 .update(|_window, cx| active_call.0.is_in_room(cx))
2890 .unwrap_or(false)
2891 {
2892 if close_intent == CloseIntent::CloseWindow {
2893 this.update(cx, |_, cx| cx.emit(Event::Activate))?;
2894 let answer = cx.update(|window, cx| {
2895 window.prompt(
2896 PromptLevel::Warning,
2897 "Do you want to leave the current call?",
2898 None,
2899 &["Close window and hang up", "Cancel"],
2900 cx,
2901 )
2902 })?;
2903
2904 if answer.await.log_err() == Some(1) {
2905 return anyhow::Ok(false);
2906 } else {
2907 if let Ok(task) = cx.update(|_window, cx| active_call.0.hang_up(cx)) {
2908 task.await.log_err();
2909 }
2910 }
2911 }
2912 if close_intent == CloseIntent::ReplaceWindow {
2913 _ = cx.update(|_window, cx| {
2914 let multi_workspace = cx
2915 .windows()
2916 .iter()
2917 .filter_map(|window| window.downcast::<MultiWorkspace>())
2918 .next()
2919 .unwrap();
2920 let project = multi_workspace
2921 .read(cx)?
2922 .workspace()
2923 .read(cx)
2924 .project
2925 .clone();
2926 if project.read(cx).is_shared() {
2927 active_call.0.unshare_project(project, cx)?;
2928 }
2929 Ok::<_, anyhow::Error>(())
2930 });
2931 }
2932 }
2933
2934 let save_result = this
2935 .update_in(cx, |this, window, cx| {
2936 this.save_all_internal(SaveIntent::Close, window, cx)
2937 })?
2938 .await;
2939
2940 // If we're not quitting, but closing, we remove the workspace from
2941 // the current session.
2942 if close_intent != CloseIntent::Quit
2943 && !save_last_workspace
2944 && save_result.as_ref().is_ok_and(|&res| res)
2945 {
2946 this.update_in(cx, |this, window, cx| this.remove_from_session(window, cx))?
2947 .await;
2948 }
2949
2950 save_result
2951 })
2952 }
2953
2954 fn save_all(&mut self, action: &SaveAll, window: &mut Window, cx: &mut Context<Self>) {
2955 self.save_all_internal(
2956 action.save_intent.unwrap_or(SaveIntent::SaveAll),
2957 window,
2958 cx,
2959 )
2960 .detach_and_log_err(cx);
2961 }
2962
2963 fn send_keystrokes(
2964 &mut self,
2965 action: &SendKeystrokes,
2966 window: &mut Window,
2967 cx: &mut Context<Self>,
2968 ) {
2969 let keystrokes: Vec<Keystroke> = action
2970 .0
2971 .split(' ')
2972 .flat_map(|k| Keystroke::parse(k).log_err())
2973 .map(|k| {
2974 cx.keyboard_mapper()
2975 .map_key_equivalent(k, false)
2976 .inner()
2977 .clone()
2978 })
2979 .collect();
2980 let _ = self.send_keystrokes_impl(keystrokes, window, cx);
2981 }
2982
2983 pub fn send_keystrokes_impl(
2984 &mut self,
2985 keystrokes: Vec<Keystroke>,
2986 window: &mut Window,
2987 cx: &mut Context<Self>,
2988 ) -> Shared<Task<()>> {
2989 let mut state = self.dispatching_keystrokes.borrow_mut();
2990 if !state.dispatched.insert(keystrokes.clone()) {
2991 cx.propagate();
2992 return state.task.clone().unwrap();
2993 }
2994
2995 state.queue.extend(keystrokes);
2996
2997 let keystrokes = self.dispatching_keystrokes.clone();
2998 if state.task.is_none() {
2999 state.task = Some(
3000 window
3001 .spawn(cx, async move |cx| {
3002 // limit to 100 keystrokes to avoid infinite recursion.
3003 for _ in 0..100 {
3004 let keystroke = {
3005 let mut state = keystrokes.borrow_mut();
3006 let Some(keystroke) = state.queue.pop_front() else {
3007 state.dispatched.clear();
3008 state.task.take();
3009 return;
3010 };
3011 keystroke
3012 };
3013 cx.update(|window, cx| {
3014 let focused = window.focused(cx);
3015 window.dispatch_keystroke(keystroke.clone(), cx);
3016 if window.focused(cx) != focused {
3017 // dispatch_keystroke may cause the focus to change.
3018 // draw's side effect is to schedule the FocusChanged events in the current flush effect cycle
3019 // And we need that to happen before the next keystroke to keep vim mode happy...
3020 // (Note that the tests always do this implicitly, so you must manually test with something like:
3021 // "bindings": { "g z": ["workspace::SendKeystrokes", ": j <enter> u"]}
3022 // )
3023 window.draw(cx).clear();
3024 }
3025 })
3026 .ok();
3027
3028 // Yield between synthetic keystrokes so deferred focus and
3029 // other effects can settle before dispatching the next key.
3030 yield_now().await;
3031 }
3032
3033 *keystrokes.borrow_mut() = Default::default();
3034 log::error!("over 100 keystrokes passed to send_keystrokes");
3035 })
3036 .shared(),
3037 );
3038 }
3039 state.task.clone().unwrap()
3040 }
3041
3042 fn save_all_internal(
3043 &mut self,
3044 mut save_intent: SaveIntent,
3045 window: &mut Window,
3046 cx: &mut Context<Self>,
3047 ) -> Task<Result<bool>> {
3048 if self.project.read(cx).is_disconnected(cx) {
3049 return Task::ready(Ok(true));
3050 }
3051 let dirty_items = self
3052 .panes
3053 .iter()
3054 .flat_map(|pane| {
3055 pane.read(cx).items().filter_map(|item| {
3056 if item.is_dirty(cx) {
3057 item.tab_content_text(0, cx);
3058 Some((pane.downgrade(), item.boxed_clone()))
3059 } else {
3060 None
3061 }
3062 })
3063 })
3064 .collect::<Vec<_>>();
3065
3066 let project = self.project.clone();
3067 cx.spawn_in(window, async move |workspace, cx| {
3068 let dirty_items = if save_intent == SaveIntent::Close && !dirty_items.is_empty() {
3069 let (serialize_tasks, remaining_dirty_items) =
3070 workspace.update_in(cx, |workspace, window, cx| {
3071 let mut remaining_dirty_items = Vec::new();
3072 let mut serialize_tasks = Vec::new();
3073 for (pane, item) in dirty_items {
3074 if let Some(task) = item
3075 .to_serializable_item_handle(cx)
3076 .and_then(|handle| handle.serialize(workspace, true, window, cx))
3077 {
3078 serialize_tasks.push(task);
3079 } else {
3080 remaining_dirty_items.push((pane, item));
3081 }
3082 }
3083 (serialize_tasks, remaining_dirty_items)
3084 })?;
3085
3086 futures::future::try_join_all(serialize_tasks).await?;
3087
3088 if !remaining_dirty_items.is_empty() {
3089 workspace.update(cx, |_, cx| cx.emit(Event::Activate))?;
3090 }
3091
3092 if remaining_dirty_items.len() > 1 {
3093 let answer = workspace.update_in(cx, |_, window, cx| {
3094 let detail = Pane::file_names_for_prompt(
3095 &mut remaining_dirty_items.iter().map(|(_, handle)| handle),
3096 cx,
3097 );
3098 window.prompt(
3099 PromptLevel::Warning,
3100 "Do you want to save all changes in the following files?",
3101 Some(&detail),
3102 &["Save all", "Discard all", "Cancel"],
3103 cx,
3104 )
3105 })?;
3106 match answer.await.log_err() {
3107 Some(0) => save_intent = SaveIntent::SaveAll,
3108 Some(1) => save_intent = SaveIntent::Skip,
3109 Some(2) => return Ok(false),
3110 _ => {}
3111 }
3112 }
3113
3114 remaining_dirty_items
3115 } else {
3116 dirty_items
3117 };
3118
3119 for (pane, item) in dirty_items {
3120 let (singleton, project_entry_ids) = cx.update(|_, cx| {
3121 (
3122 item.buffer_kind(cx) == ItemBufferKind::Singleton,
3123 item.project_entry_ids(cx),
3124 )
3125 })?;
3126 if (singleton || !project_entry_ids.is_empty())
3127 && !Pane::save_item(project.clone(), &pane, &*item, save_intent, cx).await?
3128 {
3129 return Ok(false);
3130 }
3131 }
3132 Ok(true)
3133 })
3134 }
3135
3136 pub fn open_workspace_for_paths(
3137 &mut self,
3138 replace_current_window: bool,
3139 paths: Vec<PathBuf>,
3140 window: &mut Window,
3141 cx: &mut Context<Self>,
3142 ) -> Task<Result<Entity<Workspace>>> {
3143 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
3144 let is_remote = self.project.read(cx).is_via_collab();
3145 let has_worktree = self.project.read(cx).worktrees(cx).next().is_some();
3146 let has_dirty_items = self.items(cx).any(|item| item.is_dirty(cx));
3147
3148 let window_to_replace = if replace_current_window {
3149 window_handle
3150 } else if is_remote || has_worktree || has_dirty_items {
3151 None
3152 } else {
3153 window_handle
3154 };
3155 let app_state = self.app_state.clone();
3156
3157 cx.spawn(async move |_, cx| {
3158 let OpenResult { workspace, .. } = cx
3159 .update(|cx| {
3160 open_paths(
3161 &paths,
3162 app_state,
3163 OpenOptions {
3164 replace_window: window_to_replace,
3165 ..Default::default()
3166 },
3167 cx,
3168 )
3169 })
3170 .await?;
3171 Ok(workspace)
3172 })
3173 }
3174
3175 #[allow(clippy::type_complexity)]
3176 pub fn open_paths(
3177 &mut self,
3178 mut abs_paths: Vec<PathBuf>,
3179 options: OpenOptions,
3180 pane: Option<WeakEntity<Pane>>,
3181 window: &mut Window,
3182 cx: &mut Context<Self>,
3183 ) -> Task<Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>> {
3184 let fs = self.app_state.fs.clone();
3185
3186 let caller_ordered_abs_paths = abs_paths.clone();
3187
3188 // Sort the paths to ensure we add worktrees for parents before their children.
3189 abs_paths.sort_unstable();
3190 cx.spawn_in(window, async move |this, cx| {
3191 let mut tasks = Vec::with_capacity(abs_paths.len());
3192
3193 for abs_path in &abs_paths {
3194 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3195 OpenVisible::All => Some(true),
3196 OpenVisible::None => Some(false),
3197 OpenVisible::OnlyFiles => match fs.metadata(abs_path).await.log_err() {
3198 Some(Some(metadata)) => Some(!metadata.is_dir),
3199 Some(None) => Some(true),
3200 None => None,
3201 },
3202 OpenVisible::OnlyDirectories => match fs.metadata(abs_path).await.log_err() {
3203 Some(Some(metadata)) => Some(metadata.is_dir),
3204 Some(None) => Some(false),
3205 None => None,
3206 },
3207 };
3208 let project_path = match visible {
3209 Some(visible) => match this
3210 .update(cx, |this, cx| {
3211 Workspace::project_path_for_path(
3212 this.project.clone(),
3213 abs_path,
3214 visible,
3215 cx,
3216 )
3217 })
3218 .log_err()
3219 {
3220 Some(project_path) => project_path.await.log_err(),
3221 None => None,
3222 },
3223 None => None,
3224 };
3225
3226 let this = this.clone();
3227 let abs_path: Arc<Path> = SanitizedPath::new(&abs_path).as_path().into();
3228 let fs = fs.clone();
3229 let pane = pane.clone();
3230 let task = cx.spawn(async move |cx| {
3231 let (_worktree, project_path) = project_path?;
3232 if fs.is_dir(&abs_path).await {
3233 // Opening a directory should not race to update the active entry.
3234 // We'll select/reveal a deterministic final entry after all paths finish opening.
3235 None
3236 } else {
3237 Some(
3238 this.update_in(cx, |this, window, cx| {
3239 this.open_path(
3240 project_path,
3241 pane,
3242 options.focus.unwrap_or(true),
3243 window,
3244 cx,
3245 )
3246 })
3247 .ok()?
3248 .await,
3249 )
3250 }
3251 });
3252 tasks.push(task);
3253 }
3254
3255 let results = futures::future::join_all(tasks).await;
3256
3257 // Determine the winner using the fake/abstract FS metadata, not `Path::is_dir`.
3258 let mut winner: Option<(PathBuf, bool)> = None;
3259 for abs_path in caller_ordered_abs_paths.into_iter().rev() {
3260 if let Some(Some(metadata)) = fs.metadata(&abs_path).await.log_err() {
3261 if !metadata.is_dir {
3262 winner = Some((abs_path, false));
3263 break;
3264 }
3265 if winner.is_none() {
3266 winner = Some((abs_path, true));
3267 }
3268 } else if winner.is_none() {
3269 winner = Some((abs_path, false));
3270 }
3271 }
3272
3273 // Compute the winner entry id on the foreground thread and emit once, after all
3274 // paths finish opening. This avoids races between concurrently-opening paths
3275 // (directories in particular) and makes the resulting project panel selection
3276 // deterministic.
3277 if let Some((winner_abs_path, winner_is_dir)) = winner {
3278 'emit_winner: {
3279 let winner_abs_path: Arc<Path> =
3280 SanitizedPath::new(&winner_abs_path).as_path().into();
3281
3282 let visible = match options.visible.as_ref().unwrap_or(&OpenVisible::None) {
3283 OpenVisible::All => true,
3284 OpenVisible::None => false,
3285 OpenVisible::OnlyFiles => !winner_is_dir,
3286 OpenVisible::OnlyDirectories => winner_is_dir,
3287 };
3288
3289 let Some(worktree_task) = this
3290 .update(cx, |workspace, cx| {
3291 workspace.project.update(cx, |project, cx| {
3292 project.find_or_create_worktree(
3293 winner_abs_path.as_ref(),
3294 visible,
3295 cx,
3296 )
3297 })
3298 })
3299 .ok()
3300 else {
3301 break 'emit_winner;
3302 };
3303
3304 let Ok((worktree, _)) = worktree_task.await else {
3305 break 'emit_winner;
3306 };
3307
3308 let Ok(Some(entry_id)) = this.update(cx, |_, cx| {
3309 let worktree = worktree.read(cx);
3310 let worktree_abs_path = worktree.abs_path();
3311 let entry = if winner_abs_path.as_ref() == worktree_abs_path.as_ref() {
3312 worktree.root_entry()
3313 } else {
3314 winner_abs_path
3315 .strip_prefix(worktree_abs_path.as_ref())
3316 .ok()
3317 .and_then(|relative_path| {
3318 let relative_path =
3319 RelPath::new(relative_path, PathStyle::local())
3320 .log_err()?;
3321 worktree.entry_for_path(&relative_path)
3322 })
3323 }?;
3324 Some(entry.id)
3325 }) else {
3326 break 'emit_winner;
3327 };
3328
3329 this.update(cx, |workspace, cx| {
3330 workspace.project.update(cx, |_, cx| {
3331 cx.emit(project::Event::ActiveEntryChanged(Some(entry_id)));
3332 });
3333 })
3334 .ok();
3335 }
3336 }
3337
3338 results
3339 })
3340 }
3341
3342 pub fn open_resolved_path(
3343 &mut self,
3344 path: ResolvedPath,
3345 window: &mut Window,
3346 cx: &mut Context<Self>,
3347 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
3348 match path {
3349 ResolvedPath::ProjectPath { project_path, .. } => {
3350 self.open_path(project_path, None, true, window, cx)
3351 }
3352 ResolvedPath::AbsPath { path, .. } => self.open_abs_path(
3353 PathBuf::from(path),
3354 OpenOptions {
3355 visible: Some(OpenVisible::None),
3356 ..Default::default()
3357 },
3358 window,
3359 cx,
3360 ),
3361 }
3362 }
3363
3364 pub fn absolute_path_of_worktree(
3365 &self,
3366 worktree_id: WorktreeId,
3367 cx: &mut Context<Self>,
3368 ) -> Option<PathBuf> {
3369 self.project
3370 .read(cx)
3371 .worktree_for_id(worktree_id, cx)
3372 // TODO: use `abs_path` or `root_dir`
3373 .map(|wt| wt.read(cx).abs_path().as_ref().to_path_buf())
3374 }
3375
3376 pub fn add_folder_to_project(
3377 &mut self,
3378 _: &AddFolderToProject,
3379 window: &mut Window,
3380 cx: &mut Context<Self>,
3381 ) {
3382 let project = self.project.read(cx);
3383 if project.is_via_collab() {
3384 self.show_error(
3385 &anyhow!("You cannot add folders to someone else's project"),
3386 cx,
3387 );
3388 return;
3389 }
3390 let paths = self.prompt_for_open_path(
3391 PathPromptOptions {
3392 files: false,
3393 directories: true,
3394 multiple: true,
3395 prompt: None,
3396 },
3397 DirectoryLister::Project(self.project.clone()),
3398 window,
3399 cx,
3400 );
3401 cx.spawn_in(window, async move |this, cx| {
3402 if let Some(paths) = paths.await.log_err().flatten() {
3403 let results = this
3404 .update_in(cx, |this, window, cx| {
3405 this.open_paths(
3406 paths,
3407 OpenOptions {
3408 visible: Some(OpenVisible::All),
3409 ..Default::default()
3410 },
3411 None,
3412 window,
3413 cx,
3414 )
3415 })?
3416 .await;
3417 for result in results.into_iter().flatten() {
3418 result.log_err();
3419 }
3420 }
3421 anyhow::Ok(())
3422 })
3423 .detach_and_log_err(cx);
3424 }
3425
3426 pub fn project_path_for_path(
3427 project: Entity<Project>,
3428 abs_path: &Path,
3429 visible: bool,
3430 cx: &mut App,
3431 ) -> Task<Result<(Entity<Worktree>, ProjectPath)>> {
3432 let entry = project.update(cx, |project, cx| {
3433 project.find_or_create_worktree(abs_path, visible, cx)
3434 });
3435 cx.spawn(async move |cx| {
3436 let (worktree, path) = entry.await?;
3437 let worktree_id = worktree.read_with(cx, |t, _| t.id());
3438 Ok((worktree, ProjectPath { worktree_id, path }))
3439 })
3440 }
3441
3442 pub fn items<'a>(&'a self, cx: &'a App) -> impl 'a + Iterator<Item = &'a Box<dyn ItemHandle>> {
3443 self.panes.iter().flat_map(|pane| pane.read(cx).items())
3444 }
3445
3446 pub fn item_of_type<T: Item>(&self, cx: &App) -> Option<Entity<T>> {
3447 self.items_of_type(cx).max_by_key(|item| item.item_id())
3448 }
3449
3450 pub fn items_of_type<'a, T: Item>(
3451 &'a self,
3452 cx: &'a App,
3453 ) -> impl 'a + Iterator<Item = Entity<T>> {
3454 self.panes
3455 .iter()
3456 .flat_map(|pane| pane.read(cx).items_of_type())
3457 }
3458
3459 pub fn active_item(&self, cx: &App) -> Option<Box<dyn ItemHandle>> {
3460 self.active_pane().read(cx).active_item()
3461 }
3462
3463 pub fn active_item_as<I: 'static>(&self, cx: &App) -> Option<Entity<I>> {
3464 let item = self.active_item(cx)?;
3465 item.to_any_view().downcast::<I>().ok()
3466 }
3467
3468 fn active_project_path(&self, cx: &App) -> Option<ProjectPath> {
3469 self.active_item(cx).and_then(|item| item.project_path(cx))
3470 }
3471
3472 pub fn most_recent_active_path(&self, cx: &App) -> Option<PathBuf> {
3473 self.recent_navigation_history_iter(cx)
3474 .filter_map(|(path, abs_path)| {
3475 let worktree = self
3476 .project
3477 .read(cx)
3478 .worktree_for_id(path.worktree_id, cx)?;
3479 if worktree.read(cx).is_visible() {
3480 abs_path
3481 } else {
3482 None
3483 }
3484 })
3485 .next()
3486 }
3487
3488 pub fn save_active_item(
3489 &mut self,
3490 save_intent: SaveIntent,
3491 window: &mut Window,
3492 cx: &mut App,
3493 ) -> Task<Result<()>> {
3494 let project = self.project.clone();
3495 let pane = self.active_pane();
3496 let item = pane.read(cx).active_item();
3497 let pane = pane.downgrade();
3498
3499 window.spawn(cx, async move |cx| {
3500 if let Some(item) = item {
3501 Pane::save_item(project, &pane, item.as_ref(), save_intent, cx)
3502 .await
3503 .map(|_| ())
3504 } else {
3505 Ok(())
3506 }
3507 })
3508 }
3509
3510 pub fn close_inactive_items_and_panes(
3511 &mut self,
3512 action: &CloseInactiveTabsAndPanes,
3513 window: &mut Window,
3514 cx: &mut Context<Self>,
3515 ) {
3516 if let Some(task) = self.close_all_internal(
3517 true,
3518 action.save_intent.unwrap_or(SaveIntent::Close),
3519 window,
3520 cx,
3521 ) {
3522 task.detach_and_log_err(cx)
3523 }
3524 }
3525
3526 pub fn close_all_items_and_panes(
3527 &mut self,
3528 action: &CloseAllItemsAndPanes,
3529 window: &mut Window,
3530 cx: &mut Context<Self>,
3531 ) {
3532 if let Some(task) = self.close_all_internal(
3533 false,
3534 action.save_intent.unwrap_or(SaveIntent::Close),
3535 window,
3536 cx,
3537 ) {
3538 task.detach_and_log_err(cx)
3539 }
3540 }
3541
3542 /// Closes the active item across all panes.
3543 pub fn close_item_in_all_panes(
3544 &mut self,
3545 action: &CloseItemInAllPanes,
3546 window: &mut Window,
3547 cx: &mut Context<Self>,
3548 ) {
3549 let Some(active_item) = self.active_pane().read(cx).active_item() else {
3550 return;
3551 };
3552
3553 let save_intent = action.save_intent.unwrap_or(SaveIntent::Close);
3554 let close_pinned = action.close_pinned;
3555
3556 if let Some(project_path) = active_item.project_path(cx) {
3557 self.close_items_with_project_path(
3558 &project_path,
3559 save_intent,
3560 close_pinned,
3561 window,
3562 cx,
3563 );
3564 } else if close_pinned || !self.active_pane().read(cx).is_active_item_pinned() {
3565 let item_id = active_item.item_id();
3566 self.active_pane().update(cx, |pane, cx| {
3567 pane.close_item_by_id(item_id, save_intent, window, cx)
3568 .detach_and_log_err(cx);
3569 });
3570 }
3571 }
3572
3573 /// Closes all items with the given project path across all panes.
3574 pub fn close_items_with_project_path(
3575 &mut self,
3576 project_path: &ProjectPath,
3577 save_intent: SaveIntent,
3578 close_pinned: bool,
3579 window: &mut Window,
3580 cx: &mut Context<Self>,
3581 ) {
3582 let panes = self.panes().to_vec();
3583 for pane in panes {
3584 pane.update(cx, |pane, cx| {
3585 pane.close_items_for_project_path(
3586 project_path,
3587 save_intent,
3588 close_pinned,
3589 window,
3590 cx,
3591 )
3592 .detach_and_log_err(cx);
3593 });
3594 }
3595 }
3596
3597 fn close_all_internal(
3598 &mut self,
3599 retain_active_pane: bool,
3600 save_intent: SaveIntent,
3601 window: &mut Window,
3602 cx: &mut Context<Self>,
3603 ) -> Option<Task<Result<()>>> {
3604 let current_pane = self.active_pane();
3605
3606 let mut tasks = Vec::new();
3607
3608 if retain_active_pane {
3609 let current_pane_close = current_pane.update(cx, |pane, cx| {
3610 pane.close_other_items(
3611 &CloseOtherItems {
3612 save_intent: None,
3613 close_pinned: false,
3614 },
3615 None,
3616 window,
3617 cx,
3618 )
3619 });
3620
3621 tasks.push(current_pane_close);
3622 }
3623
3624 for pane in self.panes() {
3625 if retain_active_pane && pane.entity_id() == current_pane.entity_id() {
3626 continue;
3627 }
3628
3629 let close_pane_items = pane.update(cx, |pane: &mut Pane, cx| {
3630 pane.close_all_items(
3631 &CloseAllItems {
3632 save_intent: Some(save_intent),
3633 close_pinned: false,
3634 },
3635 window,
3636 cx,
3637 )
3638 });
3639
3640 tasks.push(close_pane_items)
3641 }
3642
3643 if tasks.is_empty() {
3644 None
3645 } else {
3646 Some(cx.spawn_in(window, async move |_, _| {
3647 for task in tasks {
3648 task.await?
3649 }
3650 Ok(())
3651 }))
3652 }
3653 }
3654
3655 pub fn is_dock_at_position_open(&self, position: DockPosition, cx: &mut Context<Self>) -> bool {
3656 self.dock_at_position(position).read(cx).is_open()
3657 }
3658
3659 pub fn toggle_dock(
3660 &mut self,
3661 dock_side: DockPosition,
3662 window: &mut Window,
3663 cx: &mut Context<Self>,
3664 ) {
3665 let mut focus_center = false;
3666 let mut reveal_dock = false;
3667
3668 let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
3669 let was_visible = self.is_dock_at_position_open(dock_side, cx) && !other_is_zoomed;
3670
3671 if let Some(panel) = self.dock_at_position(dock_side).read(cx).active_panel() {
3672 telemetry::event!(
3673 "Panel Button Clicked",
3674 name = panel.persistent_name(),
3675 toggle_state = !was_visible
3676 );
3677 }
3678 if was_visible {
3679 self.save_open_dock_positions(cx);
3680 }
3681
3682 let dock = self.dock_at_position(dock_side);
3683 dock.update(cx, |dock, cx| {
3684 dock.set_open(!was_visible, window, cx);
3685
3686 if dock.active_panel().is_none() {
3687 let Some(panel_ix) = dock
3688 .first_enabled_panel_idx(cx)
3689 .log_with_level(log::Level::Info)
3690 else {
3691 return;
3692 };
3693 dock.activate_panel(panel_ix, window, cx);
3694 }
3695
3696 if let Some(active_panel) = dock.active_panel() {
3697 if was_visible {
3698 if active_panel
3699 .panel_focus_handle(cx)
3700 .contains_focused(window, cx)
3701 {
3702 focus_center = true;
3703 }
3704 } else {
3705 let focus_handle = &active_panel.panel_focus_handle(cx);
3706 window.focus(focus_handle, cx);
3707 reveal_dock = true;
3708 }
3709 }
3710 });
3711
3712 if reveal_dock {
3713 self.dismiss_zoomed_items_to_reveal(Some(dock_side), window, cx);
3714 }
3715
3716 if focus_center {
3717 self.active_pane
3718 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3719 }
3720
3721 cx.notify();
3722 self.serialize_workspace(window, cx);
3723 }
3724
3725 fn active_dock(&self, window: &Window, cx: &Context<Self>) -> Option<&Entity<Dock>> {
3726 self.all_docks().into_iter().find(|&dock| {
3727 dock.read(cx).is_open() && dock.focus_handle(cx).contains_focused(window, cx)
3728 })
3729 }
3730
3731 fn close_active_dock(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
3732 if let Some(dock) = self.active_dock(window, cx).cloned() {
3733 self.save_open_dock_positions(cx);
3734 dock.update(cx, |dock, cx| {
3735 dock.set_open(false, window, cx);
3736 });
3737 return true;
3738 }
3739 false
3740 }
3741
3742 pub fn close_all_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3743 self.save_open_dock_positions(cx);
3744 for dock in self.all_docks() {
3745 dock.update(cx, |dock, cx| {
3746 dock.set_open(false, window, cx);
3747 });
3748 }
3749
3750 cx.focus_self(window);
3751 cx.notify();
3752 self.serialize_workspace(window, cx);
3753 }
3754
3755 fn get_open_dock_positions(&self, cx: &Context<Self>) -> Vec<DockPosition> {
3756 self.all_docks()
3757 .into_iter()
3758 .filter_map(|dock| {
3759 let dock_ref = dock.read(cx);
3760 if dock_ref.is_open() {
3761 Some(dock_ref.position())
3762 } else {
3763 None
3764 }
3765 })
3766 .collect()
3767 }
3768
3769 /// Saves the positions of currently open docks.
3770 ///
3771 /// Updates `last_open_dock_positions` with positions of all currently open
3772 /// docks, to later be restored by the 'Toggle All Docks' action.
3773 fn save_open_dock_positions(&mut self, cx: &mut Context<Self>) {
3774 let open_dock_positions = self.get_open_dock_positions(cx);
3775 if !open_dock_positions.is_empty() {
3776 self.last_open_dock_positions = open_dock_positions;
3777 }
3778 }
3779
3780 /// Toggles all docks between open and closed states.
3781 ///
3782 /// If any docks are open, closes all and remembers their positions. If all
3783 /// docks are closed, restores the last remembered dock configuration.
3784 fn toggle_all_docks(
3785 &mut self,
3786 _: &ToggleAllDocks,
3787 window: &mut Window,
3788 cx: &mut Context<Self>,
3789 ) {
3790 let open_dock_positions = self.get_open_dock_positions(cx);
3791
3792 if !open_dock_positions.is_empty() {
3793 self.close_all_docks(window, cx);
3794 } else if !self.last_open_dock_positions.is_empty() {
3795 self.restore_last_open_docks(window, cx);
3796 }
3797 }
3798
3799 /// Reopens docks from the most recently remembered configuration.
3800 ///
3801 /// Opens all docks whose positions are stored in `last_open_dock_positions`
3802 /// and clears the stored positions.
3803 fn restore_last_open_docks(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3804 let positions_to_open = std::mem::take(&mut self.last_open_dock_positions);
3805
3806 for position in positions_to_open {
3807 let dock = self.dock_at_position(position);
3808 dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
3809 }
3810
3811 cx.focus_self(window);
3812 cx.notify();
3813 self.serialize_workspace(window, cx);
3814 }
3815
3816 /// Transfer focus to the panel of the given type.
3817 pub fn focus_panel<T: Panel>(
3818 &mut self,
3819 window: &mut Window,
3820 cx: &mut Context<Self>,
3821 ) -> Option<Entity<T>> {
3822 let panel = self.focus_or_unfocus_panel::<T>(window, cx, &mut |_, _, _| true)?;
3823 panel.to_any().downcast().ok()
3824 }
3825
3826 /// Focus the panel of the given type if it isn't already focused. If it is
3827 /// already focused, then transfer focus back to the workspace center.
3828 /// When the `close_panel_on_toggle` setting is enabled, also closes the
3829 /// panel when transferring focus back to the center.
3830 pub fn toggle_panel_focus<T: Panel>(
3831 &mut self,
3832 window: &mut Window,
3833 cx: &mut Context<Self>,
3834 ) -> bool {
3835 let mut did_focus_panel = false;
3836 self.focus_or_unfocus_panel::<T>(window, cx, &mut |panel, window, cx| {
3837 did_focus_panel = !panel.panel_focus_handle(cx).contains_focused(window, cx);
3838 did_focus_panel
3839 });
3840
3841 if !did_focus_panel && WorkspaceSettings::get_global(cx).close_panel_on_toggle {
3842 self.close_panel::<T>(window, cx);
3843 }
3844
3845 telemetry::event!(
3846 "Panel Button Clicked",
3847 name = T::persistent_name(),
3848 toggle_state = did_focus_panel
3849 );
3850
3851 did_focus_panel
3852 }
3853
3854 pub fn focus_center_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3855 if let Some(item) = self.active_item(cx) {
3856 item.item_focus_handle(cx).focus(window, cx);
3857 } else {
3858 log::error!("Could not find a focus target when switching focus to the center panes",);
3859 }
3860 }
3861
3862 pub fn activate_panel_for_proto_id(
3863 &mut self,
3864 panel_id: PanelId,
3865 window: &mut Window,
3866 cx: &mut Context<Self>,
3867 ) -> Option<Arc<dyn PanelHandle>> {
3868 let mut panel = None;
3869 for dock in self.all_docks() {
3870 if let Some(panel_index) = dock.read(cx).panel_index_for_proto_id(panel_id) {
3871 panel = dock.update(cx, |dock, cx| {
3872 dock.activate_panel(panel_index, window, cx);
3873 dock.set_open(true, window, cx);
3874 dock.active_panel().cloned()
3875 });
3876 break;
3877 }
3878 }
3879
3880 if panel.is_some() {
3881 cx.notify();
3882 self.serialize_workspace(window, cx);
3883 }
3884
3885 panel
3886 }
3887
3888 /// Focus or unfocus the given panel type, depending on the given callback.
3889 fn focus_or_unfocus_panel<T: Panel>(
3890 &mut self,
3891 window: &mut Window,
3892 cx: &mut Context<Self>,
3893 should_focus: &mut dyn FnMut(&dyn PanelHandle, &mut Window, &mut Context<Dock>) -> bool,
3894 ) -> Option<Arc<dyn PanelHandle>> {
3895 let mut result_panel = None;
3896 let mut serialize = false;
3897 for dock in self.all_docks() {
3898 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3899 let mut focus_center = false;
3900 let panel = dock.update(cx, |dock, cx| {
3901 dock.activate_panel(panel_index, window, cx);
3902
3903 let panel = dock.active_panel().cloned();
3904 if let Some(panel) = panel.as_ref() {
3905 if should_focus(&**panel, window, cx) {
3906 dock.set_open(true, window, cx);
3907 panel.panel_focus_handle(cx).focus(window, cx);
3908 } else {
3909 focus_center = true;
3910 }
3911 }
3912 panel
3913 });
3914
3915 if focus_center {
3916 self.active_pane
3917 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3918 }
3919
3920 result_panel = panel;
3921 serialize = true;
3922 break;
3923 }
3924 }
3925
3926 if serialize {
3927 self.serialize_workspace(window, cx);
3928 }
3929
3930 cx.notify();
3931 result_panel
3932 }
3933
3934 /// Open the panel of the given type
3935 pub fn open_panel<T: Panel>(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3936 for dock in self.all_docks() {
3937 if let Some(panel_index) = dock.read(cx).panel_index_for_type::<T>() {
3938 dock.update(cx, |dock, cx| {
3939 dock.activate_panel(panel_index, window, cx);
3940 dock.set_open(true, window, cx);
3941 });
3942 }
3943 }
3944 }
3945
3946 pub fn close_panel<T: Panel>(&self, window: &mut Window, cx: &mut Context<Self>) {
3947 for dock in self.all_docks().iter() {
3948 dock.update(cx, |dock, cx| {
3949 if dock.panel::<T>().is_some() {
3950 dock.set_open(false, window, cx)
3951 }
3952 })
3953 }
3954 }
3955
3956 pub fn panel<T: Panel>(&self, cx: &App) -> Option<Entity<T>> {
3957 self.all_docks()
3958 .iter()
3959 .find_map(|dock| dock.read(cx).panel::<T>())
3960 }
3961
3962 fn dismiss_zoomed_items_to_reveal(
3963 &mut self,
3964 dock_to_reveal: Option<DockPosition>,
3965 window: &mut Window,
3966 cx: &mut Context<Self>,
3967 ) {
3968 // If a center pane is zoomed, unzoom it.
3969 for pane in &self.panes {
3970 if pane != &self.active_pane || dock_to_reveal.is_some() {
3971 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
3972 }
3973 }
3974
3975 // If another dock is zoomed, hide it.
3976 let mut focus_center = false;
3977 for dock in self.all_docks() {
3978 dock.update(cx, |dock, cx| {
3979 if Some(dock.position()) != dock_to_reveal
3980 && let Some(panel) = dock.active_panel()
3981 && panel.is_zoomed(window, cx)
3982 {
3983 focus_center |= panel.panel_focus_handle(cx).contains_focused(window, cx);
3984 dock.set_open(false, window, cx);
3985 }
3986 });
3987 }
3988
3989 if focus_center {
3990 self.active_pane
3991 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx))
3992 }
3993
3994 if self.zoomed_position != dock_to_reveal {
3995 self.zoomed = None;
3996 self.zoomed_position = None;
3997 cx.emit(Event::ZoomChanged);
3998 }
3999
4000 cx.notify();
4001 }
4002
4003 fn add_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
4004 let pane = cx.new(|cx| {
4005 let mut pane = Pane::new(
4006 self.weak_handle(),
4007 self.project.clone(),
4008 self.pane_history_timestamp.clone(),
4009 None,
4010 NewFile.boxed_clone(),
4011 true,
4012 window,
4013 cx,
4014 );
4015 pane.set_can_split(Some(Arc::new(|_, _, _, _| true)));
4016 pane
4017 });
4018 cx.subscribe_in(&pane, window, Self::handle_pane_event)
4019 .detach();
4020 self.panes.push(pane.clone());
4021
4022 window.focus(&pane.focus_handle(cx), cx);
4023
4024 cx.emit(Event::PaneAdded(pane.clone()));
4025 pane
4026 }
4027
4028 pub fn add_item_to_center(
4029 &mut self,
4030 item: Box<dyn ItemHandle>,
4031 window: &mut Window,
4032 cx: &mut Context<Self>,
4033 ) -> bool {
4034 if let Some(center_pane) = self.last_active_center_pane.clone() {
4035 if let Some(center_pane) = center_pane.upgrade() {
4036 center_pane.update(cx, |pane, cx| {
4037 pane.add_item(item, true, true, None, window, cx)
4038 });
4039 true
4040 } else {
4041 false
4042 }
4043 } else {
4044 false
4045 }
4046 }
4047
4048 pub fn add_item_to_active_pane(
4049 &mut self,
4050 item: Box<dyn ItemHandle>,
4051 destination_index: Option<usize>,
4052 focus_item: bool,
4053 window: &mut Window,
4054 cx: &mut App,
4055 ) {
4056 self.add_item(
4057 self.active_pane.clone(),
4058 item,
4059 destination_index,
4060 false,
4061 focus_item,
4062 window,
4063 cx,
4064 )
4065 }
4066
4067 pub fn add_item(
4068 &mut self,
4069 pane: Entity<Pane>,
4070 item: Box<dyn ItemHandle>,
4071 destination_index: Option<usize>,
4072 activate_pane: bool,
4073 focus_item: bool,
4074 window: &mut Window,
4075 cx: &mut App,
4076 ) {
4077 pane.update(cx, |pane, cx| {
4078 pane.add_item(
4079 item,
4080 activate_pane,
4081 focus_item,
4082 destination_index,
4083 window,
4084 cx,
4085 )
4086 });
4087 }
4088
4089 pub fn split_item(
4090 &mut self,
4091 split_direction: SplitDirection,
4092 item: Box<dyn ItemHandle>,
4093 window: &mut Window,
4094 cx: &mut Context<Self>,
4095 ) {
4096 let new_pane = self.split_pane(self.active_pane.clone(), split_direction, window, cx);
4097 self.add_item(new_pane, item, None, true, true, window, cx);
4098 }
4099
4100 pub fn open_abs_path(
4101 &mut self,
4102 abs_path: PathBuf,
4103 options: OpenOptions,
4104 window: &mut Window,
4105 cx: &mut Context<Self>,
4106 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4107 cx.spawn_in(window, async move |workspace, cx| {
4108 let open_paths_task_result = workspace
4109 .update_in(cx, |workspace, window, cx| {
4110 workspace.open_paths(vec![abs_path.clone()], options, None, window, cx)
4111 })
4112 .with_context(|| format!("open abs path {abs_path:?} task spawn"))?
4113 .await;
4114 anyhow::ensure!(
4115 open_paths_task_result.len() == 1,
4116 "open abs path {abs_path:?} task returned incorrect number of results"
4117 );
4118 match open_paths_task_result
4119 .into_iter()
4120 .next()
4121 .expect("ensured single task result")
4122 {
4123 Some(open_result) => {
4124 open_result.with_context(|| format!("open abs path {abs_path:?} task join"))
4125 }
4126 None => anyhow::bail!("open abs path {abs_path:?} task returned None"),
4127 }
4128 })
4129 }
4130
4131 pub fn split_abs_path(
4132 &mut self,
4133 abs_path: PathBuf,
4134 visible: bool,
4135 window: &mut Window,
4136 cx: &mut Context<Self>,
4137 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4138 let project_path_task =
4139 Workspace::project_path_for_path(self.project.clone(), &abs_path, visible, cx);
4140 cx.spawn_in(window, async move |this, cx| {
4141 let (_, path) = project_path_task.await?;
4142 this.update_in(cx, |this, window, cx| this.split_path(path, window, cx))?
4143 .await
4144 })
4145 }
4146
4147 pub fn open_path(
4148 &mut self,
4149 path: impl Into<ProjectPath>,
4150 pane: Option<WeakEntity<Pane>>,
4151 focus_item: bool,
4152 window: &mut Window,
4153 cx: &mut App,
4154 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4155 self.open_path_preview(path, pane, focus_item, false, true, window, cx)
4156 }
4157
4158 pub fn open_path_preview(
4159 &mut self,
4160 path: impl Into<ProjectPath>,
4161 pane: Option<WeakEntity<Pane>>,
4162 focus_item: bool,
4163 allow_preview: bool,
4164 activate: bool,
4165 window: &mut Window,
4166 cx: &mut App,
4167 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4168 let pane = pane.unwrap_or_else(|| {
4169 self.last_active_center_pane.clone().unwrap_or_else(|| {
4170 self.panes
4171 .first()
4172 .expect("There must be an active pane")
4173 .downgrade()
4174 })
4175 });
4176
4177 let project_path = path.into();
4178 let task = self.load_path(project_path.clone(), window, cx);
4179 window.spawn(cx, async move |cx| {
4180 let (project_entry_id, build_item) = task.await?;
4181
4182 pane.update_in(cx, |pane, window, cx| {
4183 pane.open_item(
4184 project_entry_id,
4185 project_path,
4186 focus_item,
4187 allow_preview,
4188 activate,
4189 None,
4190 window,
4191 cx,
4192 build_item,
4193 )
4194 })
4195 })
4196 }
4197
4198 pub fn split_path(
4199 &mut self,
4200 path: impl Into<ProjectPath>,
4201 window: &mut Window,
4202 cx: &mut Context<Self>,
4203 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4204 self.split_path_preview(path, false, None, window, cx)
4205 }
4206
4207 pub fn split_path_preview(
4208 &mut self,
4209 path: impl Into<ProjectPath>,
4210 allow_preview: bool,
4211 split_direction: Option<SplitDirection>,
4212 window: &mut Window,
4213 cx: &mut Context<Self>,
4214 ) -> Task<anyhow::Result<Box<dyn ItemHandle>>> {
4215 let pane = self.last_active_center_pane.clone().unwrap_or_else(|| {
4216 self.panes
4217 .first()
4218 .expect("There must be an active pane")
4219 .downgrade()
4220 });
4221
4222 if let Member::Pane(center_pane) = &self.center.root
4223 && center_pane.read(cx).items_len() == 0
4224 {
4225 return self.open_path(path, Some(pane), true, window, cx);
4226 }
4227
4228 let project_path = path.into();
4229 let task = self.load_path(project_path.clone(), window, cx);
4230 cx.spawn_in(window, async move |this, cx| {
4231 let (project_entry_id, build_item) = task.await?;
4232 this.update_in(cx, move |this, window, cx| -> Option<_> {
4233 let pane = pane.upgrade()?;
4234 let new_pane = this.split_pane(
4235 pane,
4236 split_direction.unwrap_or(SplitDirection::Right),
4237 window,
4238 cx,
4239 );
4240 new_pane.update(cx, |new_pane, cx| {
4241 Some(new_pane.open_item(
4242 project_entry_id,
4243 project_path,
4244 true,
4245 allow_preview,
4246 true,
4247 None,
4248 window,
4249 cx,
4250 build_item,
4251 ))
4252 })
4253 })
4254 .map(|option| option.context("pane was dropped"))?
4255 })
4256 }
4257
4258 fn load_path(
4259 &mut self,
4260 path: ProjectPath,
4261 window: &mut Window,
4262 cx: &mut App,
4263 ) -> Task<Result<(Option<ProjectEntryId>, WorkspaceItemBuilder)>> {
4264 let registry = cx.default_global::<ProjectItemRegistry>().clone();
4265 registry.open_path(self.project(), &path, window, cx)
4266 }
4267
4268 pub fn find_project_item<T>(
4269 &self,
4270 pane: &Entity<Pane>,
4271 project_item: &Entity<T::Item>,
4272 cx: &App,
4273 ) -> Option<Entity<T>>
4274 where
4275 T: ProjectItem,
4276 {
4277 use project::ProjectItem as _;
4278 let project_item = project_item.read(cx);
4279 let entry_id = project_item.entry_id(cx);
4280 let project_path = project_item.project_path(cx);
4281
4282 let mut item = None;
4283 if let Some(entry_id) = entry_id {
4284 item = pane.read(cx).item_for_entry(entry_id, cx);
4285 }
4286 if item.is_none()
4287 && let Some(project_path) = project_path
4288 {
4289 item = pane.read(cx).item_for_path(project_path, cx);
4290 }
4291
4292 item.and_then(|item| item.downcast::<T>())
4293 }
4294
4295 pub fn is_project_item_open<T>(
4296 &self,
4297 pane: &Entity<Pane>,
4298 project_item: &Entity<T::Item>,
4299 cx: &App,
4300 ) -> bool
4301 where
4302 T: ProjectItem,
4303 {
4304 self.find_project_item::<T>(pane, project_item, cx)
4305 .is_some()
4306 }
4307
4308 pub fn open_project_item<T>(
4309 &mut self,
4310 pane: Entity<Pane>,
4311 project_item: Entity<T::Item>,
4312 activate_pane: bool,
4313 focus_item: bool,
4314 keep_old_preview: bool,
4315 allow_new_preview: bool,
4316 window: &mut Window,
4317 cx: &mut Context<Self>,
4318 ) -> Entity<T>
4319 where
4320 T: ProjectItem,
4321 {
4322 let old_item_id = pane.read(cx).active_item().map(|item| item.item_id());
4323
4324 if let Some(item) = self.find_project_item(&pane, &project_item, cx) {
4325 if !keep_old_preview
4326 && let Some(old_id) = old_item_id
4327 && old_id != item.item_id()
4328 {
4329 // switching to a different item, so unpreview old active item
4330 pane.update(cx, |pane, _| {
4331 pane.unpreview_item_if_preview(old_id);
4332 });
4333 }
4334
4335 self.activate_item(&item, activate_pane, focus_item, window, cx);
4336 if !allow_new_preview {
4337 pane.update(cx, |pane, _| {
4338 pane.unpreview_item_if_preview(item.item_id());
4339 });
4340 }
4341 return item;
4342 }
4343
4344 let item = pane.update(cx, |pane, cx| {
4345 cx.new(|cx| {
4346 T::for_project_item(self.project().clone(), Some(pane), project_item, window, cx)
4347 })
4348 });
4349 let mut destination_index = None;
4350 pane.update(cx, |pane, cx| {
4351 if !keep_old_preview && let Some(old_id) = old_item_id {
4352 pane.unpreview_item_if_preview(old_id);
4353 }
4354 if allow_new_preview {
4355 destination_index = pane.replace_preview_item_id(item.item_id(), window, cx);
4356 }
4357 });
4358
4359 self.add_item(
4360 pane,
4361 Box::new(item.clone()),
4362 destination_index,
4363 activate_pane,
4364 focus_item,
4365 window,
4366 cx,
4367 );
4368 item
4369 }
4370
4371 pub fn open_shared_screen(
4372 &mut self,
4373 peer_id: PeerId,
4374 window: &mut Window,
4375 cx: &mut Context<Self>,
4376 ) {
4377 if let Some(shared_screen) =
4378 self.shared_screen_for_peer(peer_id, &self.active_pane, window, cx)
4379 {
4380 self.active_pane.update(cx, |pane, cx| {
4381 pane.add_item(Box::new(shared_screen), false, true, None, window, cx)
4382 });
4383 }
4384 }
4385
4386 pub fn activate_item(
4387 &mut self,
4388 item: &dyn ItemHandle,
4389 activate_pane: bool,
4390 focus_item: bool,
4391 window: &mut Window,
4392 cx: &mut App,
4393 ) -> bool {
4394 let result = self.panes.iter().find_map(|pane| {
4395 pane.read(cx)
4396 .index_for_item(item)
4397 .map(|ix| (pane.clone(), ix))
4398 });
4399 if let Some((pane, ix)) = result {
4400 pane.update(cx, |pane, cx| {
4401 pane.activate_item(ix, activate_pane, focus_item, window, cx)
4402 });
4403 true
4404 } else {
4405 false
4406 }
4407 }
4408
4409 fn activate_pane_at_index(
4410 &mut self,
4411 action: &ActivatePane,
4412 window: &mut Window,
4413 cx: &mut Context<Self>,
4414 ) {
4415 let panes = self.center.panes();
4416 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
4417 window.focus(&pane.focus_handle(cx), cx);
4418 } else {
4419 self.split_and_clone(self.active_pane.clone(), SplitDirection::Right, window, cx)
4420 .detach();
4421 }
4422 }
4423
4424 fn move_item_to_pane_at_index(
4425 &mut self,
4426 action: &MoveItemToPane,
4427 window: &mut Window,
4428 cx: &mut Context<Self>,
4429 ) {
4430 let panes = self.center.panes();
4431 let destination = match panes.get(action.destination) {
4432 Some(&destination) => destination.clone(),
4433 None => {
4434 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4435 return;
4436 }
4437 let direction = SplitDirection::Right;
4438 let split_off_pane = self
4439 .find_pane_in_direction(direction, cx)
4440 .unwrap_or_else(|| self.active_pane.clone());
4441 let new_pane = self.add_pane(window, cx);
4442 self.center.split(&split_off_pane, &new_pane, direction, cx);
4443 new_pane
4444 }
4445 };
4446
4447 if action.clone {
4448 if self
4449 .active_pane
4450 .read(cx)
4451 .active_item()
4452 .is_some_and(|item| item.can_split(cx))
4453 {
4454 clone_active_item(
4455 self.database_id(),
4456 &self.active_pane,
4457 &destination,
4458 action.focus,
4459 window,
4460 cx,
4461 );
4462 return;
4463 }
4464 }
4465 move_active_item(
4466 &self.active_pane,
4467 &destination,
4468 action.focus,
4469 true,
4470 window,
4471 cx,
4472 )
4473 }
4474
4475 pub fn activate_next_pane(&mut self, window: &mut Window, cx: &mut App) {
4476 let panes = self.center.panes();
4477 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4478 let next_ix = (ix + 1) % panes.len();
4479 let next_pane = panes[next_ix].clone();
4480 window.focus(&next_pane.focus_handle(cx), cx);
4481 }
4482 }
4483
4484 pub fn activate_previous_pane(&mut self, window: &mut Window, cx: &mut App) {
4485 let panes = self.center.panes();
4486 if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
4487 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
4488 let prev_pane = panes[prev_ix].clone();
4489 window.focus(&prev_pane.focus_handle(cx), cx);
4490 }
4491 }
4492
4493 pub fn activate_last_pane(&mut self, window: &mut Window, cx: &mut App) {
4494 let last_pane = self.center.last_pane();
4495 window.focus(&last_pane.focus_handle(cx), cx);
4496 }
4497
4498 pub fn activate_pane_in_direction(
4499 &mut self,
4500 direction: SplitDirection,
4501 window: &mut Window,
4502 cx: &mut App,
4503 ) {
4504 use ActivateInDirectionTarget as Target;
4505 enum Origin {
4506 Sidebar,
4507 LeftDock,
4508 RightDock,
4509 BottomDock,
4510 Center,
4511 }
4512
4513 let origin: Origin = if self
4514 .sidebar_focus_handle
4515 .as_ref()
4516 .is_some_and(|h| h.contains_focused(window, cx))
4517 {
4518 Origin::Sidebar
4519 } else {
4520 [
4521 (&self.left_dock, Origin::LeftDock),
4522 (&self.right_dock, Origin::RightDock),
4523 (&self.bottom_dock, Origin::BottomDock),
4524 ]
4525 .into_iter()
4526 .find_map(|(dock, origin)| {
4527 if dock.focus_handle(cx).contains_focused(window, cx) && dock.read(cx).is_open() {
4528 Some(origin)
4529 } else {
4530 None
4531 }
4532 })
4533 .unwrap_or(Origin::Center)
4534 };
4535
4536 let get_last_active_pane = || {
4537 let pane = self
4538 .last_active_center_pane
4539 .clone()
4540 .unwrap_or_else(|| {
4541 self.panes
4542 .first()
4543 .expect("There must be an active pane")
4544 .downgrade()
4545 })
4546 .upgrade()?;
4547 (pane.read(cx).items_len() != 0).then_some(pane)
4548 };
4549
4550 let try_dock =
4551 |dock: &Entity<Dock>| dock.read(cx).is_open().then(|| Target::Dock(dock.clone()));
4552
4553 let sidebar_target = self
4554 .sidebar_focus_handle
4555 .as_ref()
4556 .map(|h| Target::Sidebar(h.clone()));
4557
4558 let target = match (origin, direction) {
4559 // From the sidebar, only Right navigates into the workspace.
4560 (Origin::Sidebar, SplitDirection::Right) => try_dock(&self.left_dock)
4561 .or_else(|| get_last_active_pane().map(Target::Pane))
4562 .or_else(|| try_dock(&self.bottom_dock))
4563 .or_else(|| try_dock(&self.right_dock)),
4564
4565 (Origin::Sidebar, _) => None,
4566
4567 // We're in the center, so we first try to go to a different pane,
4568 // otherwise try to go to a dock.
4569 (Origin::Center, direction) => {
4570 if let Some(pane) = self.find_pane_in_direction(direction, cx) {
4571 Some(Target::Pane(pane))
4572 } else {
4573 match direction {
4574 SplitDirection::Up => None,
4575 SplitDirection::Down => try_dock(&self.bottom_dock),
4576 SplitDirection::Left => try_dock(&self.left_dock).or(sidebar_target),
4577 SplitDirection::Right => try_dock(&self.right_dock),
4578 }
4579 }
4580 }
4581
4582 (Origin::LeftDock, SplitDirection::Right) => {
4583 if let Some(last_active_pane) = get_last_active_pane() {
4584 Some(Target::Pane(last_active_pane))
4585 } else {
4586 try_dock(&self.bottom_dock).or_else(|| try_dock(&self.right_dock))
4587 }
4588 }
4589
4590 (Origin::LeftDock, SplitDirection::Left) => sidebar_target,
4591
4592 (Origin::LeftDock, SplitDirection::Down)
4593 | (Origin::RightDock, SplitDirection::Down) => try_dock(&self.bottom_dock),
4594
4595 (Origin::BottomDock, SplitDirection::Up) => get_last_active_pane().map(Target::Pane),
4596 (Origin::BottomDock, SplitDirection::Left) => {
4597 try_dock(&self.left_dock).or(sidebar_target)
4598 }
4599 (Origin::BottomDock, SplitDirection::Right) => try_dock(&self.right_dock),
4600
4601 (Origin::RightDock, SplitDirection::Left) => {
4602 if let Some(last_active_pane) = get_last_active_pane() {
4603 Some(Target::Pane(last_active_pane))
4604 } else {
4605 try_dock(&self.bottom_dock)
4606 .or_else(|| try_dock(&self.left_dock))
4607 .or(sidebar_target)
4608 }
4609 }
4610
4611 _ => None,
4612 };
4613
4614 match target {
4615 Some(ActivateInDirectionTarget::Pane(pane)) => {
4616 let pane = pane.read(cx);
4617 if let Some(item) = pane.active_item() {
4618 item.item_focus_handle(cx).focus(window, cx);
4619 } else {
4620 log::error!(
4621 "Could not find a focus target when in switching focus in {direction} direction for a pane",
4622 );
4623 }
4624 }
4625 Some(ActivateInDirectionTarget::Dock(dock)) => {
4626 // Defer this to avoid a panic when the dock's active panel is already on the stack.
4627 window.defer(cx, move |window, cx| {
4628 let dock = dock.read(cx);
4629 if let Some(panel) = dock.active_panel() {
4630 panel.panel_focus_handle(cx).focus(window, cx);
4631 } else {
4632 log::error!("Could not find a focus target when in switching focus in {direction} direction for a {:?} dock", dock.position());
4633 }
4634 })
4635 }
4636 Some(ActivateInDirectionTarget::Sidebar(focus_handle)) => {
4637 focus_handle.focus(window, cx);
4638 }
4639 None => {}
4640 }
4641 }
4642
4643 pub fn move_item_to_pane_in_direction(
4644 &mut self,
4645 action: &MoveItemToPaneInDirection,
4646 window: &mut Window,
4647 cx: &mut Context<Self>,
4648 ) {
4649 let destination = match self.find_pane_in_direction(action.direction, cx) {
4650 Some(destination) => destination,
4651 None => {
4652 if !action.clone && self.active_pane.read(cx).items_len() < 2 {
4653 return;
4654 }
4655 let new_pane = self.add_pane(window, cx);
4656 self.center
4657 .split(&self.active_pane, &new_pane, action.direction, cx);
4658 new_pane
4659 }
4660 };
4661
4662 if action.clone {
4663 if self
4664 .active_pane
4665 .read(cx)
4666 .active_item()
4667 .is_some_and(|item| item.can_split(cx))
4668 {
4669 clone_active_item(
4670 self.database_id(),
4671 &self.active_pane,
4672 &destination,
4673 action.focus,
4674 window,
4675 cx,
4676 );
4677 return;
4678 }
4679 }
4680 move_active_item(
4681 &self.active_pane,
4682 &destination,
4683 action.focus,
4684 true,
4685 window,
4686 cx,
4687 );
4688 }
4689
4690 pub fn bounding_box_for_pane(&self, pane: &Entity<Pane>) -> Option<Bounds<Pixels>> {
4691 self.center.bounding_box_for_pane(pane)
4692 }
4693
4694 pub fn find_pane_in_direction(
4695 &mut self,
4696 direction: SplitDirection,
4697 cx: &App,
4698 ) -> Option<Entity<Pane>> {
4699 self.center
4700 .find_pane_in_direction(&self.active_pane, direction, cx)
4701 .cloned()
4702 }
4703
4704 pub fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4705 if let Some(to) = self.find_pane_in_direction(direction, cx) {
4706 self.center.swap(&self.active_pane, &to, cx);
4707 cx.notify();
4708 }
4709 }
4710
4711 pub fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
4712 if self
4713 .center
4714 .move_to_border(&self.active_pane, direction, cx)
4715 .unwrap()
4716 {
4717 cx.notify();
4718 }
4719 }
4720
4721 pub fn resize_pane(
4722 &mut self,
4723 axis: gpui::Axis,
4724 amount: Pixels,
4725 window: &mut Window,
4726 cx: &mut Context<Self>,
4727 ) {
4728 let docks = self.all_docks();
4729 let active_dock = docks
4730 .into_iter()
4731 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx));
4732
4733 if let Some(dock) = active_dock {
4734 let Some(panel_size) = dock.read(cx).active_panel_size(window, cx) else {
4735 return;
4736 };
4737 match dock.read(cx).position() {
4738 DockPosition::Left => self.resize_left_dock(panel_size + amount, window, cx),
4739 DockPosition::Bottom => self.resize_bottom_dock(panel_size + amount, window, cx),
4740 DockPosition::Right => self.resize_right_dock(panel_size + amount, window, cx),
4741 }
4742 } else {
4743 self.center
4744 .resize(&self.active_pane, axis, amount, &self.bounds, cx);
4745 }
4746 cx.notify();
4747 }
4748
4749 pub fn reset_pane_sizes(&mut self, cx: &mut Context<Self>) {
4750 self.center.reset_pane_sizes(cx);
4751 cx.notify();
4752 }
4753
4754 fn handle_pane_focused(
4755 &mut self,
4756 pane: Entity<Pane>,
4757 window: &mut Window,
4758 cx: &mut Context<Self>,
4759 ) {
4760 // This is explicitly hoisted out of the following check for pane identity as
4761 // terminal panel panes are not registered as a center panes.
4762 self.status_bar.update(cx, |status_bar, cx| {
4763 status_bar.set_active_pane(&pane, window, cx);
4764 });
4765 if self.active_pane != pane {
4766 self.set_active_pane(&pane, window, cx);
4767 }
4768
4769 if self.last_active_center_pane.is_none() {
4770 self.last_active_center_pane = Some(pane.downgrade());
4771 }
4772
4773 // If this pane is in a dock, preserve that dock when dismissing zoomed items.
4774 // This prevents the dock from closing when focus events fire during window activation.
4775 // We also preserve any dock whose active panel itself has focus — this covers
4776 // panels like AgentPanel that don't implement `pane()` but can still be zoomed.
4777 let dock_to_preserve = self.all_docks().iter().find_map(|dock| {
4778 let dock_read = dock.read(cx);
4779 if let Some(panel) = dock_read.active_panel() {
4780 if panel.pane(cx).is_some_and(|dock_pane| dock_pane == pane)
4781 || panel.panel_focus_handle(cx).contains_focused(window, cx)
4782 {
4783 return Some(dock_read.position());
4784 }
4785 }
4786 None
4787 });
4788
4789 self.dismiss_zoomed_items_to_reveal(dock_to_preserve, window, cx);
4790 if pane.read(cx).is_zoomed() {
4791 self.zoomed = Some(pane.downgrade().into());
4792 } else {
4793 self.zoomed = None;
4794 }
4795 self.zoomed_position = None;
4796 cx.emit(Event::ZoomChanged);
4797 self.update_active_view_for_followers(window, cx);
4798 pane.update(cx, |pane, _| {
4799 pane.track_alternate_file_items();
4800 });
4801
4802 cx.notify();
4803 }
4804
4805 fn set_active_pane(
4806 &mut self,
4807 pane: &Entity<Pane>,
4808 window: &mut Window,
4809 cx: &mut Context<Self>,
4810 ) {
4811 self.active_pane = pane.clone();
4812 self.active_item_path_changed(true, window, cx);
4813 self.last_active_center_pane = Some(pane.downgrade());
4814 }
4815
4816 fn handle_panel_focused(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4817 self.update_active_view_for_followers(window, cx);
4818 }
4819
4820 fn handle_pane_event(
4821 &mut self,
4822 pane: &Entity<Pane>,
4823 event: &pane::Event,
4824 window: &mut Window,
4825 cx: &mut Context<Self>,
4826 ) {
4827 let mut serialize_workspace = true;
4828 match event {
4829 pane::Event::AddItem { item } => {
4830 item.added_to_pane(self, pane.clone(), window, cx);
4831 cx.emit(Event::ItemAdded {
4832 item: item.boxed_clone(),
4833 });
4834 }
4835 pane::Event::Split { direction, mode } => {
4836 match mode {
4837 SplitMode::ClonePane => {
4838 self.split_and_clone(pane.clone(), *direction, window, cx)
4839 .detach();
4840 }
4841 SplitMode::EmptyPane => {
4842 self.split_pane(pane.clone(), *direction, window, cx);
4843 }
4844 SplitMode::MovePane => {
4845 self.split_and_move(pane.clone(), *direction, window, cx);
4846 }
4847 };
4848 }
4849 pane::Event::JoinIntoNext => {
4850 self.join_pane_into_next(pane.clone(), window, cx);
4851 }
4852 pane::Event::JoinAll => {
4853 self.join_all_panes(window, cx);
4854 }
4855 pane::Event::Remove { focus_on_pane } => {
4856 self.remove_pane(pane.clone(), focus_on_pane.clone(), window, cx);
4857 }
4858 pane::Event::ActivateItem {
4859 local,
4860 focus_changed,
4861 } => {
4862 window.invalidate_character_coordinates();
4863
4864 pane.update(cx, |pane, _| {
4865 pane.track_alternate_file_items();
4866 });
4867 if *local {
4868 self.unfollow_in_pane(pane, window, cx);
4869 }
4870 serialize_workspace = *focus_changed || pane != self.active_pane();
4871 if pane == self.active_pane() {
4872 self.active_item_path_changed(*focus_changed, window, cx);
4873 self.update_active_view_for_followers(window, cx);
4874 } else if *local {
4875 self.set_active_pane(pane, window, cx);
4876 }
4877 }
4878 pane::Event::UserSavedItem { item, save_intent } => {
4879 cx.emit(Event::UserSavedItem {
4880 pane: pane.downgrade(),
4881 item: item.boxed_clone(),
4882 save_intent: *save_intent,
4883 });
4884 serialize_workspace = false;
4885 }
4886 pane::Event::ChangeItemTitle => {
4887 if *pane == self.active_pane {
4888 self.active_item_path_changed(false, window, cx);
4889 }
4890 serialize_workspace = false;
4891 }
4892 pane::Event::RemovedItem { item } => {
4893 cx.emit(Event::ActiveItemChanged);
4894 self.update_window_edited(window, cx);
4895 if let hash_map::Entry::Occupied(entry) = self.panes_by_item.entry(item.item_id())
4896 && entry.get().entity_id() == pane.entity_id()
4897 {
4898 entry.remove();
4899 }
4900 cx.emit(Event::ItemRemoved {
4901 item_id: item.item_id(),
4902 });
4903 }
4904 pane::Event::Focus => {
4905 window.invalidate_character_coordinates();
4906 self.handle_pane_focused(pane.clone(), window, cx);
4907 }
4908 pane::Event::ZoomIn => {
4909 if *pane == self.active_pane {
4910 pane.update(cx, |pane, cx| pane.set_zoomed(true, cx));
4911 if pane.read(cx).has_focus(window, cx) {
4912 self.zoomed = Some(pane.downgrade().into());
4913 self.zoomed_position = None;
4914 cx.emit(Event::ZoomChanged);
4915 }
4916 cx.notify();
4917 }
4918 }
4919 pane::Event::ZoomOut => {
4920 pane.update(cx, |pane, cx| pane.set_zoomed(false, cx));
4921 if self.zoomed_position.is_none() {
4922 self.zoomed = None;
4923 cx.emit(Event::ZoomChanged);
4924 }
4925 cx.notify();
4926 }
4927 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {}
4928 }
4929
4930 if serialize_workspace {
4931 self.serialize_workspace(window, cx);
4932 }
4933 }
4934
4935 pub fn unfollow_in_pane(
4936 &mut self,
4937 pane: &Entity<Pane>,
4938 window: &mut Window,
4939 cx: &mut Context<Workspace>,
4940 ) -> Option<CollaboratorId> {
4941 let leader_id = self.leader_for_pane(pane)?;
4942 self.unfollow(leader_id, window, cx);
4943 Some(leader_id)
4944 }
4945
4946 pub fn split_pane(
4947 &mut self,
4948 pane_to_split: Entity<Pane>,
4949 split_direction: SplitDirection,
4950 window: &mut Window,
4951 cx: &mut Context<Self>,
4952 ) -> Entity<Pane> {
4953 let new_pane = self.add_pane(window, cx);
4954 self.center
4955 .split(&pane_to_split, &new_pane, split_direction, cx);
4956 cx.notify();
4957 new_pane
4958 }
4959
4960 pub fn split_and_move(
4961 &mut self,
4962 pane: Entity<Pane>,
4963 direction: SplitDirection,
4964 window: &mut Window,
4965 cx: &mut Context<Self>,
4966 ) {
4967 let Some(item) = pane.update(cx, |pane, cx| pane.take_active_item(window, cx)) else {
4968 return;
4969 };
4970 let new_pane = self.add_pane(window, cx);
4971 new_pane.update(cx, |pane, cx| {
4972 pane.add_item(item, true, true, None, window, cx)
4973 });
4974 self.center.split(&pane, &new_pane, direction, cx);
4975 cx.notify();
4976 }
4977
4978 pub fn split_and_clone(
4979 &mut self,
4980 pane: Entity<Pane>,
4981 direction: SplitDirection,
4982 window: &mut Window,
4983 cx: &mut Context<Self>,
4984 ) -> Task<Option<Entity<Pane>>> {
4985 let Some(item) = pane.read(cx).active_item() else {
4986 return Task::ready(None);
4987 };
4988 if !item.can_split(cx) {
4989 return Task::ready(None);
4990 }
4991 let task = item.clone_on_split(self.database_id(), window, cx);
4992 cx.spawn_in(window, async move |this, cx| {
4993 if let Some(clone) = task.await {
4994 this.update_in(cx, |this, window, cx| {
4995 let new_pane = this.add_pane(window, cx);
4996 let nav_history = pane.read(cx).fork_nav_history();
4997 new_pane.update(cx, |pane, cx| {
4998 pane.set_nav_history(nav_history, cx);
4999 pane.add_item(clone, true, true, None, window, cx)
5000 });
5001 this.center.split(&pane, &new_pane, direction, cx);
5002 cx.notify();
5003 new_pane
5004 })
5005 .ok()
5006 } else {
5007 None
5008 }
5009 })
5010 }
5011
5012 pub fn join_all_panes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5013 let active_item = self.active_pane.read(cx).active_item();
5014 for pane in &self.panes {
5015 join_pane_into_active(&self.active_pane, pane, window, cx);
5016 }
5017 if let Some(active_item) = active_item {
5018 self.activate_item(active_item.as_ref(), true, true, window, cx);
5019 }
5020 cx.notify();
5021 }
5022
5023 pub fn join_pane_into_next(
5024 &mut self,
5025 pane: Entity<Pane>,
5026 window: &mut Window,
5027 cx: &mut Context<Self>,
5028 ) {
5029 let next_pane = self
5030 .find_pane_in_direction(SplitDirection::Right, cx)
5031 .or_else(|| self.find_pane_in_direction(SplitDirection::Down, cx))
5032 .or_else(|| self.find_pane_in_direction(SplitDirection::Left, cx))
5033 .or_else(|| self.find_pane_in_direction(SplitDirection::Up, cx));
5034 let Some(next_pane) = next_pane else {
5035 return;
5036 };
5037 move_all_items(&pane, &next_pane, window, cx);
5038 cx.notify();
5039 }
5040
5041 fn remove_pane(
5042 &mut self,
5043 pane: Entity<Pane>,
5044 focus_on: Option<Entity<Pane>>,
5045 window: &mut Window,
5046 cx: &mut Context<Self>,
5047 ) {
5048 if self.center.remove(&pane, cx).unwrap() {
5049 self.force_remove_pane(&pane, &focus_on, window, cx);
5050 self.unfollow_in_pane(&pane, window, cx);
5051 self.last_leaders_by_pane.remove(&pane.downgrade());
5052 for removed_item in pane.read(cx).items() {
5053 self.panes_by_item.remove(&removed_item.item_id());
5054 }
5055
5056 cx.notify();
5057 } else {
5058 self.active_item_path_changed(true, window, cx);
5059 }
5060 cx.emit(Event::PaneRemoved);
5061 }
5062
5063 pub fn panes_mut(&mut self) -> &mut [Entity<Pane>] {
5064 &mut self.panes
5065 }
5066
5067 pub fn panes(&self) -> &[Entity<Pane>] {
5068 &self.panes
5069 }
5070
5071 pub fn active_pane(&self) -> &Entity<Pane> {
5072 &self.active_pane
5073 }
5074
5075 pub fn focused_pane(&self, window: &Window, cx: &App) -> Entity<Pane> {
5076 for dock in self.all_docks() {
5077 if dock.focus_handle(cx).contains_focused(window, cx)
5078 && let Some(pane) = dock
5079 .read(cx)
5080 .active_panel()
5081 .and_then(|panel| panel.pane(cx))
5082 {
5083 return pane;
5084 }
5085 }
5086 self.active_pane().clone()
5087 }
5088
5089 pub fn adjacent_pane(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Pane> {
5090 self.find_pane_in_direction(SplitDirection::Right, cx)
5091 .unwrap_or_else(|| {
5092 self.split_pane(self.active_pane.clone(), SplitDirection::Right, window, cx)
5093 })
5094 }
5095
5096 pub fn pane_for(&self, handle: &dyn ItemHandle) -> Option<Entity<Pane>> {
5097 self.pane_for_item_id(handle.item_id())
5098 }
5099
5100 pub fn pane_for_item_id(&self, item_id: EntityId) -> Option<Entity<Pane>> {
5101 let weak_pane = self.panes_by_item.get(&item_id)?;
5102 weak_pane.upgrade()
5103 }
5104
5105 pub fn pane_for_entity_id(&self, entity_id: EntityId) -> Option<Entity<Pane>> {
5106 self.panes
5107 .iter()
5108 .find(|pane| pane.entity_id() == entity_id)
5109 .cloned()
5110 }
5111
5112 fn collaborator_left(&mut self, peer_id: PeerId, window: &mut Window, cx: &mut Context<Self>) {
5113 self.follower_states.retain(|leader_id, state| {
5114 if *leader_id == CollaboratorId::PeerId(peer_id) {
5115 for item in state.items_by_leader_view_id.values() {
5116 item.view.set_leader_id(None, window, cx);
5117 }
5118 false
5119 } else {
5120 true
5121 }
5122 });
5123 cx.notify();
5124 }
5125
5126 pub fn start_following(
5127 &mut self,
5128 leader_id: impl Into<CollaboratorId>,
5129 window: &mut Window,
5130 cx: &mut Context<Self>,
5131 ) -> Option<Task<Result<()>>> {
5132 let leader_id = leader_id.into();
5133 let pane = self.active_pane().clone();
5134
5135 self.last_leaders_by_pane
5136 .insert(pane.downgrade(), leader_id);
5137 self.unfollow(leader_id, window, cx);
5138 self.unfollow_in_pane(&pane, window, cx);
5139 self.follower_states.insert(
5140 leader_id,
5141 FollowerState {
5142 center_pane: pane.clone(),
5143 dock_pane: None,
5144 active_view_id: None,
5145 items_by_leader_view_id: Default::default(),
5146 },
5147 );
5148 cx.notify();
5149
5150 match leader_id {
5151 CollaboratorId::PeerId(leader_peer_id) => {
5152 let room_id = self.active_call()?.room_id(cx)?;
5153 let project_id = self.project.read(cx).remote_id();
5154 let request = self.app_state.client.request(proto::Follow {
5155 room_id,
5156 project_id,
5157 leader_id: Some(leader_peer_id),
5158 });
5159
5160 Some(cx.spawn_in(window, async move |this, cx| {
5161 let response = request.await?;
5162 this.update(cx, |this, _| {
5163 let state = this
5164 .follower_states
5165 .get_mut(&leader_id)
5166 .context("following interrupted")?;
5167 state.active_view_id = response
5168 .active_view
5169 .as_ref()
5170 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5171 anyhow::Ok(())
5172 })??;
5173 if let Some(view) = response.active_view {
5174 Self::add_view_from_leader(this.clone(), leader_peer_id, &view, cx).await?;
5175 }
5176 this.update_in(cx, |this, window, cx| {
5177 this.leader_updated(leader_id, window, cx)
5178 })?;
5179 Ok(())
5180 }))
5181 }
5182 CollaboratorId::Agent => {
5183 self.leader_updated(leader_id, window, cx)?;
5184 Some(Task::ready(Ok(())))
5185 }
5186 }
5187 }
5188
5189 pub fn follow_next_collaborator(
5190 &mut self,
5191 _: &FollowNextCollaborator,
5192 window: &mut Window,
5193 cx: &mut Context<Self>,
5194 ) {
5195 let collaborators = self.project.read(cx).collaborators();
5196 let next_leader_id = if let Some(leader_id) = self.leader_for_pane(&self.active_pane) {
5197 let mut collaborators = collaborators.keys().copied();
5198 for peer_id in collaborators.by_ref() {
5199 if CollaboratorId::PeerId(peer_id) == leader_id {
5200 break;
5201 }
5202 }
5203 collaborators.next().map(CollaboratorId::PeerId)
5204 } else if let Some(last_leader_id) =
5205 self.last_leaders_by_pane.get(&self.active_pane.downgrade())
5206 {
5207 match last_leader_id {
5208 CollaboratorId::PeerId(peer_id) => {
5209 if collaborators.contains_key(peer_id) {
5210 Some(*last_leader_id)
5211 } else {
5212 None
5213 }
5214 }
5215 CollaboratorId::Agent => Some(CollaboratorId::Agent),
5216 }
5217 } else {
5218 None
5219 };
5220
5221 let pane = self.active_pane.clone();
5222 let Some(leader_id) = next_leader_id.or_else(|| {
5223 Some(CollaboratorId::PeerId(
5224 collaborators.keys().copied().next()?,
5225 ))
5226 }) else {
5227 return;
5228 };
5229 if self.unfollow_in_pane(&pane, window, cx) == Some(leader_id) {
5230 return;
5231 }
5232 if let Some(task) = self.start_following(leader_id, window, cx) {
5233 task.detach_and_log_err(cx)
5234 }
5235 }
5236
5237 pub fn follow(
5238 &mut self,
5239 leader_id: impl Into<CollaboratorId>,
5240 window: &mut Window,
5241 cx: &mut Context<Self>,
5242 ) {
5243 let leader_id = leader_id.into();
5244
5245 if let CollaboratorId::PeerId(peer_id) = leader_id {
5246 let Some(active_call) = GlobalAnyActiveCall::try_global(cx) else {
5247 return;
5248 };
5249 let Some(remote_participant) =
5250 active_call.0.remote_participant_for_peer_id(peer_id, cx)
5251 else {
5252 return;
5253 };
5254
5255 let project = self.project.read(cx);
5256
5257 let other_project_id = match remote_participant.location {
5258 ParticipantLocation::External => None,
5259 ParticipantLocation::UnsharedProject => None,
5260 ParticipantLocation::SharedProject { project_id } => {
5261 if Some(project_id) == project.remote_id() {
5262 None
5263 } else {
5264 Some(project_id)
5265 }
5266 }
5267 };
5268
5269 // if they are active in another project, follow there.
5270 if let Some(project_id) = other_project_id {
5271 let app_state = self.app_state.clone();
5272 crate::join_in_room_project(project_id, remote_participant.user.id, app_state, cx)
5273 .detach_and_log_err(cx);
5274 }
5275 }
5276
5277 // if you're already following, find the right pane and focus it.
5278 if let Some(follower_state) = self.follower_states.get(&leader_id) {
5279 window.focus(&follower_state.pane().focus_handle(cx), cx);
5280
5281 return;
5282 }
5283
5284 // Otherwise, follow.
5285 if let Some(task) = self.start_following(leader_id, window, cx) {
5286 task.detach_and_log_err(cx)
5287 }
5288 }
5289
5290 pub fn unfollow(
5291 &mut self,
5292 leader_id: impl Into<CollaboratorId>,
5293 window: &mut Window,
5294 cx: &mut Context<Self>,
5295 ) -> Option<()> {
5296 cx.notify();
5297
5298 let leader_id = leader_id.into();
5299 let state = self.follower_states.remove(&leader_id)?;
5300 for (_, item) in state.items_by_leader_view_id {
5301 item.view.set_leader_id(None, window, cx);
5302 }
5303
5304 if let CollaboratorId::PeerId(leader_peer_id) = leader_id {
5305 let project_id = self.project.read(cx).remote_id();
5306 let room_id = self.active_call()?.room_id(cx)?;
5307 self.app_state
5308 .client
5309 .send(proto::Unfollow {
5310 room_id,
5311 project_id,
5312 leader_id: Some(leader_peer_id),
5313 })
5314 .log_err();
5315 }
5316
5317 Some(())
5318 }
5319
5320 pub fn is_being_followed(&self, id: impl Into<CollaboratorId>) -> bool {
5321 self.follower_states.contains_key(&id.into())
5322 }
5323
5324 fn active_item_path_changed(
5325 &mut self,
5326 focus_changed: bool,
5327 window: &mut Window,
5328 cx: &mut Context<Self>,
5329 ) {
5330 cx.emit(Event::ActiveItemChanged);
5331 let active_entry = self.active_project_path(cx);
5332 self.project.update(cx, |project, cx| {
5333 project.set_active_path(active_entry.clone(), cx)
5334 });
5335
5336 if focus_changed && let Some(project_path) = &active_entry {
5337 let git_store_entity = self.project.read(cx).git_store().clone();
5338 git_store_entity.update(cx, |git_store, cx| {
5339 git_store.set_active_repo_for_path(project_path, cx);
5340 });
5341 }
5342
5343 self.update_window_title(window, cx);
5344 }
5345
5346 fn update_window_title(&mut self, window: &mut Window, cx: &mut App) {
5347 let project = self.project().read(cx);
5348 let mut title = String::new();
5349
5350 for (i, worktree) in project.visible_worktrees(cx).enumerate() {
5351 let name = {
5352 let settings_location = SettingsLocation {
5353 worktree_id: worktree.read(cx).id(),
5354 path: RelPath::empty(),
5355 };
5356
5357 let settings = WorktreeSettings::get(Some(settings_location), cx);
5358 match &settings.project_name {
5359 Some(name) => name.as_str(),
5360 None => worktree.read(cx).root_name_str(),
5361 }
5362 };
5363 if i > 0 {
5364 title.push_str(", ");
5365 }
5366 title.push_str(name);
5367 }
5368
5369 if title.is_empty() {
5370 title = "empty project".to_string();
5371 }
5372
5373 if let Some(path) = self.active_item(cx).and_then(|item| item.project_path(cx)) {
5374 let filename = path.path.file_name().or_else(|| {
5375 Some(
5376 project
5377 .worktree_for_id(path.worktree_id, cx)?
5378 .read(cx)
5379 .root_name_str(),
5380 )
5381 });
5382
5383 if let Some(filename) = filename {
5384 title.push_str(" — ");
5385 title.push_str(filename.as_ref());
5386 }
5387 }
5388
5389 if project.is_via_collab() {
5390 title.push_str(" ↙");
5391 } else if project.is_shared() {
5392 title.push_str(" ↗");
5393 }
5394
5395 if let Some(last_title) = self.last_window_title.as_ref()
5396 && &title == last_title
5397 {
5398 return;
5399 }
5400 window.set_window_title(&title);
5401 SystemWindowTabController::update_tab_title(
5402 cx,
5403 window.window_handle().window_id(),
5404 SharedString::from(&title),
5405 );
5406 self.last_window_title = Some(title);
5407 }
5408
5409 fn update_window_edited(&mut self, window: &mut Window, cx: &mut App) {
5410 let is_edited = !self.project.read(cx).is_disconnected(cx) && !self.dirty_items.is_empty();
5411 if is_edited != self.window_edited {
5412 self.window_edited = is_edited;
5413 window.set_window_edited(self.window_edited)
5414 }
5415 }
5416
5417 fn update_item_dirty_state(
5418 &mut self,
5419 item: &dyn ItemHandle,
5420 window: &mut Window,
5421 cx: &mut App,
5422 ) {
5423 let is_dirty = item.is_dirty(cx);
5424 let item_id = item.item_id();
5425 let was_dirty = self.dirty_items.contains_key(&item_id);
5426 if is_dirty == was_dirty {
5427 return;
5428 }
5429 if was_dirty {
5430 self.dirty_items.remove(&item_id);
5431 self.update_window_edited(window, cx);
5432 return;
5433 }
5434
5435 let workspace = self.weak_handle();
5436 let Some(window_handle) = window.window_handle().downcast::<MultiWorkspace>() else {
5437 return;
5438 };
5439 let on_release_callback = Box::new(move |cx: &mut App| {
5440 window_handle
5441 .update(cx, |_, window, cx| {
5442 workspace
5443 .update(cx, |workspace, cx| {
5444 workspace.dirty_items.remove(&item_id);
5445 workspace.update_window_edited(window, cx)
5446 })
5447 .ok();
5448 })
5449 .ok();
5450 });
5451
5452 let s = item.on_release(cx, on_release_callback);
5453 self.dirty_items.insert(item_id, s);
5454 self.update_window_edited(window, cx);
5455 }
5456
5457 fn render_notifications(&self, _window: &mut Window, _cx: &mut Context<Self>) -> Option<Div> {
5458 if self.notifications.is_empty() {
5459 None
5460 } else {
5461 Some(
5462 div()
5463 .absolute()
5464 .right_3()
5465 .bottom_3()
5466 .w_112()
5467 .h_full()
5468 .flex()
5469 .flex_col()
5470 .justify_end()
5471 .gap_2()
5472 .children(
5473 self.notifications
5474 .iter()
5475 .map(|(_, notification)| notification.clone().into_any()),
5476 ),
5477 )
5478 }
5479 }
5480
5481 // RPC handlers
5482
5483 fn active_view_for_follower(
5484 &self,
5485 follower_project_id: Option<u64>,
5486 window: &mut Window,
5487 cx: &mut Context<Self>,
5488 ) -> Option<proto::View> {
5489 let (item, panel_id) = self.active_item_for_followers(window, cx);
5490 let item = item?;
5491 let leader_id = self
5492 .pane_for(&*item)
5493 .and_then(|pane| self.leader_for_pane(&pane));
5494 let leader_peer_id = match leader_id {
5495 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5496 Some(CollaboratorId::Agent) | None => None,
5497 };
5498
5499 let item_handle = item.to_followable_item_handle(cx)?;
5500 let id = item_handle.remote_id(&self.app_state.client, window, cx)?;
5501 let variant = item_handle.to_state_proto(window, cx)?;
5502
5503 if item_handle.is_project_item(window, cx)
5504 && (follower_project_id.is_none()
5505 || follower_project_id != self.project.read(cx).remote_id())
5506 {
5507 return None;
5508 }
5509
5510 Some(proto::View {
5511 id: id.to_proto(),
5512 leader_id: leader_peer_id,
5513 variant: Some(variant),
5514 panel_id: panel_id.map(|id| id as i32),
5515 })
5516 }
5517
5518 fn handle_follow(
5519 &mut self,
5520 follower_project_id: Option<u64>,
5521 window: &mut Window,
5522 cx: &mut Context<Self>,
5523 ) -> proto::FollowResponse {
5524 let active_view = self.active_view_for_follower(follower_project_id, window, cx);
5525
5526 cx.notify();
5527 proto::FollowResponse {
5528 views: active_view.iter().cloned().collect(),
5529 active_view,
5530 }
5531 }
5532
5533 fn handle_update_followers(
5534 &mut self,
5535 leader_id: PeerId,
5536 message: proto::UpdateFollowers,
5537 _window: &mut Window,
5538 _cx: &mut Context<Self>,
5539 ) {
5540 self.leader_updates_tx
5541 .unbounded_send((leader_id, message))
5542 .ok();
5543 }
5544
5545 async fn process_leader_update(
5546 this: &WeakEntity<Self>,
5547 leader_id: PeerId,
5548 update: proto::UpdateFollowers,
5549 cx: &mut AsyncWindowContext,
5550 ) -> Result<()> {
5551 match update.variant.context("invalid update")? {
5552 proto::update_followers::Variant::CreateView(view) => {
5553 let view_id = ViewId::from_proto(view.id.clone().context("invalid view id")?)?;
5554 let should_add_view = this.update(cx, |this, _| {
5555 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5556 anyhow::Ok(!state.items_by_leader_view_id.contains_key(&view_id))
5557 } else {
5558 anyhow::Ok(false)
5559 }
5560 })??;
5561
5562 if should_add_view {
5563 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5564 }
5565 }
5566 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
5567 let should_add_view = this.update(cx, |this, _| {
5568 if let Some(state) = this.follower_states.get_mut(&leader_id.into()) {
5569 state.active_view_id = update_active_view
5570 .view
5571 .as_ref()
5572 .and_then(|view| ViewId::from_proto(view.id.clone()?).ok());
5573
5574 if state.active_view_id.is_some_and(|view_id| {
5575 !state.items_by_leader_view_id.contains_key(&view_id)
5576 }) {
5577 anyhow::Ok(true)
5578 } else {
5579 anyhow::Ok(false)
5580 }
5581 } else {
5582 anyhow::Ok(false)
5583 }
5584 })??;
5585
5586 if should_add_view && let Some(view) = update_active_view.view {
5587 Self::add_view_from_leader(this.clone(), leader_id, &view, cx).await?
5588 }
5589 }
5590 proto::update_followers::Variant::UpdateView(update_view) => {
5591 let variant = update_view.variant.context("missing update view variant")?;
5592 let id = update_view.id.context("missing update view id")?;
5593 let mut tasks = Vec::new();
5594 this.update_in(cx, |this, window, cx| {
5595 let project = this.project.clone();
5596 if let Some(state) = this.follower_states.get(&leader_id.into()) {
5597 let view_id = ViewId::from_proto(id.clone())?;
5598 if let Some(item) = state.items_by_leader_view_id.get(&view_id) {
5599 tasks.push(item.view.apply_update_proto(
5600 &project,
5601 variant.clone(),
5602 window,
5603 cx,
5604 ));
5605 }
5606 }
5607 anyhow::Ok(())
5608 })??;
5609 try_join_all(tasks).await.log_err();
5610 }
5611 }
5612 this.update_in(cx, |this, window, cx| {
5613 this.leader_updated(leader_id, window, cx)
5614 })?;
5615 Ok(())
5616 }
5617
5618 async fn add_view_from_leader(
5619 this: WeakEntity<Self>,
5620 leader_id: PeerId,
5621 view: &proto::View,
5622 cx: &mut AsyncWindowContext,
5623 ) -> Result<()> {
5624 let this = this.upgrade().context("workspace dropped")?;
5625
5626 let Some(id) = view.id.clone() else {
5627 anyhow::bail!("no id for view");
5628 };
5629 let id = ViewId::from_proto(id)?;
5630 let panel_id = view.panel_id.and_then(proto::PanelId::from_i32);
5631
5632 let pane = this.update(cx, |this, _cx| {
5633 let state = this
5634 .follower_states
5635 .get(&leader_id.into())
5636 .context("stopped following")?;
5637 anyhow::Ok(state.pane().clone())
5638 })?;
5639 let existing_item = pane.update_in(cx, |pane, window, cx| {
5640 let client = this.read(cx).client().clone();
5641 pane.items().find_map(|item| {
5642 let item = item.to_followable_item_handle(cx)?;
5643 if item.remote_id(&client, window, cx) == Some(id) {
5644 Some(item)
5645 } else {
5646 None
5647 }
5648 })
5649 })?;
5650 let item = if let Some(existing_item) = existing_item {
5651 existing_item
5652 } else {
5653 let variant = view.variant.clone();
5654 anyhow::ensure!(variant.is_some(), "missing view variant");
5655
5656 let task = cx.update(|window, cx| {
5657 FollowableViewRegistry::from_state_proto(this.clone(), id, variant, window, cx)
5658 })?;
5659
5660 let Some(task) = task else {
5661 anyhow::bail!(
5662 "failed to construct view from leader (maybe from a different version of zed?)"
5663 );
5664 };
5665
5666 let mut new_item = task.await?;
5667 pane.update_in(cx, |pane, window, cx| {
5668 let mut item_to_remove = None;
5669 for (ix, item) in pane.items().enumerate() {
5670 if let Some(item) = item.to_followable_item_handle(cx) {
5671 match new_item.dedup(item.as_ref(), window, cx) {
5672 Some(item::Dedup::KeepExisting) => {
5673 new_item =
5674 item.boxed_clone().to_followable_item_handle(cx).unwrap();
5675 break;
5676 }
5677 Some(item::Dedup::ReplaceExisting) => {
5678 item_to_remove = Some((ix, item.item_id()));
5679 break;
5680 }
5681 None => {}
5682 }
5683 }
5684 }
5685
5686 if let Some((ix, id)) = item_to_remove {
5687 pane.remove_item(id, false, false, window, cx);
5688 pane.add_item(new_item.boxed_clone(), false, false, Some(ix), window, cx);
5689 }
5690 })?;
5691
5692 new_item
5693 };
5694
5695 this.update_in(cx, |this, window, cx| {
5696 let state = this.follower_states.get_mut(&leader_id.into())?;
5697 item.set_leader_id(Some(leader_id.into()), window, cx);
5698 state.items_by_leader_view_id.insert(
5699 id,
5700 FollowerView {
5701 view: item,
5702 location: panel_id,
5703 },
5704 );
5705
5706 Some(())
5707 })
5708 .context("no follower state")?;
5709
5710 Ok(())
5711 }
5712
5713 fn handle_agent_location_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5714 let Some(follower_state) = self.follower_states.get_mut(&CollaboratorId::Agent) else {
5715 return;
5716 };
5717
5718 if let Some(agent_location) = self.project.read(cx).agent_location() {
5719 let buffer_entity_id = agent_location.buffer.entity_id();
5720 let view_id = ViewId {
5721 creator: CollaboratorId::Agent,
5722 id: buffer_entity_id.as_u64(),
5723 };
5724 follower_state.active_view_id = Some(view_id);
5725
5726 let item = match follower_state.items_by_leader_view_id.entry(view_id) {
5727 hash_map::Entry::Occupied(entry) => Some(entry.into_mut()),
5728 hash_map::Entry::Vacant(entry) => {
5729 let existing_view =
5730 follower_state
5731 .center_pane
5732 .read(cx)
5733 .items()
5734 .find_map(|item| {
5735 let item = item.to_followable_item_handle(cx)?;
5736 if item.buffer_kind(cx) == ItemBufferKind::Singleton
5737 && item.project_item_model_ids(cx).as_slice()
5738 == [buffer_entity_id]
5739 {
5740 Some(item)
5741 } else {
5742 None
5743 }
5744 });
5745 let view = existing_view.or_else(|| {
5746 agent_location.buffer.upgrade().and_then(|buffer| {
5747 cx.update_default_global(|registry: &mut ProjectItemRegistry, cx| {
5748 registry.build_item(buffer, self.project.clone(), None, window, cx)
5749 })?
5750 .to_followable_item_handle(cx)
5751 })
5752 });
5753
5754 view.map(|view| {
5755 entry.insert(FollowerView {
5756 view,
5757 location: None,
5758 })
5759 })
5760 }
5761 };
5762
5763 if let Some(item) = item {
5764 item.view
5765 .set_leader_id(Some(CollaboratorId::Agent), window, cx);
5766 item.view
5767 .update_agent_location(agent_location.position, window, cx);
5768 }
5769 } else {
5770 follower_state.active_view_id = None;
5771 }
5772
5773 self.leader_updated(CollaboratorId::Agent, window, cx);
5774 }
5775
5776 pub fn update_active_view_for_followers(&mut self, window: &mut Window, cx: &mut App) {
5777 let mut is_project_item = true;
5778 let mut update = proto::UpdateActiveView::default();
5779 if window.is_window_active() {
5780 let (active_item, panel_id) = self.active_item_for_followers(window, cx);
5781
5782 if let Some(item) = active_item
5783 && item.item_focus_handle(cx).contains_focused(window, cx)
5784 {
5785 let leader_id = self
5786 .pane_for(&*item)
5787 .and_then(|pane| self.leader_for_pane(&pane));
5788 let leader_peer_id = match leader_id {
5789 Some(CollaboratorId::PeerId(peer_id)) => Some(peer_id),
5790 Some(CollaboratorId::Agent) | None => None,
5791 };
5792
5793 if let Some(item) = item.to_followable_item_handle(cx) {
5794 let id = item
5795 .remote_id(&self.app_state.client, window, cx)
5796 .map(|id| id.to_proto());
5797
5798 if let Some(id) = id
5799 && let Some(variant) = item.to_state_proto(window, cx)
5800 {
5801 let view = Some(proto::View {
5802 id,
5803 leader_id: leader_peer_id,
5804 variant: Some(variant),
5805 panel_id: panel_id.map(|id| id as i32),
5806 });
5807
5808 is_project_item = item.is_project_item(window, cx);
5809 update = proto::UpdateActiveView { view };
5810 };
5811 }
5812 }
5813 }
5814
5815 let active_view_id = update.view.as_ref().and_then(|view| view.id.as_ref());
5816 if active_view_id != self.last_active_view_id.as_ref() {
5817 self.last_active_view_id = active_view_id.cloned();
5818 self.update_followers(
5819 is_project_item,
5820 proto::update_followers::Variant::UpdateActiveView(update),
5821 window,
5822 cx,
5823 );
5824 }
5825 }
5826
5827 fn active_item_for_followers(
5828 &self,
5829 window: &mut Window,
5830 cx: &mut App,
5831 ) -> (Option<Box<dyn ItemHandle>>, Option<proto::PanelId>) {
5832 let mut active_item = None;
5833 let mut panel_id = None;
5834 for dock in self.all_docks() {
5835 if dock.focus_handle(cx).contains_focused(window, cx)
5836 && let Some(panel) = dock.read(cx).active_panel()
5837 && let Some(pane) = panel.pane(cx)
5838 && let Some(item) = pane.read(cx).active_item()
5839 {
5840 active_item = Some(item);
5841 panel_id = panel.remote_id();
5842 break;
5843 }
5844 }
5845
5846 if active_item.is_none() {
5847 active_item = self.active_pane().read(cx).active_item();
5848 }
5849 (active_item, panel_id)
5850 }
5851
5852 fn update_followers(
5853 &self,
5854 project_only: bool,
5855 update: proto::update_followers::Variant,
5856 _: &mut Window,
5857 cx: &mut App,
5858 ) -> Option<()> {
5859 // If this update only applies to for followers in the current project,
5860 // then skip it unless this project is shared. If it applies to all
5861 // followers, regardless of project, then set `project_id` to none,
5862 // indicating that it goes to all followers.
5863 let project_id = if project_only {
5864 Some(self.project.read(cx).remote_id()?)
5865 } else {
5866 None
5867 };
5868 self.app_state().workspace_store.update(cx, |store, cx| {
5869 store.update_followers(project_id, update, cx)
5870 })
5871 }
5872
5873 pub fn leader_for_pane(&self, pane: &Entity<Pane>) -> Option<CollaboratorId> {
5874 self.follower_states.iter().find_map(|(leader_id, state)| {
5875 if state.center_pane == *pane || state.dock_pane.as_ref() == Some(pane) {
5876 Some(*leader_id)
5877 } else {
5878 None
5879 }
5880 })
5881 }
5882
5883 fn leader_updated(
5884 &mut self,
5885 leader_id: impl Into<CollaboratorId>,
5886 window: &mut Window,
5887 cx: &mut Context<Self>,
5888 ) -> Option<Box<dyn ItemHandle>> {
5889 cx.notify();
5890
5891 let leader_id = leader_id.into();
5892 let (panel_id, item) = match leader_id {
5893 CollaboratorId::PeerId(peer_id) => self.active_item_for_peer(peer_id, window, cx)?,
5894 CollaboratorId::Agent => (None, self.active_item_for_agent()?),
5895 };
5896
5897 let state = self.follower_states.get(&leader_id)?;
5898 let mut transfer_focus = state.center_pane.read(cx).has_focus(window, cx);
5899 let pane;
5900 if let Some(panel_id) = panel_id {
5901 pane = self
5902 .activate_panel_for_proto_id(panel_id, window, cx)?
5903 .pane(cx)?;
5904 let state = self.follower_states.get_mut(&leader_id)?;
5905 state.dock_pane = Some(pane.clone());
5906 } else {
5907 pane = state.center_pane.clone();
5908 let state = self.follower_states.get_mut(&leader_id)?;
5909 if let Some(dock_pane) = state.dock_pane.take() {
5910 transfer_focus |= dock_pane.focus_handle(cx).contains_focused(window, cx);
5911 }
5912 }
5913
5914 pane.update(cx, |pane, cx| {
5915 let focus_active_item = pane.has_focus(window, cx) || transfer_focus;
5916 if let Some(index) = pane.index_for_item(item.as_ref()) {
5917 pane.activate_item(index, false, false, window, cx);
5918 } else {
5919 pane.add_item(item.boxed_clone(), false, false, None, window, cx)
5920 }
5921
5922 if focus_active_item {
5923 pane.focus_active_item(window, cx)
5924 }
5925 });
5926
5927 Some(item)
5928 }
5929
5930 fn active_item_for_agent(&self) -> Option<Box<dyn ItemHandle>> {
5931 let state = self.follower_states.get(&CollaboratorId::Agent)?;
5932 let active_view_id = state.active_view_id?;
5933 Some(
5934 state
5935 .items_by_leader_view_id
5936 .get(&active_view_id)?
5937 .view
5938 .boxed_clone(),
5939 )
5940 }
5941
5942 fn active_item_for_peer(
5943 &self,
5944 peer_id: PeerId,
5945 window: &mut Window,
5946 cx: &mut Context<Self>,
5947 ) -> Option<(Option<PanelId>, Box<dyn ItemHandle>)> {
5948 let call = self.active_call()?;
5949 let participant = call.remote_participant_for_peer_id(peer_id, cx)?;
5950 let leader_in_this_app;
5951 let leader_in_this_project;
5952 match participant.location {
5953 ParticipantLocation::SharedProject { project_id } => {
5954 leader_in_this_app = true;
5955 leader_in_this_project = Some(project_id) == self.project.read(cx).remote_id();
5956 }
5957 ParticipantLocation::UnsharedProject => {
5958 leader_in_this_app = true;
5959 leader_in_this_project = false;
5960 }
5961 ParticipantLocation::External => {
5962 leader_in_this_app = false;
5963 leader_in_this_project = false;
5964 }
5965 };
5966 let state = self.follower_states.get(&peer_id.into())?;
5967 let mut item_to_activate = None;
5968 if let (Some(active_view_id), true) = (state.active_view_id, leader_in_this_app) {
5969 if let Some(item) = state.items_by_leader_view_id.get(&active_view_id)
5970 && (leader_in_this_project || !item.view.is_project_item(window, cx))
5971 {
5972 item_to_activate = Some((item.location, item.view.boxed_clone()));
5973 }
5974 } else if let Some(shared_screen) =
5975 self.shared_screen_for_peer(peer_id, &state.center_pane, window, cx)
5976 {
5977 item_to_activate = Some((None, Box::new(shared_screen)));
5978 }
5979 item_to_activate
5980 }
5981
5982 fn shared_screen_for_peer(
5983 &self,
5984 peer_id: PeerId,
5985 pane: &Entity<Pane>,
5986 window: &mut Window,
5987 cx: &mut App,
5988 ) -> Option<Entity<SharedScreen>> {
5989 self.active_call()?
5990 .create_shared_screen(peer_id, pane, window, cx)
5991 }
5992
5993 pub fn on_window_activation_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5994 if window.is_window_active() {
5995 self.update_active_view_for_followers(window, cx);
5996
5997 if let Some(database_id) = self.database_id {
5998 let db = WorkspaceDb::global(cx);
5999 cx.background_spawn(async move { db.update_timestamp(database_id).await })
6000 .detach();
6001 }
6002 } else {
6003 for pane in &self.panes {
6004 pane.update(cx, |pane, cx| {
6005 if let Some(item) = pane.active_item() {
6006 item.workspace_deactivated(window, cx);
6007 }
6008 for item in pane.items() {
6009 if matches!(
6010 item.workspace_settings(cx).autosave,
6011 AutosaveSetting::OnWindowChange | AutosaveSetting::OnFocusChange
6012 ) {
6013 Pane::autosave_item(item.as_ref(), self.project.clone(), window, cx)
6014 .detach_and_log_err(cx);
6015 }
6016 }
6017 });
6018 }
6019 }
6020 }
6021
6022 pub fn active_call(&self) -> Option<&dyn AnyActiveCall> {
6023 self.active_call.as_ref().map(|(call, _)| &*call.0)
6024 }
6025
6026 pub fn active_global_call(&self) -> Option<GlobalAnyActiveCall> {
6027 self.active_call.as_ref().map(|(call, _)| call.clone())
6028 }
6029
6030 fn on_active_call_event(
6031 &mut self,
6032 event: &ActiveCallEvent,
6033 window: &mut Window,
6034 cx: &mut Context<Self>,
6035 ) {
6036 match event {
6037 ActiveCallEvent::ParticipantLocationChanged { participant_id }
6038 | ActiveCallEvent::RemoteVideoTracksChanged { participant_id } => {
6039 self.leader_updated(participant_id, window, cx);
6040 }
6041 }
6042 }
6043
6044 pub fn database_id(&self) -> Option<WorkspaceId> {
6045 self.database_id
6046 }
6047
6048 #[cfg(any(test, feature = "test-support"))]
6049 pub(crate) fn set_database_id(&mut self, id: WorkspaceId) {
6050 self.database_id = Some(id);
6051 }
6052
6053 pub fn session_id(&self) -> Option<String> {
6054 self.session_id.clone()
6055 }
6056
6057 fn save_window_bounds(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6058 let Some(display) = window.display(cx) else {
6059 return Task::ready(());
6060 };
6061 let Ok(display_uuid) = display.uuid() else {
6062 return Task::ready(());
6063 };
6064
6065 let window_bounds = window.inner_window_bounds();
6066 let database_id = self.database_id;
6067 let has_paths = !self.root_paths(cx).is_empty();
6068 let db = WorkspaceDb::global(cx);
6069 let kvp = db::kvp::KeyValueStore::global(cx);
6070
6071 cx.background_executor().spawn(async move {
6072 if !has_paths {
6073 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6074 .await
6075 .log_err();
6076 }
6077 if let Some(database_id) = database_id {
6078 db.set_window_open_status(
6079 database_id,
6080 SerializedWindowBounds(window_bounds),
6081 display_uuid,
6082 )
6083 .await
6084 .log_err();
6085 } else {
6086 persistence::write_default_window_bounds(&kvp, window_bounds, display_uuid)
6087 .await
6088 .log_err();
6089 }
6090 })
6091 }
6092
6093 /// Bypass the 200ms serialization throttle and write workspace state to
6094 /// the DB immediately. Returns a task the caller can await to ensure the
6095 /// write completes. Used by the quit handler so the most recent state
6096 /// isn't lost to a pending throttle timer when the process exits.
6097 pub fn flush_serialization(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6098 self._schedule_serialize_workspace.take();
6099 self._serialize_workspace_task.take();
6100 self.bounds_save_task_queued.take();
6101
6102 let bounds_task = self.save_window_bounds(window, cx);
6103 let serialize_task = self.serialize_workspace_internal(window, cx);
6104 cx.spawn(async move |_| {
6105 bounds_task.await;
6106 serialize_task.await;
6107 })
6108 }
6109
6110 pub fn root_paths(&self, cx: &App) -> Vec<Arc<Path>> {
6111 let project = self.project().read(cx);
6112 project
6113 .visible_worktrees(cx)
6114 .map(|worktree| worktree.read(cx).abs_path())
6115 .collect::<Vec<_>>()
6116 }
6117
6118 fn remove_panes(&mut self, member: Member, window: &mut Window, cx: &mut Context<Workspace>) {
6119 match member {
6120 Member::Axis(PaneAxis { members, .. }) => {
6121 for child in members.iter() {
6122 self.remove_panes(child.clone(), window, cx)
6123 }
6124 }
6125 Member::Pane(pane) => {
6126 self.force_remove_pane(&pane, &None, window, cx);
6127 }
6128 }
6129 }
6130
6131 fn remove_from_session(&mut self, window: &mut Window, cx: &mut App) -> Task<()> {
6132 self.session_id.take();
6133 self.serialize_workspace_internal(window, cx)
6134 }
6135
6136 fn force_remove_pane(
6137 &mut self,
6138 pane: &Entity<Pane>,
6139 focus_on: &Option<Entity<Pane>>,
6140 window: &mut Window,
6141 cx: &mut Context<Workspace>,
6142 ) {
6143 self.panes.retain(|p| p != pane);
6144 if let Some(focus_on) = focus_on {
6145 focus_on.update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6146 } else if self.active_pane() == pane {
6147 self.panes
6148 .last()
6149 .unwrap()
6150 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6151 }
6152 if self.last_active_center_pane == Some(pane.downgrade()) {
6153 self.last_active_center_pane = None;
6154 }
6155 cx.notify();
6156 }
6157
6158 fn serialize_workspace(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6159 if self._schedule_serialize_workspace.is_none() {
6160 self._schedule_serialize_workspace =
6161 Some(cx.spawn_in(window, async move |this, cx| {
6162 cx.background_executor()
6163 .timer(SERIALIZATION_THROTTLE_TIME)
6164 .await;
6165 this.update_in(cx, |this, window, cx| {
6166 this._serialize_workspace_task =
6167 Some(this.serialize_workspace_internal(window, cx));
6168 this._schedule_serialize_workspace.take();
6169 })
6170 .log_err();
6171 }));
6172 }
6173 }
6174
6175 fn serialize_workspace_internal(&self, window: &mut Window, cx: &mut App) -> Task<()> {
6176 let Some(database_id) = self.database_id() else {
6177 return Task::ready(());
6178 };
6179
6180 fn serialize_pane_handle(
6181 pane_handle: &Entity<Pane>,
6182 window: &mut Window,
6183 cx: &mut App,
6184 ) -> SerializedPane {
6185 let (items, active, pinned_count) = {
6186 let pane = pane_handle.read(cx);
6187 let active_item_id = pane.active_item().map(|item| item.item_id());
6188 (
6189 pane.items()
6190 .filter_map(|handle| {
6191 let handle = handle.to_serializable_item_handle(cx)?;
6192
6193 Some(SerializedItem {
6194 kind: Arc::from(handle.serialized_item_kind()),
6195 item_id: handle.item_id().as_u64(),
6196 active: Some(handle.item_id()) == active_item_id,
6197 preview: pane.is_active_preview_item(handle.item_id()),
6198 })
6199 })
6200 .collect::<Vec<_>>(),
6201 pane.has_focus(window, cx),
6202 pane.pinned_count(),
6203 )
6204 };
6205
6206 SerializedPane::new(items, active, pinned_count)
6207 }
6208
6209 fn build_serialized_pane_group(
6210 pane_group: &Member,
6211 window: &mut Window,
6212 cx: &mut App,
6213 ) -> SerializedPaneGroup {
6214 match pane_group {
6215 Member::Axis(PaneAxis {
6216 axis,
6217 members,
6218 flexes,
6219 bounding_boxes: _,
6220 }) => SerializedPaneGroup::Group {
6221 axis: SerializedAxis(*axis),
6222 children: members
6223 .iter()
6224 .map(|member| build_serialized_pane_group(member, window, cx))
6225 .collect::<Vec<_>>(),
6226 flexes: Some(flexes.lock().clone()),
6227 },
6228 Member::Pane(pane_handle) => {
6229 SerializedPaneGroup::Pane(serialize_pane_handle(pane_handle, window, cx))
6230 }
6231 }
6232 }
6233
6234 fn build_serialized_docks(
6235 this: &Workspace,
6236 window: &mut Window,
6237 cx: &mut App,
6238 ) -> DockStructure {
6239 this.capture_dock_state(window, cx)
6240 }
6241
6242 match self.workspace_location(cx) {
6243 WorkspaceLocation::Location(location, paths) => {
6244 let breakpoints = self.project.update(cx, |project, cx| {
6245 project
6246 .breakpoint_store()
6247 .read(cx)
6248 .all_source_breakpoints(cx)
6249 });
6250 let user_toolchains = self
6251 .project
6252 .read(cx)
6253 .user_toolchains(cx)
6254 .unwrap_or_default();
6255
6256 let center_group = build_serialized_pane_group(&self.center.root, window, cx);
6257 let docks = build_serialized_docks(self, window, cx);
6258 let window_bounds = Some(SerializedWindowBounds(window.window_bounds()));
6259
6260 let serialized_workspace = SerializedWorkspace {
6261 id: database_id,
6262 location,
6263 paths,
6264 center_group,
6265 window_bounds,
6266 display: Default::default(),
6267 docks,
6268 centered_layout: self.centered_layout,
6269 session_id: self.session_id.clone(),
6270 breakpoints,
6271 window_id: Some(window.window_handle().window_id().as_u64()),
6272 user_toolchains,
6273 };
6274
6275 let db = WorkspaceDb::global(cx);
6276 window.spawn(cx, async move |_| {
6277 db.save_workspace(serialized_workspace).await;
6278 })
6279 }
6280 WorkspaceLocation::DetachFromSession => {
6281 let window_bounds = SerializedWindowBounds(window.window_bounds());
6282 let display = window.display(cx).and_then(|d| d.uuid().ok());
6283 // Save dock state for empty local workspaces
6284 let docks = build_serialized_docks(self, window, cx);
6285 let db = WorkspaceDb::global(cx);
6286 let kvp = db::kvp::KeyValueStore::global(cx);
6287 window.spawn(cx, async move |_| {
6288 db.set_window_open_status(
6289 database_id,
6290 window_bounds,
6291 display.unwrap_or_default(),
6292 )
6293 .await
6294 .log_err();
6295 db.set_session_id(database_id, None).await.log_err();
6296 persistence::write_default_dock_state(&kvp, docks)
6297 .await
6298 .log_err();
6299 })
6300 }
6301 WorkspaceLocation::None => {
6302 // Save dock state for empty non-local workspaces
6303 let docks = build_serialized_docks(self, window, cx);
6304 let kvp = db::kvp::KeyValueStore::global(cx);
6305 window.spawn(cx, async move |_| {
6306 persistence::write_default_dock_state(&kvp, docks)
6307 .await
6308 .log_err();
6309 })
6310 }
6311 }
6312 }
6313
6314 fn has_any_items_open(&self, cx: &App) -> bool {
6315 self.panes.iter().any(|pane| pane.read(cx).items_len() > 0)
6316 }
6317
6318 fn workspace_location(&self, cx: &App) -> WorkspaceLocation {
6319 let paths = PathList::new(&self.root_paths(cx));
6320 if let Some(connection) = self.project.read(cx).remote_connection_options(cx) {
6321 WorkspaceLocation::Location(SerializedWorkspaceLocation::Remote(connection), paths)
6322 } else if self.project.read(cx).is_local() {
6323 if !paths.is_empty() || self.has_any_items_open(cx) {
6324 WorkspaceLocation::Location(SerializedWorkspaceLocation::Local, paths)
6325 } else {
6326 WorkspaceLocation::DetachFromSession
6327 }
6328 } else {
6329 WorkspaceLocation::None
6330 }
6331 }
6332
6333 fn update_history(&self, cx: &mut App) {
6334 let Some(id) = self.database_id() else {
6335 return;
6336 };
6337 if !self.project.read(cx).is_local() {
6338 return;
6339 }
6340 if let Some(manager) = HistoryManager::global(cx) {
6341 let paths = PathList::new(&self.root_paths(cx));
6342 manager.update(cx, |this, cx| {
6343 this.update_history(id, HistoryManagerEntry::new(id, &paths), cx);
6344 });
6345 }
6346 }
6347
6348 async fn serialize_items(
6349 this: &WeakEntity<Self>,
6350 items_rx: UnboundedReceiver<Box<dyn SerializableItemHandle>>,
6351 cx: &mut AsyncWindowContext,
6352 ) -> Result<()> {
6353 const CHUNK_SIZE: usize = 200;
6354
6355 let mut serializable_items = items_rx.ready_chunks(CHUNK_SIZE);
6356
6357 while let Some(items_received) = serializable_items.next().await {
6358 let unique_items =
6359 items_received
6360 .into_iter()
6361 .fold(HashMap::default(), |mut acc, item| {
6362 acc.entry(item.item_id()).or_insert(item);
6363 acc
6364 });
6365
6366 // We use into_iter() here so that the references to the items are moved into
6367 // the tasks and not kept alive while we're sleeping.
6368 for (_, item) in unique_items.into_iter() {
6369 if let Ok(Some(task)) = this.update_in(cx, |workspace, window, cx| {
6370 item.serialize(workspace, false, window, cx)
6371 }) {
6372 cx.background_spawn(async move { task.await.log_err() })
6373 .detach();
6374 }
6375 }
6376
6377 cx.background_executor()
6378 .timer(SERIALIZATION_THROTTLE_TIME)
6379 .await;
6380 }
6381
6382 Ok(())
6383 }
6384
6385 pub(crate) fn enqueue_item_serialization(
6386 &mut self,
6387 item: Box<dyn SerializableItemHandle>,
6388 ) -> Result<()> {
6389 self.serializable_items_tx
6390 .unbounded_send(item)
6391 .map_err(|err| anyhow!("failed to send serializable item over channel: {err}"))
6392 }
6393
6394 pub(crate) fn load_workspace(
6395 serialized_workspace: SerializedWorkspace,
6396 paths_to_open: Vec<Option<ProjectPath>>,
6397 window: &mut Window,
6398 cx: &mut Context<Workspace>,
6399 ) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
6400 cx.spawn_in(window, async move |workspace, cx| {
6401 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
6402
6403 let mut center_group = None;
6404 let mut center_items = None;
6405
6406 // Traverse the splits tree and add to things
6407 if let Some((group, active_pane, items)) = serialized_workspace
6408 .center_group
6409 .deserialize(&project, serialized_workspace.id, workspace.clone(), cx)
6410 .await
6411 {
6412 center_items = Some(items);
6413 center_group = Some((group, active_pane))
6414 }
6415
6416 let mut items_by_project_path = HashMap::default();
6417 let mut item_ids_by_kind = HashMap::default();
6418 let mut all_deserialized_items = Vec::default();
6419 cx.update(|_, cx| {
6420 for item in center_items.unwrap_or_default().into_iter().flatten() {
6421 if let Some(serializable_item_handle) = item.to_serializable_item_handle(cx) {
6422 item_ids_by_kind
6423 .entry(serializable_item_handle.serialized_item_kind())
6424 .or_insert(Vec::new())
6425 .push(item.item_id().as_u64() as ItemId);
6426 }
6427
6428 if let Some(project_path) = item.project_path(cx) {
6429 items_by_project_path.insert(project_path, item.clone());
6430 }
6431 all_deserialized_items.push(item);
6432 }
6433 })?;
6434
6435 let opened_items = paths_to_open
6436 .into_iter()
6437 .map(|path_to_open| {
6438 path_to_open
6439 .and_then(|path_to_open| items_by_project_path.remove(&path_to_open))
6440 })
6441 .collect::<Vec<_>>();
6442
6443 // Remove old panes from workspace panes list
6444 workspace.update_in(cx, |workspace, window, cx| {
6445 if let Some((center_group, active_pane)) = center_group {
6446 workspace.remove_panes(workspace.center.root.clone(), window, cx);
6447
6448 // Swap workspace center group
6449 workspace.center = PaneGroup::with_root(center_group);
6450 workspace.center.set_is_center(true);
6451 workspace.center.mark_positions(cx);
6452
6453 if let Some(active_pane) = active_pane {
6454 workspace.set_active_pane(&active_pane, window, cx);
6455 cx.focus_self(window);
6456 } else {
6457 workspace.set_active_pane(&workspace.center.first_pane(), window, cx);
6458 }
6459 }
6460
6461 let docks = serialized_workspace.docks;
6462
6463 for (dock, serialized_dock) in [
6464 (&mut workspace.right_dock, docks.right),
6465 (&mut workspace.left_dock, docks.left),
6466 (&mut workspace.bottom_dock, docks.bottom),
6467 ]
6468 .iter_mut()
6469 {
6470 dock.update(cx, |dock, cx| {
6471 dock.serialized_dock = Some(serialized_dock.clone());
6472 dock.restore_state(window, cx);
6473 });
6474 }
6475
6476 cx.notify();
6477 })?;
6478
6479 let _ = project
6480 .update(cx, |project, cx| {
6481 project
6482 .breakpoint_store()
6483 .update(cx, |breakpoint_store, cx| {
6484 breakpoint_store
6485 .with_serialized_breakpoints(serialized_workspace.breakpoints, cx)
6486 })
6487 })
6488 .await;
6489
6490 // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means
6491 // after loading the items, we might have different items and in order to avoid
6492 // the database filling up, we delete items that haven't been loaded now.
6493 //
6494 // The items that have been loaded, have been saved after they've been added to the workspace.
6495 let clean_up_tasks = workspace.update_in(cx, |_, window, cx| {
6496 item_ids_by_kind
6497 .into_iter()
6498 .map(|(item_kind, loaded_items)| {
6499 SerializableItemRegistry::cleanup(
6500 item_kind,
6501 serialized_workspace.id,
6502 loaded_items,
6503 window,
6504 cx,
6505 )
6506 .log_err()
6507 })
6508 .collect::<Vec<_>>()
6509 })?;
6510
6511 futures::future::join_all(clean_up_tasks).await;
6512
6513 workspace
6514 .update_in(cx, |workspace, window, cx| {
6515 // Serialize ourself to make sure our timestamps and any pane / item changes are replicated
6516 workspace.serialize_workspace_internal(window, cx).detach();
6517
6518 // Ensure that we mark the window as edited if we did load dirty items
6519 workspace.update_window_edited(window, cx);
6520 })
6521 .ok();
6522
6523 Ok(opened_items)
6524 })
6525 }
6526
6527 pub fn key_context(&self, cx: &App) -> KeyContext {
6528 let mut context = KeyContext::new_with_defaults();
6529 context.add("Workspace");
6530 context.set("keyboard_layout", cx.keyboard_layout().name().to_string());
6531 if let Some(status) = self
6532 .debugger_provider
6533 .as_ref()
6534 .and_then(|provider| provider.active_thread_state(cx))
6535 {
6536 match status {
6537 ThreadStatus::Running | ThreadStatus::Stepping => {
6538 context.add("debugger_running");
6539 }
6540 ThreadStatus::Stopped => context.add("debugger_stopped"),
6541 ThreadStatus::Exited | ThreadStatus::Ended => {}
6542 }
6543 }
6544
6545 if self.left_dock.read(cx).is_open() {
6546 if let Some(active_panel) = self.left_dock.read(cx).active_panel() {
6547 context.set("left_dock", active_panel.panel_key());
6548 }
6549 }
6550
6551 if self.right_dock.read(cx).is_open() {
6552 if let Some(active_panel) = self.right_dock.read(cx).active_panel() {
6553 context.set("right_dock", active_panel.panel_key());
6554 }
6555 }
6556
6557 if self.bottom_dock.read(cx).is_open() {
6558 if let Some(active_panel) = self.bottom_dock.read(cx).active_panel() {
6559 context.set("bottom_dock", active_panel.panel_key());
6560 }
6561 }
6562
6563 context
6564 }
6565
6566 /// Multiworkspace uses this to add workspace action handling to itself
6567 pub fn actions(&self, div: Div, window: &mut Window, cx: &mut Context<Self>) -> Div {
6568 self.add_workspace_actions_listeners(div, window, cx)
6569 .on_action(cx.listener(
6570 |_workspace, action_sequence: &settings::ActionSequence, window, cx| {
6571 for action in &action_sequence.0 {
6572 window.dispatch_action(action.boxed_clone(), cx);
6573 }
6574 },
6575 ))
6576 .on_action(cx.listener(Self::close_inactive_items_and_panes))
6577 .on_action(cx.listener(Self::close_all_items_and_panes))
6578 .on_action(cx.listener(Self::close_item_in_all_panes))
6579 .on_action(cx.listener(Self::save_all))
6580 .on_action(cx.listener(Self::send_keystrokes))
6581 .on_action(cx.listener(Self::add_folder_to_project))
6582 .on_action(cx.listener(Self::follow_next_collaborator))
6583 .on_action(cx.listener(Self::activate_pane_at_index))
6584 .on_action(cx.listener(Self::move_item_to_pane_at_index))
6585 .on_action(cx.listener(Self::move_focused_panel_to_next_position))
6586 .on_action(cx.listener(Self::toggle_edit_predictions_all_files))
6587 .on_action(cx.listener(Self::toggle_theme_mode))
6588 .on_action(cx.listener(|workspace, _: &Unfollow, window, cx| {
6589 let pane = workspace.active_pane().clone();
6590 workspace.unfollow_in_pane(&pane, window, cx);
6591 }))
6592 .on_action(cx.listener(|workspace, action: &Save, window, cx| {
6593 workspace
6594 .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), window, cx)
6595 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6596 }))
6597 .on_action(cx.listener(|workspace, _: &SaveWithoutFormat, window, cx| {
6598 workspace
6599 .save_active_item(SaveIntent::SaveWithoutFormat, window, cx)
6600 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6601 }))
6602 .on_action(cx.listener(|workspace, _: &SaveAs, window, cx| {
6603 workspace
6604 .save_active_item(SaveIntent::SaveAs, window, cx)
6605 .detach_and_prompt_err("Failed to save", window, cx, |_, _, _| None);
6606 }))
6607 .on_action(
6608 cx.listener(|workspace, _: &ActivatePreviousPane, window, cx| {
6609 workspace.activate_previous_pane(window, cx)
6610 }),
6611 )
6612 .on_action(cx.listener(|workspace, _: &ActivateNextPane, window, cx| {
6613 workspace.activate_next_pane(window, cx)
6614 }))
6615 .on_action(cx.listener(|workspace, _: &ActivateLastPane, window, cx| {
6616 workspace.activate_last_pane(window, cx)
6617 }))
6618 .on_action(
6619 cx.listener(|workspace, _: &ActivateNextWindow, _window, cx| {
6620 workspace.activate_next_window(cx)
6621 }),
6622 )
6623 .on_action(
6624 cx.listener(|workspace, _: &ActivatePreviousWindow, _window, cx| {
6625 workspace.activate_previous_window(cx)
6626 }),
6627 )
6628 .on_action(cx.listener(|workspace, _: &ActivatePaneLeft, window, cx| {
6629 workspace.activate_pane_in_direction(SplitDirection::Left, window, cx)
6630 }))
6631 .on_action(cx.listener(|workspace, _: &ActivatePaneRight, window, cx| {
6632 workspace.activate_pane_in_direction(SplitDirection::Right, window, cx)
6633 }))
6634 .on_action(cx.listener(|workspace, _: &ActivatePaneUp, window, cx| {
6635 workspace.activate_pane_in_direction(SplitDirection::Up, window, cx)
6636 }))
6637 .on_action(cx.listener(|workspace, _: &ActivatePaneDown, window, cx| {
6638 workspace.activate_pane_in_direction(SplitDirection::Down, window, cx)
6639 }))
6640 .on_action(cx.listener(
6641 |workspace, action: &MoveItemToPaneInDirection, window, cx| {
6642 workspace.move_item_to_pane_in_direction(action, window, cx)
6643 },
6644 ))
6645 .on_action(cx.listener(|workspace, _: &SwapPaneLeft, _, cx| {
6646 workspace.swap_pane_in_direction(SplitDirection::Left, cx)
6647 }))
6648 .on_action(cx.listener(|workspace, _: &SwapPaneRight, _, cx| {
6649 workspace.swap_pane_in_direction(SplitDirection::Right, cx)
6650 }))
6651 .on_action(cx.listener(|workspace, _: &SwapPaneUp, _, cx| {
6652 workspace.swap_pane_in_direction(SplitDirection::Up, cx)
6653 }))
6654 .on_action(cx.listener(|workspace, _: &SwapPaneDown, _, cx| {
6655 workspace.swap_pane_in_direction(SplitDirection::Down, cx)
6656 }))
6657 .on_action(cx.listener(|workspace, _: &SwapPaneAdjacent, window, cx| {
6658 const DIRECTION_PRIORITY: [SplitDirection; 4] = [
6659 SplitDirection::Down,
6660 SplitDirection::Up,
6661 SplitDirection::Right,
6662 SplitDirection::Left,
6663 ];
6664 for dir in DIRECTION_PRIORITY {
6665 if workspace.find_pane_in_direction(dir, cx).is_some() {
6666 workspace.swap_pane_in_direction(dir, cx);
6667 workspace.activate_pane_in_direction(dir.opposite(), window, cx);
6668 break;
6669 }
6670 }
6671 }))
6672 .on_action(cx.listener(|workspace, _: &MovePaneLeft, _, cx| {
6673 workspace.move_pane_to_border(SplitDirection::Left, cx)
6674 }))
6675 .on_action(cx.listener(|workspace, _: &MovePaneRight, _, cx| {
6676 workspace.move_pane_to_border(SplitDirection::Right, cx)
6677 }))
6678 .on_action(cx.listener(|workspace, _: &MovePaneUp, _, cx| {
6679 workspace.move_pane_to_border(SplitDirection::Up, cx)
6680 }))
6681 .on_action(cx.listener(|workspace, _: &MovePaneDown, _, cx| {
6682 workspace.move_pane_to_border(SplitDirection::Down, cx)
6683 }))
6684 .on_action(cx.listener(|this, _: &ToggleLeftDock, window, cx| {
6685 this.toggle_dock(DockPosition::Left, window, cx);
6686 }))
6687 .on_action(cx.listener(
6688 |workspace: &mut Workspace, _: &ToggleRightDock, window, cx| {
6689 workspace.toggle_dock(DockPosition::Right, window, cx);
6690 },
6691 ))
6692 .on_action(cx.listener(
6693 |workspace: &mut Workspace, _: &ToggleBottomDock, window, cx| {
6694 workspace.toggle_dock(DockPosition::Bottom, window, cx);
6695 },
6696 ))
6697 .on_action(cx.listener(
6698 |workspace: &mut Workspace, _: &CloseActiveDock, window, cx| {
6699 if !workspace.close_active_dock(window, cx) {
6700 cx.propagate();
6701 }
6702 },
6703 ))
6704 .on_action(
6705 cx.listener(|workspace: &mut Workspace, _: &CloseAllDocks, window, cx| {
6706 workspace.close_all_docks(window, cx);
6707 }),
6708 )
6709 .on_action(cx.listener(Self::toggle_all_docks))
6710 .on_action(cx.listener(
6711 |workspace: &mut Workspace, _: &ClearAllNotifications, _, cx| {
6712 workspace.clear_all_notifications(cx);
6713 },
6714 ))
6715 .on_action(cx.listener(
6716 |workspace: &mut Workspace, _: &ClearNavigationHistory, window, cx| {
6717 workspace.clear_navigation_history(window, cx);
6718 },
6719 ))
6720 .on_action(cx.listener(
6721 |workspace: &mut Workspace, _: &SuppressNotification, _, cx| {
6722 if let Some((notification_id, _)) = workspace.notifications.pop() {
6723 workspace.suppress_notification(¬ification_id, cx);
6724 }
6725 },
6726 ))
6727 .on_action(cx.listener(
6728 |workspace: &mut Workspace, _: &ToggleWorktreeSecurity, window, cx| {
6729 workspace.show_worktree_trust_security_modal(true, window, cx);
6730 },
6731 ))
6732 .on_action(
6733 cx.listener(|_: &mut Workspace, _: &ClearTrustedWorktrees, _, cx| {
6734 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
6735 trusted_worktrees.update(cx, |trusted_worktrees, _| {
6736 trusted_worktrees.clear_trusted_paths()
6737 });
6738 let db = WorkspaceDb::global(cx);
6739 cx.spawn(async move |_, cx| {
6740 if db.clear_trusted_worktrees().await.log_err().is_some() {
6741 cx.update(|cx| reload(cx));
6742 }
6743 })
6744 .detach();
6745 }
6746 }),
6747 )
6748 .on_action(cx.listener(
6749 |workspace: &mut Workspace, _: &ReopenClosedItem, window, cx| {
6750 workspace.reopen_closed_item(window, cx).detach();
6751 },
6752 ))
6753 .on_action(cx.listener(
6754 |workspace: &mut Workspace, _: &ResetActiveDockSize, window, cx| {
6755 for dock in workspace.all_docks() {
6756 if dock.focus_handle(cx).contains_focused(window, cx) {
6757 let Some(panel) = dock.read(cx).active_panel() else {
6758 return;
6759 };
6760
6761 // Set to `None`, then the size will fall back to the default.
6762 panel.clone().set_size(None, window, cx);
6763
6764 return;
6765 }
6766 }
6767 },
6768 ))
6769 .on_action(cx.listener(
6770 |workspace: &mut Workspace, _: &ResetOpenDocksSize, window, cx| {
6771 for dock in workspace.all_docks() {
6772 if let Some(panel) = dock.read(cx).visible_panel() {
6773 // Set to `None`, then the size will fall back to the default.
6774 panel.clone().set_size(None, window, cx);
6775 }
6776 }
6777 },
6778 ))
6779 .on_action(cx.listener(
6780 |workspace: &mut Workspace, act: &IncreaseActiveDockSize, window, cx| {
6781 adjust_active_dock_size_by_px(
6782 px_with_ui_font_fallback(act.px, cx),
6783 workspace,
6784 window,
6785 cx,
6786 );
6787 },
6788 ))
6789 .on_action(cx.listener(
6790 |workspace: &mut Workspace, act: &DecreaseActiveDockSize, window, cx| {
6791 adjust_active_dock_size_by_px(
6792 px_with_ui_font_fallback(act.px, cx) * -1.,
6793 workspace,
6794 window,
6795 cx,
6796 );
6797 },
6798 ))
6799 .on_action(cx.listener(
6800 |workspace: &mut Workspace, act: &IncreaseOpenDocksSize, window, cx| {
6801 adjust_open_docks_size_by_px(
6802 px_with_ui_font_fallback(act.px, cx),
6803 workspace,
6804 window,
6805 cx,
6806 );
6807 },
6808 ))
6809 .on_action(cx.listener(
6810 |workspace: &mut Workspace, act: &DecreaseOpenDocksSize, window, cx| {
6811 adjust_open_docks_size_by_px(
6812 px_with_ui_font_fallback(act.px, cx) * -1.,
6813 workspace,
6814 window,
6815 cx,
6816 );
6817 },
6818 ))
6819 .on_action(cx.listener(Workspace::toggle_centered_layout))
6820 .on_action(cx.listener(
6821 |workspace: &mut Workspace, _action: &pane::ActivateNextItem, window, cx| {
6822 if let Some(active_dock) = workspace.active_dock(window, cx) {
6823 let dock = active_dock.read(cx);
6824 if let Some(active_panel) = dock.active_panel() {
6825 if active_panel.pane(cx).is_none() {
6826 let mut recent_pane: Option<Entity<Pane>> = None;
6827 let mut recent_timestamp = 0;
6828 for pane_handle in workspace.panes() {
6829 let pane = pane_handle.read(cx);
6830 for entry in pane.activation_history() {
6831 if entry.timestamp > recent_timestamp {
6832 recent_timestamp = entry.timestamp;
6833 recent_pane = Some(pane_handle.clone());
6834 }
6835 }
6836 }
6837
6838 if let Some(pane) = recent_pane {
6839 pane.update(cx, |pane, cx| {
6840 let current_index = pane.active_item_index();
6841 let items_len = pane.items_len();
6842 if items_len > 0 {
6843 let next_index = if current_index + 1 < items_len {
6844 current_index + 1
6845 } else {
6846 0
6847 };
6848 pane.activate_item(
6849 next_index, false, false, window, cx,
6850 );
6851 }
6852 });
6853 return;
6854 }
6855 }
6856 }
6857 }
6858 cx.propagate();
6859 },
6860 ))
6861 .on_action(cx.listener(
6862 |workspace: &mut Workspace, _action: &pane::ActivatePreviousItem, window, cx| {
6863 if let Some(active_dock) = workspace.active_dock(window, cx) {
6864 let dock = active_dock.read(cx);
6865 if let Some(active_panel) = dock.active_panel() {
6866 if active_panel.pane(cx).is_none() {
6867 let mut recent_pane: Option<Entity<Pane>> = None;
6868 let mut recent_timestamp = 0;
6869 for pane_handle in workspace.panes() {
6870 let pane = pane_handle.read(cx);
6871 for entry in pane.activation_history() {
6872 if entry.timestamp > recent_timestamp {
6873 recent_timestamp = entry.timestamp;
6874 recent_pane = Some(pane_handle.clone());
6875 }
6876 }
6877 }
6878
6879 if let Some(pane) = recent_pane {
6880 pane.update(cx, |pane, cx| {
6881 let current_index = pane.active_item_index();
6882 let items_len = pane.items_len();
6883 if items_len > 0 {
6884 let prev_index = if current_index > 0 {
6885 current_index - 1
6886 } else {
6887 items_len.saturating_sub(1)
6888 };
6889 pane.activate_item(
6890 prev_index, false, false, window, cx,
6891 );
6892 }
6893 });
6894 return;
6895 }
6896 }
6897 }
6898 }
6899 cx.propagate();
6900 },
6901 ))
6902 .on_action(cx.listener(
6903 |workspace: &mut Workspace, action: &pane::CloseActiveItem, window, cx| {
6904 if let Some(active_dock) = workspace.active_dock(window, cx) {
6905 let dock = active_dock.read(cx);
6906 if let Some(active_panel) = dock.active_panel() {
6907 if active_panel.pane(cx).is_none() {
6908 let active_pane = workspace.active_pane().clone();
6909 active_pane.update(cx, |pane, cx| {
6910 pane.close_active_item(action, window, cx)
6911 .detach_and_log_err(cx);
6912 });
6913 return;
6914 }
6915 }
6916 }
6917 cx.propagate();
6918 },
6919 ))
6920 .on_action(
6921 cx.listener(|workspace, _: &ToggleReadOnlyFile, window, cx| {
6922 let pane = workspace.active_pane().clone();
6923 if let Some(item) = pane.read(cx).active_item() {
6924 item.toggle_read_only(window, cx);
6925 }
6926 }),
6927 )
6928 .on_action(cx.listener(|workspace, _: &FocusCenterPane, window, cx| {
6929 workspace.focus_center_pane(window, cx);
6930 }))
6931 .on_action(cx.listener(Workspace::cancel))
6932 }
6933
6934 #[cfg(any(test, feature = "test-support"))]
6935 pub fn set_random_database_id(&mut self) {
6936 self.database_id = Some(WorkspaceId(Uuid::new_v4().as_u64_pair().0 as i64));
6937 }
6938
6939 #[cfg(any(test, feature = "test-support"))]
6940 pub(crate) fn test_new(
6941 project: Entity<Project>,
6942 window: &mut Window,
6943 cx: &mut Context<Self>,
6944 ) -> Self {
6945 use node_runtime::NodeRuntime;
6946 use session::Session;
6947
6948 let client = project.read(cx).client();
6949 let user_store = project.read(cx).user_store();
6950 let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
6951 let session = cx.new(|cx| AppSession::new(Session::test(), cx));
6952 window.activate_window();
6953 let app_state = Arc::new(AppState {
6954 languages: project.read(cx).languages().clone(),
6955 workspace_store,
6956 client,
6957 user_store,
6958 fs: project.read(cx).fs().clone(),
6959 build_window_options: |_, _| Default::default(),
6960 node_runtime: NodeRuntime::unavailable(),
6961 session,
6962 });
6963 let workspace = Self::new(Default::default(), project, app_state, window, cx);
6964 workspace
6965 .active_pane
6966 .update(cx, |pane, cx| window.focus(&pane.focus_handle(cx), cx));
6967 workspace
6968 }
6969
6970 pub fn register_action<A: Action>(
6971 &mut self,
6972 callback: impl Fn(&mut Self, &A, &mut Window, &mut Context<Self>) + 'static,
6973 ) -> &mut Self {
6974 let callback = Arc::new(callback);
6975
6976 self.workspace_actions.push(Box::new(move |div, _, _, cx| {
6977 let callback = callback.clone();
6978 div.on_action(cx.listener(move |workspace, event, window, cx| {
6979 (callback)(workspace, event, window, cx)
6980 }))
6981 }));
6982 self
6983 }
6984 pub fn register_action_renderer(
6985 &mut self,
6986 callback: impl Fn(Div, &Workspace, &mut Window, &mut Context<Self>) -> Div + 'static,
6987 ) -> &mut Self {
6988 self.workspace_actions.push(Box::new(callback));
6989 self
6990 }
6991
6992 fn add_workspace_actions_listeners(
6993 &self,
6994 mut div: Div,
6995 window: &mut Window,
6996 cx: &mut Context<Self>,
6997 ) -> Div {
6998 for action in self.workspace_actions.iter() {
6999 div = (action)(div, self, window, cx)
7000 }
7001 div
7002 }
7003
7004 pub fn has_active_modal(&self, _: &mut Window, cx: &mut App) -> bool {
7005 self.modal_layer.read(cx).has_active_modal()
7006 }
7007
7008 pub fn is_active_modal_command_palette(&self, cx: &mut App) -> bool {
7009 self.modal_layer
7010 .read(cx)
7011 .is_active_modal_command_palette(cx)
7012 }
7013
7014 pub fn active_modal<V: ManagedView + 'static>(&self, cx: &App) -> Option<Entity<V>> {
7015 self.modal_layer.read(cx).active_modal()
7016 }
7017
7018 /// Toggles a modal of type `V`. If a modal of the same type is currently active,
7019 /// it will be hidden. If a different modal is active, it will be replaced with the new one.
7020 /// If no modal is active, the new modal will be shown.
7021 ///
7022 /// If closing the current modal fails (e.g., due to `on_before_dismiss` returning
7023 /// `DismissDecision::Dismiss(false)` or `DismissDecision::Pending`), the new modal
7024 /// will not be shown.
7025 pub fn toggle_modal<V: ModalView, B>(&mut self, window: &mut Window, cx: &mut App, build: B)
7026 where
7027 B: FnOnce(&mut Window, &mut Context<V>) -> V,
7028 {
7029 self.modal_layer.update(cx, |modal_layer, cx| {
7030 modal_layer.toggle_modal(window, cx, build)
7031 })
7032 }
7033
7034 pub fn hide_modal(&mut self, window: &mut Window, cx: &mut App) -> bool {
7035 self.modal_layer
7036 .update(cx, |modal_layer, cx| modal_layer.hide_modal(window, cx))
7037 }
7038
7039 pub fn toggle_status_toast<V: ToastView>(&mut self, entity: Entity<V>, cx: &mut App) {
7040 self.toast_layer
7041 .update(cx, |toast_layer, cx| toast_layer.toggle_toast(cx, entity))
7042 }
7043
7044 pub fn toggle_centered_layout(
7045 &mut self,
7046 _: &ToggleCenteredLayout,
7047 _: &mut Window,
7048 cx: &mut Context<Self>,
7049 ) {
7050 self.centered_layout = !self.centered_layout;
7051 if let Some(database_id) = self.database_id() {
7052 let db = WorkspaceDb::global(cx);
7053 let centered_layout = self.centered_layout;
7054 cx.background_spawn(async move {
7055 db.set_centered_layout(database_id, centered_layout).await
7056 })
7057 .detach_and_log_err(cx);
7058 }
7059 cx.notify();
7060 }
7061
7062 fn adjust_padding(padding: Option<f32>) -> f32 {
7063 padding
7064 .unwrap_or(CenteredPaddingSettings::default().0)
7065 .clamp(
7066 CenteredPaddingSettings::MIN_PADDING,
7067 CenteredPaddingSettings::MAX_PADDING,
7068 )
7069 }
7070
7071 fn render_dock(
7072 &self,
7073 position: DockPosition,
7074 dock: &Entity<Dock>,
7075 window: &mut Window,
7076 cx: &mut App,
7077 ) -> Option<Div> {
7078 if self.zoomed_position == Some(position) {
7079 return None;
7080 }
7081
7082 let leader_border = dock.read(cx).active_panel().and_then(|panel| {
7083 let pane = panel.pane(cx)?;
7084 let follower_states = &self.follower_states;
7085 leader_border_for_pane(follower_states, &pane, window, cx)
7086 });
7087
7088 Some(
7089 div()
7090 .flex()
7091 .flex_none()
7092 .overflow_hidden()
7093 .child(dock.clone())
7094 .children(leader_border),
7095 )
7096 }
7097
7098 pub fn for_window(window: &Window, cx: &App) -> Option<Entity<Workspace>> {
7099 window
7100 .root::<MultiWorkspace>()
7101 .flatten()
7102 .map(|multi_workspace| multi_workspace.read(cx).workspace().clone())
7103 }
7104
7105 pub fn zoomed_item(&self) -> Option<&AnyWeakView> {
7106 self.zoomed.as_ref()
7107 }
7108
7109 pub fn activate_next_window(&mut self, cx: &mut Context<Self>) {
7110 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7111 return;
7112 };
7113 let windows = cx.windows();
7114 let next_window =
7115 SystemWindowTabController::get_next_tab_group_window(cx, current_window_id).or_else(
7116 || {
7117 windows
7118 .iter()
7119 .cycle()
7120 .skip_while(|window| window.window_id() != current_window_id)
7121 .nth(1)
7122 },
7123 );
7124
7125 if let Some(window) = next_window {
7126 window
7127 .update(cx, |_, window, _| window.activate_window())
7128 .ok();
7129 }
7130 }
7131
7132 pub fn activate_previous_window(&mut self, cx: &mut Context<Self>) {
7133 let Some(current_window_id) = cx.active_window().map(|a| a.window_id()) else {
7134 return;
7135 };
7136 let windows = cx.windows();
7137 let prev_window =
7138 SystemWindowTabController::get_prev_tab_group_window(cx, current_window_id).or_else(
7139 || {
7140 windows
7141 .iter()
7142 .rev()
7143 .cycle()
7144 .skip_while(|window| window.window_id() != current_window_id)
7145 .nth(1)
7146 },
7147 );
7148
7149 if let Some(window) = prev_window {
7150 window
7151 .update(cx, |_, window, _| window.activate_window())
7152 .ok();
7153 }
7154 }
7155
7156 pub fn cancel(&mut self, _: &menu::Cancel, window: &mut Window, cx: &mut Context<Self>) {
7157 if cx.stop_active_drag(window) {
7158 } else if let Some((notification_id, _)) = self.notifications.pop() {
7159 dismiss_app_notification(¬ification_id, cx);
7160 } else {
7161 cx.propagate();
7162 }
7163 }
7164
7165 fn adjust_dock_size_by_px(
7166 &mut self,
7167 panel_size: Pixels,
7168 dock_pos: DockPosition,
7169 px: Pixels,
7170 window: &mut Window,
7171 cx: &mut Context<Self>,
7172 ) {
7173 match dock_pos {
7174 DockPosition::Left => self.resize_left_dock(panel_size + px, window, cx),
7175 DockPosition::Right => self.resize_right_dock(panel_size + px, window, cx),
7176 DockPosition::Bottom => self.resize_bottom_dock(panel_size + px, window, cx),
7177 }
7178 }
7179
7180 fn resize_left_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7181 let workspace_width = self.bounds.size.width;
7182 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7183
7184 self.right_dock.read_with(cx, |right_dock, cx| {
7185 let right_dock_size = right_dock
7186 .active_panel_size(window, cx)
7187 .unwrap_or(Pixels::ZERO);
7188 if right_dock_size + size > workspace_width {
7189 size = workspace_width - right_dock_size
7190 }
7191 });
7192
7193 self.left_dock.update(cx, |left_dock, cx| {
7194 if WorkspaceSettings::get_global(cx)
7195 .resize_all_panels_in_dock
7196 .contains(&DockPosition::Left)
7197 {
7198 left_dock.resize_all_panels(Some(size), window, cx);
7199 } else {
7200 left_dock.resize_active_panel(Some(size), window, cx);
7201 }
7202 });
7203 }
7204
7205 fn resize_right_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7206 let workspace_width = self.bounds.size.width;
7207 let mut size = new_size.min(workspace_width - RESIZE_HANDLE_SIZE);
7208 self.left_dock.read_with(cx, |left_dock, cx| {
7209 let left_dock_size = left_dock
7210 .active_panel_size(window, cx)
7211 .unwrap_or(Pixels::ZERO);
7212 if left_dock_size + size > workspace_width {
7213 size = workspace_width - left_dock_size
7214 }
7215 });
7216 self.right_dock.update(cx, |right_dock, cx| {
7217 if WorkspaceSettings::get_global(cx)
7218 .resize_all_panels_in_dock
7219 .contains(&DockPosition::Right)
7220 {
7221 right_dock.resize_all_panels(Some(size), window, cx);
7222 } else {
7223 right_dock.resize_active_panel(Some(size), window, cx);
7224 }
7225 });
7226 }
7227
7228 fn resize_bottom_dock(&mut self, new_size: Pixels, window: &mut Window, cx: &mut App) {
7229 let size = new_size.min(self.bounds.bottom() - RESIZE_HANDLE_SIZE - self.bounds.top());
7230 self.bottom_dock.update(cx, |bottom_dock, cx| {
7231 if WorkspaceSettings::get_global(cx)
7232 .resize_all_panels_in_dock
7233 .contains(&DockPosition::Bottom)
7234 {
7235 bottom_dock.resize_all_panels(Some(size), window, cx);
7236 } else {
7237 bottom_dock.resize_active_panel(Some(size), window, cx);
7238 }
7239 });
7240 }
7241
7242 fn toggle_edit_predictions_all_files(
7243 &mut self,
7244 _: &ToggleEditPrediction,
7245 _window: &mut Window,
7246 cx: &mut Context<Self>,
7247 ) {
7248 let fs = self.project().read(cx).fs().clone();
7249 let show_edit_predictions = all_language_settings(None, cx).show_edit_predictions(None, cx);
7250 update_settings_file(fs, cx, move |file, _| {
7251 file.project.all_languages.defaults.show_edit_predictions = Some(!show_edit_predictions)
7252 });
7253 }
7254
7255 fn toggle_theme_mode(&mut self, _: &ToggleMode, _window: &mut Window, cx: &mut Context<Self>) {
7256 let current_mode = ThemeSettings::get_global(cx).theme.mode();
7257 let next_mode = match current_mode {
7258 Some(theme::ThemeAppearanceMode::Light) => theme::ThemeAppearanceMode::Dark,
7259 Some(theme::ThemeAppearanceMode::Dark) => theme::ThemeAppearanceMode::Light,
7260 Some(theme::ThemeAppearanceMode::System) | None => match cx.theme().appearance() {
7261 theme::Appearance::Light => theme::ThemeAppearanceMode::Dark,
7262 theme::Appearance::Dark => theme::ThemeAppearanceMode::Light,
7263 },
7264 };
7265
7266 let fs = self.project().read(cx).fs().clone();
7267 settings::update_settings_file(fs, cx, move |settings, _cx| {
7268 theme::set_mode(settings, next_mode);
7269 });
7270 }
7271
7272 pub fn show_worktree_trust_security_modal(
7273 &mut self,
7274 toggle: bool,
7275 window: &mut Window,
7276 cx: &mut Context<Self>,
7277 ) {
7278 if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
7279 if toggle {
7280 security_modal.update(cx, |security_modal, cx| {
7281 security_modal.dismiss(cx);
7282 })
7283 } else {
7284 security_modal.update(cx, |security_modal, cx| {
7285 security_modal.refresh_restricted_paths(cx);
7286 });
7287 }
7288 } else {
7289 let has_restricted_worktrees = TrustedWorktrees::try_get_global(cx)
7290 .map(|trusted_worktrees| {
7291 trusted_worktrees
7292 .read(cx)
7293 .has_restricted_worktrees(&self.project().read(cx).worktree_store(), cx)
7294 })
7295 .unwrap_or(false);
7296 if has_restricted_worktrees {
7297 let project = self.project().read(cx);
7298 let remote_host = project
7299 .remote_connection_options(cx)
7300 .map(RemoteHostLocation::from);
7301 let worktree_store = project.worktree_store().downgrade();
7302 self.toggle_modal(window, cx, |_, cx| {
7303 SecurityModal::new(worktree_store, remote_host, cx)
7304 });
7305 }
7306 }
7307 }
7308}
7309
7310pub trait AnyActiveCall {
7311 fn entity(&self) -> AnyEntity;
7312 fn is_in_room(&self, _: &App) -> bool;
7313 fn room_id(&self, _: &App) -> Option<u64>;
7314 fn channel_id(&self, _: &App) -> Option<ChannelId>;
7315 fn hang_up(&self, _: &mut App) -> Task<Result<()>>;
7316 fn unshare_project(&self, _: Entity<Project>, _: &mut App) -> Result<()>;
7317 fn remote_participant_for_peer_id(&self, _: PeerId, _: &App) -> Option<RemoteCollaborator>;
7318 fn is_sharing_project(&self, _: &App) -> bool;
7319 fn has_remote_participants(&self, _: &App) -> bool;
7320 fn local_participant_is_guest(&self, _: &App) -> bool;
7321 fn client(&self, _: &App) -> Arc<Client>;
7322 fn share_on_join(&self, _: &App) -> bool;
7323 fn join_channel(&self, _: ChannelId, _: &mut App) -> Task<Result<bool>>;
7324 fn room_update_completed(&self, _: &mut App) -> Task<()>;
7325 fn most_active_project(&self, _: &App) -> Option<(u64, u64)>;
7326 fn share_project(&self, _: Entity<Project>, _: &mut App) -> Task<Result<u64>>;
7327 fn join_project(
7328 &self,
7329 _: u64,
7330 _: Arc<LanguageRegistry>,
7331 _: Arc<dyn Fs>,
7332 _: &mut App,
7333 ) -> Task<Result<Entity<Project>>>;
7334 fn peer_id_for_user_in_room(&self, _: u64, _: &App) -> Option<PeerId>;
7335 fn subscribe(
7336 &self,
7337 _: &mut Window,
7338 _: &mut Context<Workspace>,
7339 _: Box<dyn Fn(&mut Workspace, &ActiveCallEvent, &mut Window, &mut Context<Workspace>)>,
7340 ) -> Subscription;
7341 fn create_shared_screen(
7342 &self,
7343 _: PeerId,
7344 _: &Entity<Pane>,
7345 _: &mut Window,
7346 _: &mut App,
7347 ) -> Option<Entity<SharedScreen>>;
7348}
7349
7350#[derive(Clone)]
7351pub struct GlobalAnyActiveCall(pub Arc<dyn AnyActiveCall>);
7352impl Global for GlobalAnyActiveCall {}
7353
7354impl GlobalAnyActiveCall {
7355 pub(crate) fn try_global(cx: &App) -> Option<&Self> {
7356 cx.try_global()
7357 }
7358
7359 pub(crate) fn global(cx: &App) -> &Self {
7360 cx.global()
7361 }
7362}
7363
7364pub fn merge_conflict_notification_id() -> NotificationId {
7365 struct MergeConflictNotification;
7366 NotificationId::unique::<MergeConflictNotification>()
7367}
7368
7369/// Workspace-local view of a remote participant's location.
7370#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7371pub enum ParticipantLocation {
7372 SharedProject { project_id: u64 },
7373 UnsharedProject,
7374 External,
7375}
7376
7377impl ParticipantLocation {
7378 pub fn from_proto(location: Option<proto::ParticipantLocation>) -> Result<Self> {
7379 match location
7380 .and_then(|l| l.variant)
7381 .context("participant location was not provided")?
7382 {
7383 proto::participant_location::Variant::SharedProject(project) => {
7384 Ok(Self::SharedProject {
7385 project_id: project.id,
7386 })
7387 }
7388 proto::participant_location::Variant::UnsharedProject(_) => Ok(Self::UnsharedProject),
7389 proto::participant_location::Variant::External(_) => Ok(Self::External),
7390 }
7391 }
7392}
7393/// Workspace-local view of a remote collaborator's state.
7394/// This is the subset of `call::RemoteParticipant` that workspace needs.
7395#[derive(Clone)]
7396pub struct RemoteCollaborator {
7397 pub user: Arc<User>,
7398 pub peer_id: PeerId,
7399 pub location: ParticipantLocation,
7400 pub participant_index: ParticipantIndex,
7401}
7402
7403pub enum ActiveCallEvent {
7404 ParticipantLocationChanged { participant_id: PeerId },
7405 RemoteVideoTracksChanged { participant_id: PeerId },
7406}
7407
7408fn leader_border_for_pane(
7409 follower_states: &HashMap<CollaboratorId, FollowerState>,
7410 pane: &Entity<Pane>,
7411 _: &Window,
7412 cx: &App,
7413) -> Option<Div> {
7414 let (leader_id, _follower_state) = follower_states.iter().find_map(|(leader_id, state)| {
7415 if state.pane() == pane {
7416 Some((*leader_id, state))
7417 } else {
7418 None
7419 }
7420 })?;
7421
7422 let mut leader_color = match leader_id {
7423 CollaboratorId::PeerId(leader_peer_id) => {
7424 let leader = GlobalAnyActiveCall::try_global(cx)?
7425 .0
7426 .remote_participant_for_peer_id(leader_peer_id, cx)?;
7427
7428 cx.theme()
7429 .players()
7430 .color_for_participant(leader.participant_index.0)
7431 .cursor
7432 }
7433 CollaboratorId::Agent => cx.theme().players().agent().cursor,
7434 };
7435 leader_color.fade_out(0.3);
7436 Some(
7437 div()
7438 .absolute()
7439 .size_full()
7440 .left_0()
7441 .top_0()
7442 .border_2()
7443 .border_color(leader_color),
7444 )
7445}
7446
7447fn window_bounds_env_override() -> Option<Bounds<Pixels>> {
7448 ZED_WINDOW_POSITION
7449 .zip(*ZED_WINDOW_SIZE)
7450 .map(|(position, size)| Bounds {
7451 origin: position,
7452 size,
7453 })
7454}
7455
7456fn open_items(
7457 serialized_workspace: Option<SerializedWorkspace>,
7458 mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
7459 window: &mut Window,
7460 cx: &mut Context<Workspace>,
7461) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
7462 let restored_items = serialized_workspace.map(|serialized_workspace| {
7463 Workspace::load_workspace(
7464 serialized_workspace,
7465 project_paths_to_open
7466 .iter()
7467 .map(|(_, project_path)| project_path)
7468 .cloned()
7469 .collect(),
7470 window,
7471 cx,
7472 )
7473 });
7474
7475 cx.spawn_in(window, async move |workspace, cx| {
7476 let mut opened_items = Vec::with_capacity(project_paths_to_open.len());
7477
7478 if let Some(restored_items) = restored_items {
7479 let restored_items = restored_items.await?;
7480
7481 let restored_project_paths = restored_items
7482 .iter()
7483 .filter_map(|item| {
7484 cx.update(|_, cx| item.as_ref()?.project_path(cx))
7485 .ok()
7486 .flatten()
7487 })
7488 .collect::<HashSet<_>>();
7489
7490 for restored_item in restored_items {
7491 opened_items.push(restored_item.map(Ok));
7492 }
7493
7494 project_paths_to_open
7495 .iter_mut()
7496 .for_each(|(_, project_path)| {
7497 if let Some(project_path_to_open) = project_path
7498 && restored_project_paths.contains(project_path_to_open)
7499 {
7500 *project_path = None;
7501 }
7502 });
7503 } else {
7504 for _ in 0..project_paths_to_open.len() {
7505 opened_items.push(None);
7506 }
7507 }
7508 assert!(opened_items.len() == project_paths_to_open.len());
7509
7510 let tasks =
7511 project_paths_to_open
7512 .into_iter()
7513 .enumerate()
7514 .map(|(ix, (abs_path, project_path))| {
7515 let workspace = workspace.clone();
7516 cx.spawn(async move |cx| {
7517 let file_project_path = project_path?;
7518 let abs_path_task = workspace.update(cx, |workspace, cx| {
7519 workspace.project().update(cx, |project, cx| {
7520 project.resolve_abs_path(abs_path.to_string_lossy().as_ref(), cx)
7521 })
7522 });
7523
7524 // We only want to open file paths here. If one of the items
7525 // here is a directory, it was already opened further above
7526 // with a `find_or_create_worktree`.
7527 if let Ok(task) = abs_path_task
7528 && task.await.is_none_or(|p| p.is_file())
7529 {
7530 return Some((
7531 ix,
7532 workspace
7533 .update_in(cx, |workspace, window, cx| {
7534 workspace.open_path(
7535 file_project_path,
7536 None,
7537 true,
7538 window,
7539 cx,
7540 )
7541 })
7542 .log_err()?
7543 .await,
7544 ));
7545 }
7546 None
7547 })
7548 });
7549
7550 let tasks = tasks.collect::<Vec<_>>();
7551
7552 let tasks = futures::future::join_all(tasks);
7553 for (ix, path_open_result) in tasks.await.into_iter().flatten() {
7554 opened_items[ix] = Some(path_open_result);
7555 }
7556
7557 Ok(opened_items)
7558 })
7559}
7560
7561#[derive(Clone)]
7562enum ActivateInDirectionTarget {
7563 Pane(Entity<Pane>),
7564 Dock(Entity<Dock>),
7565 Sidebar(FocusHandle),
7566}
7567
7568fn notify_if_database_failed(window: WindowHandle<MultiWorkspace>, cx: &mut AsyncApp) {
7569 window
7570 .update(cx, |multi_workspace, _, cx| {
7571 let workspace = multi_workspace.workspace().clone();
7572 workspace.update(cx, |workspace, cx| {
7573 if (*db::ALL_FILE_DB_FAILED).load(std::sync::atomic::Ordering::Acquire) {
7574 struct DatabaseFailedNotification;
7575
7576 workspace.show_notification(
7577 NotificationId::unique::<DatabaseFailedNotification>(),
7578 cx,
7579 |cx| {
7580 cx.new(|cx| {
7581 MessageNotification::new("Failed to load the database file.", cx)
7582 .primary_message("File an Issue")
7583 .primary_icon(IconName::Plus)
7584 .primary_on_click(|window, cx| {
7585 window.dispatch_action(Box::new(FileBugReport), cx)
7586 })
7587 })
7588 },
7589 );
7590 }
7591 });
7592 })
7593 .log_err();
7594}
7595
7596fn px_with_ui_font_fallback(val: u32, cx: &Context<Workspace>) -> Pixels {
7597 if val == 0 {
7598 ThemeSettings::get_global(cx).ui_font_size(cx)
7599 } else {
7600 px(val as f32)
7601 }
7602}
7603
7604fn adjust_active_dock_size_by_px(
7605 px: Pixels,
7606 workspace: &mut Workspace,
7607 window: &mut Window,
7608 cx: &mut Context<Workspace>,
7609) {
7610 let Some(active_dock) = workspace
7611 .all_docks()
7612 .into_iter()
7613 .find(|dock| dock.focus_handle(cx).contains_focused(window, cx))
7614 else {
7615 return;
7616 };
7617 let dock = active_dock.read(cx);
7618 let Some(panel_size) = dock.active_panel_size(window, cx) else {
7619 return;
7620 };
7621 let dock_pos = dock.position();
7622 workspace.adjust_dock_size_by_px(panel_size, dock_pos, px, window, cx);
7623}
7624
7625fn adjust_open_docks_size_by_px(
7626 px: Pixels,
7627 workspace: &mut Workspace,
7628 window: &mut Window,
7629 cx: &mut Context<Workspace>,
7630) {
7631 let docks = workspace
7632 .all_docks()
7633 .into_iter()
7634 .filter_map(|dock| {
7635 if dock.read(cx).is_open() {
7636 let dock = dock.read(cx);
7637 let panel_size = dock.active_panel_size(window, cx)?;
7638 let dock_pos = dock.position();
7639 Some((panel_size, dock_pos, px))
7640 } else {
7641 None
7642 }
7643 })
7644 .collect::<Vec<_>>();
7645
7646 docks
7647 .into_iter()
7648 .for_each(|(panel_size, dock_pos, offset)| {
7649 workspace.adjust_dock_size_by_px(panel_size, dock_pos, offset, window, cx);
7650 });
7651}
7652
7653impl Focusable for Workspace {
7654 fn focus_handle(&self, cx: &App) -> FocusHandle {
7655 self.active_pane.focus_handle(cx)
7656 }
7657}
7658
7659#[derive(Clone)]
7660struct DraggedDock(DockPosition);
7661
7662impl Render for DraggedDock {
7663 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7664 gpui::Empty
7665 }
7666}
7667
7668impl Render for Workspace {
7669 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7670 static FIRST_PAINT: AtomicBool = AtomicBool::new(true);
7671 if FIRST_PAINT.swap(false, std::sync::atomic::Ordering::Relaxed) {
7672 log::info!("Rendered first frame");
7673 }
7674
7675 let centered_layout = self.centered_layout
7676 && self.center.panes().len() == 1
7677 && self.active_item(cx).is_some();
7678 let render_padding = |size| {
7679 (size > 0.0).then(|| {
7680 div()
7681 .h_full()
7682 .w(relative(size))
7683 .bg(cx.theme().colors().editor_background)
7684 .border_color(cx.theme().colors().pane_group_border)
7685 })
7686 };
7687 let paddings = if centered_layout {
7688 let settings = WorkspaceSettings::get_global(cx).centered_layout;
7689 (
7690 render_padding(Self::adjust_padding(
7691 settings.left_padding.map(|padding| padding.0),
7692 )),
7693 render_padding(Self::adjust_padding(
7694 settings.right_padding.map(|padding| padding.0),
7695 )),
7696 )
7697 } else {
7698 (None, None)
7699 };
7700 let ui_font = theme::setup_ui_font(window, cx);
7701
7702 let theme = cx.theme().clone();
7703 let colors = theme.colors();
7704 let notification_entities = self
7705 .notifications
7706 .iter()
7707 .map(|(_, notification)| notification.entity_id())
7708 .collect::<Vec<_>>();
7709 let bottom_dock_layout = WorkspaceSettings::get_global(cx).bottom_dock_layout;
7710
7711 div()
7712 .relative()
7713 .size_full()
7714 .flex()
7715 .flex_col()
7716 .font(ui_font)
7717 .gap_0()
7718 .justify_start()
7719 .items_start()
7720 .text_color(colors.text)
7721 .overflow_hidden()
7722 .children(self.titlebar_item.clone())
7723 .on_modifiers_changed(move |_, _, cx| {
7724 for &id in ¬ification_entities {
7725 cx.notify(id);
7726 }
7727 })
7728 .child(
7729 div()
7730 .size_full()
7731 .relative()
7732 .flex_1()
7733 .flex()
7734 .flex_col()
7735 .child(
7736 div()
7737 .id("workspace")
7738 .bg(colors.background)
7739 .relative()
7740 .flex_1()
7741 .w_full()
7742 .flex()
7743 .flex_col()
7744 .overflow_hidden()
7745 .border_t_1()
7746 .border_b_1()
7747 .border_color(colors.border)
7748 .child({
7749 let this = cx.entity();
7750 canvas(
7751 move |bounds, window, cx| {
7752 this.update(cx, |this, cx| {
7753 let bounds_changed = this.bounds != bounds;
7754 this.bounds = bounds;
7755
7756 if bounds_changed {
7757 this.left_dock.update(cx, |dock, cx| {
7758 dock.clamp_panel_size(
7759 bounds.size.width,
7760 window,
7761 cx,
7762 )
7763 });
7764
7765 this.right_dock.update(cx, |dock, cx| {
7766 dock.clamp_panel_size(
7767 bounds.size.width,
7768 window,
7769 cx,
7770 )
7771 });
7772
7773 this.bottom_dock.update(cx, |dock, cx| {
7774 dock.clamp_panel_size(
7775 bounds.size.height,
7776 window,
7777 cx,
7778 )
7779 });
7780 }
7781 })
7782 },
7783 |_, _, _, _| {},
7784 )
7785 .absolute()
7786 .size_full()
7787 })
7788 .when(self.zoomed.is_none(), |this| {
7789 this.on_drag_move(cx.listener(
7790 move |workspace,
7791 e: &DragMoveEvent<DraggedDock>,
7792 window,
7793 cx| {
7794 if workspace.previous_dock_drag_coordinates
7795 != Some(e.event.position)
7796 {
7797 workspace.previous_dock_drag_coordinates =
7798 Some(e.event.position);
7799
7800 match e.drag(cx).0 {
7801 DockPosition::Left => {
7802 workspace.resize_left_dock(
7803 e.event.position.x
7804 - workspace.bounds.left(),
7805 window,
7806 cx,
7807 );
7808 }
7809 DockPosition::Right => {
7810 workspace.resize_right_dock(
7811 workspace.bounds.right()
7812 - e.event.position.x,
7813 window,
7814 cx,
7815 );
7816 }
7817 DockPosition::Bottom => {
7818 workspace.resize_bottom_dock(
7819 workspace.bounds.bottom()
7820 - e.event.position.y,
7821 window,
7822 cx,
7823 );
7824 }
7825 };
7826 workspace.serialize_workspace(window, cx);
7827 }
7828 },
7829 ))
7830
7831 })
7832 .child({
7833 match bottom_dock_layout {
7834 BottomDockLayout::Full => div()
7835 .flex()
7836 .flex_col()
7837 .h_full()
7838 .child(
7839 div()
7840 .flex()
7841 .flex_row()
7842 .flex_1()
7843 .overflow_hidden()
7844 .children(self.render_dock(
7845 DockPosition::Left,
7846 &self.left_dock,
7847 window,
7848 cx,
7849 ))
7850
7851 .child(
7852 div()
7853 .flex()
7854 .flex_col()
7855 .flex_1()
7856 .overflow_hidden()
7857 .child(
7858 h_flex()
7859 .flex_1()
7860 .when_some(
7861 paddings.0,
7862 |this, p| {
7863 this.child(
7864 p.border_r_1(),
7865 )
7866 },
7867 )
7868 .child(self.center.render(
7869 self.zoomed.as_ref(),
7870 &PaneRenderContext {
7871 follower_states:
7872 &self.follower_states,
7873 active_call: self.active_call(),
7874 active_pane: &self.active_pane,
7875 app_state: &self.app_state,
7876 project: &self.project,
7877 workspace: &self.weak_self,
7878 },
7879 window,
7880 cx,
7881 ))
7882 .when_some(
7883 paddings.1,
7884 |this, p| {
7885 this.child(
7886 p.border_l_1(),
7887 )
7888 },
7889 ),
7890 ),
7891 )
7892
7893 .children(self.render_dock(
7894 DockPosition::Right,
7895 &self.right_dock,
7896 window,
7897 cx,
7898 )),
7899 )
7900 .child(div().w_full().children(self.render_dock(
7901 DockPosition::Bottom,
7902 &self.bottom_dock,
7903 window,
7904 cx
7905 ))),
7906
7907 BottomDockLayout::LeftAligned => div()
7908 .flex()
7909 .flex_row()
7910 .h_full()
7911 .child(
7912 div()
7913 .flex()
7914 .flex_col()
7915 .flex_1()
7916 .h_full()
7917 .child(
7918 div()
7919 .flex()
7920 .flex_row()
7921 .flex_1()
7922 .children(self.render_dock(DockPosition::Left, &self.left_dock, window, cx))
7923
7924 .child(
7925 div()
7926 .flex()
7927 .flex_col()
7928 .flex_1()
7929 .overflow_hidden()
7930 .child(
7931 h_flex()
7932 .flex_1()
7933 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7934 .child(self.center.render(
7935 self.zoomed.as_ref(),
7936 &PaneRenderContext {
7937 follower_states:
7938 &self.follower_states,
7939 active_call: self.active_call(),
7940 active_pane: &self.active_pane,
7941 app_state: &self.app_state,
7942 project: &self.project,
7943 workspace: &self.weak_self,
7944 },
7945 window,
7946 cx,
7947 ))
7948 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
7949 )
7950 )
7951
7952 )
7953 .child(
7954 div()
7955 .w_full()
7956 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
7957 ),
7958 )
7959 .children(self.render_dock(
7960 DockPosition::Right,
7961 &self.right_dock,
7962 window,
7963 cx,
7964 )),
7965 BottomDockLayout::RightAligned => div()
7966 .flex()
7967 .flex_row()
7968 .h_full()
7969 .children(self.render_dock(
7970 DockPosition::Left,
7971 &self.left_dock,
7972 window,
7973 cx,
7974 ))
7975
7976 .child(
7977 div()
7978 .flex()
7979 .flex_col()
7980 .flex_1()
7981 .h_full()
7982 .child(
7983 div()
7984 .flex()
7985 .flex_row()
7986 .flex_1()
7987 .child(
7988 div()
7989 .flex()
7990 .flex_col()
7991 .flex_1()
7992 .overflow_hidden()
7993 .child(
7994 h_flex()
7995 .flex_1()
7996 .when_some(paddings.0, |this, p| this.child(p.border_r_1()))
7997 .child(self.center.render(
7998 self.zoomed.as_ref(),
7999 &PaneRenderContext {
8000 follower_states:
8001 &self.follower_states,
8002 active_call: self.active_call(),
8003 active_pane: &self.active_pane,
8004 app_state: &self.app_state,
8005 project: &self.project,
8006 workspace: &self.weak_self,
8007 },
8008 window,
8009 cx,
8010 ))
8011 .when_some(paddings.1, |this, p| this.child(p.border_l_1())),
8012 )
8013 )
8014
8015 .children(self.render_dock(DockPosition::Right, &self.right_dock, window, cx))
8016 )
8017 .child(
8018 div()
8019 .w_full()
8020 .children(self.render_dock(DockPosition::Bottom, &self.bottom_dock, window, cx))
8021 ),
8022 ),
8023 BottomDockLayout::Contained => div()
8024 .flex()
8025 .flex_row()
8026 .h_full()
8027 .children(self.render_dock(
8028 DockPosition::Left,
8029 &self.left_dock,
8030 window,
8031 cx,
8032 ))
8033
8034 .child(
8035 div()
8036 .flex()
8037 .flex_col()
8038 .flex_1()
8039 .overflow_hidden()
8040 .child(
8041 h_flex()
8042 .flex_1()
8043 .when_some(paddings.0, |this, p| {
8044 this.child(p.border_r_1())
8045 })
8046 .child(self.center.render(
8047 self.zoomed.as_ref(),
8048 &PaneRenderContext {
8049 follower_states:
8050 &self.follower_states,
8051 active_call: self.active_call(),
8052 active_pane: &self.active_pane,
8053 app_state: &self.app_state,
8054 project: &self.project,
8055 workspace: &self.weak_self,
8056 },
8057 window,
8058 cx,
8059 ))
8060 .when_some(paddings.1, |this, p| {
8061 this.child(p.border_l_1())
8062 }),
8063 )
8064 .children(self.render_dock(
8065 DockPosition::Bottom,
8066 &self.bottom_dock,
8067 window,
8068 cx,
8069 )),
8070 )
8071
8072 .children(self.render_dock(
8073 DockPosition::Right,
8074 &self.right_dock,
8075 window,
8076 cx,
8077 )),
8078 }
8079 })
8080 .children(self.zoomed.as_ref().and_then(|view| {
8081 let zoomed_view = view.upgrade()?;
8082 let div = div()
8083 .occlude()
8084 .absolute()
8085 .overflow_hidden()
8086 .border_color(colors.border)
8087 .bg(colors.background)
8088 .child(zoomed_view)
8089 .inset_0()
8090 .shadow_lg();
8091
8092 if !WorkspaceSettings::get_global(cx).zoomed_padding {
8093 return Some(div);
8094 }
8095
8096 Some(match self.zoomed_position {
8097 Some(DockPosition::Left) => div.right_2().border_r_1(),
8098 Some(DockPosition::Right) => div.left_2().border_l_1(),
8099 Some(DockPosition::Bottom) => div.top_2().border_t_1(),
8100 None => {
8101 div.top_2().bottom_2().left_2().right_2().border_1()
8102 }
8103 })
8104 }))
8105 .children(self.render_notifications(window, cx)),
8106 )
8107 .when(self.status_bar_visible(cx), |parent| {
8108 parent.child(self.status_bar.clone())
8109 })
8110 .child(self.toast_layer.clone()),
8111 )
8112 }
8113}
8114
8115impl WorkspaceStore {
8116 pub fn new(client: Arc<Client>, cx: &mut Context<Self>) -> Self {
8117 Self {
8118 workspaces: Default::default(),
8119 _subscriptions: vec![
8120 client.add_request_handler(cx.weak_entity(), Self::handle_follow),
8121 client.add_message_handler(cx.weak_entity(), Self::handle_update_followers),
8122 ],
8123 client,
8124 }
8125 }
8126
8127 pub fn update_followers(
8128 &self,
8129 project_id: Option<u64>,
8130 update: proto::update_followers::Variant,
8131 cx: &App,
8132 ) -> Option<()> {
8133 let active_call = GlobalAnyActiveCall::try_global(cx)?;
8134 let room_id = active_call.0.room_id(cx)?;
8135 self.client
8136 .send(proto::UpdateFollowers {
8137 room_id,
8138 project_id,
8139 variant: Some(update),
8140 })
8141 .log_err()
8142 }
8143
8144 pub async fn handle_follow(
8145 this: Entity<Self>,
8146 envelope: TypedEnvelope<proto::Follow>,
8147 mut cx: AsyncApp,
8148 ) -> Result<proto::FollowResponse> {
8149 this.update(&mut cx, |this, cx| {
8150 let follower = Follower {
8151 project_id: envelope.payload.project_id,
8152 peer_id: envelope.original_sender_id()?,
8153 };
8154
8155 let mut response = proto::FollowResponse::default();
8156
8157 this.workspaces.retain(|(window_handle, weak_workspace)| {
8158 let Some(workspace) = weak_workspace.upgrade() else {
8159 return false;
8160 };
8161 window_handle
8162 .update(cx, |_, window, cx| {
8163 workspace.update(cx, |workspace, cx| {
8164 let handler_response =
8165 workspace.handle_follow(follower.project_id, window, cx);
8166 if let Some(active_view) = handler_response.active_view
8167 && workspace.project.read(cx).remote_id() == follower.project_id
8168 {
8169 response.active_view = Some(active_view)
8170 }
8171 });
8172 })
8173 .is_ok()
8174 });
8175
8176 Ok(response)
8177 })
8178 }
8179
8180 async fn handle_update_followers(
8181 this: Entity<Self>,
8182 envelope: TypedEnvelope<proto::UpdateFollowers>,
8183 mut cx: AsyncApp,
8184 ) -> Result<()> {
8185 let leader_id = envelope.original_sender_id()?;
8186 let update = envelope.payload;
8187
8188 this.update(&mut cx, |this, cx| {
8189 this.workspaces.retain(|(window_handle, weak_workspace)| {
8190 let Some(workspace) = weak_workspace.upgrade() else {
8191 return false;
8192 };
8193 window_handle
8194 .update(cx, |_, window, cx| {
8195 workspace.update(cx, |workspace, cx| {
8196 let project_id = workspace.project.read(cx).remote_id();
8197 if update.project_id != project_id && update.project_id.is_some() {
8198 return;
8199 }
8200 workspace.handle_update_followers(
8201 leader_id,
8202 update.clone(),
8203 window,
8204 cx,
8205 );
8206 });
8207 })
8208 .is_ok()
8209 });
8210 Ok(())
8211 })
8212 }
8213
8214 pub fn workspaces(&self) -> impl Iterator<Item = &WeakEntity<Workspace>> {
8215 self.workspaces.iter().map(|(_, weak)| weak)
8216 }
8217
8218 pub fn workspaces_with_windows(
8219 &self,
8220 ) -> impl Iterator<Item = (gpui::AnyWindowHandle, &WeakEntity<Workspace>)> {
8221 self.workspaces.iter().map(|(window, weak)| (*window, weak))
8222 }
8223}
8224
8225impl ViewId {
8226 pub(crate) fn from_proto(message: proto::ViewId) -> Result<Self> {
8227 Ok(Self {
8228 creator: message
8229 .creator
8230 .map(CollaboratorId::PeerId)
8231 .context("creator is missing")?,
8232 id: message.id,
8233 })
8234 }
8235
8236 pub(crate) fn to_proto(self) -> Option<proto::ViewId> {
8237 if let CollaboratorId::PeerId(peer_id) = self.creator {
8238 Some(proto::ViewId {
8239 creator: Some(peer_id),
8240 id: self.id,
8241 })
8242 } else {
8243 None
8244 }
8245 }
8246}
8247
8248impl FollowerState {
8249 fn pane(&self) -> &Entity<Pane> {
8250 self.dock_pane.as_ref().unwrap_or(&self.center_pane)
8251 }
8252}
8253
8254pub trait WorkspaceHandle {
8255 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath>;
8256}
8257
8258impl WorkspaceHandle for Entity<Workspace> {
8259 fn file_project_paths(&self, cx: &App) -> Vec<ProjectPath> {
8260 self.read(cx)
8261 .worktrees(cx)
8262 .flat_map(|worktree| {
8263 let worktree_id = worktree.read(cx).id();
8264 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
8265 worktree_id,
8266 path: f.path.clone(),
8267 })
8268 })
8269 .collect::<Vec<_>>()
8270 }
8271}
8272
8273pub async fn last_opened_workspace_location(
8274 db: &WorkspaceDb,
8275 fs: &dyn fs::Fs,
8276) -> Option<(WorkspaceId, SerializedWorkspaceLocation, PathList)> {
8277 db.last_workspace(fs)
8278 .await
8279 .log_err()
8280 .flatten()
8281 .map(|(id, location, paths, _timestamp)| (id, location, paths))
8282}
8283
8284pub async fn last_session_workspace_locations(
8285 db: &WorkspaceDb,
8286 last_session_id: &str,
8287 last_session_window_stack: Option<Vec<WindowId>>,
8288 fs: &dyn fs::Fs,
8289) -> Option<Vec<SessionWorkspace>> {
8290 db.last_session_workspace_locations(last_session_id, last_session_window_stack, fs)
8291 .await
8292 .log_err()
8293}
8294
8295pub struct MultiWorkspaceRestoreResult {
8296 pub window_handle: WindowHandle<MultiWorkspace>,
8297 pub errors: Vec<anyhow::Error>,
8298}
8299
8300pub async fn restore_multiworkspace(
8301 multi_workspace: SerializedMultiWorkspace,
8302 app_state: Arc<AppState>,
8303 cx: &mut AsyncApp,
8304) -> anyhow::Result<MultiWorkspaceRestoreResult> {
8305 let SerializedMultiWorkspace { workspaces, state } = multi_workspace;
8306 let mut group_iter = workspaces.into_iter();
8307 let first = group_iter
8308 .next()
8309 .context("window group must not be empty")?;
8310
8311 let window_handle = if first.paths.is_empty() {
8312 cx.update(|cx| open_workspace_by_id(first.workspace_id, app_state.clone(), None, cx))
8313 .await?
8314 } else {
8315 let OpenResult { window, .. } = cx
8316 .update(|cx| {
8317 Workspace::new_local(
8318 first.paths.paths().to_vec(),
8319 app_state.clone(),
8320 None,
8321 None,
8322 None,
8323 true,
8324 cx,
8325 )
8326 })
8327 .await?;
8328 window
8329 };
8330
8331 let mut errors = Vec::new();
8332
8333 for session_workspace in group_iter {
8334 let error = if session_workspace.paths.is_empty() {
8335 cx.update(|cx| {
8336 open_workspace_by_id(
8337 session_workspace.workspace_id,
8338 app_state.clone(),
8339 Some(window_handle),
8340 cx,
8341 )
8342 })
8343 .await
8344 .err()
8345 } else {
8346 cx.update(|cx| {
8347 Workspace::new_local(
8348 session_workspace.paths.paths().to_vec(),
8349 app_state.clone(),
8350 Some(window_handle),
8351 None,
8352 None,
8353 false,
8354 cx,
8355 )
8356 })
8357 .await
8358 .err()
8359 };
8360
8361 if let Some(error) = error {
8362 errors.push(error);
8363 }
8364 }
8365
8366 if let Some(target_id) = state.active_workspace_id {
8367 window_handle
8368 .update(cx, |multi_workspace, window, cx| {
8369 let target_index = multi_workspace
8370 .workspaces()
8371 .iter()
8372 .position(|ws| ws.read(cx).database_id() == Some(target_id));
8373 if let Some(index) = target_index {
8374 multi_workspace.activate_index(index, window, cx);
8375 } else if !multi_workspace.workspaces().is_empty() {
8376 multi_workspace.activate_index(0, window, cx);
8377 }
8378 })
8379 .ok();
8380 } else {
8381 window_handle
8382 .update(cx, |multi_workspace, window, cx| {
8383 if !multi_workspace.workspaces().is_empty() {
8384 multi_workspace.activate_index(0, window, cx);
8385 }
8386 })
8387 .ok();
8388 }
8389
8390 if state.sidebar_open {
8391 window_handle
8392 .update(cx, |multi_workspace, _, cx| {
8393 multi_workspace.open_sidebar(cx);
8394 })
8395 .ok();
8396 }
8397
8398 window_handle
8399 .update(cx, |_, window, _cx| {
8400 window.activate_window();
8401 })
8402 .ok();
8403
8404 Ok(MultiWorkspaceRestoreResult {
8405 window_handle,
8406 errors,
8407 })
8408}
8409
8410actions!(
8411 collab,
8412 [
8413 /// Opens the channel notes for the current call.
8414 ///
8415 /// Use `collab_panel::OpenSelectedChannelNotes` to open the channel notes for the selected
8416 /// channel in the collab panel.
8417 ///
8418 /// If you want to open a specific channel, use `zed::OpenZedUrl` with a channel notes URL -
8419 /// can be copied via "Copy link to section" in the context menu of the channel notes
8420 /// buffer. These URLs look like `https://zed.dev/channel/channel-name-CHANNEL_ID/notes`.
8421 OpenChannelNotes,
8422 /// Mutes your microphone.
8423 Mute,
8424 /// Deafens yourself (mute both microphone and speakers).
8425 Deafen,
8426 /// Leaves the current call.
8427 LeaveCall,
8428 /// Shares the current project with collaborators.
8429 ShareProject,
8430 /// Shares your screen with collaborators.
8431 ScreenShare,
8432 /// Copies the current room name and session id for debugging purposes.
8433 CopyRoomId,
8434 ]
8435);
8436
8437/// Opens the channel notes for a specific channel by its ID.
8438#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
8439#[action(namespace = collab)]
8440#[serde(deny_unknown_fields)]
8441pub struct OpenChannelNotesById {
8442 pub channel_id: u64,
8443}
8444
8445actions!(
8446 zed,
8447 [
8448 /// Opens the Zed log file.
8449 OpenLog,
8450 /// Reveals the Zed log file in the system file manager.
8451 RevealLogInFileManager
8452 ]
8453);
8454
8455async fn join_channel_internal(
8456 channel_id: ChannelId,
8457 app_state: &Arc<AppState>,
8458 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8459 requesting_workspace: Option<WeakEntity<Workspace>>,
8460 active_call: &dyn AnyActiveCall,
8461 cx: &mut AsyncApp,
8462) -> Result<bool> {
8463 let (should_prompt, already_in_channel) = cx.update(|cx| {
8464 if !active_call.is_in_room(cx) {
8465 return (false, false);
8466 }
8467
8468 let already_in_channel = active_call.channel_id(cx) == Some(channel_id);
8469 let should_prompt = active_call.is_sharing_project(cx)
8470 && active_call.has_remote_participants(cx)
8471 && !already_in_channel;
8472 (should_prompt, already_in_channel)
8473 });
8474
8475 if already_in_channel {
8476 let task = cx.update(|cx| {
8477 if let Some((project, host)) = active_call.most_active_project(cx) {
8478 Some(join_in_room_project(project, host, app_state.clone(), cx))
8479 } else {
8480 None
8481 }
8482 });
8483 if let Some(task) = task {
8484 task.await?;
8485 }
8486 return anyhow::Ok(true);
8487 }
8488
8489 if should_prompt {
8490 if let Some(multi_workspace) = requesting_window {
8491 let answer = multi_workspace
8492 .update(cx, |_, window, cx| {
8493 window.prompt(
8494 PromptLevel::Warning,
8495 "Do you want to switch channels?",
8496 Some("Leaving this call will unshare your current project."),
8497 &["Yes, Join Channel", "Cancel"],
8498 cx,
8499 )
8500 })?
8501 .await;
8502
8503 if answer == Ok(1) {
8504 return Ok(false);
8505 }
8506 } else {
8507 return Ok(false);
8508 }
8509 }
8510
8511 let client = cx.update(|cx| active_call.client(cx));
8512
8513 let mut client_status = client.status();
8514
8515 // this loop will terminate within client::CONNECTION_TIMEOUT seconds.
8516 'outer: loop {
8517 let Some(status) = client_status.recv().await else {
8518 anyhow::bail!("error connecting");
8519 };
8520
8521 match status {
8522 Status::Connecting
8523 | Status::Authenticating
8524 | Status::Authenticated
8525 | Status::Reconnecting
8526 | Status::Reauthenticating
8527 | Status::Reauthenticated => continue,
8528 Status::Connected { .. } => break 'outer,
8529 Status::SignedOut | Status::AuthenticationError => {
8530 return Err(ErrorCode::SignedOut.into());
8531 }
8532 Status::UpgradeRequired => return Err(ErrorCode::UpgradeRequired.into()),
8533 Status::ConnectionError | Status::ConnectionLost | Status::ReconnectionError { .. } => {
8534 return Err(ErrorCode::Disconnected.into());
8535 }
8536 }
8537 }
8538
8539 let joined = cx
8540 .update(|cx| active_call.join_channel(channel_id, cx))
8541 .await?;
8542
8543 if !joined {
8544 return anyhow::Ok(true);
8545 }
8546
8547 cx.update(|cx| active_call.room_update_completed(cx)).await;
8548
8549 let task = cx.update(|cx| {
8550 if let Some((project, host)) = active_call.most_active_project(cx) {
8551 return Some(join_in_room_project(project, host, app_state.clone(), cx));
8552 }
8553
8554 // If you are the first to join a channel, see if you should share your project.
8555 if !active_call.has_remote_participants(cx)
8556 && !active_call.local_participant_is_guest(cx)
8557 && let Some(workspace) = requesting_workspace.as_ref().and_then(|w| w.upgrade())
8558 {
8559 let project = workspace.update(cx, |workspace, cx| {
8560 let project = workspace.project.read(cx);
8561
8562 if !active_call.share_on_join(cx) {
8563 return None;
8564 }
8565
8566 if (project.is_local() || project.is_via_remote_server())
8567 && project.visible_worktrees(cx).any(|tree| {
8568 tree.read(cx)
8569 .root_entry()
8570 .is_some_and(|entry| entry.is_dir())
8571 })
8572 {
8573 Some(workspace.project.clone())
8574 } else {
8575 None
8576 }
8577 });
8578 if let Some(project) = project {
8579 let share_task = active_call.share_project(project, cx);
8580 return Some(cx.spawn(async move |_cx| -> Result<()> {
8581 share_task.await?;
8582 Ok(())
8583 }));
8584 }
8585 }
8586
8587 None
8588 });
8589 if let Some(task) = task {
8590 task.await?;
8591 return anyhow::Ok(true);
8592 }
8593 anyhow::Ok(false)
8594}
8595
8596pub fn join_channel(
8597 channel_id: ChannelId,
8598 app_state: Arc<AppState>,
8599 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8600 requesting_workspace: Option<WeakEntity<Workspace>>,
8601 cx: &mut App,
8602) -> Task<Result<()>> {
8603 let active_call = GlobalAnyActiveCall::global(cx).clone();
8604 cx.spawn(async move |cx| {
8605 let result = join_channel_internal(
8606 channel_id,
8607 &app_state,
8608 requesting_window,
8609 requesting_workspace,
8610 &*active_call.0,
8611 cx,
8612 )
8613 .await;
8614
8615 // join channel succeeded, and opened a window
8616 if matches!(result, Ok(true)) {
8617 return anyhow::Ok(());
8618 }
8619
8620 // find an existing workspace to focus and show call controls
8621 let mut active_window = requesting_window.or_else(|| activate_any_workspace_window(cx));
8622 if active_window.is_none() {
8623 // no open workspaces, make one to show the error in (blergh)
8624 let OpenResult {
8625 window: window_handle,
8626 ..
8627 } = cx
8628 .update(|cx| {
8629 Workspace::new_local(
8630 vec![],
8631 app_state.clone(),
8632 requesting_window,
8633 None,
8634 None,
8635 true,
8636 cx,
8637 )
8638 })
8639 .await?;
8640
8641 window_handle
8642 .update(cx, |_, window, _cx| {
8643 window.activate_window();
8644 })
8645 .ok();
8646
8647 if result.is_ok() {
8648 cx.update(|cx| {
8649 cx.dispatch_action(&OpenChannelNotes);
8650 });
8651 }
8652
8653 active_window = Some(window_handle);
8654 }
8655
8656 if let Err(err) = result {
8657 log::error!("failed to join channel: {}", err);
8658 if let Some(active_window) = active_window {
8659 active_window
8660 .update(cx, |_, window, cx| {
8661 let detail: SharedString = match err.error_code() {
8662 ErrorCode::SignedOut => "Please sign in to continue.".into(),
8663 ErrorCode::UpgradeRequired => concat!(
8664 "Your are running an unsupported version of Zed. ",
8665 "Please update to continue."
8666 )
8667 .into(),
8668 ErrorCode::NoSuchChannel => concat!(
8669 "No matching channel was found. ",
8670 "Please check the link and try again."
8671 )
8672 .into(),
8673 ErrorCode::Forbidden => concat!(
8674 "This channel is private, and you do not have access. ",
8675 "Please ask someone to add you and try again."
8676 )
8677 .into(),
8678 ErrorCode::Disconnected => {
8679 "Please check your internet connection and try again.".into()
8680 }
8681 _ => format!("{}\n\nPlease try again.", err).into(),
8682 };
8683 window.prompt(
8684 PromptLevel::Critical,
8685 "Failed to join channel",
8686 Some(&detail),
8687 &["Ok"],
8688 cx,
8689 )
8690 })?
8691 .await
8692 .ok();
8693 }
8694 }
8695
8696 // return ok, we showed the error to the user.
8697 anyhow::Ok(())
8698 })
8699}
8700
8701pub async fn get_any_active_multi_workspace(
8702 app_state: Arc<AppState>,
8703 mut cx: AsyncApp,
8704) -> anyhow::Result<WindowHandle<MultiWorkspace>> {
8705 // find an existing workspace to focus and show call controls
8706 let active_window = activate_any_workspace_window(&mut cx);
8707 if active_window.is_none() {
8708 cx.update(|cx| Workspace::new_local(vec![], app_state.clone(), None, None, None, true, cx))
8709 .await?;
8710 }
8711 activate_any_workspace_window(&mut cx).context("could not open zed")
8712}
8713
8714fn activate_any_workspace_window(cx: &mut AsyncApp) -> Option<WindowHandle<MultiWorkspace>> {
8715 cx.update(|cx| {
8716 if let Some(workspace_window) = cx
8717 .active_window()
8718 .and_then(|window| window.downcast::<MultiWorkspace>())
8719 {
8720 return Some(workspace_window);
8721 }
8722
8723 for window in cx.windows() {
8724 if let Some(workspace_window) = window.downcast::<MultiWorkspace>() {
8725 workspace_window
8726 .update(cx, |_, window, _| window.activate_window())
8727 .ok();
8728 return Some(workspace_window);
8729 }
8730 }
8731 None
8732 })
8733}
8734
8735pub fn local_workspace_windows(cx: &App) -> Vec<WindowHandle<MultiWorkspace>> {
8736 workspace_windows_for_location(&SerializedWorkspaceLocation::Local, cx)
8737}
8738
8739pub fn workspace_windows_for_location(
8740 serialized_location: &SerializedWorkspaceLocation,
8741 cx: &App,
8742) -> Vec<WindowHandle<MultiWorkspace>> {
8743 cx.windows()
8744 .into_iter()
8745 .filter_map(|window| window.downcast::<MultiWorkspace>())
8746 .filter(|multi_workspace| {
8747 let same_host = |left: &RemoteConnectionOptions, right: &RemoteConnectionOptions| match (left, right) {
8748 (RemoteConnectionOptions::Ssh(a), RemoteConnectionOptions::Ssh(b)) => {
8749 (&a.host, &a.username, &a.port) == (&b.host, &b.username, &b.port)
8750 }
8751 (RemoteConnectionOptions::Wsl(a), RemoteConnectionOptions::Wsl(b)) => {
8752 // The WSL username is not consistently populated in the workspace location, so ignore it for now.
8753 a.distro_name == b.distro_name
8754 }
8755 (RemoteConnectionOptions::Docker(a), RemoteConnectionOptions::Docker(b)) => {
8756 a.container_id == b.container_id
8757 }
8758 #[cfg(any(test, feature = "test-support"))]
8759 (RemoteConnectionOptions::Mock(a), RemoteConnectionOptions::Mock(b)) => {
8760 a.id == b.id
8761 }
8762 _ => false,
8763 };
8764
8765 multi_workspace.read(cx).is_ok_and(|multi_workspace| {
8766 multi_workspace.workspaces().iter().any(|workspace| {
8767 match workspace.read(cx).workspace_location(cx) {
8768 WorkspaceLocation::Location(location, _) => {
8769 match (&location, serialized_location) {
8770 (
8771 SerializedWorkspaceLocation::Local,
8772 SerializedWorkspaceLocation::Local,
8773 ) => true,
8774 (
8775 SerializedWorkspaceLocation::Remote(a),
8776 SerializedWorkspaceLocation::Remote(b),
8777 ) => same_host(a, b),
8778 _ => false,
8779 }
8780 }
8781 _ => false,
8782 }
8783 })
8784 })
8785 })
8786 .collect()
8787}
8788
8789pub async fn find_existing_workspace(
8790 abs_paths: &[PathBuf],
8791 open_options: &OpenOptions,
8792 location: &SerializedWorkspaceLocation,
8793 cx: &mut AsyncApp,
8794) -> (
8795 Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)>,
8796 OpenVisible,
8797) {
8798 let mut existing: Option<(WindowHandle<MultiWorkspace>, Entity<Workspace>)> = None;
8799 let mut open_visible = OpenVisible::All;
8800 let mut best_match = None;
8801
8802 if open_options.open_new_workspace != Some(true) {
8803 cx.update(|cx| {
8804 for window in workspace_windows_for_location(location, cx) {
8805 if let Ok(multi_workspace) = window.read(cx) {
8806 for workspace in multi_workspace.workspaces() {
8807 let project = workspace.read(cx).project.read(cx);
8808 let m = project.visibility_for_paths(
8809 abs_paths,
8810 open_options.open_new_workspace == None,
8811 cx,
8812 );
8813 if m > best_match {
8814 existing = Some((window, workspace.clone()));
8815 best_match = m;
8816 } else if best_match.is_none()
8817 && open_options.open_new_workspace == Some(false)
8818 {
8819 existing = Some((window, workspace.clone()))
8820 }
8821 }
8822 }
8823 }
8824 });
8825
8826 let all_paths_are_files = existing
8827 .as_ref()
8828 .and_then(|(_, target_workspace)| {
8829 cx.update(|cx| {
8830 let workspace = target_workspace.read(cx);
8831 let project = workspace.project.read(cx);
8832 let path_style = workspace.path_style(cx);
8833 Some(!abs_paths.iter().any(|path| {
8834 let path = util::paths::SanitizedPath::new(path);
8835 project.worktrees(cx).any(|worktree| {
8836 let worktree = worktree.read(cx);
8837 let abs_path = worktree.abs_path();
8838 path_style
8839 .strip_prefix(path.as_ref(), abs_path.as_ref())
8840 .and_then(|rel| worktree.entry_for_path(&rel))
8841 .is_some_and(|e| e.is_dir())
8842 })
8843 }))
8844 })
8845 })
8846 .unwrap_or(false);
8847
8848 if open_options.open_new_workspace.is_none()
8849 && existing.is_some()
8850 && open_options.wait
8851 && all_paths_are_files
8852 {
8853 cx.update(|cx| {
8854 let windows = workspace_windows_for_location(location, cx);
8855 let window = cx
8856 .active_window()
8857 .and_then(|window| window.downcast::<MultiWorkspace>())
8858 .filter(|window| windows.contains(window))
8859 .or_else(|| windows.into_iter().next());
8860 if let Some(window) = window {
8861 if let Ok(multi_workspace) = window.read(cx) {
8862 let active_workspace = multi_workspace.workspace().clone();
8863 existing = Some((window, active_workspace));
8864 open_visible = OpenVisible::None;
8865 }
8866 }
8867 });
8868 }
8869 }
8870 (existing, open_visible)
8871}
8872
8873#[derive(Default, Clone)]
8874pub struct OpenOptions {
8875 pub visible: Option<OpenVisible>,
8876 pub focus: Option<bool>,
8877 pub open_new_workspace: Option<bool>,
8878 pub wait: bool,
8879 pub replace_window: Option<WindowHandle<MultiWorkspace>>,
8880 pub env: Option<HashMap<String, String>>,
8881}
8882
8883/// The result of opening a workspace via [`open_paths`], [`Workspace::new_local`],
8884/// or [`Workspace::open_workspace_for_paths`].
8885pub struct OpenResult {
8886 pub window: WindowHandle<MultiWorkspace>,
8887 pub workspace: Entity<Workspace>,
8888 pub opened_items: Vec<Option<anyhow::Result<Box<dyn ItemHandle>>>>,
8889}
8890
8891/// Opens a workspace by its database ID, used for restoring empty workspaces with unsaved content.
8892pub fn open_workspace_by_id(
8893 workspace_id: WorkspaceId,
8894 app_state: Arc<AppState>,
8895 requesting_window: Option<WindowHandle<MultiWorkspace>>,
8896 cx: &mut App,
8897) -> Task<anyhow::Result<WindowHandle<MultiWorkspace>>> {
8898 let project_handle = Project::local(
8899 app_state.client.clone(),
8900 app_state.node_runtime.clone(),
8901 app_state.user_store.clone(),
8902 app_state.languages.clone(),
8903 app_state.fs.clone(),
8904 None,
8905 project::LocalProjectFlags {
8906 init_worktree_trust: true,
8907 ..project::LocalProjectFlags::default()
8908 },
8909 cx,
8910 );
8911
8912 let db = WorkspaceDb::global(cx);
8913 let kvp = db::kvp::KeyValueStore::global(cx);
8914 cx.spawn(async move |cx| {
8915 let serialized_workspace = db
8916 .workspace_for_id(workspace_id)
8917 .with_context(|| format!("Workspace {workspace_id:?} not found"))?;
8918
8919 let centered_layout = serialized_workspace.centered_layout;
8920
8921 let (window, workspace) = if let Some(window) = requesting_window {
8922 let workspace = window.update(cx, |multi_workspace, window, cx| {
8923 let workspace = cx.new(|cx| {
8924 let mut workspace = Workspace::new(
8925 Some(workspace_id),
8926 project_handle.clone(),
8927 app_state.clone(),
8928 window,
8929 cx,
8930 );
8931 workspace.centered_layout = centered_layout;
8932 workspace
8933 });
8934 multi_workspace.add_workspace(workspace.clone(), cx);
8935 workspace
8936 })?;
8937 (window, workspace)
8938 } else {
8939 let window_bounds_override = window_bounds_env_override();
8940
8941 let (window_bounds, display) = if let Some(bounds) = window_bounds_override {
8942 (Some(WindowBounds::Windowed(bounds)), None)
8943 } else if let Some(display) = serialized_workspace.display
8944 && let Some(bounds) = serialized_workspace.window_bounds.as_ref()
8945 {
8946 (Some(bounds.0), Some(display))
8947 } else if let Some((display, bounds)) = persistence::read_default_window_bounds(&kvp) {
8948 (Some(bounds), Some(display))
8949 } else {
8950 (None, None)
8951 };
8952
8953 let options = cx.update(|cx| {
8954 let mut options = (app_state.build_window_options)(display, cx);
8955 options.window_bounds = window_bounds;
8956 options
8957 });
8958
8959 let window = cx.open_window(options, {
8960 let app_state = app_state.clone();
8961 let project_handle = project_handle.clone();
8962 move |window, cx| {
8963 let workspace = cx.new(|cx| {
8964 let mut workspace = Workspace::new(
8965 Some(workspace_id),
8966 project_handle,
8967 app_state,
8968 window,
8969 cx,
8970 );
8971 workspace.centered_layout = centered_layout;
8972 workspace
8973 });
8974 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
8975 }
8976 })?;
8977
8978 let workspace = window.update(cx, |multi_workspace: &mut MultiWorkspace, _, _cx| {
8979 multi_workspace.workspace().clone()
8980 })?;
8981
8982 (window, workspace)
8983 };
8984
8985 notify_if_database_failed(window, cx);
8986
8987 // Restore items from the serialized workspace
8988 window
8989 .update(cx, |_, window, cx| {
8990 workspace.update(cx, |_workspace, cx| {
8991 open_items(Some(serialized_workspace), vec![], window, cx)
8992 })
8993 })?
8994 .await?;
8995
8996 window.update(cx, |_, window, cx| {
8997 workspace.update(cx, |workspace, cx| {
8998 workspace.serialize_workspace(window, cx);
8999 });
9000 })?;
9001
9002 Ok(window)
9003 })
9004}
9005
9006#[allow(clippy::type_complexity)]
9007pub fn open_paths(
9008 abs_paths: &[PathBuf],
9009 app_state: Arc<AppState>,
9010 open_options: OpenOptions,
9011 cx: &mut App,
9012) -> Task<anyhow::Result<OpenResult>> {
9013 let abs_paths = abs_paths.to_vec();
9014 #[cfg(target_os = "windows")]
9015 let wsl_path = abs_paths
9016 .iter()
9017 .find_map(|p| util::paths::WslPath::from_path(p));
9018
9019 cx.spawn(async move |cx| {
9020 let (mut existing, mut open_visible) = find_existing_workspace(
9021 &abs_paths,
9022 &open_options,
9023 &SerializedWorkspaceLocation::Local,
9024 cx,
9025 )
9026 .await;
9027
9028 // Fallback: if no workspace contains the paths and all paths are files,
9029 // prefer an existing local workspace window (active window first).
9030 if open_options.open_new_workspace.is_none() && existing.is_none() {
9031 let all_paths = abs_paths.iter().map(|path| app_state.fs.metadata(path));
9032 let all_metadatas = futures::future::join_all(all_paths)
9033 .await
9034 .into_iter()
9035 .filter_map(|result| result.ok().flatten())
9036 .collect::<Vec<_>>();
9037
9038 if all_metadatas.iter().all(|file| !file.is_dir) {
9039 cx.update(|cx| {
9040 let windows = workspace_windows_for_location(
9041 &SerializedWorkspaceLocation::Local,
9042 cx,
9043 );
9044 let window = cx
9045 .active_window()
9046 .and_then(|window| window.downcast::<MultiWorkspace>())
9047 .filter(|window| windows.contains(window))
9048 .or_else(|| windows.into_iter().next());
9049 if let Some(window) = window {
9050 if let Ok(multi_workspace) = window.read(cx) {
9051 let active_workspace = multi_workspace.workspace().clone();
9052 existing = Some((window, active_workspace));
9053 open_visible = OpenVisible::None;
9054 }
9055 }
9056 });
9057 }
9058 }
9059
9060 let result = if let Some((existing, target_workspace)) = existing {
9061 let open_task = existing
9062 .update(cx, |multi_workspace, window, cx| {
9063 window.activate_window();
9064 multi_workspace.activate(target_workspace.clone(), cx);
9065 target_workspace.update(cx, |workspace, cx| {
9066 workspace.open_paths(
9067 abs_paths,
9068 OpenOptions {
9069 visible: Some(open_visible),
9070 ..Default::default()
9071 },
9072 None,
9073 window,
9074 cx,
9075 )
9076 })
9077 })?
9078 .await;
9079
9080 _ = existing.update(cx, |multi_workspace, _, cx| {
9081 let workspace = multi_workspace.workspace().clone();
9082 workspace.update(cx, |workspace, cx| {
9083 for item in open_task.iter().flatten() {
9084 if let Err(e) = item {
9085 workspace.show_error(&e, cx);
9086 }
9087 }
9088 });
9089 });
9090
9091 Ok(OpenResult { window: existing, workspace: target_workspace, opened_items: open_task })
9092 } else {
9093 let result = cx
9094 .update(move |cx| {
9095 Workspace::new_local(
9096 abs_paths,
9097 app_state.clone(),
9098 open_options.replace_window,
9099 open_options.env,
9100 None,
9101 true,
9102 cx,
9103 )
9104 })
9105 .await;
9106
9107 if let Ok(ref result) = result {
9108 result.window
9109 .update(cx, |_, window, _cx| {
9110 window.activate_window();
9111 })
9112 .log_err();
9113 }
9114
9115 result
9116 };
9117
9118 #[cfg(target_os = "windows")]
9119 if let Some(util::paths::WslPath{distro, path}) = wsl_path
9120 && let Ok(ref result) = result
9121 {
9122 result.window
9123 .update(cx, move |multi_workspace, _window, cx| {
9124 struct OpenInWsl;
9125 let workspace = multi_workspace.workspace().clone();
9126 workspace.update(cx, |workspace, cx| {
9127 workspace.show_notification(NotificationId::unique::<OpenInWsl>(), cx, move |cx| {
9128 let display_path = util::markdown::MarkdownInlineCode(&path.to_string_lossy());
9129 let msg = format!("{display_path} is inside a WSL filesystem, some features may not work unless you open it with WSL remote");
9130 cx.new(move |cx| {
9131 MessageNotification::new(msg, cx)
9132 .primary_message("Open in WSL")
9133 .primary_icon(IconName::FolderOpen)
9134 .primary_on_click(move |window, cx| {
9135 window.dispatch_action(Box::new(remote::OpenWslPath {
9136 distro: remote::WslConnectionOptions {
9137 distro_name: distro.clone(),
9138 user: None,
9139 },
9140 paths: vec![path.clone().into()],
9141 }), cx)
9142 })
9143 })
9144 });
9145 });
9146 })
9147 .unwrap();
9148 };
9149 result
9150 })
9151}
9152
9153pub fn open_new(
9154 open_options: OpenOptions,
9155 app_state: Arc<AppState>,
9156 cx: &mut App,
9157 init: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + 'static + Send,
9158) -> Task<anyhow::Result<()>> {
9159 let task = Workspace::new_local(
9160 Vec::new(),
9161 app_state,
9162 open_options.replace_window,
9163 open_options.env,
9164 Some(Box::new(init)),
9165 true,
9166 cx,
9167 );
9168 cx.spawn(async move |cx| {
9169 let OpenResult { window, .. } = task.await?;
9170 window
9171 .update(cx, |_, window, _cx| {
9172 window.activate_window();
9173 })
9174 .ok();
9175 Ok(())
9176 })
9177}
9178
9179pub fn create_and_open_local_file(
9180 path: &'static Path,
9181 window: &mut Window,
9182 cx: &mut Context<Workspace>,
9183 default_content: impl 'static + Send + FnOnce() -> Rope,
9184) -> Task<Result<Box<dyn ItemHandle>>> {
9185 cx.spawn_in(window, async move |workspace, cx| {
9186 let fs = workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
9187 if !fs.is_file(path).await {
9188 fs.create_file(path, Default::default()).await?;
9189 fs.save(path, &default_content(), Default::default())
9190 .await?;
9191 }
9192
9193 workspace
9194 .update_in(cx, |workspace, window, cx| {
9195 workspace.with_local_or_wsl_workspace(window, cx, |workspace, window, cx| {
9196 let path = workspace
9197 .project
9198 .read_with(cx, |project, cx| project.try_windows_path_to_wsl(path, cx));
9199 cx.spawn_in(window, async move |workspace, cx| {
9200 let path = path.await?;
9201 let mut items = workspace
9202 .update_in(cx, |workspace, window, cx| {
9203 workspace.open_paths(
9204 vec![path.to_path_buf()],
9205 OpenOptions {
9206 visible: Some(OpenVisible::None),
9207 ..Default::default()
9208 },
9209 None,
9210 window,
9211 cx,
9212 )
9213 })?
9214 .await;
9215 let item = items.pop().flatten();
9216 item.with_context(|| format!("path {path:?} is not a file"))?
9217 })
9218 })
9219 })?
9220 .await?
9221 .await
9222 })
9223}
9224
9225pub fn open_remote_project_with_new_connection(
9226 window: WindowHandle<MultiWorkspace>,
9227 remote_connection: Arc<dyn RemoteConnection>,
9228 cancel_rx: oneshot::Receiver<()>,
9229 delegate: Arc<dyn RemoteClientDelegate>,
9230 app_state: Arc<AppState>,
9231 paths: Vec<PathBuf>,
9232 cx: &mut App,
9233) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9234 cx.spawn(async move |cx| {
9235 let (workspace_id, serialized_workspace) =
9236 deserialize_remote_project(remote_connection.connection_options(), paths.clone(), cx)
9237 .await?;
9238
9239 let session = match cx
9240 .update(|cx| {
9241 remote::RemoteClient::new(
9242 ConnectionIdentifier::Workspace(workspace_id.0),
9243 remote_connection,
9244 cancel_rx,
9245 delegate,
9246 cx,
9247 )
9248 })
9249 .await?
9250 {
9251 Some(result) => result,
9252 None => return Ok(Vec::new()),
9253 };
9254
9255 let project = cx.update(|cx| {
9256 project::Project::remote(
9257 session,
9258 app_state.client.clone(),
9259 app_state.node_runtime.clone(),
9260 app_state.user_store.clone(),
9261 app_state.languages.clone(),
9262 app_state.fs.clone(),
9263 true,
9264 cx,
9265 )
9266 });
9267
9268 open_remote_project_inner(
9269 project,
9270 paths,
9271 workspace_id,
9272 serialized_workspace,
9273 app_state,
9274 window,
9275 cx,
9276 )
9277 .await
9278 })
9279}
9280
9281pub fn open_remote_project_with_existing_connection(
9282 connection_options: RemoteConnectionOptions,
9283 project: Entity<Project>,
9284 paths: Vec<PathBuf>,
9285 app_state: Arc<AppState>,
9286 window: WindowHandle<MultiWorkspace>,
9287 cx: &mut AsyncApp,
9288) -> Task<Result<Vec<Option<Box<dyn ItemHandle>>>>> {
9289 cx.spawn(async move |cx| {
9290 let (workspace_id, serialized_workspace) =
9291 deserialize_remote_project(connection_options.clone(), paths.clone(), cx).await?;
9292
9293 open_remote_project_inner(
9294 project,
9295 paths,
9296 workspace_id,
9297 serialized_workspace,
9298 app_state,
9299 window,
9300 cx,
9301 )
9302 .await
9303 })
9304}
9305
9306async fn open_remote_project_inner(
9307 project: Entity<Project>,
9308 paths: Vec<PathBuf>,
9309 workspace_id: WorkspaceId,
9310 serialized_workspace: Option<SerializedWorkspace>,
9311 app_state: Arc<AppState>,
9312 window: WindowHandle<MultiWorkspace>,
9313 cx: &mut AsyncApp,
9314) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
9315 let db = cx.update(|cx| WorkspaceDb::global(cx));
9316 let toolchains = db.toolchains(workspace_id).await?;
9317 for (toolchain, worktree_path, path) in toolchains {
9318 project
9319 .update(cx, |this, cx| {
9320 let Some(worktree_id) =
9321 this.find_worktree(&worktree_path, cx)
9322 .and_then(|(worktree, rel_path)| {
9323 if rel_path.is_empty() {
9324 Some(worktree.read(cx).id())
9325 } else {
9326 None
9327 }
9328 })
9329 else {
9330 return Task::ready(None);
9331 };
9332
9333 this.activate_toolchain(ProjectPath { worktree_id, path }, toolchain, cx)
9334 })
9335 .await;
9336 }
9337 let mut project_paths_to_open = vec![];
9338 let mut project_path_errors = vec![];
9339
9340 for path in paths {
9341 let result = cx
9342 .update(|cx| Workspace::project_path_for_path(project.clone(), &path, true, cx))
9343 .await;
9344 match result {
9345 Ok((_, project_path)) => {
9346 project_paths_to_open.push((path.clone(), Some(project_path)));
9347 }
9348 Err(error) => {
9349 project_path_errors.push(error);
9350 }
9351 };
9352 }
9353
9354 if project_paths_to_open.is_empty() {
9355 return Err(project_path_errors.pop().context("no paths given")?);
9356 }
9357
9358 let workspace = window.update(cx, |multi_workspace, window, cx| {
9359 telemetry::event!("SSH Project Opened");
9360
9361 let new_workspace = cx.new(|cx| {
9362 let mut workspace =
9363 Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);
9364 workspace.update_history(cx);
9365
9366 if let Some(ref serialized) = serialized_workspace {
9367 workspace.centered_layout = serialized.centered_layout;
9368 }
9369
9370 workspace
9371 });
9372
9373 multi_workspace.activate(new_workspace.clone(), cx);
9374 new_workspace
9375 })?;
9376
9377 let items = window
9378 .update(cx, |_, window, cx| {
9379 window.activate_window();
9380 workspace.update(cx, |_workspace, cx| {
9381 open_items(serialized_workspace, project_paths_to_open, window, cx)
9382 })
9383 })?
9384 .await?;
9385
9386 workspace.update(cx, |workspace, cx| {
9387 for error in project_path_errors {
9388 if error.error_code() == proto::ErrorCode::DevServerProjectPathDoesNotExist {
9389 if let Some(path) = error.error_tag("path") {
9390 workspace.show_error(&anyhow!("'{path}' does not exist"), cx)
9391 }
9392 } else {
9393 workspace.show_error(&error, cx)
9394 }
9395 }
9396 });
9397
9398 Ok(items.into_iter().map(|item| item?.ok()).collect())
9399}
9400
9401fn deserialize_remote_project(
9402 connection_options: RemoteConnectionOptions,
9403 paths: Vec<PathBuf>,
9404 cx: &AsyncApp,
9405) -> Task<Result<(WorkspaceId, Option<SerializedWorkspace>)>> {
9406 let db = cx.update(|cx| WorkspaceDb::global(cx));
9407 cx.background_spawn(async move {
9408 let remote_connection_id = db
9409 .get_or_create_remote_connection(connection_options)
9410 .await?;
9411
9412 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
9413
9414 let workspace_id = if let Some(workspace_id) =
9415 serialized_workspace.as_ref().map(|workspace| workspace.id)
9416 {
9417 workspace_id
9418 } else {
9419 db.next_id().await?
9420 };
9421
9422 Ok((workspace_id, serialized_workspace))
9423 })
9424}
9425
9426pub fn join_in_room_project(
9427 project_id: u64,
9428 follow_user_id: u64,
9429 app_state: Arc<AppState>,
9430 cx: &mut App,
9431) -> Task<Result<()>> {
9432 let windows = cx.windows();
9433 cx.spawn(async move |cx| {
9434 let existing_window_and_workspace: Option<(
9435 WindowHandle<MultiWorkspace>,
9436 Entity<Workspace>,
9437 )> = windows.into_iter().find_map(|window_handle| {
9438 window_handle
9439 .downcast::<MultiWorkspace>()
9440 .and_then(|window_handle| {
9441 window_handle
9442 .update(cx, |multi_workspace, _window, cx| {
9443 for workspace in multi_workspace.workspaces() {
9444 if workspace.read(cx).project().read(cx).remote_id()
9445 == Some(project_id)
9446 {
9447 return Some((window_handle, workspace.clone()));
9448 }
9449 }
9450 None
9451 })
9452 .unwrap_or(None)
9453 })
9454 });
9455
9456 let multi_workspace_window = if let Some((existing_window, target_workspace)) =
9457 existing_window_and_workspace
9458 {
9459 existing_window
9460 .update(cx, |multi_workspace, _, cx| {
9461 multi_workspace.activate(target_workspace, cx);
9462 })
9463 .ok();
9464 existing_window
9465 } else {
9466 let active_call = cx.update(|cx| GlobalAnyActiveCall::global(cx).clone());
9467 let project = cx
9468 .update(|cx| {
9469 active_call.0.join_project(
9470 project_id,
9471 app_state.languages.clone(),
9472 app_state.fs.clone(),
9473 cx,
9474 )
9475 })
9476 .await?;
9477
9478 let window_bounds_override = window_bounds_env_override();
9479 cx.update(|cx| {
9480 let mut options = (app_state.build_window_options)(None, cx);
9481 options.window_bounds = window_bounds_override.map(WindowBounds::Windowed);
9482 cx.open_window(options, |window, cx| {
9483 let workspace = cx.new(|cx| {
9484 Workspace::new(Default::default(), project, app_state.clone(), window, cx)
9485 });
9486 cx.new(|cx| MultiWorkspace::new(workspace, window, cx))
9487 })
9488 })?
9489 };
9490
9491 multi_workspace_window.update(cx, |multi_workspace, window, cx| {
9492 cx.activate(true);
9493 window.activate_window();
9494
9495 // We set the active workspace above, so this is the correct workspace.
9496 let workspace = multi_workspace.workspace().clone();
9497 workspace.update(cx, |workspace, cx| {
9498 let follow_peer_id = GlobalAnyActiveCall::try_global(cx)
9499 .and_then(|call| call.0.peer_id_for_user_in_room(follow_user_id, cx))
9500 .or_else(|| {
9501 // If we couldn't follow the given user, follow the host instead.
9502 let collaborator = workspace
9503 .project()
9504 .read(cx)
9505 .collaborators()
9506 .values()
9507 .find(|collaborator| collaborator.is_host)?;
9508 Some(collaborator.peer_id)
9509 });
9510
9511 if let Some(follow_peer_id) = follow_peer_id {
9512 workspace.follow(follow_peer_id, window, cx);
9513 }
9514 });
9515 })?;
9516
9517 anyhow::Ok(())
9518 })
9519}
9520
9521pub fn reload(cx: &mut App) {
9522 let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
9523 let mut workspace_windows = cx
9524 .windows()
9525 .into_iter()
9526 .filter_map(|window| window.downcast::<MultiWorkspace>())
9527 .collect::<Vec<_>>();
9528
9529 // If multiple windows have unsaved changes, and need a save prompt,
9530 // prompt in the active window before switching to a different window.
9531 workspace_windows.sort_by_key(|window| window.is_active(cx) == Some(false));
9532
9533 let mut prompt = None;
9534 if let (true, Some(window)) = (should_confirm, workspace_windows.first()) {
9535 prompt = window
9536 .update(cx, |_, window, cx| {
9537 window.prompt(
9538 PromptLevel::Info,
9539 "Are you sure you want to restart?",
9540 None,
9541 &["Restart", "Cancel"],
9542 cx,
9543 )
9544 })
9545 .ok();
9546 }
9547
9548 cx.spawn(async move |cx| {
9549 if let Some(prompt) = prompt {
9550 let answer = prompt.await?;
9551 if answer != 0 {
9552 return anyhow::Ok(());
9553 }
9554 }
9555
9556 // If the user cancels any save prompt, then keep the app open.
9557 for window in workspace_windows {
9558 if let Ok(should_close) = window.update(cx, |multi_workspace, window, cx| {
9559 let workspace = multi_workspace.workspace().clone();
9560 workspace.update(cx, |workspace, cx| {
9561 workspace.prepare_to_close(CloseIntent::Quit, window, cx)
9562 })
9563 }) && !should_close.await?
9564 {
9565 return anyhow::Ok(());
9566 }
9567 }
9568 cx.update(|cx| cx.restart());
9569 anyhow::Ok(())
9570 })
9571 .detach_and_log_err(cx);
9572}
9573
9574fn parse_pixel_position_env_var(value: &str) -> Option<Point<Pixels>> {
9575 let mut parts = value.split(',');
9576 let x: usize = parts.next()?.parse().ok()?;
9577 let y: usize = parts.next()?.parse().ok()?;
9578 Some(point(px(x as f32), px(y as f32)))
9579}
9580
9581fn parse_pixel_size_env_var(value: &str) -> Option<Size<Pixels>> {
9582 let mut parts = value.split(',');
9583 let width: usize = parts.next()?.parse().ok()?;
9584 let height: usize = parts.next()?.parse().ok()?;
9585 Some(size(px(width as f32), px(height as f32)))
9586}
9587
9588/// Add client-side decorations (rounded corners, shadows, resize handling) when
9589/// appropriate.
9590///
9591/// The `border_radius_tiling` parameter allows overriding which corners get
9592/// rounded, independently of the actual window tiling state. This is used
9593/// specifically for the workspace switcher sidebar: when the sidebar is open,
9594/// we want square corners on the left (so the sidebar appears flush with the
9595/// window edge) but we still need the shadow padding for proper visual
9596/// appearance. Unlike actual window tiling, this only affects border radius -
9597/// not padding or shadows.
9598pub fn client_side_decorations(
9599 element: impl IntoElement,
9600 window: &mut Window,
9601 cx: &mut App,
9602 border_radius_tiling: Tiling,
9603) -> Stateful<Div> {
9604 const BORDER_SIZE: Pixels = px(1.0);
9605 let decorations = window.window_decorations();
9606 let tiling = match decorations {
9607 Decorations::Server => Tiling::default(),
9608 Decorations::Client { tiling } => tiling,
9609 };
9610
9611 match decorations {
9612 Decorations::Client { .. } => window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW),
9613 Decorations::Server => window.set_client_inset(px(0.0)),
9614 }
9615
9616 struct GlobalResizeEdge(ResizeEdge);
9617 impl Global for GlobalResizeEdge {}
9618
9619 div()
9620 .id("window-backdrop")
9621 .bg(transparent_black())
9622 .map(|div| match decorations {
9623 Decorations::Server => div,
9624 Decorations::Client { .. } => div
9625 .when(
9626 !(tiling.top
9627 || tiling.right
9628 || border_radius_tiling.top
9629 || border_radius_tiling.right),
9630 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9631 )
9632 .when(
9633 !(tiling.top
9634 || tiling.left
9635 || border_radius_tiling.top
9636 || border_radius_tiling.left),
9637 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9638 )
9639 .when(
9640 !(tiling.bottom
9641 || tiling.right
9642 || border_radius_tiling.bottom
9643 || border_radius_tiling.right),
9644 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9645 )
9646 .when(
9647 !(tiling.bottom
9648 || tiling.left
9649 || border_radius_tiling.bottom
9650 || border_radius_tiling.left),
9651 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9652 )
9653 .when(!tiling.top, |div| {
9654 div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW)
9655 })
9656 .when(!tiling.bottom, |div| {
9657 div.pb(theme::CLIENT_SIDE_DECORATION_SHADOW)
9658 })
9659 .when(!tiling.left, |div| {
9660 div.pl(theme::CLIENT_SIDE_DECORATION_SHADOW)
9661 })
9662 .when(!tiling.right, |div| {
9663 div.pr(theme::CLIENT_SIDE_DECORATION_SHADOW)
9664 })
9665 .on_mouse_move(move |e, window, cx| {
9666 let size = window.window_bounds().get_bounds().size;
9667 let pos = e.position;
9668
9669 let new_edge =
9670 resize_edge(pos, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling);
9671
9672 let edge = cx.try_global::<GlobalResizeEdge>();
9673 if new_edge != edge.map(|edge| edge.0) {
9674 window
9675 .window_handle()
9676 .update(cx, |workspace, _, cx| {
9677 cx.notify(workspace.entity_id());
9678 })
9679 .ok();
9680 }
9681 })
9682 .on_mouse_down(MouseButton::Left, move |e, window, _| {
9683 let size = window.window_bounds().get_bounds().size;
9684 let pos = e.position;
9685
9686 let edge = match resize_edge(
9687 pos,
9688 theme::CLIENT_SIDE_DECORATION_SHADOW,
9689 size,
9690 tiling,
9691 ) {
9692 Some(value) => value,
9693 None => return,
9694 };
9695
9696 window.start_window_resize(edge);
9697 }),
9698 })
9699 .size_full()
9700 .child(
9701 div()
9702 .cursor(CursorStyle::Arrow)
9703 .map(|div| match decorations {
9704 Decorations::Server => div,
9705 Decorations::Client { .. } => div
9706 .border_color(cx.theme().colors().border)
9707 .when(
9708 !(tiling.top
9709 || tiling.right
9710 || border_radius_tiling.top
9711 || border_radius_tiling.right),
9712 |div| div.rounded_tr(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9713 )
9714 .when(
9715 !(tiling.top
9716 || tiling.left
9717 || border_radius_tiling.top
9718 || border_radius_tiling.left),
9719 |div| div.rounded_tl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9720 )
9721 .when(
9722 !(tiling.bottom
9723 || tiling.right
9724 || border_radius_tiling.bottom
9725 || border_radius_tiling.right),
9726 |div| div.rounded_br(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9727 )
9728 .when(
9729 !(tiling.bottom
9730 || tiling.left
9731 || border_radius_tiling.bottom
9732 || border_radius_tiling.left),
9733 |div| div.rounded_bl(theme::CLIENT_SIDE_DECORATION_ROUNDING),
9734 )
9735 .when(!tiling.top, |div| div.border_t(BORDER_SIZE))
9736 .when(!tiling.bottom, |div| div.border_b(BORDER_SIZE))
9737 .when(!tiling.left, |div| div.border_l(BORDER_SIZE))
9738 .when(!tiling.right, |div| div.border_r(BORDER_SIZE))
9739 .when(!tiling.is_tiled(), |div| {
9740 div.shadow(vec![gpui::BoxShadow {
9741 color: Hsla {
9742 h: 0.,
9743 s: 0.,
9744 l: 0.,
9745 a: 0.4,
9746 },
9747 blur_radius: theme::CLIENT_SIDE_DECORATION_SHADOW / 2.,
9748 spread_radius: px(0.),
9749 offset: point(px(0.0), px(0.0)),
9750 }])
9751 }),
9752 })
9753 .on_mouse_move(|_e, _, cx| {
9754 cx.stop_propagation();
9755 })
9756 .size_full()
9757 .child(element),
9758 )
9759 .map(|div| match decorations {
9760 Decorations::Server => div,
9761 Decorations::Client { tiling, .. } => div.child(
9762 canvas(
9763 |_bounds, window, _| {
9764 window.insert_hitbox(
9765 Bounds::new(
9766 point(px(0.0), px(0.0)),
9767 window.window_bounds().get_bounds().size,
9768 ),
9769 HitboxBehavior::Normal,
9770 )
9771 },
9772 move |_bounds, hitbox, window, cx| {
9773 let mouse = window.mouse_position();
9774 let size = window.window_bounds().get_bounds().size;
9775 let Some(edge) =
9776 resize_edge(mouse, theme::CLIENT_SIDE_DECORATION_SHADOW, size, tiling)
9777 else {
9778 return;
9779 };
9780 cx.set_global(GlobalResizeEdge(edge));
9781 window.set_cursor_style(
9782 match edge {
9783 ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown,
9784 ResizeEdge::Left | ResizeEdge::Right => {
9785 CursorStyle::ResizeLeftRight
9786 }
9787 ResizeEdge::TopLeft | ResizeEdge::BottomRight => {
9788 CursorStyle::ResizeUpLeftDownRight
9789 }
9790 ResizeEdge::TopRight | ResizeEdge::BottomLeft => {
9791 CursorStyle::ResizeUpRightDownLeft
9792 }
9793 },
9794 &hitbox,
9795 );
9796 },
9797 )
9798 .size_full()
9799 .absolute(),
9800 ),
9801 })
9802}
9803
9804fn resize_edge(
9805 pos: Point<Pixels>,
9806 shadow_size: Pixels,
9807 window_size: Size<Pixels>,
9808 tiling: Tiling,
9809) -> Option<ResizeEdge> {
9810 let bounds = Bounds::new(Point::default(), window_size).inset(shadow_size * 1.5);
9811 if bounds.contains(&pos) {
9812 return None;
9813 }
9814
9815 let corner_size = size(shadow_size * 1.5, shadow_size * 1.5);
9816 let top_left_bounds = Bounds::new(Point::new(px(0.), px(0.)), corner_size);
9817 if !tiling.top && top_left_bounds.contains(&pos) {
9818 return Some(ResizeEdge::TopLeft);
9819 }
9820
9821 let top_right_bounds = Bounds::new(
9822 Point::new(window_size.width - corner_size.width, px(0.)),
9823 corner_size,
9824 );
9825 if !tiling.top && top_right_bounds.contains(&pos) {
9826 return Some(ResizeEdge::TopRight);
9827 }
9828
9829 let bottom_left_bounds = Bounds::new(
9830 Point::new(px(0.), window_size.height - corner_size.height),
9831 corner_size,
9832 );
9833 if !tiling.bottom && bottom_left_bounds.contains(&pos) {
9834 return Some(ResizeEdge::BottomLeft);
9835 }
9836
9837 let bottom_right_bounds = Bounds::new(
9838 Point::new(
9839 window_size.width - corner_size.width,
9840 window_size.height - corner_size.height,
9841 ),
9842 corner_size,
9843 );
9844 if !tiling.bottom && bottom_right_bounds.contains(&pos) {
9845 return Some(ResizeEdge::BottomRight);
9846 }
9847
9848 if !tiling.top && pos.y < shadow_size {
9849 Some(ResizeEdge::Top)
9850 } else if !tiling.bottom && pos.y > window_size.height - shadow_size {
9851 Some(ResizeEdge::Bottom)
9852 } else if !tiling.left && pos.x < shadow_size {
9853 Some(ResizeEdge::Left)
9854 } else if !tiling.right && pos.x > window_size.width - shadow_size {
9855 Some(ResizeEdge::Right)
9856 } else {
9857 None
9858 }
9859}
9860
9861fn join_pane_into_active(
9862 active_pane: &Entity<Pane>,
9863 pane: &Entity<Pane>,
9864 window: &mut Window,
9865 cx: &mut App,
9866) {
9867 if pane == active_pane {
9868 } else if pane.read(cx).items_len() == 0 {
9869 pane.update(cx, |_, cx| {
9870 cx.emit(pane::Event::Remove {
9871 focus_on_pane: None,
9872 });
9873 })
9874 } else {
9875 move_all_items(pane, active_pane, window, cx);
9876 }
9877}
9878
9879fn move_all_items(
9880 from_pane: &Entity<Pane>,
9881 to_pane: &Entity<Pane>,
9882 window: &mut Window,
9883 cx: &mut App,
9884) {
9885 let destination_is_different = from_pane != to_pane;
9886 let mut moved_items = 0;
9887 for (item_ix, item_handle) in from_pane
9888 .read(cx)
9889 .items()
9890 .enumerate()
9891 .map(|(ix, item)| (ix, item.clone()))
9892 .collect::<Vec<_>>()
9893 {
9894 let ix = item_ix - moved_items;
9895 if destination_is_different {
9896 // Close item from previous pane
9897 from_pane.update(cx, |source, cx| {
9898 source.remove_item_and_focus_on_pane(ix, false, to_pane.clone(), window, cx);
9899 });
9900 moved_items += 1;
9901 }
9902
9903 // This automatically removes duplicate items in the pane
9904 to_pane.update(cx, |destination, cx| {
9905 destination.add_item(item_handle, true, true, None, window, cx);
9906 window.focus(&destination.focus_handle(cx), cx)
9907 });
9908 }
9909}
9910
9911pub fn move_item(
9912 source: &Entity<Pane>,
9913 destination: &Entity<Pane>,
9914 item_id_to_move: EntityId,
9915 destination_index: usize,
9916 activate: bool,
9917 window: &mut Window,
9918 cx: &mut App,
9919) {
9920 let Some((item_ix, item_handle)) = source
9921 .read(cx)
9922 .items()
9923 .enumerate()
9924 .find(|(_, item_handle)| item_handle.item_id() == item_id_to_move)
9925 .map(|(ix, item)| (ix, item.clone()))
9926 else {
9927 // Tab was closed during drag
9928 return;
9929 };
9930
9931 if source != destination {
9932 // Close item from previous pane
9933 source.update(cx, |source, cx| {
9934 source.remove_item_and_focus_on_pane(item_ix, false, destination.clone(), window, cx);
9935 });
9936 }
9937
9938 // This automatically removes duplicate items in the pane
9939 destination.update(cx, |destination, cx| {
9940 destination.add_item_inner(
9941 item_handle,
9942 activate,
9943 activate,
9944 activate,
9945 Some(destination_index),
9946 window,
9947 cx,
9948 );
9949 if activate {
9950 window.focus(&destination.focus_handle(cx), cx)
9951 }
9952 });
9953}
9954
9955pub fn move_active_item(
9956 source: &Entity<Pane>,
9957 destination: &Entity<Pane>,
9958 focus_destination: bool,
9959 close_if_empty: bool,
9960 window: &mut Window,
9961 cx: &mut App,
9962) {
9963 if source == destination {
9964 return;
9965 }
9966 let Some(active_item) = source.read(cx).active_item() else {
9967 return;
9968 };
9969 source.update(cx, |source_pane, cx| {
9970 let item_id = active_item.item_id();
9971 source_pane.remove_item(item_id, false, close_if_empty, window, cx);
9972 destination.update(cx, |target_pane, cx| {
9973 target_pane.add_item(
9974 active_item,
9975 focus_destination,
9976 focus_destination,
9977 Some(target_pane.items_len()),
9978 window,
9979 cx,
9980 );
9981 });
9982 });
9983}
9984
9985pub fn clone_active_item(
9986 workspace_id: Option<WorkspaceId>,
9987 source: &Entity<Pane>,
9988 destination: &Entity<Pane>,
9989 focus_destination: bool,
9990 window: &mut Window,
9991 cx: &mut App,
9992) {
9993 if source == destination {
9994 return;
9995 }
9996 let Some(active_item) = source.read(cx).active_item() else {
9997 return;
9998 };
9999 if !active_item.can_split(cx) {
10000 return;
10001 }
10002 let destination = destination.downgrade();
10003 let task = active_item.clone_on_split(workspace_id, window, cx);
10004 window
10005 .spawn(cx, async move |cx| {
10006 let Some(clone) = task.await else {
10007 return;
10008 };
10009 destination
10010 .update_in(cx, |target_pane, window, cx| {
10011 target_pane.add_item(
10012 clone,
10013 focus_destination,
10014 focus_destination,
10015 Some(target_pane.items_len()),
10016 window,
10017 cx,
10018 );
10019 })
10020 .log_err();
10021 })
10022 .detach();
10023}
10024
10025#[derive(Debug)]
10026pub struct WorkspacePosition {
10027 pub window_bounds: Option<WindowBounds>,
10028 pub display: Option<Uuid>,
10029 pub centered_layout: bool,
10030}
10031
10032pub fn remote_workspace_position_from_db(
10033 connection_options: RemoteConnectionOptions,
10034 paths_to_open: &[PathBuf],
10035 cx: &App,
10036) -> Task<Result<WorkspacePosition>> {
10037 let paths = paths_to_open.to_vec();
10038 let db = WorkspaceDb::global(cx);
10039 let kvp = db::kvp::KeyValueStore::global(cx);
10040
10041 cx.background_spawn(async move {
10042 let remote_connection_id = db
10043 .get_or_create_remote_connection(connection_options)
10044 .await
10045 .context("fetching serialized ssh project")?;
10046 let serialized_workspace = db.remote_workspace_for_roots(&paths, remote_connection_id);
10047
10048 let (window_bounds, display) = if let Some(bounds) = window_bounds_env_override() {
10049 (Some(WindowBounds::Windowed(bounds)), None)
10050 } else {
10051 let restorable_bounds = serialized_workspace
10052 .as_ref()
10053 .and_then(|workspace| {
10054 Some((workspace.display?, workspace.window_bounds.map(|b| b.0)?))
10055 })
10056 .or_else(|| persistence::read_default_window_bounds(&kvp));
10057
10058 if let Some((serialized_display, serialized_bounds)) = restorable_bounds {
10059 (Some(serialized_bounds), Some(serialized_display))
10060 } else {
10061 (None, None)
10062 }
10063 };
10064
10065 let centered_layout = serialized_workspace
10066 .as_ref()
10067 .map(|w| w.centered_layout)
10068 .unwrap_or(false);
10069
10070 Ok(WorkspacePosition {
10071 window_bounds,
10072 display,
10073 centered_layout,
10074 })
10075 })
10076}
10077
10078pub fn with_active_or_new_workspace(
10079 cx: &mut App,
10080 f: impl FnOnce(&mut Workspace, &mut Window, &mut Context<Workspace>) + Send + 'static,
10081) {
10082 match cx
10083 .active_window()
10084 .and_then(|w| w.downcast::<MultiWorkspace>())
10085 {
10086 Some(multi_workspace) => {
10087 cx.defer(move |cx| {
10088 multi_workspace
10089 .update(cx, |multi_workspace, window, cx| {
10090 let workspace = multi_workspace.workspace().clone();
10091 workspace.update(cx, |workspace, cx| f(workspace, window, cx));
10092 })
10093 .log_err();
10094 });
10095 }
10096 None => {
10097 let app_state = AppState::global(cx);
10098 if let Some(app_state) = app_state.upgrade() {
10099 open_new(
10100 OpenOptions::default(),
10101 app_state,
10102 cx,
10103 move |workspace, window, cx| f(workspace, window, cx),
10104 )
10105 .detach_and_log_err(cx);
10106 }
10107 }
10108 }
10109}
10110
10111#[cfg(test)]
10112mod tests {
10113 use std::{cell::RefCell, rc::Rc, sync::Arc, time::Duration};
10114
10115 use super::*;
10116 use crate::{
10117 dock::{PanelEvent, test::TestPanel},
10118 item::{
10119 ItemBufferKind, ItemEvent,
10120 test::{TestItem, TestProjectItem},
10121 },
10122 };
10123 use fs::FakeFs;
10124 use gpui::{
10125 DismissEvent, Empty, EventEmitter, FocusHandle, Focusable, Render, TestAppContext,
10126 UpdateGlobal, VisualTestContext, px,
10127 };
10128 use project::{Project, ProjectEntryId};
10129 use serde_json::json;
10130 use settings::SettingsStore;
10131 use util::path;
10132 use util::rel_path::rel_path;
10133
10134 #[gpui::test]
10135 async fn test_tab_disambiguation(cx: &mut TestAppContext) {
10136 init_test(cx);
10137
10138 let fs = FakeFs::new(cx.executor());
10139 let project = Project::test(fs, [], cx).await;
10140 let (workspace, cx) =
10141 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10142
10143 // Adding an item with no ambiguity renders the tab without detail.
10144 let item1 = cx.new(|cx| {
10145 let mut item = TestItem::new(cx);
10146 item.tab_descriptions = Some(vec!["c", "b1/c", "a/b1/c"]);
10147 item
10148 });
10149 workspace.update_in(cx, |workspace, window, cx| {
10150 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10151 });
10152 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(0)));
10153
10154 // Adding an item that creates ambiguity increases the level of detail on
10155 // both tabs.
10156 let item2 = cx.new_window_entity(|_window, cx| {
10157 let mut item = TestItem::new(cx);
10158 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10159 item
10160 });
10161 workspace.update_in(cx, |workspace, window, cx| {
10162 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10163 });
10164 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10165 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10166
10167 // Adding an item that creates ambiguity increases the level of detail only
10168 // on the ambiguous tabs. In this case, the ambiguity can't be resolved so
10169 // we stop at the highest detail available.
10170 let item3 = cx.new(|cx| {
10171 let mut item = TestItem::new(cx);
10172 item.tab_descriptions = Some(vec!["c", "b2/c", "a/b2/c"]);
10173 item
10174 });
10175 workspace.update_in(cx, |workspace, window, cx| {
10176 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10177 });
10178 item1.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(1)));
10179 item2.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10180 item3.read_with(cx, |item, _| assert_eq!(item.tab_detail.get(), Some(3)));
10181 }
10182
10183 #[gpui::test]
10184 async fn test_tracking_active_path(cx: &mut TestAppContext) {
10185 init_test(cx);
10186
10187 let fs = FakeFs::new(cx.executor());
10188 fs.insert_tree(
10189 "/root1",
10190 json!({
10191 "one.txt": "",
10192 "two.txt": "",
10193 }),
10194 )
10195 .await;
10196 fs.insert_tree(
10197 "/root2",
10198 json!({
10199 "three.txt": "",
10200 }),
10201 )
10202 .await;
10203
10204 let project = Project::test(fs, ["root1".as_ref()], cx).await;
10205 let (workspace, cx) =
10206 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10207 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10208 let worktree_id = project.update(cx, |project, cx| {
10209 project.worktrees(cx).next().unwrap().read(cx).id()
10210 });
10211
10212 let item1 = cx.new(|cx| {
10213 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "one.txt", cx)])
10214 });
10215 let item2 = cx.new(|cx| {
10216 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "two.txt", cx)])
10217 });
10218
10219 // Add an item to an empty pane
10220 workspace.update_in(cx, |workspace, window, cx| {
10221 workspace.add_item_to_active_pane(Box::new(item1), None, true, window, cx)
10222 });
10223 project.update(cx, |project, cx| {
10224 assert_eq!(
10225 project.active_entry(),
10226 project
10227 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10228 .map(|e| e.id)
10229 );
10230 });
10231 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10232
10233 // Add a second item to a non-empty pane
10234 workspace.update_in(cx, |workspace, window, cx| {
10235 workspace.add_item_to_active_pane(Box::new(item2), None, true, window, cx)
10236 });
10237 assert_eq!(cx.window_title().as_deref(), Some("root1 — two.txt"));
10238 project.update(cx, |project, cx| {
10239 assert_eq!(
10240 project.active_entry(),
10241 project
10242 .entry_for_path(&(worktree_id, rel_path("two.txt")).into(), cx)
10243 .map(|e| e.id)
10244 );
10245 });
10246
10247 // Close the active item
10248 pane.update_in(cx, |pane, window, cx| {
10249 pane.close_active_item(&Default::default(), window, cx)
10250 })
10251 .await
10252 .unwrap();
10253 assert_eq!(cx.window_title().as_deref(), Some("root1 — one.txt"));
10254 project.update(cx, |project, cx| {
10255 assert_eq!(
10256 project.active_entry(),
10257 project
10258 .entry_for_path(&(worktree_id, rel_path("one.txt")).into(), cx)
10259 .map(|e| e.id)
10260 );
10261 });
10262
10263 // Add a project folder
10264 project
10265 .update(cx, |project, cx| {
10266 project.find_or_create_worktree("root2", true, cx)
10267 })
10268 .await
10269 .unwrap();
10270 assert_eq!(cx.window_title().as_deref(), Some("root1, root2 — one.txt"));
10271
10272 // Remove a project folder
10273 project.update(cx, |project, cx| project.remove_worktree(worktree_id, cx));
10274 assert_eq!(cx.window_title().as_deref(), Some("root2 — one.txt"));
10275 }
10276
10277 #[gpui::test]
10278 async fn test_close_window(cx: &mut TestAppContext) {
10279 init_test(cx);
10280
10281 let fs = FakeFs::new(cx.executor());
10282 fs.insert_tree("/root", json!({ "one": "" })).await;
10283
10284 let project = Project::test(fs, ["root".as_ref()], cx).await;
10285 let (workspace, cx) =
10286 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10287
10288 // When there are no dirty items, there's nothing to do.
10289 let item1 = cx.new(TestItem::new);
10290 workspace.update_in(cx, |w, window, cx| {
10291 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx)
10292 });
10293 let task = workspace.update_in(cx, |w, window, cx| {
10294 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10295 });
10296 assert!(task.await.unwrap());
10297
10298 // When there are dirty untitled items, prompt to save each one. If the user
10299 // cancels any prompt, then abort.
10300 let item2 = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10301 let item3 = cx.new(|cx| {
10302 TestItem::new(cx)
10303 .with_dirty(true)
10304 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10305 });
10306 workspace.update_in(cx, |w, window, cx| {
10307 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10308 w.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10309 });
10310 let task = workspace.update_in(cx, |w, window, cx| {
10311 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10312 });
10313 cx.executor().run_until_parked();
10314 cx.simulate_prompt_answer("Cancel"); // cancel save all
10315 cx.executor().run_until_parked();
10316 assert!(!cx.has_pending_prompt());
10317 assert!(!task.await.unwrap());
10318 }
10319
10320 #[gpui::test]
10321 async fn test_multi_workspace_close_window_multiple_workspaces_cancel(cx: &mut TestAppContext) {
10322 init_test(cx);
10323
10324 let fs = FakeFs::new(cx.executor());
10325 fs.insert_tree("/root", json!({ "one": "" })).await;
10326
10327 let project_a = Project::test(fs.clone(), ["root".as_ref()], cx).await;
10328 let project_b = Project::test(fs, ["root".as_ref()], cx).await;
10329 let multi_workspace_handle =
10330 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
10331 cx.run_until_parked();
10332
10333 let workspace_a = multi_workspace_handle
10334 .read_with(cx, |mw, _| mw.workspace().clone())
10335 .unwrap();
10336
10337 let workspace_b = multi_workspace_handle
10338 .update(cx, |mw, window, cx| {
10339 mw.test_add_workspace(project_b, window, cx)
10340 })
10341 .unwrap();
10342
10343 // Activate workspace A
10344 multi_workspace_handle
10345 .update(cx, |mw, window, cx| {
10346 mw.activate_index(0, window, cx);
10347 })
10348 .unwrap();
10349
10350 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
10351
10352 // Workspace A has a clean item
10353 let item_a = cx.new(TestItem::new);
10354 workspace_a.update_in(cx, |w, window, cx| {
10355 w.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
10356 });
10357
10358 // Workspace B has a dirty item
10359 let item_b = cx.new(|cx| TestItem::new(cx).with_dirty(true));
10360 workspace_b.update_in(cx, |w, window, cx| {
10361 w.add_item_to_active_pane(Box::new(item_b.clone()), None, true, window, cx)
10362 });
10363
10364 // Verify workspace A is active
10365 multi_workspace_handle
10366 .read_with(cx, |mw, _| {
10367 assert_eq!(mw.active_workspace_index(), 0);
10368 })
10369 .unwrap();
10370
10371 // Dispatch CloseWindow — workspace A will pass, workspace B will prompt
10372 multi_workspace_handle
10373 .update(cx, |mw, window, cx| {
10374 mw.close_window(&CloseWindow, window, cx);
10375 })
10376 .unwrap();
10377 cx.run_until_parked();
10378
10379 // Workspace B should now be active since it has dirty items that need attention
10380 multi_workspace_handle
10381 .read_with(cx, |mw, _| {
10382 assert_eq!(
10383 mw.active_workspace_index(),
10384 1,
10385 "workspace B should be activated when it prompts"
10386 );
10387 })
10388 .unwrap();
10389
10390 // User cancels the save prompt from workspace B
10391 cx.simulate_prompt_answer("Cancel");
10392 cx.run_until_parked();
10393
10394 // Window should still exist because workspace B's close was cancelled
10395 assert!(
10396 multi_workspace_handle.update(cx, |_, _, _| ()).is_ok(),
10397 "window should still exist after cancelling one workspace's close"
10398 );
10399 }
10400
10401 #[gpui::test]
10402 async fn test_close_window_with_serializable_items(cx: &mut TestAppContext) {
10403 init_test(cx);
10404
10405 // Register TestItem as a serializable item
10406 cx.update(|cx| {
10407 register_serializable_item::<TestItem>(cx);
10408 });
10409
10410 let fs = FakeFs::new(cx.executor());
10411 fs.insert_tree("/root", json!({ "one": "" })).await;
10412
10413 let project = Project::test(fs, ["root".as_ref()], cx).await;
10414 let (workspace, cx) =
10415 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
10416
10417 // When there are dirty untitled items, but they can serialize, then there is no prompt.
10418 let item1 = cx.new(|cx| {
10419 TestItem::new(cx)
10420 .with_dirty(true)
10421 .with_serialize(|| Some(Task::ready(Ok(()))))
10422 });
10423 let item2 = cx.new(|cx| {
10424 TestItem::new(cx)
10425 .with_dirty(true)
10426 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10427 .with_serialize(|| Some(Task::ready(Ok(()))))
10428 });
10429 workspace.update_in(cx, |w, window, cx| {
10430 w.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10431 w.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10432 });
10433 let task = workspace.update_in(cx, |w, window, cx| {
10434 w.prepare_to_close(CloseIntent::CloseWindow, window, cx)
10435 });
10436 assert!(task.await.unwrap());
10437 }
10438
10439 #[gpui::test]
10440 async fn test_close_pane_items(cx: &mut TestAppContext) {
10441 init_test(cx);
10442
10443 let fs = FakeFs::new(cx.executor());
10444
10445 let project = Project::test(fs, None, cx).await;
10446 let (workspace, cx) =
10447 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10448
10449 let item1 = cx.new(|cx| {
10450 TestItem::new(cx)
10451 .with_dirty(true)
10452 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
10453 });
10454 let item2 = cx.new(|cx| {
10455 TestItem::new(cx)
10456 .with_dirty(true)
10457 .with_conflict(true)
10458 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
10459 });
10460 let item3 = cx.new(|cx| {
10461 TestItem::new(cx)
10462 .with_dirty(true)
10463 .with_conflict(true)
10464 .with_project_items(&[dirty_project_item(3, "3.txt", cx)])
10465 });
10466 let item4 = cx.new(|cx| {
10467 TestItem::new(cx).with_dirty(true).with_project_items(&[{
10468 let project_item = TestProjectItem::new_untitled(cx);
10469 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10470 project_item
10471 }])
10472 });
10473 let pane = workspace.update_in(cx, |workspace, window, cx| {
10474 workspace.add_item_to_active_pane(Box::new(item1.clone()), None, true, window, cx);
10475 workspace.add_item_to_active_pane(Box::new(item2.clone()), None, true, window, cx);
10476 workspace.add_item_to_active_pane(Box::new(item3.clone()), None, true, window, cx);
10477 workspace.add_item_to_active_pane(Box::new(item4.clone()), None, true, window, cx);
10478 workspace.active_pane().clone()
10479 });
10480
10481 let close_items = pane.update_in(cx, |pane, window, cx| {
10482 pane.activate_item(1, true, true, window, cx);
10483 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10484 let item1_id = item1.item_id();
10485 let item3_id = item3.item_id();
10486 let item4_id = item4.item_id();
10487 pane.close_items(window, cx, SaveIntent::Close, &move |id| {
10488 [item1_id, item3_id, item4_id].contains(&id)
10489 })
10490 });
10491 cx.executor().run_until_parked();
10492
10493 assert!(cx.has_pending_prompt());
10494 cx.simulate_prompt_answer("Save all");
10495
10496 cx.executor().run_until_parked();
10497
10498 // Item 1 is saved. There's a prompt to save item 3.
10499 pane.update(cx, |pane, cx| {
10500 assert_eq!(item1.read(cx).save_count, 1);
10501 assert_eq!(item1.read(cx).save_as_count, 0);
10502 assert_eq!(item1.read(cx).reload_count, 0);
10503 assert_eq!(pane.items_len(), 3);
10504 assert_eq!(pane.active_item().unwrap().item_id(), item3.item_id());
10505 });
10506 assert!(cx.has_pending_prompt());
10507
10508 // Cancel saving item 3.
10509 cx.simulate_prompt_answer("Discard");
10510 cx.executor().run_until_parked();
10511
10512 // Item 3 is reloaded. There's a prompt to save item 4.
10513 pane.update(cx, |pane, cx| {
10514 assert_eq!(item3.read(cx).save_count, 0);
10515 assert_eq!(item3.read(cx).save_as_count, 0);
10516 assert_eq!(item3.read(cx).reload_count, 1);
10517 assert_eq!(pane.items_len(), 2);
10518 assert_eq!(pane.active_item().unwrap().item_id(), item4.item_id());
10519 });
10520
10521 // There's a prompt for a path for item 4.
10522 cx.simulate_new_path_selection(|_| Some(Default::default()));
10523 close_items.await.unwrap();
10524
10525 // The requested items are closed.
10526 pane.update(cx, |pane, cx| {
10527 assert_eq!(item4.read(cx).save_count, 0);
10528 assert_eq!(item4.read(cx).save_as_count, 1);
10529 assert_eq!(item4.read(cx).reload_count, 0);
10530 assert_eq!(pane.items_len(), 1);
10531 assert_eq!(pane.active_item().unwrap().item_id(), item2.item_id());
10532 });
10533 }
10534
10535 #[gpui::test]
10536 async fn test_prompting_to_save_only_on_last_item_for_entry(cx: &mut TestAppContext) {
10537 init_test(cx);
10538
10539 let fs = FakeFs::new(cx.executor());
10540 let project = Project::test(fs, [], cx).await;
10541 let (workspace, cx) =
10542 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10543
10544 // Create several workspace items with single project entries, and two
10545 // workspace items with multiple project entries.
10546 let single_entry_items = (0..=4)
10547 .map(|project_entry_id| {
10548 cx.new(|cx| {
10549 TestItem::new(cx)
10550 .with_dirty(true)
10551 .with_project_items(&[dirty_project_item(
10552 project_entry_id,
10553 &format!("{project_entry_id}.txt"),
10554 cx,
10555 )])
10556 })
10557 })
10558 .collect::<Vec<_>>();
10559 let item_2_3 = cx.new(|cx| {
10560 TestItem::new(cx)
10561 .with_dirty(true)
10562 .with_buffer_kind(ItemBufferKind::Multibuffer)
10563 .with_project_items(&[
10564 single_entry_items[2].read(cx).project_items[0].clone(),
10565 single_entry_items[3].read(cx).project_items[0].clone(),
10566 ])
10567 });
10568 let item_3_4 = cx.new(|cx| {
10569 TestItem::new(cx)
10570 .with_dirty(true)
10571 .with_buffer_kind(ItemBufferKind::Multibuffer)
10572 .with_project_items(&[
10573 single_entry_items[3].read(cx).project_items[0].clone(),
10574 single_entry_items[4].read(cx).project_items[0].clone(),
10575 ])
10576 });
10577
10578 // Create two panes that contain the following project entries:
10579 // left pane:
10580 // multi-entry items: (2, 3)
10581 // single-entry items: 0, 2, 3, 4
10582 // right pane:
10583 // single-entry items: 4, 1
10584 // multi-entry items: (3, 4)
10585 let (left_pane, right_pane) = workspace.update_in(cx, |workspace, window, cx| {
10586 let left_pane = workspace.active_pane().clone();
10587 workspace.add_item_to_active_pane(Box::new(item_2_3.clone()), None, true, window, cx);
10588 workspace.add_item_to_active_pane(
10589 single_entry_items[0].boxed_clone(),
10590 None,
10591 true,
10592 window,
10593 cx,
10594 );
10595 workspace.add_item_to_active_pane(
10596 single_entry_items[2].boxed_clone(),
10597 None,
10598 true,
10599 window,
10600 cx,
10601 );
10602 workspace.add_item_to_active_pane(
10603 single_entry_items[3].boxed_clone(),
10604 None,
10605 true,
10606 window,
10607 cx,
10608 );
10609 workspace.add_item_to_active_pane(
10610 single_entry_items[4].boxed_clone(),
10611 None,
10612 true,
10613 window,
10614 cx,
10615 );
10616
10617 let right_pane =
10618 workspace.split_and_clone(left_pane.clone(), SplitDirection::Right, window, cx);
10619
10620 let boxed_clone = single_entry_items[1].boxed_clone();
10621 let right_pane = window.spawn(cx, async move |cx| {
10622 right_pane.await.inspect(|right_pane| {
10623 right_pane
10624 .update_in(cx, |pane, window, cx| {
10625 pane.add_item(boxed_clone, true, true, None, window, cx);
10626 pane.add_item(Box::new(item_3_4.clone()), true, true, None, window, cx);
10627 })
10628 .unwrap();
10629 })
10630 });
10631
10632 (left_pane, right_pane)
10633 });
10634 let right_pane = right_pane.await.unwrap();
10635 cx.focus(&right_pane);
10636
10637 let close = right_pane.update_in(cx, |pane, window, cx| {
10638 pane.close_all_items(&CloseAllItems::default(), window, cx)
10639 .unwrap()
10640 });
10641 cx.executor().run_until_parked();
10642
10643 let msg = cx.pending_prompt().unwrap().0;
10644 assert!(msg.contains("1.txt"));
10645 assert!(!msg.contains("2.txt"));
10646 assert!(!msg.contains("3.txt"));
10647 assert!(!msg.contains("4.txt"));
10648
10649 // With best-effort close, cancelling item 1 keeps it open but items 4
10650 // and (3,4) still close since their entries exist in left pane.
10651 cx.simulate_prompt_answer("Cancel");
10652 close.await;
10653
10654 right_pane.read_with(cx, |pane, _| {
10655 assert_eq!(pane.items_len(), 1);
10656 });
10657
10658 // Remove item 3 from left pane, making (2,3) the only item with entry 3.
10659 left_pane
10660 .update_in(cx, |left_pane, window, cx| {
10661 left_pane.close_item_by_id(
10662 single_entry_items[3].entity_id(),
10663 SaveIntent::Skip,
10664 window,
10665 cx,
10666 )
10667 })
10668 .await
10669 .unwrap();
10670
10671 let close = left_pane.update_in(cx, |pane, window, cx| {
10672 pane.close_all_items(&CloseAllItems::default(), window, cx)
10673 .unwrap()
10674 });
10675 cx.executor().run_until_parked();
10676
10677 let details = cx.pending_prompt().unwrap().1;
10678 assert!(details.contains("0.txt"));
10679 assert!(details.contains("3.txt"));
10680 assert!(details.contains("4.txt"));
10681 // Ideally 2.txt wouldn't appear since entry 2 still exists in item 2.
10682 // But we can only save whole items, so saving (2,3) for entry 3 includes 2.
10683 // assert!(!details.contains("2.txt"));
10684
10685 cx.simulate_prompt_answer("Save all");
10686 cx.executor().run_until_parked();
10687 close.await;
10688
10689 left_pane.read_with(cx, |pane, _| {
10690 assert_eq!(pane.items_len(), 0);
10691 });
10692 }
10693
10694 #[gpui::test]
10695 async fn test_autosave(cx: &mut gpui::TestAppContext) {
10696 init_test(cx);
10697
10698 let fs = FakeFs::new(cx.executor());
10699 let project = Project::test(fs, [], cx).await;
10700 let (workspace, cx) =
10701 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10702 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10703
10704 let item = cx.new(|cx| {
10705 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10706 });
10707 let item_id = item.entity_id();
10708 workspace.update_in(cx, |workspace, window, cx| {
10709 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10710 });
10711
10712 // Autosave on window change.
10713 item.update(cx, |item, cx| {
10714 SettingsStore::update_global(cx, |settings, cx| {
10715 settings.update_user_settings(cx, |settings| {
10716 settings.workspace.autosave = Some(AutosaveSetting::OnWindowChange);
10717 })
10718 });
10719 item.is_dirty = true;
10720 });
10721
10722 // Deactivating the window saves the file.
10723 cx.deactivate_window();
10724 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10725
10726 // Re-activating the window doesn't save the file.
10727 cx.update(|window, _| window.activate_window());
10728 cx.executor().run_until_parked();
10729 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10730
10731 // Autosave on focus change.
10732 item.update_in(cx, |item, window, cx| {
10733 cx.focus_self(window);
10734 SettingsStore::update_global(cx, |settings, cx| {
10735 settings.update_user_settings(cx, |settings| {
10736 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10737 })
10738 });
10739 item.is_dirty = true;
10740 });
10741 // Blurring the item saves the file.
10742 item.update_in(cx, |_, window, _| window.blur());
10743 cx.executor().run_until_parked();
10744 item.read_with(cx, |item, _| assert_eq!(item.save_count, 2));
10745
10746 // Deactivating the window still saves the file.
10747 item.update_in(cx, |item, window, cx| {
10748 cx.focus_self(window);
10749 item.is_dirty = true;
10750 });
10751 cx.deactivate_window();
10752 item.update(cx, |item, _| assert_eq!(item.save_count, 3));
10753
10754 // Autosave after delay.
10755 item.update(cx, |item, cx| {
10756 SettingsStore::update_global(cx, |settings, cx| {
10757 settings.update_user_settings(cx, |settings| {
10758 settings.workspace.autosave = Some(AutosaveSetting::AfterDelay {
10759 milliseconds: 500.into(),
10760 });
10761 })
10762 });
10763 item.is_dirty = true;
10764 cx.emit(ItemEvent::Edit);
10765 });
10766
10767 // Delay hasn't fully expired, so the file is still dirty and unsaved.
10768 cx.executor().advance_clock(Duration::from_millis(250));
10769 item.read_with(cx, |item, _| assert_eq!(item.save_count, 3));
10770
10771 // After delay expires, the file is saved.
10772 cx.executor().advance_clock(Duration::from_millis(250));
10773 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10774
10775 // Autosave after delay, should save earlier than delay if tab is closed
10776 item.update(cx, |item, cx| {
10777 item.is_dirty = true;
10778 cx.emit(ItemEvent::Edit);
10779 });
10780 cx.executor().advance_clock(Duration::from_millis(250));
10781 item.read_with(cx, |item, _| assert_eq!(item.save_count, 4));
10782
10783 // // Ensure auto save with delay saves the item on close, even if the timer hasn't yet run out.
10784 pane.update_in(cx, |pane, window, cx| {
10785 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10786 })
10787 .await
10788 .unwrap();
10789 assert!(!cx.has_pending_prompt());
10790 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10791
10792 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10793 workspace.update_in(cx, |workspace, window, cx| {
10794 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10795 });
10796 item.update_in(cx, |item, _window, cx| {
10797 item.is_dirty = true;
10798 for project_item in &mut item.project_items {
10799 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10800 }
10801 });
10802 cx.run_until_parked();
10803 item.read_with(cx, |item, _| assert_eq!(item.save_count, 5));
10804
10805 // Autosave on focus change, ensuring closing the tab counts as such.
10806 item.update(cx, |item, cx| {
10807 SettingsStore::update_global(cx, |settings, cx| {
10808 settings.update_user_settings(cx, |settings| {
10809 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10810 })
10811 });
10812 item.is_dirty = true;
10813 for project_item in &mut item.project_items {
10814 project_item.update(cx, |project_item, _| project_item.is_dirty = true);
10815 }
10816 });
10817
10818 pane.update_in(cx, |pane, window, cx| {
10819 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10820 })
10821 .await
10822 .unwrap();
10823 assert!(!cx.has_pending_prompt());
10824 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10825
10826 // Add the item again, ensuring autosave is prevented if the underlying file has been deleted.
10827 workspace.update_in(cx, |workspace, window, cx| {
10828 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10829 });
10830 item.update_in(cx, |item, window, cx| {
10831 item.project_items[0].update(cx, |item, _| {
10832 item.entry_id = None;
10833 });
10834 item.is_dirty = true;
10835 window.blur();
10836 });
10837 cx.run_until_parked();
10838 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10839
10840 // Ensure autosave is prevented for deleted files also when closing the buffer.
10841 let _close_items = pane.update_in(cx, |pane, window, cx| {
10842 pane.close_items(window, cx, SaveIntent::Close, &move |id| id == item_id)
10843 });
10844 cx.run_until_parked();
10845 assert!(cx.has_pending_prompt());
10846 item.read_with(cx, |item, _| assert_eq!(item.save_count, 6));
10847 }
10848
10849 #[gpui::test]
10850 async fn test_autosave_on_focus_change_in_multibuffer(cx: &mut gpui::TestAppContext) {
10851 init_test(cx);
10852
10853 let fs = FakeFs::new(cx.executor());
10854 let project = Project::test(fs, [], cx).await;
10855 let (workspace, cx) =
10856 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10857
10858 // Create a multibuffer-like item with two child focus handles,
10859 // simulating individual buffer editors within a multibuffer.
10860 let item = cx.new(|cx| {
10861 TestItem::new(cx)
10862 .with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10863 .with_child_focus_handles(2, cx)
10864 });
10865 workspace.update_in(cx, |workspace, window, cx| {
10866 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10867 });
10868
10869 // Set autosave to OnFocusChange and focus the first child handle,
10870 // simulating the user's cursor being inside one of the multibuffer's excerpts.
10871 item.update_in(cx, |item, window, cx| {
10872 SettingsStore::update_global(cx, |settings, cx| {
10873 settings.update_user_settings(cx, |settings| {
10874 settings.workspace.autosave = Some(AutosaveSetting::OnFocusChange);
10875 })
10876 });
10877 item.is_dirty = true;
10878 window.focus(&item.child_focus_handles[0], cx);
10879 });
10880 cx.executor().run_until_parked();
10881 item.read_with(cx, |item, _| assert_eq!(item.save_count, 0));
10882
10883 // Moving focus from one child to another within the same item should
10884 // NOT trigger autosave — focus is still within the item's focus hierarchy.
10885 item.update_in(cx, |item, window, cx| {
10886 window.focus(&item.child_focus_handles[1], cx);
10887 });
10888 cx.executor().run_until_parked();
10889 item.read_with(cx, |item, _| {
10890 assert_eq!(
10891 item.save_count, 0,
10892 "Switching focus between children within the same item should not autosave"
10893 );
10894 });
10895
10896 // Blurring the item saves the file. This is the core regression scenario:
10897 // with `on_blur`, this would NOT trigger because `on_blur` only fires when
10898 // the item's own focus handle is the leaf that lost focus. In a multibuffer,
10899 // the leaf is always a child focus handle, so `on_blur` never detected
10900 // focus leaving the item.
10901 item.update_in(cx, |_, window, _| window.blur());
10902 cx.executor().run_until_parked();
10903 item.read_with(cx, |item, _| {
10904 assert_eq!(
10905 item.save_count, 1,
10906 "Blurring should trigger autosave when focus was on a child of the item"
10907 );
10908 });
10909
10910 // Deactivating the window should also trigger autosave when a child of
10911 // the multibuffer item currently owns focus.
10912 item.update_in(cx, |item, window, cx| {
10913 item.is_dirty = true;
10914 window.focus(&item.child_focus_handles[0], cx);
10915 });
10916 cx.executor().run_until_parked();
10917 item.read_with(cx, |item, _| assert_eq!(item.save_count, 1));
10918
10919 cx.deactivate_window();
10920 item.read_with(cx, |item, _| {
10921 assert_eq!(
10922 item.save_count, 2,
10923 "Deactivating window should trigger autosave when focus was on a child"
10924 );
10925 });
10926 }
10927
10928 #[gpui::test]
10929 async fn test_pane_navigation(cx: &mut gpui::TestAppContext) {
10930 init_test(cx);
10931
10932 let fs = FakeFs::new(cx.executor());
10933
10934 let project = Project::test(fs, [], cx).await;
10935 let (workspace, cx) =
10936 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
10937
10938 let item = cx.new(|cx| {
10939 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10940 });
10941 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
10942 let toolbar = pane.read_with(cx, |pane, _| pane.toolbar().clone());
10943 let toolbar_notify_count = Rc::new(RefCell::new(0));
10944
10945 workspace.update_in(cx, |workspace, window, cx| {
10946 workspace.add_item_to_active_pane(Box::new(item.clone()), None, true, window, cx);
10947 let toolbar_notification_count = toolbar_notify_count.clone();
10948 cx.observe_in(&toolbar, window, move |_, _, _, _| {
10949 *toolbar_notification_count.borrow_mut() += 1
10950 })
10951 .detach();
10952 });
10953
10954 pane.read_with(cx, |pane, _| {
10955 assert!(!pane.can_navigate_backward());
10956 assert!(!pane.can_navigate_forward());
10957 });
10958
10959 item.update_in(cx, |item, _, cx| {
10960 item.set_state("one".to_string(), cx);
10961 });
10962
10963 // Toolbar must be notified to re-render the navigation buttons
10964 assert_eq!(*toolbar_notify_count.borrow(), 1);
10965
10966 pane.read_with(cx, |pane, _| {
10967 assert!(pane.can_navigate_backward());
10968 assert!(!pane.can_navigate_forward());
10969 });
10970
10971 workspace
10972 .update_in(cx, |workspace, window, cx| {
10973 workspace.go_back(pane.downgrade(), window, cx)
10974 })
10975 .await
10976 .unwrap();
10977
10978 assert_eq!(*toolbar_notify_count.borrow(), 2);
10979 pane.read_with(cx, |pane, _| {
10980 assert!(!pane.can_navigate_backward());
10981 assert!(pane.can_navigate_forward());
10982 });
10983 }
10984
10985 #[gpui::test]
10986 async fn test_activate_last_pane(cx: &mut gpui::TestAppContext) {
10987 init_test(cx);
10988 let fs = FakeFs::new(cx.executor());
10989 let project = Project::test(fs, [], cx).await;
10990 let (multi_workspace, cx) =
10991 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
10992 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
10993
10994 workspace.update_in(cx, |workspace, window, cx| {
10995 let first_item = cx.new(|cx| {
10996 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "1.txt", cx)])
10997 });
10998 workspace.add_item_to_active_pane(Box::new(first_item), None, true, window, cx);
10999 workspace.split_pane(
11000 workspace.active_pane().clone(),
11001 SplitDirection::Right,
11002 window,
11003 cx,
11004 );
11005 workspace.split_pane(
11006 workspace.active_pane().clone(),
11007 SplitDirection::Right,
11008 window,
11009 cx,
11010 );
11011 });
11012
11013 let (first_pane_id, target_last_pane_id) = workspace.update(cx, |workspace, _cx| {
11014 let panes = workspace.center.panes();
11015 assert!(panes.len() >= 2);
11016 (
11017 panes.first().expect("at least one pane").entity_id(),
11018 panes.last().expect("at least one pane").entity_id(),
11019 )
11020 });
11021
11022 workspace.update_in(cx, |workspace, window, cx| {
11023 workspace.activate_pane_at_index(&ActivatePane(0), window, cx);
11024 });
11025 workspace.update(cx, |workspace, _| {
11026 assert_eq!(workspace.active_pane().entity_id(), first_pane_id);
11027 assert_ne!(workspace.active_pane().entity_id(), target_last_pane_id);
11028 });
11029
11030 cx.dispatch_action(ActivateLastPane);
11031
11032 workspace.update(cx, |workspace, _| {
11033 assert_eq!(workspace.active_pane().entity_id(), target_last_pane_id);
11034 });
11035 }
11036
11037 #[gpui::test]
11038 async fn test_toggle_docks_and_panels(cx: &mut gpui::TestAppContext) {
11039 init_test(cx);
11040 let fs = FakeFs::new(cx.executor());
11041
11042 let project = Project::test(fs, [], cx).await;
11043 let (workspace, cx) =
11044 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11045
11046 let panel = workspace.update_in(cx, |workspace, window, cx| {
11047 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11048 workspace.add_panel(panel.clone(), window, cx);
11049
11050 workspace
11051 .right_dock()
11052 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
11053
11054 panel
11055 });
11056
11057 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11058 pane.update_in(cx, |pane, window, cx| {
11059 let item = cx.new(TestItem::new);
11060 pane.add_item(Box::new(item), true, true, None, window, cx);
11061 });
11062
11063 // Transfer focus from center to panel
11064 workspace.update_in(cx, |workspace, window, cx| {
11065 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11066 });
11067
11068 workspace.update_in(cx, |workspace, window, cx| {
11069 assert!(workspace.right_dock().read(cx).is_open());
11070 assert!(!panel.is_zoomed(window, cx));
11071 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11072 });
11073
11074 // Transfer focus from panel to center
11075 workspace.update_in(cx, |workspace, window, cx| {
11076 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11077 });
11078
11079 workspace.update_in(cx, |workspace, window, cx| {
11080 assert!(workspace.right_dock().read(cx).is_open());
11081 assert!(!panel.is_zoomed(window, cx));
11082 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11083 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11084 });
11085
11086 // Close the dock
11087 workspace.update_in(cx, |workspace, window, cx| {
11088 workspace.toggle_dock(DockPosition::Right, window, cx);
11089 });
11090
11091 workspace.update_in(cx, |workspace, window, cx| {
11092 assert!(!workspace.right_dock().read(cx).is_open());
11093 assert!(!panel.is_zoomed(window, cx));
11094 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11095 assert!(pane.read(cx).focus_handle(cx).contains_focused(window, cx));
11096 });
11097
11098 // Open the dock
11099 workspace.update_in(cx, |workspace, window, cx| {
11100 workspace.toggle_dock(DockPosition::Right, window, cx);
11101 });
11102
11103 workspace.update_in(cx, |workspace, window, cx| {
11104 assert!(workspace.right_dock().read(cx).is_open());
11105 assert!(!panel.is_zoomed(window, cx));
11106 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11107 });
11108
11109 // Focus and zoom panel
11110 panel.update_in(cx, |panel, window, cx| {
11111 cx.focus_self(window);
11112 panel.set_zoomed(true, window, cx)
11113 });
11114
11115 workspace.update_in(cx, |workspace, window, cx| {
11116 assert!(workspace.right_dock().read(cx).is_open());
11117 assert!(panel.is_zoomed(window, cx));
11118 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11119 });
11120
11121 // Transfer focus to the center closes the dock
11122 workspace.update_in(cx, |workspace, window, cx| {
11123 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11124 });
11125
11126 workspace.update_in(cx, |workspace, window, cx| {
11127 assert!(!workspace.right_dock().read(cx).is_open());
11128 assert!(panel.is_zoomed(window, cx));
11129 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11130 });
11131
11132 // Transferring focus back to the panel keeps it zoomed
11133 workspace.update_in(cx, |workspace, window, cx| {
11134 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11135 });
11136
11137 workspace.update_in(cx, |workspace, window, cx| {
11138 assert!(workspace.right_dock().read(cx).is_open());
11139 assert!(panel.is_zoomed(window, cx));
11140 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11141 });
11142
11143 // Close the dock while it is zoomed
11144 workspace.update_in(cx, |workspace, window, cx| {
11145 workspace.toggle_dock(DockPosition::Right, window, cx)
11146 });
11147
11148 workspace.update_in(cx, |workspace, window, cx| {
11149 assert!(!workspace.right_dock().read(cx).is_open());
11150 assert!(panel.is_zoomed(window, cx));
11151 assert!(workspace.zoomed.is_none());
11152 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11153 });
11154
11155 // Opening the dock, when it's zoomed, retains focus
11156 workspace.update_in(cx, |workspace, window, cx| {
11157 workspace.toggle_dock(DockPosition::Right, window, cx)
11158 });
11159
11160 workspace.update_in(cx, |workspace, window, cx| {
11161 assert!(workspace.right_dock().read(cx).is_open());
11162 assert!(panel.is_zoomed(window, cx));
11163 assert!(workspace.zoomed.is_some());
11164 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11165 });
11166
11167 // Unzoom and close the panel, zoom the active pane.
11168 panel.update_in(cx, |panel, window, cx| panel.set_zoomed(false, window, cx));
11169 workspace.update_in(cx, |workspace, window, cx| {
11170 workspace.toggle_dock(DockPosition::Right, window, cx)
11171 });
11172 pane.update_in(cx, |pane, window, cx| {
11173 pane.toggle_zoom(&Default::default(), window, cx)
11174 });
11175
11176 // Opening a dock unzooms the pane.
11177 workspace.update_in(cx, |workspace, window, cx| {
11178 workspace.toggle_dock(DockPosition::Right, window, cx)
11179 });
11180 workspace.update_in(cx, |workspace, window, cx| {
11181 let pane = pane.read(cx);
11182 assert!(!pane.is_zoomed());
11183 assert!(!pane.focus_handle(cx).is_focused(window));
11184 assert!(workspace.right_dock().read(cx).is_open());
11185 assert!(workspace.zoomed.is_none());
11186 });
11187 }
11188
11189 #[gpui::test]
11190 async fn test_close_panel_on_toggle(cx: &mut gpui::TestAppContext) {
11191 init_test(cx);
11192 let fs = FakeFs::new(cx.executor());
11193
11194 let project = Project::test(fs, [], cx).await;
11195 let (workspace, cx) =
11196 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11197
11198 let panel = workspace.update_in(cx, |workspace, window, cx| {
11199 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
11200 workspace.add_panel(panel.clone(), window, cx);
11201 panel
11202 });
11203
11204 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
11205 pane.update_in(cx, |pane, window, cx| {
11206 let item = cx.new(TestItem::new);
11207 pane.add_item(Box::new(item), true, true, None, window, cx);
11208 });
11209
11210 // Enable close_panel_on_toggle
11211 cx.update_global(|store: &mut SettingsStore, cx| {
11212 store.update_user_settings(cx, |settings| {
11213 settings.workspace.close_panel_on_toggle = Some(true);
11214 });
11215 });
11216
11217 // Panel starts closed. Toggling should open and focus it.
11218 workspace.update_in(cx, |workspace, window, cx| {
11219 assert!(!workspace.right_dock().read(cx).is_open());
11220 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11221 });
11222
11223 workspace.update_in(cx, |workspace, window, cx| {
11224 assert!(
11225 workspace.right_dock().read(cx).is_open(),
11226 "Dock should be open after toggling from center"
11227 );
11228 assert!(
11229 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11230 "Panel should be focused after toggling from center"
11231 );
11232 });
11233
11234 // Panel is open and focused. Toggling should close the panel and
11235 // return focus to the center.
11236 workspace.update_in(cx, |workspace, window, cx| {
11237 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11238 });
11239
11240 workspace.update_in(cx, |workspace, window, cx| {
11241 assert!(
11242 !workspace.right_dock().read(cx).is_open(),
11243 "Dock should be closed after toggling from focused panel"
11244 );
11245 assert!(
11246 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11247 "Panel should not be focused after toggling from focused panel"
11248 );
11249 });
11250
11251 // Open the dock and focus something else so the panel is open but not
11252 // focused. Toggling should focus the panel (not close it).
11253 workspace.update_in(cx, |workspace, window, cx| {
11254 workspace
11255 .right_dock()
11256 .update(cx, |dock, cx| dock.set_open(true, window, cx));
11257 window.focus(&pane.read(cx).focus_handle(cx), cx);
11258 });
11259
11260 workspace.update_in(cx, |workspace, window, cx| {
11261 assert!(workspace.right_dock().read(cx).is_open());
11262 assert!(!panel.read(cx).focus_handle(cx).contains_focused(window, cx));
11263 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11264 });
11265
11266 workspace.update_in(cx, |workspace, window, cx| {
11267 assert!(
11268 workspace.right_dock().read(cx).is_open(),
11269 "Dock should remain open when toggling focuses an open-but-unfocused panel"
11270 );
11271 assert!(
11272 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11273 "Panel should be focused after toggling an open-but-unfocused panel"
11274 );
11275 });
11276
11277 // Now disable the setting and verify the original behavior: toggling
11278 // from a focused panel moves focus to center but leaves the dock open.
11279 cx.update_global(|store: &mut SettingsStore, cx| {
11280 store.update_user_settings(cx, |settings| {
11281 settings.workspace.close_panel_on_toggle = Some(false);
11282 });
11283 });
11284
11285 workspace.update_in(cx, |workspace, window, cx| {
11286 workspace.toggle_panel_focus::<TestPanel>(window, cx);
11287 });
11288
11289 workspace.update_in(cx, |workspace, window, cx| {
11290 assert!(
11291 workspace.right_dock().read(cx).is_open(),
11292 "Dock should remain open when setting is disabled"
11293 );
11294 assert!(
11295 !panel.read(cx).focus_handle(cx).contains_focused(window, cx),
11296 "Panel should not be focused after toggling with setting disabled"
11297 );
11298 });
11299 }
11300
11301 #[gpui::test]
11302 async fn test_pane_zoom_in_out(cx: &mut TestAppContext) {
11303 init_test(cx);
11304 let fs = FakeFs::new(cx.executor());
11305
11306 let project = Project::test(fs, [], cx).await;
11307 let (workspace, cx) =
11308 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11309
11310 let pane = workspace.update_in(cx, |workspace, _window, _cx| {
11311 workspace.active_pane().clone()
11312 });
11313
11314 // Add an item to the pane so it can be zoomed
11315 workspace.update_in(cx, |workspace, window, cx| {
11316 let item = cx.new(TestItem::new);
11317 workspace.add_item(pane.clone(), Box::new(item), None, true, true, window, cx);
11318 });
11319
11320 // Initially not zoomed
11321 workspace.update_in(cx, |workspace, _window, cx| {
11322 assert!(!pane.read(cx).is_zoomed(), "Pane starts unzoomed");
11323 assert!(
11324 workspace.zoomed.is_none(),
11325 "Workspace should track no zoomed pane"
11326 );
11327 assert!(pane.read(cx).items_len() > 0, "Pane should have items");
11328 });
11329
11330 // Zoom In
11331 pane.update_in(cx, |pane, window, cx| {
11332 pane.zoom_in(&crate::ZoomIn, window, cx);
11333 });
11334
11335 workspace.update_in(cx, |workspace, window, cx| {
11336 assert!(
11337 pane.read(cx).is_zoomed(),
11338 "Pane should be zoomed after ZoomIn"
11339 );
11340 assert!(
11341 workspace.zoomed.is_some(),
11342 "Workspace should track the zoomed pane"
11343 );
11344 assert!(
11345 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11346 "ZoomIn should focus the pane"
11347 );
11348 });
11349
11350 // Zoom In again is a no-op
11351 pane.update_in(cx, |pane, window, cx| {
11352 pane.zoom_in(&crate::ZoomIn, window, cx);
11353 });
11354
11355 workspace.update_in(cx, |workspace, window, cx| {
11356 assert!(pane.read(cx).is_zoomed(), "Second ZoomIn keeps pane zoomed");
11357 assert!(
11358 workspace.zoomed.is_some(),
11359 "Workspace still tracks zoomed pane"
11360 );
11361 assert!(
11362 pane.read(cx).focus_handle(cx).contains_focused(window, cx),
11363 "Pane remains focused after repeated ZoomIn"
11364 );
11365 });
11366
11367 // Zoom Out
11368 pane.update_in(cx, |pane, window, cx| {
11369 pane.zoom_out(&crate::ZoomOut, window, cx);
11370 });
11371
11372 workspace.update_in(cx, |workspace, _window, cx| {
11373 assert!(
11374 !pane.read(cx).is_zoomed(),
11375 "Pane should unzoom after ZoomOut"
11376 );
11377 assert!(
11378 workspace.zoomed.is_none(),
11379 "Workspace clears zoom tracking after ZoomOut"
11380 );
11381 });
11382
11383 // Zoom Out again is a no-op
11384 pane.update_in(cx, |pane, window, cx| {
11385 pane.zoom_out(&crate::ZoomOut, window, cx);
11386 });
11387
11388 workspace.update_in(cx, |workspace, _window, cx| {
11389 assert!(
11390 !pane.read(cx).is_zoomed(),
11391 "Second ZoomOut keeps pane unzoomed"
11392 );
11393 assert!(
11394 workspace.zoomed.is_none(),
11395 "Workspace remains without zoomed pane"
11396 );
11397 });
11398 }
11399
11400 #[gpui::test]
11401 async fn test_toggle_all_docks(cx: &mut gpui::TestAppContext) {
11402 init_test(cx);
11403 let fs = FakeFs::new(cx.executor());
11404
11405 let project = Project::test(fs, [], cx).await;
11406 let (workspace, cx) =
11407 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11408 workspace.update_in(cx, |workspace, window, cx| {
11409 // Open two docks
11410 let left_dock = workspace.dock_at_position(DockPosition::Left);
11411 let right_dock = workspace.dock_at_position(DockPosition::Right);
11412
11413 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11414 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11415
11416 assert!(left_dock.read(cx).is_open());
11417 assert!(right_dock.read(cx).is_open());
11418 });
11419
11420 workspace.update_in(cx, |workspace, window, cx| {
11421 // Toggle all docks - should close both
11422 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11423
11424 let left_dock = workspace.dock_at_position(DockPosition::Left);
11425 let right_dock = workspace.dock_at_position(DockPosition::Right);
11426 assert!(!left_dock.read(cx).is_open());
11427 assert!(!right_dock.read(cx).is_open());
11428 });
11429
11430 workspace.update_in(cx, |workspace, window, cx| {
11431 // Toggle again - should reopen both
11432 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11433
11434 let left_dock = workspace.dock_at_position(DockPosition::Left);
11435 let right_dock = workspace.dock_at_position(DockPosition::Right);
11436 assert!(left_dock.read(cx).is_open());
11437 assert!(right_dock.read(cx).is_open());
11438 });
11439 }
11440
11441 #[gpui::test]
11442 async fn test_toggle_all_with_manual_close(cx: &mut gpui::TestAppContext) {
11443 init_test(cx);
11444 let fs = FakeFs::new(cx.executor());
11445
11446 let project = Project::test(fs, [], cx).await;
11447 let (workspace, cx) =
11448 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11449 workspace.update_in(cx, |workspace, window, cx| {
11450 // Open two docks
11451 let left_dock = workspace.dock_at_position(DockPosition::Left);
11452 let right_dock = workspace.dock_at_position(DockPosition::Right);
11453
11454 left_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11455 right_dock.update(cx, |dock, cx| dock.set_open(true, window, cx));
11456
11457 assert!(left_dock.read(cx).is_open());
11458 assert!(right_dock.read(cx).is_open());
11459 });
11460
11461 workspace.update_in(cx, |workspace, window, cx| {
11462 // Close them manually
11463 workspace.toggle_dock(DockPosition::Left, window, cx);
11464 workspace.toggle_dock(DockPosition::Right, window, cx);
11465
11466 let left_dock = workspace.dock_at_position(DockPosition::Left);
11467 let right_dock = workspace.dock_at_position(DockPosition::Right);
11468 assert!(!left_dock.read(cx).is_open());
11469 assert!(!right_dock.read(cx).is_open());
11470 });
11471
11472 workspace.update_in(cx, |workspace, window, cx| {
11473 // Toggle all docks - only last closed (right dock) should reopen
11474 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11475
11476 let left_dock = workspace.dock_at_position(DockPosition::Left);
11477 let right_dock = workspace.dock_at_position(DockPosition::Right);
11478 assert!(!left_dock.read(cx).is_open());
11479 assert!(right_dock.read(cx).is_open());
11480 });
11481 }
11482
11483 #[gpui::test]
11484 async fn test_toggle_all_docks_after_dock_move(cx: &mut gpui::TestAppContext) {
11485 init_test(cx);
11486 let fs = FakeFs::new(cx.executor());
11487 let project = Project::test(fs, [], cx).await;
11488 let (multi_workspace, cx) =
11489 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11490 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11491
11492 // Open two docks (left and right) with one panel each
11493 let (left_panel, right_panel) = workspace.update_in(cx, |workspace, window, cx| {
11494 let left_panel = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11495 workspace.add_panel(left_panel.clone(), window, cx);
11496
11497 let right_panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11498 workspace.add_panel(right_panel.clone(), window, cx);
11499
11500 workspace.toggle_dock(DockPosition::Left, window, cx);
11501 workspace.toggle_dock(DockPosition::Right, window, cx);
11502
11503 // Verify initial state
11504 assert!(
11505 workspace.left_dock().read(cx).is_open(),
11506 "Left dock should be open"
11507 );
11508 assert_eq!(
11509 workspace
11510 .left_dock()
11511 .read(cx)
11512 .visible_panel()
11513 .unwrap()
11514 .panel_id(),
11515 left_panel.panel_id(),
11516 "Left panel should be visible in left dock"
11517 );
11518 assert!(
11519 workspace.right_dock().read(cx).is_open(),
11520 "Right dock should be open"
11521 );
11522 assert_eq!(
11523 workspace
11524 .right_dock()
11525 .read(cx)
11526 .visible_panel()
11527 .unwrap()
11528 .panel_id(),
11529 right_panel.panel_id(),
11530 "Right panel should be visible in right dock"
11531 );
11532 assert!(
11533 !workspace.bottom_dock().read(cx).is_open(),
11534 "Bottom dock should be closed"
11535 );
11536
11537 (left_panel, right_panel)
11538 });
11539
11540 // Focus the left panel and move it to the next position (bottom dock)
11541 workspace.update_in(cx, |workspace, window, cx| {
11542 workspace.toggle_panel_focus::<TestPanel>(window, cx); // Focus left panel
11543 assert!(
11544 left_panel.read(cx).focus_handle(cx).is_focused(window),
11545 "Left panel should be focused"
11546 );
11547 });
11548
11549 cx.dispatch_action(MoveFocusedPanelToNextPosition);
11550
11551 // Verify the left panel has moved to the bottom dock, and the bottom dock is now open
11552 workspace.update(cx, |workspace, cx| {
11553 assert!(
11554 !workspace.left_dock().read(cx).is_open(),
11555 "Left dock should be closed"
11556 );
11557 assert!(
11558 workspace.bottom_dock().read(cx).is_open(),
11559 "Bottom dock should now be open"
11560 );
11561 assert_eq!(
11562 left_panel.read(cx).position,
11563 DockPosition::Bottom,
11564 "Left panel should now be in the bottom dock"
11565 );
11566 assert_eq!(
11567 workspace
11568 .bottom_dock()
11569 .read(cx)
11570 .visible_panel()
11571 .unwrap()
11572 .panel_id(),
11573 left_panel.panel_id(),
11574 "Left panel should be the visible panel in the bottom dock"
11575 );
11576 });
11577
11578 // Toggle all docks off
11579 workspace.update_in(cx, |workspace, window, cx| {
11580 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11581 assert!(
11582 !workspace.left_dock().read(cx).is_open(),
11583 "Left dock should be closed"
11584 );
11585 assert!(
11586 !workspace.right_dock().read(cx).is_open(),
11587 "Right dock should be closed"
11588 );
11589 assert!(
11590 !workspace.bottom_dock().read(cx).is_open(),
11591 "Bottom dock should be closed"
11592 );
11593 });
11594
11595 // Toggle all docks back on and verify positions are restored
11596 workspace.update_in(cx, |workspace, window, cx| {
11597 workspace.toggle_all_docks(&ToggleAllDocks, window, cx);
11598 assert!(
11599 !workspace.left_dock().read(cx).is_open(),
11600 "Left dock should remain closed"
11601 );
11602 assert!(
11603 workspace.right_dock().read(cx).is_open(),
11604 "Right dock should remain open"
11605 );
11606 assert!(
11607 workspace.bottom_dock().read(cx).is_open(),
11608 "Bottom dock should remain open"
11609 );
11610 assert_eq!(
11611 left_panel.read(cx).position,
11612 DockPosition::Bottom,
11613 "Left panel should remain in the bottom dock"
11614 );
11615 assert_eq!(
11616 right_panel.read(cx).position,
11617 DockPosition::Right,
11618 "Right panel should remain in the right dock"
11619 );
11620 assert_eq!(
11621 workspace
11622 .bottom_dock()
11623 .read(cx)
11624 .visible_panel()
11625 .unwrap()
11626 .panel_id(),
11627 left_panel.panel_id(),
11628 "Left panel should be the visible panel in the right dock"
11629 );
11630 });
11631 }
11632
11633 #[gpui::test]
11634 async fn test_join_pane_into_next(cx: &mut gpui::TestAppContext) {
11635 init_test(cx);
11636
11637 let fs = FakeFs::new(cx.executor());
11638
11639 let project = Project::test(fs, None, cx).await;
11640 let (workspace, cx) =
11641 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11642
11643 // Let's arrange the panes like this:
11644 //
11645 // +-----------------------+
11646 // | top |
11647 // +------+--------+-------+
11648 // | left | center | right |
11649 // +------+--------+-------+
11650 // | bottom |
11651 // +-----------------------+
11652
11653 let top_item = cx.new(|cx| {
11654 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "top.txt", cx)])
11655 });
11656 let bottom_item = cx.new(|cx| {
11657 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "bottom.txt", cx)])
11658 });
11659 let left_item = cx.new(|cx| {
11660 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "left.txt", cx)])
11661 });
11662 let right_item = cx.new(|cx| {
11663 TestItem::new(cx).with_project_items(&[TestProjectItem::new(4, "right.txt", cx)])
11664 });
11665 let center_item = cx.new(|cx| {
11666 TestItem::new(cx).with_project_items(&[TestProjectItem::new(5, "center.txt", cx)])
11667 });
11668
11669 let top_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11670 let top_pane_id = workspace.active_pane().entity_id();
11671 workspace.add_item_to_active_pane(Box::new(top_item.clone()), None, false, window, cx);
11672 workspace.split_pane(
11673 workspace.active_pane().clone(),
11674 SplitDirection::Down,
11675 window,
11676 cx,
11677 );
11678 top_pane_id
11679 });
11680 let bottom_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11681 let bottom_pane_id = workspace.active_pane().entity_id();
11682 workspace.add_item_to_active_pane(
11683 Box::new(bottom_item.clone()),
11684 None,
11685 false,
11686 window,
11687 cx,
11688 );
11689 workspace.split_pane(
11690 workspace.active_pane().clone(),
11691 SplitDirection::Up,
11692 window,
11693 cx,
11694 );
11695 bottom_pane_id
11696 });
11697 let left_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11698 let left_pane_id = workspace.active_pane().entity_id();
11699 workspace.add_item_to_active_pane(Box::new(left_item.clone()), None, false, window, cx);
11700 workspace.split_pane(
11701 workspace.active_pane().clone(),
11702 SplitDirection::Right,
11703 window,
11704 cx,
11705 );
11706 left_pane_id
11707 });
11708 let right_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11709 let right_pane_id = workspace.active_pane().entity_id();
11710 workspace.add_item_to_active_pane(
11711 Box::new(right_item.clone()),
11712 None,
11713 false,
11714 window,
11715 cx,
11716 );
11717 workspace.split_pane(
11718 workspace.active_pane().clone(),
11719 SplitDirection::Left,
11720 window,
11721 cx,
11722 );
11723 right_pane_id
11724 });
11725 let center_pane_id = workspace.update_in(cx, |workspace, window, cx| {
11726 let center_pane_id = workspace.active_pane().entity_id();
11727 workspace.add_item_to_active_pane(
11728 Box::new(center_item.clone()),
11729 None,
11730 false,
11731 window,
11732 cx,
11733 );
11734 center_pane_id
11735 });
11736 cx.executor().run_until_parked();
11737
11738 workspace.update_in(cx, |workspace, window, cx| {
11739 assert_eq!(center_pane_id, workspace.active_pane().entity_id());
11740
11741 // Join into next from center pane into right
11742 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11743 });
11744
11745 workspace.update_in(cx, |workspace, window, cx| {
11746 let active_pane = workspace.active_pane();
11747 assert_eq!(right_pane_id, active_pane.entity_id());
11748 assert_eq!(2, active_pane.read(cx).items_len());
11749 let item_ids_in_pane =
11750 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11751 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11752 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11753
11754 // Join into next from right pane into bottom
11755 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11756 });
11757
11758 workspace.update_in(cx, |workspace, window, cx| {
11759 let active_pane = workspace.active_pane();
11760 assert_eq!(bottom_pane_id, active_pane.entity_id());
11761 assert_eq!(3, active_pane.read(cx).items_len());
11762 let item_ids_in_pane =
11763 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11764 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11765 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11766 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11767
11768 // Join into next from bottom pane into left
11769 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11770 });
11771
11772 workspace.update_in(cx, |workspace, window, cx| {
11773 let active_pane = workspace.active_pane();
11774 assert_eq!(left_pane_id, active_pane.entity_id());
11775 assert_eq!(4, active_pane.read(cx).items_len());
11776 let item_ids_in_pane =
11777 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11778 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11779 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11780 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11781 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11782
11783 // Join into next from left pane into top
11784 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx);
11785 });
11786
11787 workspace.update_in(cx, |workspace, window, cx| {
11788 let active_pane = workspace.active_pane();
11789 assert_eq!(top_pane_id, active_pane.entity_id());
11790 assert_eq!(5, active_pane.read(cx).items_len());
11791 let item_ids_in_pane =
11792 HashSet::from_iter(active_pane.read(cx).items().map(|item| item.item_id()));
11793 assert!(item_ids_in_pane.contains(¢er_item.item_id()));
11794 assert!(item_ids_in_pane.contains(&right_item.item_id()));
11795 assert!(item_ids_in_pane.contains(&bottom_item.item_id()));
11796 assert!(item_ids_in_pane.contains(&left_item.item_id()));
11797 assert!(item_ids_in_pane.contains(&top_item.item_id()));
11798
11799 // Single pane left: no-op
11800 workspace.join_pane_into_next(workspace.active_pane().clone(), window, cx)
11801 });
11802
11803 workspace.update(cx, |workspace, _cx| {
11804 let active_pane = workspace.active_pane();
11805 assert_eq!(top_pane_id, active_pane.entity_id());
11806 });
11807 }
11808
11809 fn add_an_item_to_active_pane(
11810 cx: &mut VisualTestContext,
11811 workspace: &Entity<Workspace>,
11812 item_id: u64,
11813 ) -> Entity<TestItem> {
11814 let item = cx.new(|cx| {
11815 TestItem::new(cx).with_project_items(&[TestProjectItem::new(
11816 item_id,
11817 "item{item_id}.txt",
11818 cx,
11819 )])
11820 });
11821 workspace.update_in(cx, |workspace, window, cx| {
11822 workspace.add_item_to_active_pane(Box::new(item.clone()), None, false, window, cx);
11823 });
11824 item
11825 }
11826
11827 fn split_pane(cx: &mut VisualTestContext, workspace: &Entity<Workspace>) -> Entity<Pane> {
11828 workspace.update_in(cx, |workspace, window, cx| {
11829 workspace.split_pane(
11830 workspace.active_pane().clone(),
11831 SplitDirection::Right,
11832 window,
11833 cx,
11834 )
11835 })
11836 }
11837
11838 #[gpui::test]
11839 async fn test_join_all_panes(cx: &mut gpui::TestAppContext) {
11840 init_test(cx);
11841 let fs = FakeFs::new(cx.executor());
11842 let project = Project::test(fs, None, cx).await;
11843 let (workspace, cx) =
11844 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
11845
11846 add_an_item_to_active_pane(cx, &workspace, 1);
11847 split_pane(cx, &workspace);
11848 add_an_item_to_active_pane(cx, &workspace, 2);
11849 split_pane(cx, &workspace); // empty pane
11850 split_pane(cx, &workspace);
11851 let last_item = add_an_item_to_active_pane(cx, &workspace, 3);
11852
11853 cx.executor().run_until_parked();
11854
11855 workspace.update(cx, |workspace, cx| {
11856 let num_panes = workspace.panes().len();
11857 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11858 let active_item = workspace
11859 .active_pane()
11860 .read(cx)
11861 .active_item()
11862 .expect("item is in focus");
11863
11864 assert_eq!(num_panes, 4);
11865 assert_eq!(num_items_in_current_pane, 1);
11866 assert_eq!(active_item.item_id(), last_item.item_id());
11867 });
11868
11869 workspace.update_in(cx, |workspace, window, cx| {
11870 workspace.join_all_panes(window, cx);
11871 });
11872
11873 workspace.update(cx, |workspace, cx| {
11874 let num_panes = workspace.panes().len();
11875 let num_items_in_current_pane = workspace.active_pane().read(cx).items().count();
11876 let active_item = workspace
11877 .active_pane()
11878 .read(cx)
11879 .active_item()
11880 .expect("item is in focus");
11881
11882 assert_eq!(num_panes, 1);
11883 assert_eq!(num_items_in_current_pane, 3);
11884 assert_eq!(active_item.item_id(), last_item.item_id());
11885 });
11886 }
11887 struct TestModal(FocusHandle);
11888
11889 impl TestModal {
11890 fn new(_: &mut Window, cx: &mut Context<Self>) -> Self {
11891 Self(cx.focus_handle())
11892 }
11893 }
11894
11895 impl EventEmitter<DismissEvent> for TestModal {}
11896
11897 impl Focusable for TestModal {
11898 fn focus_handle(&self, _cx: &App) -> FocusHandle {
11899 self.0.clone()
11900 }
11901 }
11902
11903 impl ModalView for TestModal {}
11904
11905 impl Render for TestModal {
11906 fn render(
11907 &mut self,
11908 _window: &mut Window,
11909 _cx: &mut Context<TestModal>,
11910 ) -> impl IntoElement {
11911 div().track_focus(&self.0)
11912 }
11913 }
11914
11915 #[gpui::test]
11916 async fn test_panels(cx: &mut gpui::TestAppContext) {
11917 init_test(cx);
11918 let fs = FakeFs::new(cx.executor());
11919
11920 let project = Project::test(fs, [], cx).await;
11921 let (multi_workspace, cx) =
11922 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
11923 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
11924
11925 let (panel_1, panel_2) = workspace.update_in(cx, |workspace, window, cx| {
11926 let panel_1 = cx.new(|cx| TestPanel::new(DockPosition::Left, 100, cx));
11927 workspace.add_panel(panel_1.clone(), window, cx);
11928 workspace.toggle_dock(DockPosition::Left, window, cx);
11929 let panel_2 = cx.new(|cx| TestPanel::new(DockPosition::Right, 101, cx));
11930 workspace.add_panel(panel_2.clone(), window, cx);
11931 workspace.toggle_dock(DockPosition::Right, window, cx);
11932
11933 let left_dock = workspace.left_dock();
11934 assert_eq!(
11935 left_dock.read(cx).visible_panel().unwrap().panel_id(),
11936 panel_1.panel_id()
11937 );
11938 assert_eq!(
11939 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
11940 panel_1.size(window, cx)
11941 );
11942
11943 left_dock.update(cx, |left_dock, cx| {
11944 left_dock.resize_active_panel(Some(px(1337.)), window, cx)
11945 });
11946 assert_eq!(
11947 workspace
11948 .right_dock()
11949 .read(cx)
11950 .visible_panel()
11951 .unwrap()
11952 .panel_id(),
11953 panel_2.panel_id(),
11954 );
11955
11956 (panel_1, panel_2)
11957 });
11958
11959 // Move panel_1 to the right
11960 panel_1.update_in(cx, |panel_1, window, cx| {
11961 panel_1.set_position(DockPosition::Right, window, cx)
11962 });
11963
11964 workspace.update_in(cx, |workspace, window, cx| {
11965 // Since panel_1 was visible on the left, it should now be visible now that it's been moved to the right.
11966 // Since it was the only panel on the left, the left dock should now be closed.
11967 assert!(!workspace.left_dock().read(cx).is_open());
11968 assert!(workspace.left_dock().read(cx).visible_panel().is_none());
11969 let right_dock = workspace.right_dock();
11970 assert_eq!(
11971 right_dock.read(cx).visible_panel().unwrap().panel_id(),
11972 panel_1.panel_id()
11973 );
11974 assert_eq!(
11975 right_dock.read(cx).active_panel_size(window, cx).unwrap(),
11976 px(1337.)
11977 );
11978
11979 // Now we move panel_2 to the left
11980 panel_2.set_position(DockPosition::Left, window, cx);
11981 });
11982
11983 workspace.update(cx, |workspace, cx| {
11984 // Since panel_2 was not visible on the right, we don't open the left dock.
11985 assert!(!workspace.left_dock().read(cx).is_open());
11986 // And the right dock is unaffected in its displaying of panel_1
11987 assert!(workspace.right_dock().read(cx).is_open());
11988 assert_eq!(
11989 workspace
11990 .right_dock()
11991 .read(cx)
11992 .visible_panel()
11993 .unwrap()
11994 .panel_id(),
11995 panel_1.panel_id(),
11996 );
11997 });
11998
11999 // Move panel_1 back to the left
12000 panel_1.update_in(cx, |panel_1, window, cx| {
12001 panel_1.set_position(DockPosition::Left, window, cx)
12002 });
12003
12004 workspace.update_in(cx, |workspace, window, cx| {
12005 // Since panel_1 was visible on the right, we open the left dock and make panel_1 active.
12006 let left_dock = workspace.left_dock();
12007 assert!(left_dock.read(cx).is_open());
12008 assert_eq!(
12009 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12010 panel_1.panel_id()
12011 );
12012 assert_eq!(
12013 left_dock.read(cx).active_panel_size(window, cx).unwrap(),
12014 px(1337.)
12015 );
12016 // And the right dock should be closed as it no longer has any panels.
12017 assert!(!workspace.right_dock().read(cx).is_open());
12018
12019 // Now we move panel_1 to the bottom
12020 panel_1.set_position(DockPosition::Bottom, window, cx);
12021 });
12022
12023 workspace.update_in(cx, |workspace, window, cx| {
12024 // Since panel_1 was visible on the left, we close the left dock.
12025 assert!(!workspace.left_dock().read(cx).is_open());
12026 // The bottom dock is sized based on the panel's default size,
12027 // since the panel orientation changed from vertical to horizontal.
12028 let bottom_dock = workspace.bottom_dock();
12029 assert_eq!(
12030 bottom_dock.read(cx).active_panel_size(window, cx).unwrap(),
12031 panel_1.size(window, cx),
12032 );
12033 // Close bottom dock and move panel_1 back to the left.
12034 bottom_dock.update(cx, |bottom_dock, cx| {
12035 bottom_dock.set_open(false, window, cx)
12036 });
12037 panel_1.set_position(DockPosition::Left, window, cx);
12038 });
12039
12040 // Emit activated event on panel 1
12041 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Activate));
12042
12043 // Now the left dock is open and panel_1 is active and focused.
12044 workspace.update_in(cx, |workspace, window, cx| {
12045 let left_dock = workspace.left_dock();
12046 assert!(left_dock.read(cx).is_open());
12047 assert_eq!(
12048 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12049 panel_1.panel_id(),
12050 );
12051 assert!(panel_1.focus_handle(cx).is_focused(window));
12052 });
12053
12054 // Emit closed event on panel 2, which is not active
12055 panel_2.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12056
12057 // Wo don't close the left dock, because panel_2 wasn't the active panel
12058 workspace.update(cx, |workspace, cx| {
12059 let left_dock = workspace.left_dock();
12060 assert!(left_dock.read(cx).is_open());
12061 assert_eq!(
12062 left_dock.read(cx).visible_panel().unwrap().panel_id(),
12063 panel_1.panel_id(),
12064 );
12065 });
12066
12067 // Emitting a ZoomIn event shows the panel as zoomed.
12068 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn));
12069 workspace.read_with(cx, |workspace, _| {
12070 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12071 assert_eq!(workspace.zoomed_position, Some(DockPosition::Left));
12072 });
12073
12074 // Move panel to another dock while it is zoomed
12075 panel_1.update_in(cx, |panel, window, cx| {
12076 panel.set_position(DockPosition::Right, window, cx)
12077 });
12078 workspace.read_with(cx, |workspace, _| {
12079 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12080
12081 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12082 });
12083
12084 // This is a helper for getting a:
12085 // - valid focus on an element,
12086 // - that isn't a part of the panes and panels system of the Workspace,
12087 // - and doesn't trigger the 'on_focus_lost' API.
12088 let focus_other_view = {
12089 let workspace = workspace.clone();
12090 move |cx: &mut VisualTestContext| {
12091 workspace.update_in(cx, |workspace, window, cx| {
12092 if workspace.active_modal::<TestModal>(cx).is_some() {
12093 workspace.toggle_modal(window, cx, TestModal::new);
12094 workspace.toggle_modal(window, cx, TestModal::new);
12095 } else {
12096 workspace.toggle_modal(window, cx, TestModal::new);
12097 }
12098 })
12099 }
12100 };
12101
12102 // If focus is transferred to another view that's not a panel or another pane, we still show
12103 // the panel as zoomed.
12104 focus_other_view(cx);
12105 workspace.read_with(cx, |workspace, _| {
12106 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12107 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12108 });
12109
12110 // If focus is transferred elsewhere in the workspace, the panel is no longer zoomed.
12111 workspace.update_in(cx, |_workspace, window, cx| {
12112 cx.focus_self(window);
12113 });
12114 workspace.read_with(cx, |workspace, _| {
12115 assert_eq!(workspace.zoomed, None);
12116 assert_eq!(workspace.zoomed_position, None);
12117 });
12118
12119 // If focus is transferred again to another view that's not a panel or a pane, we won't
12120 // show the panel as zoomed because it wasn't zoomed before.
12121 focus_other_view(cx);
12122 workspace.read_with(cx, |workspace, _| {
12123 assert_eq!(workspace.zoomed, None);
12124 assert_eq!(workspace.zoomed_position, None);
12125 });
12126
12127 // When the panel is activated, it is zoomed again.
12128 cx.dispatch_action(ToggleRightDock);
12129 workspace.read_with(cx, |workspace, _| {
12130 assert_eq!(workspace.zoomed, Some(panel_1.to_any().downgrade()));
12131 assert_eq!(workspace.zoomed_position, Some(DockPosition::Right));
12132 });
12133
12134 // Emitting a ZoomOut event unzooms the panel.
12135 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::ZoomOut));
12136 workspace.read_with(cx, |workspace, _| {
12137 assert_eq!(workspace.zoomed, None);
12138 assert_eq!(workspace.zoomed_position, None);
12139 });
12140
12141 // Emit closed event on panel 1, which is active
12142 panel_1.update(cx, |_, cx| cx.emit(PanelEvent::Close));
12143
12144 // Now the left dock is closed, because panel_1 was the active panel
12145 workspace.update(cx, |workspace, cx| {
12146 let right_dock = workspace.right_dock();
12147 assert!(!right_dock.read(cx).is_open());
12148 });
12149 }
12150
12151 #[gpui::test]
12152 async fn test_no_save_prompt_when_multi_buffer_dirty_items_closed(cx: &mut TestAppContext) {
12153 init_test(cx);
12154
12155 let fs = FakeFs::new(cx.background_executor.clone());
12156 let project = Project::test(fs, [], cx).await;
12157 let (workspace, cx) =
12158 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12159 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12160
12161 let dirty_regular_buffer = cx.new(|cx| {
12162 TestItem::new(cx)
12163 .with_dirty(true)
12164 .with_label("1.txt")
12165 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12166 });
12167 let dirty_regular_buffer_2 = cx.new(|cx| {
12168 TestItem::new(cx)
12169 .with_dirty(true)
12170 .with_label("2.txt")
12171 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12172 });
12173 let dirty_multi_buffer_with_both = cx.new(|cx| {
12174 TestItem::new(cx)
12175 .with_dirty(true)
12176 .with_buffer_kind(ItemBufferKind::Multibuffer)
12177 .with_label("Fake Project Search")
12178 .with_project_items(&[
12179 dirty_regular_buffer.read(cx).project_items[0].clone(),
12180 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12181 ])
12182 });
12183 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12184 workspace.update_in(cx, |workspace, window, cx| {
12185 workspace.add_item(
12186 pane.clone(),
12187 Box::new(dirty_regular_buffer.clone()),
12188 None,
12189 false,
12190 false,
12191 window,
12192 cx,
12193 );
12194 workspace.add_item(
12195 pane.clone(),
12196 Box::new(dirty_regular_buffer_2.clone()),
12197 None,
12198 false,
12199 false,
12200 window,
12201 cx,
12202 );
12203 workspace.add_item(
12204 pane.clone(),
12205 Box::new(dirty_multi_buffer_with_both.clone()),
12206 None,
12207 false,
12208 false,
12209 window,
12210 cx,
12211 );
12212 });
12213
12214 pane.update_in(cx, |pane, window, cx| {
12215 pane.activate_item(2, true, true, window, cx);
12216 assert_eq!(
12217 pane.active_item().unwrap().item_id(),
12218 multi_buffer_with_both_files_id,
12219 "Should select the multi buffer in the pane"
12220 );
12221 });
12222 let close_all_but_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12223 pane.close_other_items(
12224 &CloseOtherItems {
12225 save_intent: Some(SaveIntent::Save),
12226 close_pinned: true,
12227 },
12228 None,
12229 window,
12230 cx,
12231 )
12232 });
12233 cx.background_executor.run_until_parked();
12234 assert!(!cx.has_pending_prompt());
12235 close_all_but_multi_buffer_task
12236 .await
12237 .expect("Closing all buffers but the multi buffer failed");
12238 pane.update(cx, |pane, cx| {
12239 assert_eq!(dirty_regular_buffer.read(cx).save_count, 1);
12240 assert_eq!(dirty_multi_buffer_with_both.read(cx).save_count, 0);
12241 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 1);
12242 assert_eq!(pane.items_len(), 1);
12243 assert_eq!(
12244 pane.active_item().unwrap().item_id(),
12245 multi_buffer_with_both_files_id,
12246 "Should have only the multi buffer left in the pane"
12247 );
12248 assert!(
12249 dirty_multi_buffer_with_both.read(cx).is_dirty,
12250 "The multi buffer containing the unsaved buffer should still be dirty"
12251 );
12252 });
12253
12254 dirty_regular_buffer.update(cx, |buffer, cx| {
12255 buffer.project_items[0].update(cx, |pi, _| pi.is_dirty = true)
12256 });
12257
12258 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12259 pane.close_active_item(
12260 &CloseActiveItem {
12261 save_intent: Some(SaveIntent::Close),
12262 close_pinned: false,
12263 },
12264 window,
12265 cx,
12266 )
12267 });
12268 cx.background_executor.run_until_parked();
12269 assert!(
12270 cx.has_pending_prompt(),
12271 "Dirty multi buffer should prompt a save dialog"
12272 );
12273 cx.simulate_prompt_answer("Save");
12274 cx.background_executor.run_until_parked();
12275 close_multi_buffer_task
12276 .await
12277 .expect("Closing the multi buffer failed");
12278 pane.update(cx, |pane, cx| {
12279 assert_eq!(
12280 dirty_multi_buffer_with_both.read(cx).save_count,
12281 1,
12282 "Multi buffer item should get be saved"
12283 );
12284 // Test impl does not save inner items, so we do not assert them
12285 assert_eq!(
12286 pane.items_len(),
12287 0,
12288 "No more items should be left in the pane"
12289 );
12290 assert!(pane.active_item().is_none());
12291 });
12292 }
12293
12294 #[gpui::test]
12295 async fn test_save_prompt_when_dirty_multi_buffer_closed_with_some_of_its_dirty_items_not_present_in_the_pane(
12296 cx: &mut TestAppContext,
12297 ) {
12298 init_test(cx);
12299
12300 let fs = FakeFs::new(cx.background_executor.clone());
12301 let project = Project::test(fs, [], cx).await;
12302 let (workspace, cx) =
12303 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12304 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12305
12306 let dirty_regular_buffer = cx.new(|cx| {
12307 TestItem::new(cx)
12308 .with_dirty(true)
12309 .with_label("1.txt")
12310 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12311 });
12312 let dirty_regular_buffer_2 = cx.new(|cx| {
12313 TestItem::new(cx)
12314 .with_dirty(true)
12315 .with_label("2.txt")
12316 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12317 });
12318 let clear_regular_buffer = cx.new(|cx| {
12319 TestItem::new(cx)
12320 .with_label("3.txt")
12321 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12322 });
12323
12324 let dirty_multi_buffer_with_both = cx.new(|cx| {
12325 TestItem::new(cx)
12326 .with_dirty(true)
12327 .with_buffer_kind(ItemBufferKind::Multibuffer)
12328 .with_label("Fake Project Search")
12329 .with_project_items(&[
12330 dirty_regular_buffer.read(cx).project_items[0].clone(),
12331 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12332 clear_regular_buffer.read(cx).project_items[0].clone(),
12333 ])
12334 });
12335 let multi_buffer_with_both_files_id = dirty_multi_buffer_with_both.item_id();
12336 workspace.update_in(cx, |workspace, window, cx| {
12337 workspace.add_item(
12338 pane.clone(),
12339 Box::new(dirty_regular_buffer.clone()),
12340 None,
12341 false,
12342 false,
12343 window,
12344 cx,
12345 );
12346 workspace.add_item(
12347 pane.clone(),
12348 Box::new(dirty_multi_buffer_with_both.clone()),
12349 None,
12350 false,
12351 false,
12352 window,
12353 cx,
12354 );
12355 });
12356
12357 pane.update_in(cx, |pane, window, cx| {
12358 pane.activate_item(1, true, true, window, cx);
12359 assert_eq!(
12360 pane.active_item().unwrap().item_id(),
12361 multi_buffer_with_both_files_id,
12362 "Should select the multi buffer in the pane"
12363 );
12364 });
12365 let _close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12366 pane.close_active_item(
12367 &CloseActiveItem {
12368 save_intent: None,
12369 close_pinned: false,
12370 },
12371 window,
12372 cx,
12373 )
12374 });
12375 cx.background_executor.run_until_parked();
12376 assert!(
12377 cx.has_pending_prompt(),
12378 "With one dirty item from the multi buffer not being in the pane, a save prompt should be shown"
12379 );
12380 }
12381
12382 /// Tests that when `close_on_file_delete` is enabled, files are automatically
12383 /// closed when they are deleted from disk.
12384 #[gpui::test]
12385 async fn test_close_on_disk_deletion_enabled(cx: &mut TestAppContext) {
12386 init_test(cx);
12387
12388 // Enable the close_on_disk_deletion setting
12389 cx.update_global(|store: &mut SettingsStore, cx| {
12390 store.update_user_settings(cx, |settings| {
12391 settings.workspace.close_on_file_delete = Some(true);
12392 });
12393 });
12394
12395 let fs = FakeFs::new(cx.background_executor.clone());
12396 let project = Project::test(fs, [], cx).await;
12397 let (workspace, cx) =
12398 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12399 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12400
12401 // Create a test item that simulates a file
12402 let item = cx.new(|cx| {
12403 TestItem::new(cx)
12404 .with_label("test.txt")
12405 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12406 });
12407
12408 // Add item to workspace
12409 workspace.update_in(cx, |workspace, window, cx| {
12410 workspace.add_item(
12411 pane.clone(),
12412 Box::new(item.clone()),
12413 None,
12414 false,
12415 false,
12416 window,
12417 cx,
12418 );
12419 });
12420
12421 // Verify the item is in the pane
12422 pane.read_with(cx, |pane, _| {
12423 assert_eq!(pane.items().count(), 1);
12424 });
12425
12426 // Simulate file deletion by setting the item's deleted state
12427 item.update(cx, |item, _| {
12428 item.set_has_deleted_file(true);
12429 });
12430
12431 // Emit UpdateTab event to trigger the close behavior
12432 cx.run_until_parked();
12433 item.update(cx, |_, cx| {
12434 cx.emit(ItemEvent::UpdateTab);
12435 });
12436
12437 // Allow the close operation to complete
12438 cx.run_until_parked();
12439
12440 // Verify the item was automatically closed
12441 pane.read_with(cx, |pane, _| {
12442 assert_eq!(
12443 pane.items().count(),
12444 0,
12445 "Item should be automatically closed when file is deleted"
12446 );
12447 });
12448 }
12449
12450 /// Tests that when `close_on_file_delete` is disabled (default), files remain
12451 /// open with a strikethrough when they are deleted from disk.
12452 #[gpui::test]
12453 async fn test_close_on_disk_deletion_disabled(cx: &mut TestAppContext) {
12454 init_test(cx);
12455
12456 // Ensure close_on_disk_deletion is disabled (default)
12457 cx.update_global(|store: &mut SettingsStore, cx| {
12458 store.update_user_settings(cx, |settings| {
12459 settings.workspace.close_on_file_delete = Some(false);
12460 });
12461 });
12462
12463 let fs = FakeFs::new(cx.background_executor.clone());
12464 let project = Project::test(fs, [], cx).await;
12465 let (workspace, cx) =
12466 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12467 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12468
12469 // Create a test item that simulates a file
12470 let item = cx.new(|cx| {
12471 TestItem::new(cx)
12472 .with_label("test.txt")
12473 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12474 });
12475
12476 // Add item to workspace
12477 workspace.update_in(cx, |workspace, window, cx| {
12478 workspace.add_item(
12479 pane.clone(),
12480 Box::new(item.clone()),
12481 None,
12482 false,
12483 false,
12484 window,
12485 cx,
12486 );
12487 });
12488
12489 // Verify the item is in the pane
12490 pane.read_with(cx, |pane, _| {
12491 assert_eq!(pane.items().count(), 1);
12492 });
12493
12494 // Simulate file deletion
12495 item.update(cx, |item, _| {
12496 item.set_has_deleted_file(true);
12497 });
12498
12499 // Emit UpdateTab event
12500 cx.run_until_parked();
12501 item.update(cx, |_, cx| {
12502 cx.emit(ItemEvent::UpdateTab);
12503 });
12504
12505 // Allow any potential close operation to complete
12506 cx.run_until_parked();
12507
12508 // Verify the item remains open (with strikethrough)
12509 pane.read_with(cx, |pane, _| {
12510 assert_eq!(
12511 pane.items().count(),
12512 1,
12513 "Item should remain open when close_on_disk_deletion is disabled"
12514 );
12515 });
12516
12517 // Verify the item shows as deleted
12518 item.read_with(cx, |item, _| {
12519 assert!(
12520 item.has_deleted_file,
12521 "Item should be marked as having deleted file"
12522 );
12523 });
12524 }
12525
12526 /// Tests that dirty files are not automatically closed when deleted from disk,
12527 /// even when `close_on_file_delete` is enabled. This ensures users don't lose
12528 /// unsaved changes without being prompted.
12529 #[gpui::test]
12530 async fn test_close_on_disk_deletion_with_dirty_file(cx: &mut TestAppContext) {
12531 init_test(cx);
12532
12533 // Enable the close_on_file_delete setting
12534 cx.update_global(|store: &mut SettingsStore, cx| {
12535 store.update_user_settings(cx, |settings| {
12536 settings.workspace.close_on_file_delete = Some(true);
12537 });
12538 });
12539
12540 let fs = FakeFs::new(cx.background_executor.clone());
12541 let project = Project::test(fs, [], cx).await;
12542 let (workspace, cx) =
12543 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12544 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12545
12546 // Create a dirty test item
12547 let item = cx.new(|cx| {
12548 TestItem::new(cx)
12549 .with_dirty(true)
12550 .with_label("test.txt")
12551 .with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
12552 });
12553
12554 // Add item to workspace
12555 workspace.update_in(cx, |workspace, window, cx| {
12556 workspace.add_item(
12557 pane.clone(),
12558 Box::new(item.clone()),
12559 None,
12560 false,
12561 false,
12562 window,
12563 cx,
12564 );
12565 });
12566
12567 // Simulate file deletion
12568 item.update(cx, |item, _| {
12569 item.set_has_deleted_file(true);
12570 });
12571
12572 // Emit UpdateTab event to trigger the close behavior
12573 cx.run_until_parked();
12574 item.update(cx, |_, cx| {
12575 cx.emit(ItemEvent::UpdateTab);
12576 });
12577
12578 // Allow any potential close operation to complete
12579 cx.run_until_parked();
12580
12581 // Verify the item remains open (dirty files are not auto-closed)
12582 pane.read_with(cx, |pane, _| {
12583 assert_eq!(
12584 pane.items().count(),
12585 1,
12586 "Dirty items should not be automatically closed even when file is deleted"
12587 );
12588 });
12589
12590 // Verify the item is marked as deleted and still dirty
12591 item.read_with(cx, |item, _| {
12592 assert!(
12593 item.has_deleted_file,
12594 "Item should be marked as having deleted file"
12595 );
12596 assert!(item.is_dirty, "Item should still be dirty");
12597 });
12598 }
12599
12600 /// Tests that navigation history is cleaned up when files are auto-closed
12601 /// due to deletion from disk.
12602 #[gpui::test]
12603 async fn test_close_on_disk_deletion_cleans_navigation_history(cx: &mut TestAppContext) {
12604 init_test(cx);
12605
12606 // Enable the close_on_file_delete setting
12607 cx.update_global(|store: &mut SettingsStore, cx| {
12608 store.update_user_settings(cx, |settings| {
12609 settings.workspace.close_on_file_delete = Some(true);
12610 });
12611 });
12612
12613 let fs = FakeFs::new(cx.background_executor.clone());
12614 let project = Project::test(fs, [], cx).await;
12615 let (workspace, cx) =
12616 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12617 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12618
12619 // Create test items
12620 let item1 = cx.new(|cx| {
12621 TestItem::new(cx)
12622 .with_label("test1.txt")
12623 .with_project_items(&[TestProjectItem::new(1, "test1.txt", cx)])
12624 });
12625 let item1_id = item1.item_id();
12626
12627 let item2 = cx.new(|cx| {
12628 TestItem::new(cx)
12629 .with_label("test2.txt")
12630 .with_project_items(&[TestProjectItem::new(2, "test2.txt", cx)])
12631 });
12632
12633 // Add items to workspace
12634 workspace.update_in(cx, |workspace, window, cx| {
12635 workspace.add_item(
12636 pane.clone(),
12637 Box::new(item1.clone()),
12638 None,
12639 false,
12640 false,
12641 window,
12642 cx,
12643 );
12644 workspace.add_item(
12645 pane.clone(),
12646 Box::new(item2.clone()),
12647 None,
12648 false,
12649 false,
12650 window,
12651 cx,
12652 );
12653 });
12654
12655 // Activate item1 to ensure it gets navigation entries
12656 pane.update_in(cx, |pane, window, cx| {
12657 pane.activate_item(0, true, true, window, cx);
12658 });
12659
12660 // Switch to item2 and back to create navigation history
12661 pane.update_in(cx, |pane, window, cx| {
12662 pane.activate_item(1, true, true, window, cx);
12663 });
12664 cx.run_until_parked();
12665
12666 pane.update_in(cx, |pane, window, cx| {
12667 pane.activate_item(0, true, true, window, cx);
12668 });
12669 cx.run_until_parked();
12670
12671 // Simulate file deletion for item1
12672 item1.update(cx, |item, _| {
12673 item.set_has_deleted_file(true);
12674 });
12675
12676 // Emit UpdateTab event to trigger the close behavior
12677 item1.update(cx, |_, cx| {
12678 cx.emit(ItemEvent::UpdateTab);
12679 });
12680 cx.run_until_parked();
12681
12682 // Verify item1 was closed
12683 pane.read_with(cx, |pane, _| {
12684 assert_eq!(
12685 pane.items().count(),
12686 1,
12687 "Should have 1 item remaining after auto-close"
12688 );
12689 });
12690
12691 // Check navigation history after close
12692 let has_item = pane.read_with(cx, |pane, cx| {
12693 let mut has_item = false;
12694 pane.nav_history().for_each_entry(cx, &mut |entry, _| {
12695 if entry.item.id() == item1_id {
12696 has_item = true;
12697 }
12698 });
12699 has_item
12700 });
12701
12702 assert!(
12703 !has_item,
12704 "Navigation history should not contain closed item entries"
12705 );
12706 }
12707
12708 #[gpui::test]
12709 async fn test_no_save_prompt_when_dirty_multi_buffer_closed_with_all_of_its_dirty_items_present_in_the_pane(
12710 cx: &mut TestAppContext,
12711 ) {
12712 init_test(cx);
12713
12714 let fs = FakeFs::new(cx.background_executor.clone());
12715 let project = Project::test(fs, [], cx).await;
12716 let (workspace, cx) =
12717 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
12718 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
12719
12720 let dirty_regular_buffer = cx.new(|cx| {
12721 TestItem::new(cx)
12722 .with_dirty(true)
12723 .with_label("1.txt")
12724 .with_project_items(&[dirty_project_item(1, "1.txt", cx)])
12725 });
12726 let dirty_regular_buffer_2 = cx.new(|cx| {
12727 TestItem::new(cx)
12728 .with_dirty(true)
12729 .with_label("2.txt")
12730 .with_project_items(&[dirty_project_item(2, "2.txt", cx)])
12731 });
12732 let clear_regular_buffer = cx.new(|cx| {
12733 TestItem::new(cx)
12734 .with_label("3.txt")
12735 .with_project_items(&[TestProjectItem::new(3, "3.txt", cx)])
12736 });
12737
12738 let dirty_multi_buffer = cx.new(|cx| {
12739 TestItem::new(cx)
12740 .with_dirty(true)
12741 .with_buffer_kind(ItemBufferKind::Multibuffer)
12742 .with_label("Fake Project Search")
12743 .with_project_items(&[
12744 dirty_regular_buffer.read(cx).project_items[0].clone(),
12745 dirty_regular_buffer_2.read(cx).project_items[0].clone(),
12746 clear_regular_buffer.read(cx).project_items[0].clone(),
12747 ])
12748 });
12749 workspace.update_in(cx, |workspace, window, cx| {
12750 workspace.add_item(
12751 pane.clone(),
12752 Box::new(dirty_regular_buffer.clone()),
12753 None,
12754 false,
12755 false,
12756 window,
12757 cx,
12758 );
12759 workspace.add_item(
12760 pane.clone(),
12761 Box::new(dirty_regular_buffer_2.clone()),
12762 None,
12763 false,
12764 false,
12765 window,
12766 cx,
12767 );
12768 workspace.add_item(
12769 pane.clone(),
12770 Box::new(dirty_multi_buffer.clone()),
12771 None,
12772 false,
12773 false,
12774 window,
12775 cx,
12776 );
12777 });
12778
12779 pane.update_in(cx, |pane, window, cx| {
12780 pane.activate_item(2, true, true, window, cx);
12781 assert_eq!(
12782 pane.active_item().unwrap().item_id(),
12783 dirty_multi_buffer.item_id(),
12784 "Should select the multi buffer in the pane"
12785 );
12786 });
12787 let close_multi_buffer_task = pane.update_in(cx, |pane, window, cx| {
12788 pane.close_active_item(
12789 &CloseActiveItem {
12790 save_intent: None,
12791 close_pinned: false,
12792 },
12793 window,
12794 cx,
12795 )
12796 });
12797 cx.background_executor.run_until_parked();
12798 assert!(
12799 !cx.has_pending_prompt(),
12800 "All dirty items from the multi buffer are in the pane still, no save prompts should be shown"
12801 );
12802 close_multi_buffer_task
12803 .await
12804 .expect("Closing multi buffer failed");
12805 pane.update(cx, |pane, cx| {
12806 assert_eq!(dirty_regular_buffer.read(cx).save_count, 0);
12807 assert_eq!(dirty_multi_buffer.read(cx).save_count, 0);
12808 assert_eq!(dirty_regular_buffer_2.read(cx).save_count, 0);
12809 assert_eq!(
12810 pane.items()
12811 .map(|item| item.item_id())
12812 .sorted()
12813 .collect::<Vec<_>>(),
12814 vec![
12815 dirty_regular_buffer.item_id(),
12816 dirty_regular_buffer_2.item_id(),
12817 ],
12818 "Should have no multi buffer left in the pane"
12819 );
12820 assert!(dirty_regular_buffer.read(cx).is_dirty);
12821 assert!(dirty_regular_buffer_2.read(cx).is_dirty);
12822 });
12823 }
12824
12825 #[gpui::test]
12826 async fn test_move_focused_panel_to_next_position(cx: &mut gpui::TestAppContext) {
12827 init_test(cx);
12828 let fs = FakeFs::new(cx.executor());
12829 let project = Project::test(fs, [], cx).await;
12830 let (multi_workspace, cx) =
12831 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
12832 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
12833
12834 // Add a new panel to the right dock, opening the dock and setting the
12835 // focus to the new panel.
12836 let panel = workspace.update_in(cx, |workspace, window, cx| {
12837 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
12838 workspace.add_panel(panel.clone(), window, cx);
12839
12840 workspace
12841 .right_dock()
12842 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
12843
12844 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12845
12846 panel
12847 });
12848
12849 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12850 // panel to the next valid position which, in this case, is the left
12851 // dock.
12852 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12853 workspace.update(cx, |workspace, cx| {
12854 assert!(workspace.left_dock().read(cx).is_open());
12855 assert_eq!(panel.read(cx).position, DockPosition::Left);
12856 });
12857
12858 // Dispatch the `MoveFocusedPanelToNextPosition` action, moving the
12859 // panel to the next valid position which, in this case, is the bottom
12860 // dock.
12861 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12862 workspace.update(cx, |workspace, cx| {
12863 assert!(workspace.bottom_dock().read(cx).is_open());
12864 assert_eq!(panel.read(cx).position, DockPosition::Bottom);
12865 });
12866
12867 // Dispatch the `MoveFocusedPanelToNextPosition` action again, this time
12868 // around moving the panel to its initial position, the right dock.
12869 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12870 workspace.update(cx, |workspace, cx| {
12871 assert!(workspace.right_dock().read(cx).is_open());
12872 assert_eq!(panel.read(cx).position, DockPosition::Right);
12873 });
12874
12875 // Remove focus from the panel, ensuring that, if the panel is not
12876 // focused, the `MoveFocusedPanelToNextPosition` action does not update
12877 // the panel's position, so the panel is still in the right dock.
12878 workspace.update_in(cx, |workspace, window, cx| {
12879 workspace.toggle_panel_focus::<TestPanel>(window, cx);
12880 });
12881
12882 cx.dispatch_action(MoveFocusedPanelToNextPosition);
12883 workspace.update(cx, |workspace, cx| {
12884 assert!(workspace.right_dock().read(cx).is_open());
12885 assert_eq!(panel.read(cx).position, DockPosition::Right);
12886 });
12887 }
12888
12889 #[gpui::test]
12890 async fn test_moving_items_create_panes(cx: &mut TestAppContext) {
12891 init_test(cx);
12892
12893 let fs = FakeFs::new(cx.executor());
12894 let project = Project::test(fs, [], cx).await;
12895 let (workspace, cx) =
12896 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
12897
12898 let item_1 = cx.new(|cx| {
12899 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
12900 });
12901 workspace.update_in(cx, |workspace, window, cx| {
12902 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
12903 workspace.move_item_to_pane_in_direction(
12904 &MoveItemToPaneInDirection {
12905 direction: SplitDirection::Right,
12906 focus: true,
12907 clone: false,
12908 },
12909 window,
12910 cx,
12911 );
12912 workspace.move_item_to_pane_at_index(
12913 &MoveItemToPane {
12914 destination: 3,
12915 focus: true,
12916 clone: false,
12917 },
12918 window,
12919 cx,
12920 );
12921
12922 assert_eq!(workspace.panes.len(), 1, "No new panes were created");
12923 assert_eq!(
12924 pane_items_paths(&workspace.active_pane, cx),
12925 vec!["first.txt".to_string()],
12926 "Single item was not moved anywhere"
12927 );
12928 });
12929
12930 let item_2 = cx.new(|cx| {
12931 TestItem::new(cx).with_project_items(&[TestProjectItem::new(2, "second.txt", cx)])
12932 });
12933 workspace.update_in(cx, |workspace, window, cx| {
12934 workspace.add_item_to_active_pane(Box::new(item_2), None, true, window, cx);
12935 assert_eq!(
12936 pane_items_paths(&workspace.panes[0], cx),
12937 vec!["first.txt".to_string(), "second.txt".to_string()],
12938 );
12939 workspace.move_item_to_pane_in_direction(
12940 &MoveItemToPaneInDirection {
12941 direction: SplitDirection::Right,
12942 focus: true,
12943 clone: false,
12944 },
12945 window,
12946 cx,
12947 );
12948
12949 assert_eq!(workspace.panes.len(), 2, "A new pane should be created");
12950 assert_eq!(
12951 pane_items_paths(&workspace.panes[0], cx),
12952 vec!["first.txt".to_string()],
12953 "After moving, one item should be left in the original pane"
12954 );
12955 assert_eq!(
12956 pane_items_paths(&workspace.panes[1], cx),
12957 vec!["second.txt".to_string()],
12958 "New item should have been moved to the new pane"
12959 );
12960 });
12961
12962 let item_3 = cx.new(|cx| {
12963 TestItem::new(cx).with_project_items(&[TestProjectItem::new(3, "third.txt", cx)])
12964 });
12965 workspace.update_in(cx, |workspace, window, cx| {
12966 let original_pane = workspace.panes[0].clone();
12967 workspace.set_active_pane(&original_pane, window, cx);
12968 workspace.add_item_to_active_pane(Box::new(item_3), None, true, window, cx);
12969 assert_eq!(workspace.panes.len(), 2, "No new panes were created");
12970 assert_eq!(
12971 pane_items_paths(&workspace.active_pane, cx),
12972 vec!["first.txt".to_string(), "third.txt".to_string()],
12973 "New pane should be ready to move one item out"
12974 );
12975
12976 workspace.move_item_to_pane_at_index(
12977 &MoveItemToPane {
12978 destination: 3,
12979 focus: true,
12980 clone: false,
12981 },
12982 window,
12983 cx,
12984 );
12985 assert_eq!(workspace.panes.len(), 3, "A new pane should be created");
12986 assert_eq!(
12987 pane_items_paths(&workspace.active_pane, cx),
12988 vec!["first.txt".to_string()],
12989 "After moving, one item should be left in the original pane"
12990 );
12991 assert_eq!(
12992 pane_items_paths(&workspace.panes[1], cx),
12993 vec!["second.txt".to_string()],
12994 "Previously created pane should be unchanged"
12995 );
12996 assert_eq!(
12997 pane_items_paths(&workspace.panes[2], cx),
12998 vec!["third.txt".to_string()],
12999 "New item should have been moved to the new pane"
13000 );
13001 });
13002 }
13003
13004 #[gpui::test]
13005 async fn test_moving_items_can_clone_panes(cx: &mut TestAppContext) {
13006 init_test(cx);
13007
13008 let fs = FakeFs::new(cx.executor());
13009 let project = Project::test(fs, [], cx).await;
13010 let (workspace, cx) =
13011 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13012
13013 let item_1 = cx.new(|cx| {
13014 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "first.txt", cx)])
13015 });
13016 workspace.update_in(cx, |workspace, window, cx| {
13017 workspace.add_item_to_active_pane(Box::new(item_1), None, true, window, cx);
13018 workspace.move_item_to_pane_in_direction(
13019 &MoveItemToPaneInDirection {
13020 direction: SplitDirection::Right,
13021 focus: true,
13022 clone: true,
13023 },
13024 window,
13025 cx,
13026 );
13027 });
13028 cx.run_until_parked();
13029 workspace.update_in(cx, |workspace, window, cx| {
13030 workspace.move_item_to_pane_at_index(
13031 &MoveItemToPane {
13032 destination: 3,
13033 focus: true,
13034 clone: true,
13035 },
13036 window,
13037 cx,
13038 );
13039 });
13040 cx.run_until_parked();
13041
13042 workspace.update(cx, |workspace, cx| {
13043 assert_eq!(workspace.panes.len(), 3, "Two new panes were created");
13044 for pane in workspace.panes() {
13045 assert_eq!(
13046 pane_items_paths(pane, cx),
13047 vec!["first.txt".to_string()],
13048 "Single item exists in all panes"
13049 );
13050 }
13051 });
13052
13053 // verify that the active pane has been updated after waiting for the
13054 // pane focus event to fire and resolve
13055 workspace.read_with(cx, |workspace, _app| {
13056 assert_eq!(
13057 workspace.active_pane(),
13058 &workspace.panes[2],
13059 "The third pane should be the active one: {:?}",
13060 workspace.panes
13061 );
13062 })
13063 }
13064
13065 #[gpui::test]
13066 async fn test_close_item_in_all_panes(cx: &mut TestAppContext) {
13067 init_test(cx);
13068
13069 let fs = FakeFs::new(cx.executor());
13070 fs.insert_tree("/root", json!({ "test.txt": "" })).await;
13071
13072 let project = Project::test(fs, ["root".as_ref()], cx).await;
13073 let (workspace, cx) =
13074 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13075
13076 let pane_a = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13077 // Add item to pane A with project path
13078 let item_a = cx.new(|cx| {
13079 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13080 });
13081 workspace.update_in(cx, |workspace, window, cx| {
13082 workspace.add_item_to_active_pane(Box::new(item_a.clone()), None, true, window, cx)
13083 });
13084
13085 // Split to create pane B
13086 let pane_b = workspace.update_in(cx, |workspace, window, cx| {
13087 workspace.split_pane(pane_a.clone(), SplitDirection::Right, window, cx)
13088 });
13089
13090 // Add item with SAME project path to pane B, and pin it
13091 let item_b = cx.new(|cx| {
13092 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13093 });
13094 pane_b.update_in(cx, |pane, window, cx| {
13095 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13096 pane.set_pinned_count(1);
13097 });
13098
13099 assert_eq!(pane_a.read_with(cx, |pane, _| pane.items_len()), 1);
13100 assert_eq!(pane_b.read_with(cx, |pane, _| pane.items_len()), 1);
13101
13102 // close_pinned: false should only close the unpinned copy
13103 workspace.update_in(cx, |workspace, window, cx| {
13104 workspace.close_item_in_all_panes(
13105 &CloseItemInAllPanes {
13106 save_intent: Some(SaveIntent::Close),
13107 close_pinned: false,
13108 },
13109 window,
13110 cx,
13111 )
13112 });
13113 cx.executor().run_until_parked();
13114
13115 let item_count_a = pane_a.read_with(cx, |pane, _| pane.items_len());
13116 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13117 assert_eq!(item_count_a, 0, "Unpinned item in pane A should be closed");
13118 assert_eq!(item_count_b, 1, "Pinned item in pane B should remain");
13119
13120 // Split again, seeing as closing the previous item also closed its
13121 // pane, so only pane remains, which does not allow us to properly test
13122 // that both items close when `close_pinned: true`.
13123 let pane_c = workspace.update_in(cx, |workspace, window, cx| {
13124 workspace.split_pane(pane_b.clone(), SplitDirection::Right, window, cx)
13125 });
13126
13127 // Add an item with the same project path to pane C so that
13128 // close_item_in_all_panes can determine what to close across all panes
13129 // (it reads the active item from the active pane, and split_pane
13130 // creates an empty pane).
13131 let item_c = cx.new(|cx| {
13132 TestItem::new(cx).with_project_items(&[TestProjectItem::new(1, "test.txt", cx)])
13133 });
13134 pane_c.update_in(cx, |pane, window, cx| {
13135 pane.add_item(Box::new(item_c.clone()), true, true, None, window, cx);
13136 });
13137
13138 // close_pinned: true should close the pinned copy too
13139 workspace.update_in(cx, |workspace, window, cx| {
13140 let panes_count = workspace.panes().len();
13141 assert_eq!(panes_count, 2, "Workspace should have two panes (B and C)");
13142
13143 workspace.close_item_in_all_panes(
13144 &CloseItemInAllPanes {
13145 save_intent: Some(SaveIntent::Close),
13146 close_pinned: true,
13147 },
13148 window,
13149 cx,
13150 )
13151 });
13152 cx.executor().run_until_parked();
13153
13154 let item_count_b = pane_b.read_with(cx, |pane, _| pane.items_len());
13155 let item_count_c = pane_c.read_with(cx, |pane, _| pane.items_len());
13156 assert_eq!(item_count_b, 0, "Pinned item in pane B should be closed");
13157 assert_eq!(item_count_c, 0, "Unpinned item in pane C should be closed");
13158 }
13159
13160 mod register_project_item_tests {
13161
13162 use super::*;
13163
13164 // View
13165 struct TestPngItemView {
13166 focus_handle: FocusHandle,
13167 }
13168 // Model
13169 struct TestPngItem {}
13170
13171 impl project::ProjectItem for TestPngItem {
13172 fn try_open(
13173 _project: &Entity<Project>,
13174 path: &ProjectPath,
13175 cx: &mut App,
13176 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13177 if path.path.extension().unwrap() == "png" {
13178 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestPngItem {}))))
13179 } else {
13180 None
13181 }
13182 }
13183
13184 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13185 None
13186 }
13187
13188 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13189 None
13190 }
13191
13192 fn is_dirty(&self) -> bool {
13193 false
13194 }
13195 }
13196
13197 impl Item for TestPngItemView {
13198 type Event = ();
13199 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13200 "".into()
13201 }
13202 }
13203 impl EventEmitter<()> for TestPngItemView {}
13204 impl Focusable for TestPngItemView {
13205 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13206 self.focus_handle.clone()
13207 }
13208 }
13209
13210 impl Render for TestPngItemView {
13211 fn render(
13212 &mut self,
13213 _window: &mut Window,
13214 _cx: &mut Context<Self>,
13215 ) -> impl IntoElement {
13216 Empty
13217 }
13218 }
13219
13220 impl ProjectItem for TestPngItemView {
13221 type Item = TestPngItem;
13222
13223 fn for_project_item(
13224 _project: Entity<Project>,
13225 _pane: Option<&Pane>,
13226 _item: Entity<Self::Item>,
13227 _: &mut Window,
13228 cx: &mut Context<Self>,
13229 ) -> Self
13230 where
13231 Self: Sized,
13232 {
13233 Self {
13234 focus_handle: cx.focus_handle(),
13235 }
13236 }
13237 }
13238
13239 // View
13240 struct TestIpynbItemView {
13241 focus_handle: FocusHandle,
13242 }
13243 // Model
13244 struct TestIpynbItem {}
13245
13246 impl project::ProjectItem for TestIpynbItem {
13247 fn try_open(
13248 _project: &Entity<Project>,
13249 path: &ProjectPath,
13250 cx: &mut App,
13251 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
13252 if path.path.extension().unwrap() == "ipynb" {
13253 Some(cx.spawn(async move |cx| Ok(cx.new(|_| TestIpynbItem {}))))
13254 } else {
13255 None
13256 }
13257 }
13258
13259 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
13260 None
13261 }
13262
13263 fn project_path(&self, _: &App) -> Option<ProjectPath> {
13264 None
13265 }
13266
13267 fn is_dirty(&self) -> bool {
13268 false
13269 }
13270 }
13271
13272 impl Item for TestIpynbItemView {
13273 type Event = ();
13274 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13275 "".into()
13276 }
13277 }
13278 impl EventEmitter<()> for TestIpynbItemView {}
13279 impl Focusable for TestIpynbItemView {
13280 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13281 self.focus_handle.clone()
13282 }
13283 }
13284
13285 impl Render for TestIpynbItemView {
13286 fn render(
13287 &mut self,
13288 _window: &mut Window,
13289 _cx: &mut Context<Self>,
13290 ) -> impl IntoElement {
13291 Empty
13292 }
13293 }
13294
13295 impl ProjectItem for TestIpynbItemView {
13296 type Item = TestIpynbItem;
13297
13298 fn for_project_item(
13299 _project: Entity<Project>,
13300 _pane: Option<&Pane>,
13301 _item: Entity<Self::Item>,
13302 _: &mut Window,
13303 cx: &mut Context<Self>,
13304 ) -> Self
13305 where
13306 Self: Sized,
13307 {
13308 Self {
13309 focus_handle: cx.focus_handle(),
13310 }
13311 }
13312 }
13313
13314 struct TestAlternatePngItemView {
13315 focus_handle: FocusHandle,
13316 }
13317
13318 impl Item for TestAlternatePngItemView {
13319 type Event = ();
13320 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
13321 "".into()
13322 }
13323 }
13324
13325 impl EventEmitter<()> for TestAlternatePngItemView {}
13326 impl Focusable for TestAlternatePngItemView {
13327 fn focus_handle(&self, _cx: &App) -> FocusHandle {
13328 self.focus_handle.clone()
13329 }
13330 }
13331
13332 impl Render for TestAlternatePngItemView {
13333 fn render(
13334 &mut self,
13335 _window: &mut Window,
13336 _cx: &mut Context<Self>,
13337 ) -> impl IntoElement {
13338 Empty
13339 }
13340 }
13341
13342 impl ProjectItem for TestAlternatePngItemView {
13343 type Item = TestPngItem;
13344
13345 fn for_project_item(
13346 _project: Entity<Project>,
13347 _pane: Option<&Pane>,
13348 _item: Entity<Self::Item>,
13349 _: &mut Window,
13350 cx: &mut Context<Self>,
13351 ) -> Self
13352 where
13353 Self: Sized,
13354 {
13355 Self {
13356 focus_handle: cx.focus_handle(),
13357 }
13358 }
13359 }
13360
13361 #[gpui::test]
13362 async fn test_register_project_item(cx: &mut TestAppContext) {
13363 init_test(cx);
13364
13365 cx.update(|cx| {
13366 register_project_item::<TestPngItemView>(cx);
13367 register_project_item::<TestIpynbItemView>(cx);
13368 });
13369
13370 let fs = FakeFs::new(cx.executor());
13371 fs.insert_tree(
13372 "/root1",
13373 json!({
13374 "one.png": "BINARYDATAHERE",
13375 "two.ipynb": "{ totally a notebook }",
13376 "three.txt": "editing text, sure why not?"
13377 }),
13378 )
13379 .await;
13380
13381 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13382 let (workspace, cx) =
13383 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13384
13385 let worktree_id = project.update(cx, |project, cx| {
13386 project.worktrees(cx).next().unwrap().read(cx).id()
13387 });
13388
13389 let handle = workspace
13390 .update_in(cx, |workspace, window, cx| {
13391 let project_path = (worktree_id, rel_path("one.png"));
13392 workspace.open_path(project_path, None, true, window, cx)
13393 })
13394 .await
13395 .unwrap();
13396
13397 // Now we can check if the handle we got back errored or not
13398 assert_eq!(
13399 handle.to_any_view().entity_type(),
13400 TypeId::of::<TestPngItemView>()
13401 );
13402
13403 let handle = workspace
13404 .update_in(cx, |workspace, window, cx| {
13405 let project_path = (worktree_id, rel_path("two.ipynb"));
13406 workspace.open_path(project_path, None, true, window, cx)
13407 })
13408 .await
13409 .unwrap();
13410
13411 assert_eq!(
13412 handle.to_any_view().entity_type(),
13413 TypeId::of::<TestIpynbItemView>()
13414 );
13415
13416 let handle = workspace
13417 .update_in(cx, |workspace, window, cx| {
13418 let project_path = (worktree_id, rel_path("three.txt"));
13419 workspace.open_path(project_path, None, true, window, cx)
13420 })
13421 .await;
13422 assert!(handle.is_err());
13423 }
13424
13425 #[gpui::test]
13426 async fn test_register_project_item_two_enter_one_leaves(cx: &mut TestAppContext) {
13427 init_test(cx);
13428
13429 cx.update(|cx| {
13430 register_project_item::<TestPngItemView>(cx);
13431 register_project_item::<TestAlternatePngItemView>(cx);
13432 });
13433
13434 let fs = FakeFs::new(cx.executor());
13435 fs.insert_tree(
13436 "/root1",
13437 json!({
13438 "one.png": "BINARYDATAHERE",
13439 "two.ipynb": "{ totally a notebook }",
13440 "three.txt": "editing text, sure why not?"
13441 }),
13442 )
13443 .await;
13444 let project = Project::test(fs, ["root1".as_ref()], cx).await;
13445 let (workspace, cx) =
13446 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13447 let worktree_id = project.update(cx, |project, cx| {
13448 project.worktrees(cx).next().unwrap().read(cx).id()
13449 });
13450
13451 let handle = workspace
13452 .update_in(cx, |workspace, window, cx| {
13453 let project_path = (worktree_id, rel_path("one.png"));
13454 workspace.open_path(project_path, None, true, window, cx)
13455 })
13456 .await
13457 .unwrap();
13458
13459 // This _must_ be the second item registered
13460 assert_eq!(
13461 handle.to_any_view().entity_type(),
13462 TypeId::of::<TestAlternatePngItemView>()
13463 );
13464
13465 let handle = workspace
13466 .update_in(cx, |workspace, window, cx| {
13467 let project_path = (worktree_id, rel_path("three.txt"));
13468 workspace.open_path(project_path, None, true, window, cx)
13469 })
13470 .await;
13471 assert!(handle.is_err());
13472 }
13473 }
13474
13475 #[gpui::test]
13476 async fn test_status_bar_visibility(cx: &mut TestAppContext) {
13477 init_test(cx);
13478
13479 let fs = FakeFs::new(cx.executor());
13480 let project = Project::test(fs, [], cx).await;
13481 let (workspace, _cx) =
13482 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13483
13484 // Test with status bar shown (default)
13485 workspace.read_with(cx, |workspace, cx| {
13486 let visible = workspace.status_bar_visible(cx);
13487 assert!(visible, "Status bar should be visible by default");
13488 });
13489
13490 // Test with status bar hidden
13491 cx.update_global(|store: &mut SettingsStore, cx| {
13492 store.update_user_settings(cx, |settings| {
13493 settings.status_bar.get_or_insert_default().show = Some(false);
13494 });
13495 });
13496
13497 workspace.read_with(cx, |workspace, cx| {
13498 let visible = workspace.status_bar_visible(cx);
13499 assert!(!visible, "Status bar should be hidden when show is false");
13500 });
13501
13502 // Test with status bar shown explicitly
13503 cx.update_global(|store: &mut SettingsStore, cx| {
13504 store.update_user_settings(cx, |settings| {
13505 settings.status_bar.get_or_insert_default().show = Some(true);
13506 });
13507 });
13508
13509 workspace.read_with(cx, |workspace, cx| {
13510 let visible = workspace.status_bar_visible(cx);
13511 assert!(visible, "Status bar should be visible when show is true");
13512 });
13513 }
13514
13515 #[gpui::test]
13516 async fn test_pane_close_active_item(cx: &mut TestAppContext) {
13517 init_test(cx);
13518
13519 let fs = FakeFs::new(cx.executor());
13520 let project = Project::test(fs, [], cx).await;
13521 let (multi_workspace, cx) =
13522 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
13523 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
13524 let panel = workspace.update_in(cx, |workspace, window, cx| {
13525 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13526 workspace.add_panel(panel.clone(), window, cx);
13527
13528 workspace
13529 .right_dock()
13530 .update(cx, |right_dock, cx| right_dock.set_open(true, window, cx));
13531
13532 panel
13533 });
13534
13535 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13536 let item_a = cx.new(TestItem::new);
13537 let item_b = cx.new(TestItem::new);
13538 let item_a_id = item_a.entity_id();
13539 let item_b_id = item_b.entity_id();
13540
13541 pane.update_in(cx, |pane, window, cx| {
13542 pane.add_item(Box::new(item_a.clone()), true, true, None, window, cx);
13543 pane.add_item(Box::new(item_b.clone()), true, true, None, window, cx);
13544 });
13545
13546 pane.read_with(cx, |pane, _| {
13547 assert_eq!(pane.items_len(), 2);
13548 assert_eq!(pane.active_item().unwrap().item_id(), item_b_id);
13549 });
13550
13551 workspace.update_in(cx, |workspace, window, cx| {
13552 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13553 });
13554
13555 workspace.update_in(cx, |_, window, cx| {
13556 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13557 });
13558
13559 // Assert that the `pane::CloseActiveItem` action is handled at the
13560 // workspace level when one of the dock panels is focused and, in that
13561 // case, the center pane's active item is closed but the focus is not
13562 // moved.
13563 cx.dispatch_action(pane::CloseActiveItem::default());
13564 cx.run_until_parked();
13565
13566 pane.read_with(cx, |pane, _| {
13567 assert_eq!(pane.items_len(), 1);
13568 assert_eq!(pane.active_item().unwrap().item_id(), item_a_id);
13569 });
13570
13571 workspace.update_in(cx, |workspace, window, cx| {
13572 assert!(workspace.right_dock().read(cx).is_open());
13573 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13574 });
13575 }
13576
13577 #[gpui::test]
13578 async fn test_panel_zoom_preserved_across_workspace_switch(cx: &mut TestAppContext) {
13579 init_test(cx);
13580 let fs = FakeFs::new(cx.executor());
13581
13582 let project_a = Project::test(fs.clone(), [], cx).await;
13583 let project_b = Project::test(fs, [], cx).await;
13584
13585 let multi_workspace_handle =
13586 cx.add_window(|window, cx| MultiWorkspace::test_new(project_a.clone(), window, cx));
13587 cx.run_until_parked();
13588
13589 let workspace_a = multi_workspace_handle
13590 .read_with(cx, |mw, _| mw.workspace().clone())
13591 .unwrap();
13592
13593 let _workspace_b = multi_workspace_handle
13594 .update(cx, |mw, window, cx| {
13595 mw.test_add_workspace(project_b, window, cx)
13596 })
13597 .unwrap();
13598
13599 // Switch to workspace A
13600 multi_workspace_handle
13601 .update(cx, |mw, window, cx| {
13602 mw.activate_index(0, window, cx);
13603 })
13604 .unwrap();
13605
13606 let cx = &mut VisualTestContext::from_window(multi_workspace_handle.into(), cx);
13607
13608 // Add a panel to workspace A's right dock and open the dock
13609 let panel = workspace_a.update_in(cx, |workspace, window, cx| {
13610 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13611 workspace.add_panel(panel.clone(), window, cx);
13612 workspace
13613 .right_dock()
13614 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13615 panel
13616 });
13617
13618 // Focus the panel through the workspace (matching existing test pattern)
13619 workspace_a.update_in(cx, |workspace, window, cx| {
13620 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13621 });
13622
13623 // Zoom the panel
13624 panel.update_in(cx, |panel, window, cx| {
13625 panel.set_zoomed(true, window, cx);
13626 });
13627
13628 // Verify the panel is zoomed and the dock is open
13629 workspace_a.update_in(cx, |workspace, window, cx| {
13630 assert!(
13631 workspace.right_dock().read(cx).is_open(),
13632 "dock should be open before switch"
13633 );
13634 assert!(
13635 panel.is_zoomed(window, cx),
13636 "panel should be zoomed before switch"
13637 );
13638 assert!(
13639 panel.read(cx).focus_handle(cx).contains_focused(window, cx),
13640 "panel should be focused before switch"
13641 );
13642 });
13643
13644 // Switch to workspace B
13645 multi_workspace_handle
13646 .update(cx, |mw, window, cx| {
13647 mw.activate_index(1, window, cx);
13648 })
13649 .unwrap();
13650 cx.run_until_parked();
13651
13652 // Switch back to workspace A
13653 multi_workspace_handle
13654 .update(cx, |mw, window, cx| {
13655 mw.activate_index(0, window, cx);
13656 })
13657 .unwrap();
13658 cx.run_until_parked();
13659
13660 // Verify the panel is still zoomed and the dock is still open
13661 workspace_a.update_in(cx, |workspace, window, cx| {
13662 assert!(
13663 workspace.right_dock().read(cx).is_open(),
13664 "dock should still be open after switching back"
13665 );
13666 assert!(
13667 panel.is_zoomed(window, cx),
13668 "panel should still be zoomed after switching back"
13669 );
13670 });
13671 }
13672
13673 fn pane_items_paths(pane: &Entity<Pane>, cx: &App) -> Vec<String> {
13674 pane.read(cx)
13675 .items()
13676 .flat_map(|item| {
13677 item.project_paths(cx)
13678 .into_iter()
13679 .map(|path| path.path.display(PathStyle::local()).into_owned())
13680 })
13681 .collect()
13682 }
13683
13684 pub fn init_test(cx: &mut TestAppContext) {
13685 cx.update(|cx| {
13686 let settings_store = SettingsStore::test(cx);
13687 cx.set_global(settings_store);
13688 cx.set_global(db::AppDatabase::test_new());
13689 theme::init(theme::LoadThemes::JustBase, cx);
13690 });
13691 }
13692
13693 #[gpui::test]
13694 async fn test_toggle_theme_mode_persists_and_updates_active_theme(cx: &mut TestAppContext) {
13695 use settings::{ThemeName, ThemeSelection};
13696 use theme::SystemAppearance;
13697 use zed_actions::theme::ToggleMode;
13698
13699 init_test(cx);
13700
13701 let fs = FakeFs::new(cx.executor());
13702 let settings_fs: Arc<dyn fs::Fs> = fs.clone();
13703
13704 fs.insert_tree(path!("/root"), json!({ "file.rs": "fn main() {}\n" }))
13705 .await;
13706
13707 // Build a test project and workspace view so the test can invoke
13708 // the workspace action handler the same way the UI would.
13709 let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await;
13710 let (workspace, cx) =
13711 cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
13712
13713 // Seed the settings file with a plain static light theme so the
13714 // first toggle always starts from a known persisted state.
13715 workspace.update_in(cx, |_workspace, _window, cx| {
13716 *SystemAppearance::global_mut(cx) = SystemAppearance(theme::Appearance::Light);
13717 settings::update_settings_file(settings_fs.clone(), cx, |settings, _cx| {
13718 settings.theme.theme = Some(ThemeSelection::Static(ThemeName("One Light".into())));
13719 });
13720 });
13721 cx.executor().advance_clock(Duration::from_millis(200));
13722 cx.run_until_parked();
13723
13724 // Confirm the initial persisted settings contain the static theme
13725 // we just wrote before any toggling happens.
13726 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13727 assert!(settings_text.contains(r#""theme": "One Light""#));
13728
13729 // Toggle once. This should migrate the persisted theme settings
13730 // into light/dark slots and enable system mode.
13731 workspace.update_in(cx, |workspace, window, cx| {
13732 workspace.toggle_theme_mode(&ToggleMode, window, cx);
13733 });
13734 cx.executor().advance_clock(Duration::from_millis(200));
13735 cx.run_until_parked();
13736
13737 // 1. Static -> Dynamic
13738 // this assertion checks theme changed from static to dynamic.
13739 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13740 let parsed: serde_json::Value = settings::parse_json_with_comments(&settings_text).unwrap();
13741 assert_eq!(
13742 parsed["theme"],
13743 serde_json::json!({
13744 "mode": "system",
13745 "light": "One Light",
13746 "dark": "One Dark"
13747 })
13748 );
13749
13750 // 2. Toggle again, suppose it will change the mode to light
13751 workspace.update_in(cx, |workspace, window, cx| {
13752 workspace.toggle_theme_mode(&ToggleMode, window, cx);
13753 });
13754 cx.executor().advance_clock(Duration::from_millis(200));
13755 cx.run_until_parked();
13756
13757 let settings_text = SettingsStore::load_settings(&settings_fs).await.unwrap();
13758 assert!(settings_text.contains(r#""mode": "light""#));
13759 }
13760
13761 fn dirty_project_item(id: u64, path: &str, cx: &mut App) -> Entity<TestProjectItem> {
13762 let item = TestProjectItem::new(id, path, cx);
13763 item.update(cx, |item, _| {
13764 item.is_dirty = true;
13765 });
13766 item
13767 }
13768
13769 #[gpui::test]
13770 async fn test_zoomed_panel_without_pane_preserved_on_center_focus(
13771 cx: &mut gpui::TestAppContext,
13772 ) {
13773 init_test(cx);
13774 let fs = FakeFs::new(cx.executor());
13775
13776 let project = Project::test(fs, [], cx).await;
13777 let (workspace, cx) =
13778 cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx));
13779
13780 let panel = workspace.update_in(cx, |workspace, window, cx| {
13781 let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx));
13782 workspace.add_panel(panel.clone(), window, cx);
13783 workspace
13784 .right_dock()
13785 .update(cx, |dock, cx| dock.set_open(true, window, cx));
13786 panel
13787 });
13788
13789 let pane = workspace.read_with(cx, |workspace, _| workspace.active_pane().clone());
13790 pane.update_in(cx, |pane, window, cx| {
13791 let item = cx.new(TestItem::new);
13792 pane.add_item(Box::new(item), true, true, None, window, cx);
13793 });
13794
13795 // Transfer focus to the panel, then zoom it. Using toggle_panel_focus
13796 // mirrors the real-world flow and avoids side effects from directly
13797 // focusing the panel while the center pane is active.
13798 workspace.update_in(cx, |workspace, window, cx| {
13799 workspace.toggle_panel_focus::<TestPanel>(window, cx);
13800 });
13801
13802 panel.update_in(cx, |panel, window, cx| {
13803 panel.set_zoomed(true, window, cx);
13804 });
13805
13806 workspace.update_in(cx, |workspace, window, cx| {
13807 assert!(workspace.right_dock().read(cx).is_open());
13808 assert!(panel.is_zoomed(window, cx));
13809 assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx));
13810 });
13811
13812 // Simulate a spurious pane::Event::Focus on the center pane while the
13813 // panel still has focus. This mirrors what happens during macOS window
13814 // activation: the center pane fires a focus event even though actual
13815 // focus remains on the dock panel.
13816 pane.update_in(cx, |_, _, cx| {
13817 cx.emit(pane::Event::Focus);
13818 });
13819
13820 // The dock must remain open because the panel had focus at the time the
13821 // event was processed. Before the fix, dock_to_preserve was None for
13822 // panels that don't implement pane(), causing the dock to close.
13823 workspace.update_in(cx, |workspace, window, cx| {
13824 assert!(
13825 workspace.right_dock().read(cx).is_open(),
13826 "Dock should stay open when its zoomed panel (without pane()) still has focus"
13827 );
13828 assert!(panel.is_zoomed(window, cx));
13829 });
13830 }
13831}